(bug 3825) Namespace filtering on Special:Newpages
[mediawiki.git] / includes / Image.php
blobbb8ce4f1a9bbe739718a04554c91f51231fa85e7
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 if ($wgShowEXIF)
16 require_once('Exif.php');
18 /**
19 * Bump this number when serialized cache records may be incompatible.
21 define( 'MW_IMAGE_VERSION', 1 );
23 /**
24 * Class to represent an image
26 * Provides methods to retrieve paths (physical, logical, URL),
27 * to generate thumbnails or for uploading.
28 * @package MediaWiki
30 class Image
32 /**#@+
33 * @private
35 var $name, # name of the image (constructor)
36 $imagePath, # Path of the image (loadFromXxx)
37 $url, # Image URL (accessor)
38 $title, # Title object for this image (constructor)
39 $fileExists, # does the image file exist on disk? (loadFromXxx)
40 $fromSharedDirectory, # load this image from $wgSharedUploadDirectory (loadFromXxx)
41 $historyLine, # Number of line to return by nextHistoryLine() (constructor)
42 $historyRes, # result of the query for the image's history (nextHistoryLine)
43 $width, # \
44 $height, # |
45 $bits, # --- returned by getimagesize (loadFromXxx)
46 $attr, # /
47 $type, # MEDIATYPE_xxx (bitmap, drawing, audio...)
48 $mime, # MIME type, determined by MimeMagic::guessMimeType
49 $size, # Size in bytes (loadFromXxx)
50 $metadata, # Metadata
51 $dataLoaded, # Whether or not all this has been loaded from the database (loadFromXxx)
52 $lastError; # Error string associated with a thumbnail display error
55 /**#@-*/
57 /**
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
61 * @public
63 function newFromName( $name ) {
64 $title = Title::makeTitleSafe( NS_IMAGE, $name );
65 if ( is_object( $title ) ) {
66 return new Image( $title );
67 } else {
68 return NULL;
72 /**
73 * Obsolete factory function, use constructor
75 function newFromTitle( $title ) {
76 return new Image( $title );
79 function Image( $title ) {
80 if( !is_object( $title ) ) {
81 wfDebugDieBacktrace( 'Image constructor given bogus title.' );
83 $this->title =& $title;
84 $this->name = $title->getDBkey();
85 $this->metadata = serialize ( array() ) ;
87 $n = strrpos( $this->name, '.' );
88 $this->extension = strtolower( $n ? substr( $this->name, $n + 1 ) : '' );
89 $this->historyLine = 0;
91 $this->dataLoaded = false;
94 /**
95 * Get the memcached keys
96 * Returns an array, first element is the local cache key, second is the shared cache key, if there is one
98 function getCacheKeys( $shared = false ) {
99 global $wgDBname, $wgUseSharedUploads, $wgSharedUploadDBname, $wgCacheSharedUploads;
101 $foundCached = false;
102 $hashedName = md5($this->name);
103 $keys = array( "$wgDBname:Image:$hashedName" );
104 if ( $wgUseSharedUploads && $wgSharedUploadDBname && $wgCacheSharedUploads ) {
105 $keys[] = "$wgSharedUploadDBname:Image:$hashedName";
107 return $keys;
111 * Try to load image metadata from memcached. Returns true on success.
113 function loadFromCache() {
114 global $wgUseSharedUploads, $wgMemc;
115 $fname = 'Image::loadFromMemcached';
116 wfProfileIn( $fname );
117 $this->dataLoaded = false;
118 $keys = $this->getCacheKeys();
119 $cachedValues = $wgMemc->get( $keys[0] );
121 // Check if the key existed and belongs to this version of MediaWiki
122 if (!empty($cachedValues) && is_array($cachedValues)
123 && isset($cachedValues['version']) && ( $cachedValues['version'] == MW_IMAGE_VERSION )
124 && $cachedValues['fileExists'] && isset( $cachedValues['mime'] ) && isset( $cachedValues['metadata'] ) )
126 if ( $wgUseSharedUploads && $cachedValues['fromShared']) {
127 # if this is shared file, we need to check if image
128 # in shared repository has not changed
129 if ( isset( $keys[1] ) ) {
130 $commonsCachedValues = $wgMemc->get( $keys[1] );
131 if (!empty($commonsCachedValues) && is_array($commonsCachedValues)
132 && isset($commonsCachedValues['version'])
133 && ( $commonsCachedValues['version'] == MW_IMAGE_VERSION )
134 && isset($commonsCachedValues['mime'])) {
135 wfDebug( "Pulling image metadata from shared repository cache\n" );
136 $this->name = $commonsCachedValues['name'];
137 $this->imagePath = $commonsCachedValues['imagePath'];
138 $this->fileExists = $commonsCachedValues['fileExists'];
139 $this->width = $commonsCachedValues['width'];
140 $this->height = $commonsCachedValues['height'];
141 $this->bits = $commonsCachedValues['bits'];
142 $this->type = $commonsCachedValues['type'];
143 $this->mime = $commonsCachedValues['mime'];
144 $this->metadata = $commonsCachedValues['metadata'];
145 $this->size = $commonsCachedValues['size'];
146 $this->fromSharedDirectory = true;
147 $this->dataLoaded = true;
148 $this->imagePath = $this->getFullPath(true);
151 } else {
152 wfDebug( "Pulling image metadata from local cache\n" );
153 $this->name = $cachedValues['name'];
154 $this->imagePath = $cachedValues['imagePath'];
155 $this->fileExists = $cachedValues['fileExists'];
156 $this->width = $cachedValues['width'];
157 $this->height = $cachedValues['height'];
158 $this->bits = $cachedValues['bits'];
159 $this->type = $cachedValues['type'];
160 $this->mime = $cachedValues['mime'];
161 $this->metadata = $cachedValues['metadata'];
162 $this->size = $cachedValues['size'];
163 $this->fromSharedDirectory = false;
164 $this->dataLoaded = true;
165 $this->imagePath = $this->getFullPath();
168 if ( $this->dataLoaded ) {
169 wfIncrStats( 'image_cache_hit' );
170 } else {
171 wfIncrStats( 'image_cache_miss' );
174 wfProfileOut( $fname );
175 return $this->dataLoaded;
179 * Save the image metadata to memcached
181 function saveToCache() {
182 global $wgMemc;
183 $this->load();
184 $keys = $this->getCacheKeys();
185 if ( $this->fileExists ) {
186 // We can't cache negative metadata for non-existent files,
187 // because if the file later appears in commons, the local
188 // keys won't be purged.
189 $cachedValues = array(
190 'version' => MW_IMAGE_VERSION,
191 'name' => $this->name,
192 'imagePath' => $this->imagePath,
193 'fileExists' => $this->fileExists,
194 'fromShared' => $this->fromSharedDirectory,
195 'width' => $this->width,
196 'height' => $this->height,
197 'bits' => $this->bits,
198 'type' => $this->type,
199 'mime' => $this->mime,
200 'metadata' => $this->metadata,
201 'size' => $this->size );
203 $wgMemc->set( $keys[0], $cachedValues, 60 * 60 * 24 * 7 ); // A week
204 } else {
205 // However we should clear them, so they aren't leftover
206 // if we've deleted the file.
207 $wgMemc->delete( $keys[0] );
212 * Load metadata from the file itself
214 function loadFromFile() {
215 global $wgUseSharedUploads, $wgSharedUploadDirectory, $wgContLang, $wgShowEXIF;
216 $fname = 'Image::loadFromFile';
217 wfProfileIn( $fname );
218 $this->imagePath = $this->getFullPath();
219 $this->fileExists = file_exists( $this->imagePath );
220 $this->fromSharedDirectory = false;
221 $gis = array();
223 if (!$this->fileExists) wfDebug("$fname: ".$this->imagePath." not found locally!\n");
225 # If the file is not found, and a shared upload directory is used, look for it there.
226 if (!$this->fileExists && $wgUseSharedUploads && $wgSharedUploadDirectory) {
227 # In case we're on a wgCapitalLinks=false wiki, we
228 # capitalize the first letter of the filename before
229 # looking it up in the shared repository.
230 $sharedImage = Image::newFromName( $wgContLang->ucfirst($this->name) );
231 $this->fileExists = $sharedImage && file_exists( $sharedImage->getFullPath(true) );
232 if ( $this->fileExists ) {
233 $this->name = $sharedImage->name;
234 $this->imagePath = $this->getFullPath(true);
235 $this->fromSharedDirectory = true;
240 if ( $this->fileExists ) {
241 $magic=& wfGetMimeMagic();
243 $this->mime = $magic->guessMimeType($this->imagePath,true);
244 $this->type = $magic->getMediaType($this->imagePath,$this->mime);
246 # Get size in bytes
247 $this->size = filesize( $this->imagePath );
249 $magic=& wfGetMimeMagic();
251 # Height and width
252 if( $this->mime == 'image/svg' ) {
253 wfSuppressWarnings();
254 $gis = wfGetSVGsize( $this->imagePath );
255 wfRestoreWarnings();
257 elseif ( !$magic->isPHPImageType( $this->mime ) ) {
258 # Don't try to get the width and height of sound and video files, that's bad for performance
259 $gis[0]= 0; //width
260 $gis[1]= 0; //height
261 $gis[2]= 0; //unknown
262 $gis[3]= ""; //width height string
264 else {
265 wfSuppressWarnings();
266 $gis = getimagesize( $this->imagePath );
267 wfRestoreWarnings();
270 wfDebug("$fname: ".$this->imagePath." loaded, ".$this->size." bytes, ".$this->mime.".\n");
272 else {
273 $gis[0]= 0; //width
274 $gis[1]= 0; //height
275 $gis[2]= 0; //unknown
276 $gis[3]= ""; //width height string
278 $this->mime = NULL;
279 $this->type = MEDIATYPE_UNKNOWN;
280 wfDebug("$fname: ".$this->imagePath." NOT FOUND!\n");
283 $this->width = $gis[0];
284 $this->height = $gis[1];
286 #NOTE: $gis[2] contains a code for the image type. This is no longer used.
288 #NOTE: we have to set this flag early to avoid load() to be called
289 # be some of the functions below. This may lead to recursion or other bad things!
290 # as ther's only one thread of execution, this should be safe anyway.
291 $this->dataLoaded = true;
294 if ($this->fileExists && $wgShowEXIF) $this->metadata = serialize ( $this->retrieveExifData() ) ;
295 else $this->metadata = serialize ( array() ) ;
297 if ( isset( $gis['bits'] ) ) $this->bits = $gis['bits'];
298 else $this->bits = 0;
300 wfProfileOut( $fname );
304 * Load image metadata from the DB
306 function loadFromDB() {
307 global $wgUseSharedUploads, $wgSharedUploadDBname, $wgSharedUploadDBprefix, $wgContLang;
308 $fname = 'Image::loadFromDB';
309 wfProfileIn( $fname );
311 $dbr =& wfGetDB( DB_SLAVE );
313 $this->checkDBSchema($dbr);
315 $row = $dbr->selectRow( 'image',
316 array( 'img_size', 'img_width', 'img_height', 'img_bits',
317 'img_media_type', 'img_major_mime', 'img_minor_mime', 'img_metadata' ),
318 array( 'img_name' => $this->name ), $fname );
319 if ( $row ) {
320 $this->fromSharedDirectory = false;
321 $this->fileExists = true;
322 $this->loadFromRow( $row );
323 $this->imagePath = $this->getFullPath();
324 // Check for rows from a previous schema, quietly upgrade them
325 if ( is_null($this->type) ) {
326 $this->upgradeRow();
328 } elseif ( $wgUseSharedUploads && $wgSharedUploadDBname ) {
329 # In case we're on a wgCapitalLinks=false wiki, we
330 # capitalize the first letter of the filename before
331 # looking it up in the shared repository.
332 $name = $wgContLang->ucfirst($this->name);
333 $dbc =& wfGetDB( DB_SLAVE, 'commons' );
335 $row = $dbc->selectRow( "`$wgSharedUploadDBname`.{$wgSharedUploadDBprefix}image",
336 array(
337 'img_size', 'img_width', 'img_height', 'img_bits',
338 'img_media_type', 'img_major_mime', 'img_minor_mime', 'img_metadata' ),
339 array( 'img_name' => $name ), $fname );
340 if ( $row ) {
341 $this->fromSharedDirectory = true;
342 $this->fileExists = true;
343 $this->imagePath = $this->getFullPath(true);
344 $this->name = $name;
345 $this->loadFromRow( $row );
347 // Check for rows from a previous schema, quietly upgrade them
348 if ( is_null($this->type) ) {
349 $this->upgradeRow();
354 if ( !$row ) {
355 $this->size = 0;
356 $this->width = 0;
357 $this->height = 0;
358 $this->bits = 0;
359 $this->type = 0;
360 $this->fileExists = false;
361 $this->fromSharedDirectory = false;
362 $this->metadata = serialize ( array() ) ;
365 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
366 $this->dataLoaded = true;
367 wfProfileOut( $fname );
371 * Load image metadata from a DB result row
373 function loadFromRow( &$row ) {
374 $this->size = $row->img_size;
375 $this->width = $row->img_width;
376 $this->height = $row->img_height;
377 $this->bits = $row->img_bits;
378 $this->type = $row->img_media_type;
380 $major= $row->img_major_mime;
381 $minor= $row->img_minor_mime;
383 if (!$major) $this->mime = "unknown/unknown";
384 else {
385 if (!$minor) $minor= "unknown";
386 $this->mime = $major.'/'.$minor;
389 $this->metadata = $row->img_metadata;
390 if ( $this->metadata == "" ) $this->metadata = serialize ( array() ) ;
392 $this->dataLoaded = true;
396 * Load image metadata from cache or DB, unless already loaded
398 function load() {
399 global $wgSharedUploadDBname, $wgUseSharedUploads;
400 if ( !$this->dataLoaded ) {
401 if ( !$this->loadFromCache() ) {
402 $this->loadFromDB();
403 if ( !$wgSharedUploadDBname && $wgUseSharedUploads ) {
404 $this->loadFromFile();
405 } elseif ( $this->fileExists ) {
406 $this->saveToCache();
409 $this->dataLoaded = true;
414 * Metadata was loaded from the database, but the row had a marker indicating it needs to be
415 * upgraded from the 1.4 schema, which had no width, height, bits or type. Upgrade the row.
417 function upgradeRow() {
418 global $wgDBname, $wgSharedUploadDBname;
419 $fname = 'Image::upgradeRow';
420 wfProfileIn( $fname );
422 $this->loadFromFile();
424 if ( $this->fromSharedDirectory ) {
425 if ( !$wgSharedUploadDBname ) {
426 wfProfileOut( $fname );
427 return;
430 // Write to the other DB using selectDB, not database selectors
431 // This avoids breaking replication in MySQL
432 $dbw =& wfGetDB( DB_MASTER, 'commons' );
433 $dbw->selectDB( $wgSharedUploadDBname );
434 } else {
435 $dbw =& wfGetDB( DB_MASTER );
438 $this->checkDBSchema($dbw);
440 if (strpos($this->mime,'/')!==false) {
441 list($major,$minor)= explode('/',$this->mime,2);
443 else {
444 $major= $this->mime;
445 $minor= "unknown";
448 wfDebug("$fname: upgrading ".$this->name." to 1.5 schema\n");
450 $dbw->update( 'image',
451 array(
452 'img_width' => $this->width,
453 'img_height' => $this->height,
454 'img_bits' => $this->bits,
455 'img_media_type' => $this->type,
456 'img_major_mime' => $major,
457 'img_minor_mime' => $minor,
458 'img_metadata' => $this->metadata,
459 ), array( 'img_name' => $this->name ), $fname
461 if ( $this->fromSharedDirectory ) {
462 $dbw->selectDB( $wgDBname );
464 wfProfileOut( $fname );
468 * Return the name of this image
469 * @public
471 function getName() {
472 return $this->name;
476 * Return the associated title object
477 * @public
479 function getTitle() {
480 return $this->title;
484 * Return the URL of the image file
485 * @public
487 function getURL() {
488 if ( !$this->url ) {
489 $this->load();
490 if($this->fileExists) {
491 $this->url = Image::imageUrl( $this->name, $this->fromSharedDirectory );
492 } else {
493 $this->url = '';
496 return $this->url;
499 function getViewURL() {
500 if( $this->mustRender()) {
501 if( $this->canRender() ) {
502 return $this->createThumb( $this->getWidth() );
504 else {
505 wfDebug('Image::getViewURL(): supposed to render '.$this->name.' ('.$this->mime."), but can't!\n");
506 return $this->getURL(); #hm... return NULL?
508 } else {
509 return $this->getURL();
514 * Return the image path of the image in the
515 * local file system as an absolute path
516 * @public
518 function getImagePath() {
519 $this->load();
520 return $this->imagePath;
524 * Return the width of the image
526 * Returns -1 if the file specified is not a known image type
527 * @public
529 function getWidth() {
530 $this->load();
531 return $this->width;
535 * Return the height of the image
537 * Returns -1 if the file specified is not a known image type
538 * @public
540 function getHeight() {
541 $this->load();
542 return $this->height;
546 * Return the size of the image file, in bytes
547 * @public
549 function getSize() {
550 $this->load();
551 return $this->size;
555 * Returns the mime type of the file.
557 function getMimeType() {
558 $this->load();
559 return $this->mime;
563 * Return the type of the media in the file.
564 * Use the value returned by this function with the MEDIATYPE_xxx constants.
566 function getMediaType() {
567 $this->load();
568 return $this->type;
572 * Checks if the file can be presented to the browser as a bitmap.
574 * Currently, this checks if the file is an image format
575 * that can be converted to a format
576 * supported by all browsers (namely GIF, PNG and JPEG),
577 * or if it is an SVG image and SVG conversion is enabled.
579 * @todo remember the result of this check.
581 function canRender() {
582 global $wgUseImageMagick;
584 if( $this->getWidth()<=0 || $this->getHeight()<=0 ) return false;
586 $mime= $this->getMimeType();
588 if (!$mime || $mime==='unknown' || $mime==='unknown/unknown') return false;
590 #if it's SVG, check if there's a converter enabled
591 if ($mime === 'image/svg') {
592 global $wgSVGConverters, $wgSVGConverter;
594 if ($wgSVGConverter && isset( $wgSVGConverters[$wgSVGConverter])) {
595 wfDebug( "Image::canRender: SVG is ready!\n" );
596 return true;
597 } else {
598 wfDebug( "Image::canRender: SVG renderer missing\n" );
602 #image formats available on ALL browsers
603 if ( $mime === 'image/gif'
604 || $mime === 'image/png'
605 || $mime === 'image/jpeg' ) return true;
607 #image formats that can be converted to the above formats
608 if ($wgUseImageMagick) {
609 #convertable by ImageMagick (there are more...)
610 if ( $mime === 'image/vnd.wap.wbmp'
611 || $mime === 'image/x-xbitmap'
612 || $mime === 'image/x-xpixmap'
613 #|| $mime === 'image/x-icon' #file may be split into multiple parts
614 || $mime === 'image/x-portable-anymap'
615 || $mime === 'image/x-portable-bitmap'
616 || $mime === 'image/x-portable-graymap'
617 || $mime === 'image/x-portable-pixmap'
618 #|| $mime === 'image/x-photoshop' #this takes a lot of CPU and RAM!
619 || $mime === 'image/x-rgb'
620 || $mime === 'image/x-bmp'
621 || $mime === 'image/tiff' ) return true;
623 else {
624 #convertable by the PHP GD image lib
625 if ( $mime === 'image/vnd.wap.wbmp'
626 || $mime === 'image/x-xbitmap' ) return true;
629 return false;
634 * Return true if the file is of a type that can't be directly
635 * rendered by typical browsers and needs to be re-rasterized.
637 * This returns true for everything but the bitmap types
638 * supported by all browsers, i.e. JPEG; GIF and PNG. It will
639 * also return true for any non-image formats.
641 * @return bool
643 function mustRender() {
644 $mime= $this->getMimeType();
646 if ( $mime === "image/gif"
647 || $mime === "image/png"
648 || $mime === "image/jpeg" ) return false;
650 return true;
654 * Determines if this media file may be shown inline on a page.
656 * This is currently synonymous to canRender(), but this could be
657 * extended to also allow inline display of other media,
658 * like flash animations or videos. If you do so, please keep in mind that
659 * that could be a security risk.
661 function allowInlineDisplay() {
662 return $this->canRender();
666 * Determines if this media file is in a format that is unlikely to
667 * contain viruses or malicious content. It uses the global
668 * $wgTrustedMediaFormats list to determine if the file is safe.
670 * This is used to show a warning on the description page of non-safe files.
671 * It may also be used to disallow direct [[media:...]] links to such files.
673 * Note that this function will always return true if allowInlineDisplay()
674 * or isTrustedFile() is true for this file.
676 function isSafeFile() {
677 if ($this->allowInlineDisplay()) return true;
678 if ($this->isTrustedFile()) return true;
680 global $wgTrustedMediaFormats;
682 $type= $this->getMediaType();
683 $mime= $this->getMimeType();
684 #wfDebug("Image::isSafeFile: type= $type, mime= $mime\n");
686 if (!$type || $type===MEDIATYPE_UNKNOWN) return false; #unknown type, not trusted
687 if ( in_array( $type, $wgTrustedMediaFormats) ) return true;
689 if ($mime==="unknown/unknown") return false; #unknown type, not trusted
690 if ( in_array( $mime, $wgTrustedMediaFormats) ) return true;
692 return false;
695 /** Returns true if the file is flagged as trusted. Files flagged that way
696 * can be linked to directly, even if that is not allowed for this type of
697 * file normally.
699 * This is a dummy function right now and always returns false. It could be
700 * implemented to extract a flag from the database. The trusted flag could be
701 * set on upload, if the user has sufficient privileges, to bypass script-
702 * and html-filters. It may even be coupled with cryptographics signatures
703 * or such.
705 function isTrustedFile() {
706 #this could be implemented to check a flag in the databas,
707 #look for signatures, etc
708 return false;
712 * Return the escapeLocalURL of this image
713 * @public
715 function getEscapeLocalURL() {
716 $this->getTitle();
717 return $this->title->escapeLocalURL();
721 * Return the escapeFullURL of this image
722 * @public
724 function getEscapeFullURL() {
725 $this->getTitle();
726 return $this->title->escapeFullURL();
730 * Return the URL of an image, provided its name.
732 * @param string $name Name of the image, without the leading "Image:"
733 * @param boolean $fromSharedDirectory Should this be in $wgSharedUploadPath?
734 * @return string URL of $name image
735 * @public
736 * @static
738 function imageUrl( $name, $fromSharedDirectory = false ) {
739 global $wgUploadPath,$wgUploadBaseUrl,$wgSharedUploadPath;
740 if($fromSharedDirectory) {
741 $base = '';
742 $path = $wgSharedUploadPath;
743 } else {
744 $base = $wgUploadBaseUrl;
745 $path = $wgUploadPath;
747 $url = "{$base}{$path}" . wfGetHashPath($name, $fromSharedDirectory) . "{$name}";
748 return wfUrlencode( $url );
752 * Returns true if the image file exists on disk.
753 * @return boolean Whether image file exist on disk.
754 * @public
756 function exists() {
757 $this->load();
758 return $this->fileExists;
762 * @todo document
763 * @private
765 function thumbUrl( $width, $subdir='thumb') {
766 global $wgUploadPath, $wgUploadBaseUrl, $wgSharedUploadPath;
767 global $wgSharedThumbnailScriptPath, $wgThumbnailScriptPath;
769 // Generate thumb.php URL if possible
770 $script = false;
771 $url = false;
773 if ( $this->fromSharedDirectory ) {
774 if ( $wgSharedThumbnailScriptPath ) {
775 $script = $wgSharedThumbnailScriptPath;
777 } else {
778 if ( $wgThumbnailScriptPath ) {
779 $script = $wgThumbnailScriptPath;
782 if ( $script ) {
783 $url = $script . '?f=' . urlencode( $this->name ) . '&w=' . urlencode( $width );
784 if( $this->mustRender() ) {
785 $url.= '&r=1';
787 } else {
788 $name = $this->thumbName( $width );
789 if($this->fromSharedDirectory) {
790 $base = '';
791 $path = $wgSharedUploadPath;
792 } else {
793 $base = $wgUploadBaseUrl;
794 $path = $wgUploadPath;
796 if ( Image::isHashed( $this->fromSharedDirectory ) ) {
797 $url = "{$base}{$path}/{$subdir}" .
798 wfGetHashPath($this->name, $this->fromSharedDirectory)
799 . $this->name.'/'.$name;
800 $url = wfUrlencode( $url );
801 } else {
802 $url = "{$base}{$path}/{$subdir}/{$name}";
805 return array( $script !== false, $url );
809 * Return the file name of a thumbnail of the specified width
811 * @param integer $width Width of the thumbnail image
812 * @param boolean $shared Does the thumbnail come from the shared repository?
813 * @private
815 function thumbName( $width ) {
816 $thumb = $width."px-".$this->name;
818 if( $this->mustRender() ) {
819 if( $this->canRender() ) {
820 # Rasterize to PNG (for SVG vector images, etc)
821 $thumb .= '.png';
823 else {
824 #should we use iconThumb here to get a symbolic thumbnail?
825 #or should we fail with an internal error?
826 return NULL; //can't make bitmap
829 return $thumb;
833 * Create a thumbnail of the image having the specified width/height.
834 * The thumbnail will not be created if the width is larger than the
835 * image's width. Let the browser do the scaling in this case.
836 * The thumbnail is stored on disk and is only computed if the thumbnail
837 * file does not exist OR if it is older than the image.
838 * Returns the URL.
840 * Keeps aspect ratio of original image. If both width and height are
841 * specified, the generated image will be no bigger than width x height,
842 * and will also have correct aspect ratio.
844 * @param integer $width maximum width of the generated thumbnail
845 * @param integer $height maximum height of the image (optional)
846 * @public
848 function createThumb( $width, $height=-1 ) {
849 $thumb = $this->getThumbnail( $width, $height );
850 if( is_null( $thumb ) ) return '';
851 return $thumb->getUrl();
855 * As createThumb, but returns a ThumbnailImage object. This can
856 * provide access to the actual file, the real size of the thumb,
857 * and can produce a convenient <img> tag for you.
859 * @param integer $width maximum width of the generated thumbnail
860 * @param integer $height maximum height of the image (optional)
861 * @return ThumbnailImage
862 * @public
864 function getThumbnail( $width, $height=-1 ) {
865 if ( $height <= 0 ) {
866 return $this->renderThumb( $width );
868 $this->load();
870 if ($this->canRender()) {
871 if ( $width > $this->width * $height / $this->height )
872 $width = wfFitBoxWidth( $this->width, $this->height, $height );
873 $thumb = $this->renderThumb( $width );
875 else $thumb= NULL; #not a bitmap or renderable image, don't try.
877 if( is_null( $thumb ) ) {
878 $thumb = $this->iconThumb();
880 return $thumb;
884 * @return ThumbnailImage
886 function iconThumb() {
887 global $wgStylePath, $wgStyleDirectory;
889 $try = array( 'fileicon-' . $this->extension . '.png', 'fileicon.png' );
890 foreach( $try as $icon ) {
891 $path = '/common/images/icons/' . $icon;
892 $filepath = $wgStyleDirectory . $path;
893 if( file_exists( $filepath ) ) {
894 return new ThumbnailImage( $wgStylePath . $path, 120, 120 );
897 return null;
901 * Create a thumbnail of the image having the specified width.
902 * The thumbnail will not be created if the width is larger than the
903 * image's width. Let the browser do the scaling in this case.
904 * The thumbnail is stored on disk and is only computed if the thumbnail
905 * file does not exist OR if it is older than the image.
906 * Returns an object which can return the pathname, URL, and physical
907 * pixel size of the thumbnail -- or null on failure.
909 * @return ThumbnailImage
910 * @private
912 function renderThumb( $width, $useScript = true ) {
913 global $wgUseSquid, $wgInternalServer;
914 global $wgSVGMaxSize, $wgMaxImageArea, $wgThumbnailEpoch;
916 $fname = 'Image::renderThumb';
917 wfProfileIn( $fname );
919 $width = intval( $width );
921 $this->load();
922 if ( ! $this->exists() )
924 # If there is no image, there will be no thumbnail
925 wfProfileOut( $fname );
926 return null;
929 # Sanity check $width
930 if( $width <= 0 || $this->width <= 0) {
931 # BZZZT
932 wfProfileOut( $fname );
933 return null;
936 # Don't thumbnail an image so big that it will fill hard drives and send servers into swap
937 # JPEG has the handy property of allowing thumbnailing without full decompression, so we make
938 # an exception for it.
939 if ( $this->getMediaType() == MEDIATYPE_BITMAP &&
940 $this->getMimeType() !== 'image/jpeg' &&
941 $this->width * $this->height > $wgMaxImageArea )
943 wfProfileOut( $fname );
944 return null;
947 # Don't make an image bigger than the source, or wgMaxSVGSize for SVGs
948 if ( $this->mustRender() ) {
949 $width = min( $width, $wgSVGMaxSize );
950 } elseif ( $width > $this->width - 1 ) {
951 $thumb = new ThumbnailImage( $this->getURL(), $this->getWidth(), $this->getHeight() );
952 wfProfileOut( $fname );
953 return $thumb;
956 $height = round( $this->height * $width / $this->width );
958 list( $isScriptUrl, $url ) = $this->thumbUrl( $width );
959 if ( $isScriptUrl && $useScript ) {
960 // Use thumb.php to render the image
961 $thumb = new ThumbnailImage( $url, $width, $height );
962 wfProfileOut( $fname );
963 return $thumb;
966 $thumbName = $this->thumbName( $width, $this->fromSharedDirectory );
967 $thumbPath = wfImageThumbDir( $this->name, $this->fromSharedDirectory ).'/'.$thumbName;
969 if ( is_dir( $thumbPath ) ) {
970 // Directory where file should be
971 // This happened occasionally due to broken migration code in 1.5
972 // Rename to broken-*
973 global $wgUploadDirectory;
974 for ( $i = 0; $i < 100 ; $i++ ) {
975 $broken = "$wgUploadDirectory/broken-$i-$thumbName";
976 if ( !file_exists( $broken ) ) {
977 rename( $thumbPath, $broken );
978 break;
981 // Code below will ask if it exists, and the answer is now no
982 clearstatcache();
985 $done = true;
986 if ( !file_exists( $thumbPath ) ||
987 filemtime( $thumbPath ) < wfTimestamp( TS_UNIX, $wgThumbnailEpoch ) ) {
988 $oldThumbPath = wfDeprecatedThumbDir( $thumbName, 'thumb', $this->fromSharedDirectory ).
989 '/'.$thumbName;
990 $done = false;
992 // Migration from old directory structure
993 if ( is_file( $oldThumbPath ) ) {
994 if ( filemtime($oldThumbPath) >= filemtime($this->imagePath) ) {
995 if ( file_exists( $thumbPath ) ) {
996 if ( !is_dir( $thumbPath ) ) {
997 // Old image in the way of rename
998 unlink( $thumbPath );
999 } else {
1000 // This should have been dealt with already
1001 wfDebugDieBacktrace( "Directory where image should be: $thumbPath" );
1004 // Rename the old image into the new location
1005 rename( $oldThumbPath, $thumbPath );
1006 $done = true;
1007 } else {
1008 unlink( $oldThumbPath );
1011 if ( !$done ) {
1012 $this->lastError = $this->reallyRenderThumb( $thumbPath, $width, $height );
1013 if ( $this->lastError === true ) {
1014 $done = true;
1017 # Purge squid
1018 # This has to be done after the image is updated and present for all machines on NFS,
1019 # or else the old version might be stored into the squid again
1020 if ( $wgUseSquid ) {
1021 if ( substr( $url, 0, 4 ) == 'http' ) {
1022 $urlArr = array( $url );
1023 } else {
1024 $urlArr = array( $wgInternalServer.$url );
1026 wfPurgeSquidServers($urlArr);
1031 if ( $done ) {
1032 $thumb = new ThumbnailImage( $url, $width, $height, $thumbPath );
1033 } else {
1034 $thumb = null;
1036 wfProfileOut( $fname );
1037 return $thumb;
1038 } // END OF function renderThumb
1041 * Really render a thumbnail
1042 * Call this only for images for which canRender() returns true.
1044 * @param string $thumbPath Path to thumbnail
1045 * @param int $width Desired width in pixels
1046 * @param int $height Desired height in pixels
1047 * @return bool True on error, false or error string on failure.
1048 * @private
1050 function reallyRenderThumb( $thumbPath, $width, $height ) {
1051 global $wgSVGConverters, $wgSVGConverter;
1052 global $wgUseImageMagick, $wgImageMagickConvertCommand;
1053 global $wgCustomConvertCommand;
1055 $this->load();
1057 $err = false;
1058 if( $this->mime === "image/svg" ) {
1059 #Right now we have only SVG
1061 global $wgSVGConverters, $wgSVGConverter;
1062 if( isset( $wgSVGConverters[$wgSVGConverter] ) ) {
1063 global $wgSVGConverterPath;
1064 $cmd = str_replace(
1065 array( '$path/', '$width', '$height', '$input', '$output' ),
1066 array( $wgSVGConverterPath ? "$wgSVGConverterPath/" : "",
1067 intval( $width ),
1068 intval( $height ),
1069 wfEscapeShellArg( $this->imagePath ),
1070 wfEscapeShellArg( $thumbPath ) ),
1071 $wgSVGConverters[$wgSVGConverter] );
1072 wfProfileIn( 'rsvg' );
1073 wfDebug( "reallyRenderThumb SVG: $cmd\n" );
1074 $err = wfShellExec( $cmd );
1075 wfProfileOut( 'rsvg' );
1077 } elseif ( $wgUseImageMagick ) {
1078 # use ImageMagick
1080 if ( $this->mime == 'image/jpeg' ) {
1081 $quality = "-quality 80"; // 80%
1082 } elseif ( $this->mime == 'image/png' ) {
1083 $quality = "-quality 95"; // zlib 9, adaptive filtering
1084 } else {
1085 $quality = ''; // default
1088 # Specify white background color, will be used for transparent images
1089 # in Internet Explorer/Windows instead of default black.
1091 # Note, we specify "-size {$width}" and NOT "-size {$width}x{$height}".
1092 # It seems that ImageMagick has a bug wherein it produces thumbnails of
1093 # the wrong size in the second case.
1095 $cmd = wfEscapeShellArg($wgImageMagickConvertCommand) .
1096 " {$quality} -background white -size {$width} ".
1097 wfEscapeShellArg($this->imagePath) .
1098 // For the -resize option a "!" is needed to force exact size,
1099 // or ImageMagick may decide your ratio is wrong and slice off
1100 // a pixel.
1101 " -resize " . wfEscapeShellArg( "{$width}x{$height}!" ) .
1102 " -depth 8 " .
1103 wfEscapeShellArg($thumbPath) . " 2>&1";
1104 wfDebug("reallyRenderThumb: running ImageMagick: $cmd\n");
1105 wfProfileIn( 'convert' );
1106 $err = wfShellExec( $cmd );
1107 wfProfileOut( 'convert' );
1108 } elseif( $wgCustomConvertCommand ) {
1109 # Use a custom convert command
1110 # Variables: %s %d %w %h
1111 $src = wfEscapeShellArg( $this->imagePath );
1112 $dst = wfEscapeShellArg( $thumbPath );
1113 $cmd = $wgCustomConvertCommand;
1114 $cmd = str_replace( '%s', $src, str_replace( '%d', $dst, $cmd ) ); # Filenames
1115 $cmd = str_replace( '%h', $height, str_replace( '%w', $width, $cmd ) ); # Size
1116 wfDebug( "reallyRenderThumb: Running custom convert command $cmd\n" );
1117 wfProfileIn( 'convert' );
1118 $err = wfShellExec( $cmd );
1119 wfProfileOut( 'convert' );
1120 } else {
1121 # Use PHP's builtin GD library functions.
1123 # First find out what kind of file this is, and select the correct
1124 # input routine for this.
1126 $typemap = array(
1127 'image/gif' => array( 'imagecreatefromgif', 'palette', 'imagegif' ),
1128 'image/jpeg' => array( 'imagecreatefromjpeg', 'truecolor', array( &$this, 'imageJpegWrapper' ) ),
1129 'image/png' => array( 'imagecreatefrompng', 'bits', 'imagepng' ),
1130 'image/vnd.wap.wmbp' => array( 'imagecreatefromwbmp', 'palette', 'imagewbmp' ),
1131 'image/xbm' => array( 'imagecreatefromxbm', 'palette', 'imagexbm' ),
1133 if( !isset( $typemap[$this->mime] ) ) {
1134 $err = 'Image type not supported';
1135 wfDebug( "$err\n" );
1136 return $err;
1138 list( $loader, $colorStyle, $saveType ) = $typemap[$this->mime];
1140 if( !function_exists( $loader ) ) {
1141 $err = "Incomplete GD library configuration: missing function $loader";
1142 wfDebug( "$err\n" );
1143 return $err;
1145 if( $colorStyle == 'palette' ) {
1146 $truecolor = false;
1147 } elseif( $colorStyle == 'truecolor' ) {
1148 $truecolor = true;
1149 } elseif( $colorStyle == 'bits' ) {
1150 $truecolor = ( $this->bits > 8 );
1153 $src_image = call_user_func( $loader, $this->imagePath );
1154 if ( $truecolor ) {
1155 $dst_image = imagecreatetruecolor( $width, $height );
1156 } else {
1157 $dst_image = imagecreate( $width, $height );
1159 imagecopyresampled( $dst_image, $src_image,
1160 0,0,0,0,
1161 $width, $height, $this->width, $this->height );
1162 call_user_func( $saveType, $dst_image, $thumbPath );
1163 imagedestroy( $dst_image );
1164 imagedestroy( $src_image );
1168 # Check for zero-sized thumbnails. Those can be generated when
1169 # no disk space is available or some other error occurs
1171 if( file_exists( $thumbPath ) ) {
1172 $thumbstat = stat( $thumbPath );
1173 if( $thumbstat['size'] == 0 ) {
1174 unlink( $thumbPath );
1175 } else {
1176 // All good
1177 $err = true;
1180 if ( $err !== true ) {
1181 return wfMsg( 'thumbnail_error', $err );
1182 } else {
1183 return true;
1187 function getLastError() {
1188 return $this->lastError;
1191 function imageJpegWrapper( $dst_image, $thumbPath ) {
1192 imageinterlace( $dst_image );
1193 imagejpeg( $dst_image, $thumbPath, 95 );
1197 * Get all thumbnail names previously generated for this image
1199 function getThumbnails( $shared = false ) {
1200 if ( Image::isHashed( $shared ) ) {
1201 $this->load();
1202 $files = array();
1203 $dir = wfImageThumbDir( $this->name, $shared );
1205 // This generates an error on failure, hence the @
1206 $handle = @opendir( $dir );
1208 if ( $handle ) {
1209 while ( false !== ( $file = readdir($handle) ) ) {
1210 if ( $file{0} != '.' ) {
1211 $files[] = $file;
1214 closedir( $handle );
1216 } else {
1217 $files = array();
1220 return $files;
1224 * Refresh metadata in memcached, but don't touch thumbnails or squid
1226 function purgeMetadataCache() {
1227 clearstatcache();
1228 $this->loadFromFile();
1229 $this->saveToCache();
1233 * Delete all previously generated thumbnails, refresh metadata in memcached and purge the squid
1235 function purgeCache( $archiveFiles = array(), $shared = false ) {
1236 global $wgInternalServer, $wgUseSquid;
1238 // Refresh metadata cache
1239 $this->purgeMetadataCache();
1241 // Delete thumbnails
1242 $files = $this->getThumbnails( $shared );
1243 $dir = wfImageThumbDir( $this->name, $shared );
1244 $urls = array();
1245 foreach ( $files as $file ) {
1246 if ( preg_match( '/^(\d+)px/', $file, $m ) ) {
1247 $urls[] = $wgInternalServer . $this->thumbUrl( $m[1], $this->fromSharedDirectory );
1248 @unlink( "$dir/$file" );
1252 // Purge the squid
1253 if ( $wgUseSquid ) {
1254 $urls[] = $wgInternalServer . $this->getViewURL();
1255 foreach ( $archiveFiles as $file ) {
1256 $urls[] = $wgInternalServer . wfImageArchiveUrl( $file );
1258 wfPurgeSquidServers( $urls );
1262 function checkDBSchema(&$db) {
1263 global $wgCheckDBSchema;
1264 if (!$wgCheckDBSchema) {
1265 return;
1267 # img_name must be unique
1268 if ( !$db->indexUnique( 'image', 'img_name' ) && !$db->indexExists('image','PRIMARY') ) {
1269 wfDebugDieBacktrace( 'Database schema not up to date, please run maintenance/archives/patch-image_name_unique.sql' );
1272 #new fields must exist
1273 if ( !$db->fieldExists( 'image', 'img_media_type' )
1274 || !$db->fieldExists( 'image', 'img_metadata' )
1275 || !$db->fieldExists( 'image', 'img_width' ) ) {
1277 wfDebugDieBacktrace( 'Database schema not up to date, please run maintenance/update.php' );
1282 * Return the image history of this image, line by line.
1283 * starts with current version, then old versions.
1284 * uses $this->historyLine to check which line to return:
1285 * 0 return line for current version
1286 * 1 query for old versions, return first one
1287 * 2, ... return next old version from above query
1289 * @public
1291 function nextHistoryLine() {
1292 $fname = 'Image::nextHistoryLine()';
1293 $dbr =& wfGetDB( DB_SLAVE );
1295 $this->checkDBSchema($dbr);
1297 if ( $this->historyLine == 0 ) {// called for the first time, return line from cur
1298 $this->historyRes = $dbr->select( 'image',
1299 array(
1300 'img_size',
1301 'img_description',
1302 'img_user','img_user_text',
1303 'img_timestamp',
1304 'img_width',
1305 'img_height',
1306 "'' AS oi_archive_name"
1308 array( 'img_name' => $this->title->getDBkey() ),
1309 $fname
1311 if ( 0 == wfNumRows( $this->historyRes ) ) {
1312 return FALSE;
1314 } else if ( $this->historyLine == 1 ) {
1315 $this->historyRes = $dbr->select( 'oldimage',
1316 array(
1317 'oi_size AS img_size',
1318 'oi_description AS img_description',
1319 'oi_user AS img_user',
1320 'oi_user_text AS img_user_text',
1321 'oi_timestamp AS img_timestamp',
1322 'oi_width as img_width',
1323 'oi_height as img_height',
1324 'oi_archive_name'
1326 array( 'oi_name' => $this->title->getDBkey() ),
1327 $fname,
1328 array( 'ORDER BY' => 'oi_timestamp DESC' )
1331 $this->historyLine ++;
1333 return $dbr->fetchObject( $this->historyRes );
1337 * Reset the history pointer to the first element of the history
1338 * @public
1340 function resetHistory() {
1341 $this->historyLine = 0;
1345 * Return the full filesystem path to the file. Note that this does
1346 * not mean that a file actually exists under that location.
1348 * This path depends on whether directory hashing is active or not,
1349 * i.e. whether the images are all found in the same directory,
1350 * or in hashed paths like /images/3/3c.
1352 * @public
1353 * @param boolean $fromSharedDirectory Return the path to the file
1354 * in a shared repository (see $wgUseSharedRepository and related
1355 * options in DefaultSettings.php) instead of a local one.
1358 function getFullPath( $fromSharedRepository = false ) {
1359 global $wgUploadDirectory, $wgSharedUploadDirectory;
1361 $dir = $fromSharedRepository ? $wgSharedUploadDirectory :
1362 $wgUploadDirectory;
1364 // $wgSharedUploadDirectory may be false, if thumb.php is used
1365 if ( $dir ) {
1366 $fullpath = $dir . wfGetHashPath($this->name, $fromSharedRepository) . $this->name;
1367 } else {
1368 $fullpath = false;
1371 return $fullpath;
1375 * @return bool
1376 * @static
1378 function isHashed( $shared ) {
1379 global $wgHashedUploadDirectory, $wgHashedSharedUploadDirectory;
1380 return $shared ? $wgHashedSharedUploadDirectory : $wgHashedUploadDirectory;
1384 * Record an image upload in the upload log and the image table
1386 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '', $watch = false ) {
1387 global $wgUser, $wgUseCopyrightUpload, $wgUseSquid, $wgPostCommitUpdateList;
1389 $fname = 'Image::recordUpload';
1390 $dbw =& wfGetDB( DB_MASTER );
1392 $this->checkDBSchema($dbw);
1394 // Delete thumbnails and refresh the metadata cache
1395 $this->purgeCache();
1397 // Fail now if the image isn't there
1398 if ( !$this->fileExists || $this->fromSharedDirectory ) {
1399 wfDebug( "Image::recordUpload: File ".$this->imagePath." went missing!\n" );
1400 return false;
1403 if ( $wgUseCopyrightUpload ) {
1404 if ( $license != '' ) {
1405 $licensetxt = '== ' . wfMsgForContent( 'license' ) . " ==\n" . '{{' . $license . '}}' . "\n";
1407 $textdesc = '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $desc . "\n" .
1408 '== ' . wfMsgForContent ( 'filestatus' ) . " ==\n" . $copyStatus . "\n" .
1409 "$licensetxt" .
1410 '== ' . wfMsgForContent ( 'filesource' ) . " ==\n" . $source ;
1411 } else {
1412 if ( $license != '' ) {
1413 $filedesc = $desc == '' ? '' : '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $desc . "\n";
1414 $textdesc = $filedesc .
1415 '== ' . wfMsgForContent ( 'license' ) . " ==\n" . '{{' . $license . '}}' . "\n";
1416 } else {
1417 $textdesc = $desc;
1421 $now = $dbw->timestamp();
1423 #split mime type
1424 if (strpos($this->mime,'/')!==false) {
1425 list($major,$minor)= explode('/',$this->mime,2);
1427 else {
1428 $major= $this->mime;
1429 $minor= "unknown";
1432 # Test to see if the row exists using INSERT IGNORE
1433 # This avoids race conditions by locking the row until the commit, and also
1434 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
1435 $dbw->insert( 'image',
1436 array(
1437 'img_name' => $this->name,
1438 'img_size'=> $this->size,
1439 'img_width' => intval( $this->width ),
1440 'img_height' => intval( $this->height ),
1441 'img_bits' => $this->bits,
1442 'img_media_type' => $this->type,
1443 'img_major_mime' => $major,
1444 'img_minor_mime' => $minor,
1445 'img_timestamp' => $now,
1446 'img_description' => $desc,
1447 'img_user' => $wgUser->getID(),
1448 'img_user_text' => $wgUser->getName(),
1449 'img_metadata' => $this->metadata,
1451 $fname,
1452 'IGNORE'
1454 $descTitle = $this->getTitle();
1455 $purgeURLs = array();
1457 if( $dbw->affectedRows() == 0 ) {
1458 # Collision, this is an update of an image
1459 # Insert previous contents into oldimage
1460 $dbw->insertSelect( 'oldimage', 'image',
1461 array(
1462 'oi_name' => 'img_name',
1463 'oi_archive_name' => $dbw->addQuotes( $oldver ),
1464 'oi_size' => 'img_size',
1465 'oi_width' => 'img_width',
1466 'oi_height' => 'img_height',
1467 'oi_bits' => 'img_bits',
1468 'oi_timestamp' => 'img_timestamp',
1469 'oi_description' => 'img_description',
1470 'oi_user' => 'img_user',
1471 'oi_user_text' => 'img_user_text',
1472 ), array( 'img_name' => $this->name ), $fname
1475 # Update the current image row
1476 $dbw->update( 'image',
1477 array( /* SET */
1478 'img_size' => $this->size,
1479 'img_width' => intval( $this->width ),
1480 'img_height' => intval( $this->height ),
1481 'img_bits' => $this->bits,
1482 'img_media_type' => $this->type,
1483 'img_major_mime' => $major,
1484 'img_minor_mime' => $minor,
1485 'img_timestamp' => $now,
1486 'img_description' => $desc,
1487 'img_user' => $wgUser->getID(),
1488 'img_user_text' => $wgUser->getName(),
1489 'img_metadata' => $this->metadata,
1490 ), array( /* WHERE */
1491 'img_name' => $this->name
1492 ), $fname
1494 } else {
1495 # This is a new image
1496 # Update the image count
1497 $site_stats = $dbw->tableName( 'site_stats' );
1498 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images+1", $fname );
1501 $article = new Article( $descTitle );
1502 $minor = false;
1503 $watch = $watch || $wgUser->isWatched( $descTitle );
1504 $suppressRC = true; // There's already a log entry, so don't double the RC load
1506 if( $descTitle->exists() ) {
1507 // TODO: insert a null revision into the page history for this update.
1508 if( $watch ) {
1509 $wgUser->addWatch( $descTitle );
1512 # Invalidate the cache for the description page
1513 $descTitle->invalidateCache();
1514 $purgeURLs[] = $descTitle->getInternalURL();
1515 } else {
1516 // New image; create the description page.
1517 $article->insertNewArticle( $textdesc, $desc, $minor, $watch, $suppressRC );
1520 # Invalidate cache for all pages using this image
1521 $linksTo = $this->getLinksTo();
1523 if ( $wgUseSquid ) {
1524 $u = SquidUpdate::newFromTitles( $linksTo, $purgeURLs );
1525 array_push( $wgPostCommitUpdateList, $u );
1527 Title::touchArray( $linksTo );
1529 $log = new LogPage( 'upload' );
1530 $log->addEntry( 'upload', $descTitle, $desc );
1532 return true;
1536 * Get an array of Title objects which are articles which use this image
1537 * Also adds their IDs to the link cache
1539 * This is mostly copied from Title::getLinksTo()
1541 function getLinksTo( $options = '' ) {
1542 $fname = 'Image::getLinksTo';
1543 wfProfileIn( $fname );
1545 if ( $options ) {
1546 $db =& wfGetDB( DB_MASTER );
1547 } else {
1548 $db =& wfGetDB( DB_SLAVE );
1550 $linkCache =& LinkCache::singleton();
1552 extract( $db->tableNames( 'page', 'imagelinks' ) );
1553 $encName = $db->addQuotes( $this->name );
1554 $sql = "SELECT page_namespace,page_title,page_id FROM $page,$imagelinks WHERE page_id=il_from AND il_to=$encName $options";
1555 $res = $db->query( $sql, $fname );
1557 $retVal = array();
1558 if ( $db->numRows( $res ) ) {
1559 while ( $row = $db->fetchObject( $res ) ) {
1560 if ( $titleObj = Title::makeTitle( $row->page_namespace, $row->page_title ) ) {
1561 $linkCache->addGoodLinkObj( $row->page_id, $titleObj );
1562 $retVal[] = $titleObj;
1566 $db->freeResult( $res );
1567 wfProfileOut( $fname );
1568 return $retVal;
1571 * Retrive Exif data from the database
1573 * Retrive Exif data from the database and prune unrecognized tags
1574 * and/or tags with invalid contents
1576 * @return array
1578 function retrieveExifData() {
1579 if ( $this->getMimeType() !== "image/jpeg" )
1580 return array();
1582 $exif = new Exif( $this->imagePath );
1583 return $exif->getFilteredData();
1586 function getExifData() {
1587 global $wgRequest;
1588 if ( $this->metadata === '0' )
1589 return array();
1591 $purge = $wgRequest->getVal( 'action' ) == 'purge';
1592 $ret = unserialize( $this->metadata );
1594 $oldver = isset( $ret['MEDIAWIKI_EXIF_VERSION'] ) ? $ret['MEDIAWIKI_EXIF_VERSION'] : 0;
1595 $newver = Exif::version();
1597 if ( !count( $ret ) || $purge || $oldver != $newver ) {
1598 $this->purgeMetadataCache();
1599 $this->updateExifData( $newver );
1601 if ( isset( $ret['MEDIAWIKI_EXIF_VERSION'] ) )
1602 unset( $ret['MEDIAWIKI_EXIF_VERSION'] );
1603 $format = new FormatExif( $ret );
1605 return $format->getFormattedData();
1608 function updateExifData( $version ) {
1609 $fname = 'Image:updateExifData';
1611 if ( $this->getImagePath() === false ) # Not a local image
1612 return;
1614 # Get EXIF data from image
1615 $exif = $this->retrieveExifData();
1616 if ( count( $exif ) ) {
1617 $exif['MEDIAWIKI_EXIF_VERSION'] = $version;
1618 $this->metadata = serialize( $exif );
1619 } else {
1620 $this->metadata = '0';
1623 # Update EXIF data in database
1624 $dbw =& wfGetDB( DB_MASTER );
1626 $this->checkDBSchema($dbw);
1628 $dbw->update( 'image',
1629 array( 'img_metadata' => $this->metadata ),
1630 array( 'img_name' => $this->name ),
1631 $fname
1636 * Returns true if the image does not come from the shared
1637 * image repository.
1639 * @return bool
1641 function isLocal() {
1642 return !$this->fromSharedDirectory;
1645 } //class
1649 * Returns the image directory of an image
1650 * If the directory does not exist, it is created.
1651 * The result is an absolute path.
1653 * This function is called from thumb.php before Setup.php is included
1655 * @param $fname String: file name of the image file.
1656 * @public
1658 function wfImageDir( $fname ) {
1659 global $wgUploadDirectory, $wgHashedUploadDirectory;
1661 if (!$wgHashedUploadDirectory) { return $wgUploadDirectory; }
1663 $hash = md5( $fname );
1664 $oldumask = umask(0);
1665 $dest = $wgUploadDirectory . '/' . $hash{0};
1666 if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }
1667 $dest .= '/' . substr( $hash, 0, 2 );
1668 if ( ! is_dir( $dest ) ) { mkdir( $dest, 0777 ); }
1670 umask( $oldumask );
1671 return $dest;
1675 * Returns the image directory of an image's thubnail
1676 * If the directory does not exist, it is created.
1677 * The result is an absolute path.
1679 * This function is called from thumb.php before Setup.php is included
1681 * @param $fname String: file name of the original image file
1682 * @param $shared Boolean: (optional) use the shared upload directory (default: 'false').
1683 * @public
1685 function wfImageThumbDir( $fname, $shared = false ) {
1686 $base = wfImageArchiveDir( $fname, 'thumb', $shared );
1687 if ( Image::isHashed( $shared ) ) {
1688 $dir = "$base/$fname";
1690 if ( !is_dir( $base ) ) {
1691 $oldumask = umask(0);
1692 @mkdir( $base, 0777 );
1693 umask( $oldumask );
1696 if ( ! is_dir( $dir ) ) {
1697 if ( is_file( $dir ) ) {
1698 // Old thumbnail in the way of directory creation, kill it
1699 unlink( $dir );
1701 $oldumask = umask(0);
1702 @mkdir( $dir, 0777 );
1703 umask( $oldumask );
1705 } else {
1706 $dir = $base;
1709 return $dir;
1713 * Old thumbnail directory, kept for conversion
1715 function wfDeprecatedThumbDir( $thumbName , $subdir='thumb', $shared=false) {
1716 return wfImageArchiveDir( $thumbName, $subdir, $shared );
1720 * Returns the image directory of an image's old version
1721 * If the directory does not exist, it is created.
1722 * The result is an absolute path.
1724 * This function is called from thumb.php before Setup.php is included
1726 * @param $fname String: file name of the thumbnail file, including file size prefix.
1727 * @param $subdir String: subdirectory of the image upload directory that should be used for storing the old version. Default is 'archive'.
1728 * @param $shared Boolean use the shared upload directory (only relevant for other functions which call this one). Default is 'false'.
1729 * @public
1731 function wfImageArchiveDir( $fname , $subdir='archive', $shared=false ) {
1732 global $wgUploadDirectory, $wgHashedUploadDirectory;
1733 global $wgSharedUploadDirectory, $wgHashedSharedUploadDirectory;
1734 $dir = $shared ? $wgSharedUploadDirectory : $wgUploadDirectory;
1735 $hashdir = $shared ? $wgHashedSharedUploadDirectory : $wgHashedUploadDirectory;
1736 if (!$hashdir) { return $dir.'/'.$subdir; }
1737 $hash = md5( $fname );
1738 $oldumask = umask(0);
1740 # Suppress warning messages here; if the file itself can't
1741 # be written we'll worry about it then.
1742 wfSuppressWarnings();
1744 $archive = $dir.'/'.$subdir;
1745 if ( ! is_dir( $archive ) ) { mkdir( $archive, 0777 ); }
1746 $archive .= '/' . $hash{0};
1747 if ( ! is_dir( $archive ) ) { mkdir( $archive, 0777 ); }
1748 $archive .= '/' . substr( $hash, 0, 2 );
1749 if ( ! is_dir( $archive ) ) { mkdir( $archive, 0777 ); }
1751 wfRestoreWarnings();
1752 umask( $oldumask );
1753 return $archive;
1758 * Return the hash path component of an image path (URL or filesystem),
1759 * e.g. "/3/3c/", or just "/" if hashing is not used.
1761 * @param $dbkey The filesystem / database name of the file
1762 * @param $fromSharedDirectory Use the shared file repository? It may
1763 * use different hash settings from the local one.
1765 function wfGetHashPath ( $dbkey, $fromSharedDirectory = false ) {
1766 if( Image::isHashed( $fromSharedDirectory ) ) {
1767 $hash = md5($dbkey);
1768 return '/' . $hash{0} . '/' . substr( $hash, 0, 2 ) . '/';
1769 } else {
1770 return '/';
1775 * Returns the image URL of an image's old version
1777 * @param $name String: file name of the image file
1778 * @param $subdir String: (optional) subdirectory of the image upload directory that is used by the old version. Default is 'archive'
1779 * @public
1781 function wfImageArchiveUrl( $name, $subdir='archive' ) {
1782 global $wgUploadPath, $wgHashedUploadDirectory;
1784 if ($wgHashedUploadDirectory) {
1785 $hash = md5( substr( $name, 15) );
1786 $url = $wgUploadPath.'/'.$subdir.'/' . $hash{0} . '/' .
1787 substr( $hash, 0, 2 ) . '/'.$name;
1788 } else {
1789 $url = $wgUploadPath.'/'.$subdir.'/'.$name;
1791 return wfUrlencode($url);
1795 * Return a rounded pixel equivalent for a labeled CSS/SVG length.
1796 * http://www.w3.org/TR/SVG11/coords.html#UnitIdentifiers
1798 * @param $length String: CSS/SVG length.
1799 * @return Integer: length in pixels
1801 function wfScaleSVGUnit( $length ) {
1802 static $unitLength = array(
1803 'px' => 1.0,
1804 'pt' => 1.25,
1805 'pc' => 15.0,
1806 'mm' => 3.543307,
1807 'cm' => 35.43307,
1808 'in' => 90.0,
1809 '' => 1.0, // "User units" pixels by default
1810 '%' => 2.0, // Fake it!
1812 if( preg_match( '/^(\d+(?:\.\d+)?)(em|ex|px|pt|pc|cm|mm|in|%|)$/', $length, $matches ) ) {
1813 $length = floatval( $matches[1] );
1814 $unit = $matches[2];
1815 return round( $length * $unitLength[$unit] );
1816 } else {
1817 // Assume pixels
1818 return round( floatval( $length ) );
1823 * Compatible with PHP getimagesize()
1824 * @todo support gzipped SVGZ
1825 * @todo check XML more carefully
1826 * @todo sensible defaults
1828 * @param $filename String: full name of the file (passed to php fopen()).
1829 * @return array
1831 function wfGetSVGsize( $filename ) {
1832 $width = 256;
1833 $height = 256;
1835 // Read a chunk of the file
1836 $f = fopen( $filename, "rt" );
1837 if( !$f ) return false;
1838 $chunk = fread( $f, 4096 );
1839 fclose( $f );
1841 // Uber-crappy hack! Run through a real XML parser.
1842 if( !preg_match( '/<svg\s*([^>]*)\s*>/s', $chunk, $matches ) ) {
1843 return false;
1845 $tag = $matches[1];
1846 if( preg_match( '/\bwidth\s*=\s*("[^"]+"|\'[^\']+\')/s', $tag, $matches ) ) {
1847 $width = wfScaleSVGUnit( trim( substr( $matches[1], 1, -1 ) ) );
1849 if( preg_match( '/\bheight\s*=\s*("[^"]+"|\'[^\']+\')/s', $tag, $matches ) ) {
1850 $height = wfScaleSVGUnit( trim( substr( $matches[1], 1, -1 ) ) );
1853 return array( $width, $height, 'SVG',
1854 "width=\"$width\" height=\"$height\"" );
1858 * Determine if an image exists on the 'bad image list'.
1860 * @param $name String: the image name to check
1861 * @return bool
1863 function wfIsBadImage( $name ) {
1864 global $wgContLang;
1865 static $titleList = false;
1866 if ( $titleList === false ) {
1867 $titleList = array();
1869 $lines = explode("\n", wfMsgForContent( 'bad_image_list' ));
1870 foreach ( $lines as $line ) {
1871 if ( preg_match( '/^\*\s*\[{2}:(' . $wgContLang->getNsText( NS_IMAGE ) . ':.*?)\]{2}/', $line, $m ) ) {
1872 $t = Title::newFromText( $m[1] );
1873 $titleList[$t->getDBkey()] = 1;
1878 return array_key_exists( $name, $titleList );
1884 * Wrapper class for thumbnail images
1885 * @package MediaWiki
1887 class ThumbnailImage {
1889 * @param string $path Filesystem path to the thumb
1890 * @param string $url URL path to the thumb
1891 * @private
1893 function ThumbnailImage( $url, $width, $height, $path = false ) {
1894 $this->url = $url;
1895 $this->width = round( $width );
1896 $this->height = round( $height );
1897 # These should be integers when they get here.
1898 # If not, there's a bug somewhere. But let's at
1899 # least produce valid HTML code regardless.
1900 $this->path = $path;
1904 * @return string The thumbnail URL
1906 function getUrl() {
1907 return $this->url;
1911 * Return HTML <img ... /> tag for the thumbnail, will include
1912 * width and height attributes and a blank alt text (as required).
1914 * You can set or override additional attributes by passing an
1915 * associative array of name => data pairs. The data will be escaped
1916 * for HTML output, so should be in plaintext.
1918 * @param array $attribs
1919 * @return string
1920 * @public
1922 function toHtml( $attribs = array() ) {
1923 $attribs['src'] = $this->url;
1924 $attribs['width'] = $this->width;
1925 $attribs['height'] = $this->height;
1926 if( !isset( $attribs['alt'] ) ) $attribs['alt'] = '';
1928 $html = '<img ';
1929 foreach( $attribs as $name => $data ) {
1930 $html .= $name . '="' . htmlspecialchars( $data ) . '" ';
1932 $html .= '/>';
1933 return $html;
1939 * Calculate the largest thumbnail width for a given original file size
1940 * such that the thumbnail's height is at most $maxHeight.
1941 * @param $boxWidth Integer Width of the thumbnail box.
1942 * @param $boxHeight Integer Height of the thumbnail box.
1943 * @param $maxHeight Integer Maximum height expected for the thumbnail.
1944 * @return Integer.
1946 function wfFitBoxWidth( $boxWidth, $boxHeight, $maxHeight ) {
1947 $idealWidth = $boxWidth * $maxHeight / $boxHeight;
1948 $roundedUp = ceil( $idealWidth );
1949 if( round( $roundedUp * $boxHeight / $boxWidth ) > $maxHeight )
1950 return floor( $idealWidth );
1951 else
1952 return $roundedUp;