hook point for injecting fields into edit form
[mediawiki.git] / includes / Image.php
blob0a3aec782e01cbad6487c1ebeb385bf18b6f100f
1 <?php
2 /**
3 */
5 /**
6 * NOTE FOR WINDOWS USERS:
7 * To enable EXIF functions, add the folloing lines to the
8 * "Windows extensions" section of php.ini:
10 * extension=extensions/php_mbstring.dll
11 * extension=extensions/php_exif.dll
14 /**
15 * Bump this number when serialized cache records may be incompatible.
17 define( 'MW_IMAGE_VERSION', 1 );
19 /**
20 * Class to represent an image
22 * Provides methods to retrieve paths (physical, logical, URL),
23 * to generate thumbnails or for uploading.
25 class Image
27 const DELETED_FILE = 1;
28 const DELETED_COMMENT = 2;
29 const DELETED_USER = 4;
30 const DELETED_RESTRICTED = 8;
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 $extension, # The file extension (constructor)
50 $size, # Size in bytes (loadFromXxx)
51 $metadata, # Metadata
52 $dataLoaded, # Whether or not all this has been loaded from the database (loadFromXxx)
53 $page, # Page to render when creating thumbnails
54 $lastError; # Error string associated with a thumbnail display error
57 /**#@-*/
59 /**
60 * Create an Image object from an image name
62 * @param string $name name of the image, used to create a title object using Title::makeTitleSafe
63 * @public
65 public static function newFromName( $name ) {
66 $title = Title::makeTitleSafe( NS_IMAGE, $name );
67 if ( is_object( $title ) ) {
68 return new Image( $title );
69 } else {
70 return NULL;
74 /**
75 * Obsolete factory function, use constructor
76 * @deprecated
78 function newFromTitle( $title ) {
79 return new Image( $title );
82 function Image( $title ) {
83 if( !is_object( $title ) ) {
84 throw new MWException( 'Image constructor given bogus title.' );
86 $this->title =& $title;
87 $this->name = $title->getDBkey();
88 $this->metadata = serialize ( array() ) ;
90 $n = strrpos( $this->name, '.' );
91 $this->extension = Image::normalizeExtension( $n ?
92 substr( $this->name, $n + 1 ) : '' );
93 $this->historyLine = 0;
94 $this->page = 1;
96 $this->dataLoaded = false;
99 /**
100 * Normalize a file extension to the common form, and ensure it's clean.
101 * Extensions with non-alphanumeric characters will be discarded.
103 * @param $ext string (without the .)
104 * @return string
106 static function normalizeExtension( $ext ) {
107 $lower = strtolower( $ext );
108 $squish = array(
109 'htm' => 'html',
110 'jpeg' => 'jpg',
111 'mpeg' => 'mpg',
112 'tiff' => 'tif' );
113 if( isset( $squish[$lower] ) ) {
114 return $squish[$lower];
115 } elseif( preg_match( '/^[0-9a-z]+$/', $lower ) ) {
116 return $lower;
117 } else {
118 return '';
123 * Get the memcached keys
124 * Returns an array, first element is the local cache key, second is the shared cache key, if there is one
126 function getCacheKeys( ) {
127 global $wgUseSharedUploads, $wgSharedUploadDBname, $wgCacheSharedUploads;
129 $hashedName = md5($this->name);
130 $keys = array( wfMemcKey( 'Image', $hashedName ) );
131 if ( $wgUseSharedUploads && $wgSharedUploadDBname && $wgCacheSharedUploads ) {
132 $keys[] = wfForeignMemcKey( $wgSharedUploadDBname, false, 'Image', $hashedName );
134 return $keys;
138 * Try to load image metadata from memcached. Returns true on success.
140 function loadFromCache() {
141 global $wgUseSharedUploads, $wgMemc;
142 wfProfileIn( __METHOD__ );
143 $this->dataLoaded = false;
144 $keys = $this->getCacheKeys();
145 $cachedValues = $wgMemc->get( $keys[0] );
147 // Check if the key existed and belongs to this version of MediaWiki
148 if (!empty($cachedValues) && is_array($cachedValues)
149 && isset($cachedValues['version']) && ( $cachedValues['version'] == MW_IMAGE_VERSION )
150 && isset( $cachedValues['mime'] ) && isset( $cachedValues['metadata'] ) )
152 if ( $wgUseSharedUploads && $cachedValues['fromShared']) {
153 # if this is shared file, we need to check if image
154 # in shared repository has not changed
155 if ( isset( $keys[1] ) ) {
156 $commonsCachedValues = $wgMemc->get( $keys[1] );
157 if (!empty($commonsCachedValues) && is_array($commonsCachedValues)
158 && isset($commonsCachedValues['version'])
159 && ( $commonsCachedValues['version'] == MW_IMAGE_VERSION )
160 && isset($commonsCachedValues['mime'])) {
161 wfDebug( "Pulling image metadata from shared repository cache\n" );
162 $this->name = $commonsCachedValues['name'];
163 $this->imagePath = $commonsCachedValues['imagePath'];
164 $this->fileExists = $commonsCachedValues['fileExists'];
165 $this->width = $commonsCachedValues['width'];
166 $this->height = $commonsCachedValues['height'];
167 $this->bits = $commonsCachedValues['bits'];
168 $this->type = $commonsCachedValues['type'];
169 $this->mime = $commonsCachedValues['mime'];
170 $this->metadata = $commonsCachedValues['metadata'];
171 $this->size = $commonsCachedValues['size'];
172 $this->fromSharedDirectory = true;
173 $this->dataLoaded = true;
174 $this->imagePath = $this->getFullPath(true);
177 } else {
178 wfDebug( "Pulling image metadata from local cache\n" );
179 $this->name = $cachedValues['name'];
180 $this->imagePath = $cachedValues['imagePath'];
181 $this->fileExists = $cachedValues['fileExists'];
182 $this->width = $cachedValues['width'];
183 $this->height = $cachedValues['height'];
184 $this->bits = $cachedValues['bits'];
185 $this->type = $cachedValues['type'];
186 $this->mime = $cachedValues['mime'];
187 $this->metadata = $cachedValues['metadata'];
188 $this->size = $cachedValues['size'];
189 $this->fromSharedDirectory = false;
190 $this->dataLoaded = true;
191 $this->imagePath = $this->getFullPath();
194 if ( $this->dataLoaded ) {
195 wfIncrStats( 'image_cache_hit' );
196 } else {
197 wfIncrStats( 'image_cache_miss' );
200 wfProfileOut( __METHOD__ );
201 return $this->dataLoaded;
205 * Save the image metadata to memcached
207 function saveToCache() {
208 global $wgMemc, $wgUseSharedUploads;
209 $this->load();
210 $keys = $this->getCacheKeys();
211 // We can't cache negative metadata for non-existent files,
212 // because if the file later appears in commons, the local
213 // keys won't be purged.
214 if ( $this->fileExists || !$wgUseSharedUploads ) {
215 $cachedValues = array(
216 'version' => MW_IMAGE_VERSION,
217 'name' => $this->name,
218 'imagePath' => $this->imagePath,
219 'fileExists' => $this->fileExists,
220 'fromShared' => $this->fromSharedDirectory,
221 'width' => $this->width,
222 'height' => $this->height,
223 'bits' => $this->bits,
224 'type' => $this->type,
225 'mime' => $this->mime,
226 'metadata' => $this->metadata,
227 'size' => $this->size );
229 $wgMemc->set( $keys[0], $cachedValues, 60 * 60 * 24 * 7 ); // A week
230 } else {
231 // However we should clear them, so they aren't leftover
232 // if we've deleted the file.
233 $wgMemc->delete( $keys[0] );
238 * Load metadata from the file itself
240 function loadFromFile() {
241 global $wgUseSharedUploads, $wgSharedUploadDirectory, $wgContLang;
242 wfProfileIn( __METHOD__ );
243 $this->imagePath = $this->getFullPath();
244 $this->fileExists = file_exists( $this->imagePath );
245 $this->fromSharedDirectory = false;
246 $gis = array();
247 $deja = false;
249 if (!$this->fileExists) wfDebug(__METHOD__.': '.$this->imagePath." not found locally!\n");
251 # If the file is not found, and a shared upload directory is used, look for it there.
252 if (!$this->fileExists && $wgUseSharedUploads && $wgSharedUploadDirectory) {
253 # In case we're on a wgCapitalLinks=false wiki, we
254 # capitalize the first letter of the filename before
255 # looking it up in the shared repository.
256 $sharedImage = Image::newFromName( $wgContLang->ucfirst($this->name) );
257 $this->fileExists = $sharedImage && file_exists( $sharedImage->getFullPath(true) );
258 if ( $this->fileExists ) {
259 $this->name = $sharedImage->name;
260 $this->imagePath = $this->getFullPath(true);
261 $this->fromSharedDirectory = true;
266 if ( $this->fileExists ) {
267 $magic=& MimeMagic::singleton();
269 $this->mime = $magic->guessMimeType($this->imagePath,true);
270 $this->type = $magic->getMediaType($this->imagePath,$this->mime);
272 # Get size in bytes
273 $this->size = filesize( $this->imagePath );
275 # Height and width
276 $gis = self::getImageSize( $this->imagePath, $this->mime, $deja );
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 if ( $deja ) {
303 $this->metadata = $deja->retrieveMetaData();
304 } else {
305 $this->metadata = serialize( $this->retrieveExifData( $this->imagePath ) );
308 if ( isset( $gis['bits'] ) ) $this->bits = $gis['bits'];
309 else $this->bits = 0;
311 wfProfileOut( __METHOD__ );
315 * Load image metadata from the DB
317 function loadFromDB() {
318 global $wgUseSharedUploads, $wgSharedUploadDBname, $wgSharedUploadDBprefix, $wgContLang;
319 wfProfileIn( __METHOD__ );
321 $dbr = wfGetDB( DB_SLAVE );
322 $this->checkDBSchema($dbr);
324 $row = $dbr->selectRow( 'image',
325 array( 'img_size', 'img_width', 'img_height', 'img_bits',
326 'img_media_type', 'img_major_mime', 'img_minor_mime', 'img_metadata' ),
327 array( 'img_name' => $this->name ), __METHOD__ );
328 if ( $row ) {
329 $this->fromSharedDirectory = false;
330 $this->fileExists = true;
331 $this->loadFromRow( $row );
332 $this->imagePath = $this->getFullPath();
333 // Check for rows from a previous schema, quietly upgrade them
334 if ( is_null($this->type) ) {
335 $this->upgradeRow();
337 } elseif ( $wgUseSharedUploads && $wgSharedUploadDBname ) {
338 # In case we're on a wgCapitalLinks=false wiki, we
339 # capitalize the first letter of the filename before
340 # looking it up in the shared repository.
341 $name = $wgContLang->ucfirst($this->name);
342 $dbc = Image::getCommonsDB();
344 $row = $dbc->selectRow( "`$wgSharedUploadDBname`.{$wgSharedUploadDBprefix}image",
345 array(
346 'img_size', 'img_width', 'img_height', 'img_bits',
347 'img_media_type', 'img_major_mime', 'img_minor_mime', 'img_metadata' ),
348 array( 'img_name' => $name ), __METHOD__ );
349 if ( $row ) {
350 $this->fromSharedDirectory = true;
351 $this->fileExists = true;
352 $this->imagePath = $this->getFullPath(true);
353 $this->name = $name;
354 $this->loadFromRow( $row );
356 // Check for rows from a previous schema, quietly upgrade them
357 if ( is_null($this->type) ) {
358 $this->upgradeRow();
363 if ( !$row ) {
364 $this->size = 0;
365 $this->width = 0;
366 $this->height = 0;
367 $this->bits = 0;
368 $this->type = 0;
369 $this->fileExists = false;
370 $this->fromSharedDirectory = false;
371 $this->metadata = serialize ( array() ) ;
372 $this->mime = false;
375 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
376 $this->dataLoaded = true;
377 wfProfileOut( __METHOD__ );
381 * Load image metadata from a DB result row
383 function loadFromRow( &$row ) {
384 $this->size = $row->img_size;
385 $this->width = $row->img_width;
386 $this->height = $row->img_height;
387 $this->bits = $row->img_bits;
388 $this->type = $row->img_media_type;
390 $major= $row->img_major_mime;
391 $minor= $row->img_minor_mime;
393 if (!$major) $this->mime = "unknown/unknown";
394 else {
395 if (!$minor) $minor= "unknown";
396 $this->mime = $major.'/'.$minor;
399 $this->metadata = $row->img_metadata;
400 if ( $this->metadata == "" ) $this->metadata = serialize ( array() ) ;
402 $this->dataLoaded = true;
406 * Load image metadata from cache or DB, unless already loaded
408 function load() {
409 global $wgSharedUploadDBname, $wgUseSharedUploads;
410 if ( !$this->dataLoaded ) {
411 if ( !$this->loadFromCache() ) {
412 $this->loadFromDB();
413 if ( !$wgSharedUploadDBname && $wgUseSharedUploads ) {
414 $this->loadFromFile();
415 } elseif ( $this->fileExists || !$wgUseSharedUploads ) {
416 // We can do negative caching for local images, because the cache
417 // will be purged on upload. But we can't do it when shared images
418 // are enabled, since updates to that won't purge foreign caches.
419 $this->saveToCache();
422 $this->dataLoaded = true;
427 * Metadata was loaded from the database, but the row had a marker indicating it needs to be
428 * upgraded from the 1.4 schema, which had no width, height, bits or type. Upgrade the row.
430 function upgradeRow() {
431 global $wgDBname, $wgSharedUploadDBname;
432 wfProfileIn( __METHOD__ );
434 $this->loadFromFile();
436 if ( $this->fromSharedDirectory ) {
437 if ( !$wgSharedUploadDBname ) {
438 wfProfileOut( __METHOD__ );
439 return;
442 // Write to the other DB using selectDB, not database selectors
443 // This avoids breaking replication in MySQL
444 $dbw = Image::getCommonsDB();
445 } else {
446 $dbw = wfGetDB( DB_MASTER );
449 $this->checkDBSchema($dbw);
451 list( $major, $minor ) = self::splitMime( $this->mime );
453 wfDebug(__METHOD__.': upgrading '.$this->name." to 1.5 schema\n");
455 $dbw->update( 'image',
456 array(
457 'img_width' => $this->width,
458 'img_height' => $this->height,
459 'img_bits' => $this->bits,
460 'img_media_type' => $this->type,
461 'img_major_mime' => $major,
462 'img_minor_mime' => $minor,
463 'img_metadata' => $this->metadata,
464 ), array( 'img_name' => $this->name ), __METHOD__
466 if ( $this->fromSharedDirectory ) {
467 $dbw->selectDB( $wgDBname );
469 wfProfileOut( __METHOD__ );
473 * Split an internet media type into its two components; if not
474 * a two-part name, set the minor type to 'unknown'.
476 * @param $mime "text/html" etc
477 * @return array ("text", "html") etc
479 static function splitMime( $mime ) {
480 if( strpos( $mime, '/' ) !== false ) {
481 return explode( '/', $mime, 2 );
482 } else {
483 return array( $mime, 'unknown' );
488 * Return the name of this image
489 * @public
491 function getName() {
492 return $this->name;
496 * Return the associated title object
497 * @public
499 function getTitle() {
500 return $this->title;
504 * Return the URL of the image file
505 * @public
507 function getURL() {
508 if ( !$this->url ) {
509 $this->load();
510 if($this->fileExists) {
511 $this->url = Image::imageUrl( $this->name, $this->fromSharedDirectory );
512 } else {
513 $this->url = '';
516 return $this->url;
519 function getViewURL() {
520 if( $this->mustRender()) {
521 if( $this->canRender() ) {
522 return $this->createThumb( $this->getWidth() );
524 else {
525 wfDebug('Image::getViewURL(): supposed to render '.$this->name.' ('.$this->mime."), but can't!\n");
526 return $this->getURL(); #hm... return NULL?
528 } else {
529 return $this->getURL();
534 * Return the image path of the image in the
535 * local file system as an absolute path
536 * @public
538 function getImagePath() {
539 $this->load();
540 return $this->imagePath;
544 * Return the width of the image
546 * Returns -1 if the file specified is not a known image type
547 * @public
549 function getWidth() {
550 $this->load();
551 return $this->width;
555 * Return the height of the image
557 * Returns -1 if the file specified is not a known image type
558 * @public
560 function getHeight() {
561 $this->load();
562 return $this->height;
566 * Return the size of the image file, in bytes
567 * @public
569 function getSize() {
570 $this->load();
571 return $this->size;
575 * Returns the mime type of the file.
577 function getMimeType() {
578 $this->load();
579 return $this->mime;
583 * Return the type of the media in the file.
584 * Use the value returned by this function with the MEDIATYPE_xxx constants.
586 function getMediaType() {
587 $this->load();
588 return $this->type;
592 * Checks if the file can be presented to the browser as a bitmap.
594 * Currently, this checks if the file is an image format
595 * that can be converted to a format
596 * supported by all browsers (namely GIF, PNG and JPEG),
597 * or if it is an SVG image and SVG conversion is enabled.
599 * @todo remember the result of this check.
601 function canRender() {
602 global $wgUseImageMagick, $wgDjvuRenderer;
604 if( $this->getWidth()<=0 || $this->getHeight()<=0 ) return false;
606 $mime= $this->getMimeType();
608 if (!$mime || $mime==='unknown' || $mime==='unknown/unknown') return false;
610 #if it's SVG, check if there's a converter enabled
611 if ($mime === 'image/svg' || $mime == 'image/svg+xml' ) {
612 global $wgSVGConverters, $wgSVGConverter;
614 if ($wgSVGConverter && isset( $wgSVGConverters[$wgSVGConverter])) {
615 wfDebug( "Image::canRender: SVG is ready!\n" );
616 return true;
617 } else {
618 wfDebug( "Image::canRender: SVG renderer missing\n" );
622 #image formats available on ALL browsers
623 if ( $mime === 'image/gif'
624 || $mime === 'image/png'
625 || $mime === 'image/jpeg' ) return true;
627 #image formats that can be converted to the above formats
628 if ($wgUseImageMagick) {
629 #convertable by ImageMagick (there are more...)
630 if ( $mime === 'image/vnd.wap.wbmp'
631 || $mime === 'image/x-xbitmap'
632 || $mime === 'image/x-xpixmap'
633 #|| $mime === 'image/x-icon' #file may be split into multiple parts
634 || $mime === 'image/x-portable-anymap'
635 || $mime === 'image/x-portable-bitmap'
636 || $mime === 'image/x-portable-graymap'
637 || $mime === 'image/x-portable-pixmap'
638 #|| $mime === 'image/x-photoshop' #this takes a lot of CPU and RAM!
639 || $mime === 'image/x-rgb'
640 || $mime === 'image/x-bmp'
641 || $mime === 'image/tiff' ) return true;
643 else {
644 #convertable by the PHP GD image lib
645 if ( $mime === 'image/vnd.wap.wbmp'
646 || $mime === 'image/x-xbitmap' ) return true;
648 if ( $mime === 'image/vnd.djvu' && isset( $wgDjvuRenderer ) && $wgDjvuRenderer ) return true;
650 return false;
655 * Return true if the file is of a type that can't be directly
656 * rendered by typical browsers and needs to be re-rasterized.
658 * This returns true for everything but the bitmap types
659 * supported by all browsers, i.e. JPEG; GIF and PNG. It will
660 * also return true for any non-image formats.
662 * @return bool
664 function mustRender() {
665 $mime= $this->getMimeType();
667 if ( $mime === "image/gif"
668 || $mime === "image/png"
669 || $mime === "image/jpeg" ) return false;
671 return true;
675 * Determines if this media file may be shown inline on a page.
677 * This is currently synonymous to canRender(), but this could be
678 * extended to also allow inline display of other media,
679 * like flash animations or videos. If you do so, please keep in mind that
680 * that could be a security risk.
682 function allowInlineDisplay() {
683 return $this->canRender();
687 * Determines if this media file is in a format that is unlikely to
688 * contain viruses or malicious content. It uses the global
689 * $wgTrustedMediaFormats list to determine if the file is safe.
691 * This is used to show a warning on the description page of non-safe files.
692 * It may also be used to disallow direct [[media:...]] links to such files.
694 * Note that this function will always return true if allowInlineDisplay()
695 * or isTrustedFile() is true for this file.
697 function isSafeFile() {
698 if ($this->allowInlineDisplay()) return true;
699 if ($this->isTrustedFile()) return true;
701 global $wgTrustedMediaFormats;
703 $type= $this->getMediaType();
704 $mime= $this->getMimeType();
705 #wfDebug("Image::isSafeFile: type= $type, mime= $mime\n");
707 if (!$type || $type===MEDIATYPE_UNKNOWN) return false; #unknown type, not trusted
708 if ( in_array( $type, $wgTrustedMediaFormats) ) return true;
710 if ($mime==="unknown/unknown") return false; #unknown type, not trusted
711 if ( in_array( $mime, $wgTrustedMediaFormats) ) return true;
713 return false;
716 /** Returns true if the file is flagged as trusted. Files flagged that way
717 * can be linked to directly, even if that is not allowed for this type of
718 * file normally.
720 * This is a dummy function right now and always returns false. It could be
721 * implemented to extract a flag from the database. The trusted flag could be
722 * set on upload, if the user has sufficient privileges, to bypass script-
723 * and html-filters. It may even be coupled with cryptographics signatures
724 * or such.
726 function isTrustedFile() {
727 #this could be implemented to check a flag in the databas,
728 #look for signatures, etc
729 return false;
733 * Return the escapeLocalURL of this image
734 * @public
736 function getEscapeLocalURL( $query=false) {
737 $this->getTitle();
738 if ( $query === false ) {
739 if ( $this->page != 1 ) {
740 $query = 'page=' . $this->page;
741 } else {
742 $query = '';
745 return $this->title->escapeLocalURL( $query );
749 * Return the escapeFullURL of this image
750 * @public
752 function getEscapeFullURL() {
753 $this->getTitle();
754 return $this->title->escapeFullURL();
758 * Return the URL of an image, provided its name.
760 * @param string $name Name of the image, without the leading "Image:"
761 * @param boolean $fromSharedDirectory Should this be in $wgSharedUploadPath?
762 * @return string URL of $name image
763 * @public
764 * @static
766 function imageUrl( $name, $fromSharedDirectory = false ) {
767 global $wgUploadPath,$wgUploadBaseUrl,$wgSharedUploadPath;
768 if($fromSharedDirectory) {
769 $base = '';
770 $path = $wgSharedUploadPath;
771 } else {
772 $base = $wgUploadBaseUrl;
773 $path = $wgUploadPath;
775 $url = "{$base}{$path}" . wfGetHashPath($name, $fromSharedDirectory) . "{$name}";
776 return wfUrlencode( $url );
780 * Returns true if the image file exists on disk.
781 * @return boolean Whether image file exist on disk.
782 * @public
784 function exists() {
785 $this->load();
786 return $this->fileExists;
790 * @todo document
791 * @private
793 function thumbUrl( $width, $subdir='thumb') {
794 global $wgUploadPath, $wgUploadBaseUrl, $wgSharedUploadPath;
795 global $wgSharedThumbnailScriptPath, $wgThumbnailScriptPath;
797 // Generate thumb.php URL if possible
798 $script = false;
799 $url = false;
801 if ( $this->fromSharedDirectory ) {
802 if ( $wgSharedThumbnailScriptPath ) {
803 $script = $wgSharedThumbnailScriptPath;
805 } else {
806 if ( $wgThumbnailScriptPath ) {
807 $script = $wgThumbnailScriptPath;
810 if ( $script ) {
811 $url = $script . '?f=' . urlencode( $this->name ) . '&w=' . urlencode( $width );
812 if( $this->mustRender() ) {
813 $url.= '&r=1';
815 } else {
816 $name = $this->thumbName( $width );
817 if($this->fromSharedDirectory) {
818 $base = '';
819 $path = $wgSharedUploadPath;
820 } else {
821 $base = $wgUploadBaseUrl;
822 $path = $wgUploadPath;
824 if ( Image::isHashed( $this->fromSharedDirectory ) ) {
825 $url = "{$base}{$path}/{$subdir}" .
826 wfGetHashPath($this->name, $this->fromSharedDirectory)
827 . $this->name.'/'.$name;
828 $url = wfUrlencode( $url );
829 } else {
830 $url = "{$base}{$path}/{$subdir}/{$name}";
833 return array( $script !== false, $url );
837 * Return the file name of a thumbnail of the specified width
839 * @param integer $width Width of the thumbnail image
840 * @param boolean $shared Does the thumbnail come from the shared repository?
841 * @private
843 function thumbName( $width ) {
844 global $wgDjvuOutputExtension;
845 $thumb = $width."px-".$this->name;
846 if ( $this->page != 1 ) {
847 $thumb = "page{$this->page}-$thumb";
850 if( $this->mustRender() ) {
851 if( $this->canRender() ) {
852 list( $ext, $mime ) = self::getThumbType( $this->extension, $this->mime );
853 if ( $ext != $this->extension ) {
854 $thumb .= ".$ext";
857 else {
858 #should we use iconThumb here to get a symbolic thumbnail?
859 #or should we fail with an internal error?
860 return NULL; //can't make bitmap
863 return $thumb;
867 * Create a thumbnail of the image having the specified width/height.
868 * The thumbnail will not be created if the width is larger than the
869 * image's width. Let the browser do the scaling in this case.
870 * The thumbnail is stored on disk and is only computed if the thumbnail
871 * file does not exist OR if it is older than the image.
872 * Returns the URL.
874 * Keeps aspect ratio of original image. If both width and height are
875 * specified, the generated image will be no bigger than width x height,
876 * and will also have correct aspect ratio.
878 * @param integer $width maximum width of the generated thumbnail
879 * @param integer $height maximum height of the image (optional)
880 * @public
882 function createThumb( $width, $height=-1 ) {
883 $thumb = $this->getThumbnail( $width, $height );
884 if( is_null( $thumb ) ) return '';
885 return $thumb->getUrl();
889 * As createThumb, but returns a ThumbnailImage object. This can
890 * provide access to the actual file, the real size of the thumb,
891 * and can produce a convenient <img> tag for you.
893 * For non-image formats, this may return a filetype-specific icon.
895 * @param integer $width maximum width of the generated thumbnail
896 * @param integer $height maximum height of the image (optional)
897 * @param boolean $render True to render the thumbnail if it doesn't exist,
898 * false to just return the URL
900 * @return ThumbnailImage or null on failure
901 * @public
903 function getThumbnail( $width, $height=-1, $render = true ) {
904 wfProfileIn( __METHOD__ );
905 if ($this->canRender()) {
906 if ( $height > 0 ) {
907 $this->load();
908 if ( $width > $this->width * $height / $this->height ) {
909 $width = wfFitBoxWidth( $this->width, $this->height, $height );
912 if ( $render ) {
913 $thumb = $this->renderThumb( $width );
914 } else {
915 // Don't render, just return the URL
916 if ( $this->validateThumbParams( $width, $height ) ) {
917 if ( !$this->mustRender() && $width == $this->width && $height == $this->height ) {
918 $url = $this->getURL();
919 } else {
920 list( /* $isScriptUrl */, $url ) = $this->thumbUrl( $width );
922 $thumb = new ThumbnailImage( $url, $width, $height );
923 } else {
924 $thumb = null;
927 } else {
928 // not a bitmap or renderable image, don't try.
929 $thumb = $this->iconThumb();
931 wfProfileOut( __METHOD__ );
932 return $thumb;
936 * @return ThumbnailImage
938 function iconThumb() {
939 global $wgStylePath, $wgStyleDirectory;
941 $try = array( 'fileicon-' . $this->extension . '.png', 'fileicon.png' );
942 foreach( $try as $icon ) {
943 $path = '/common/images/icons/' . $icon;
944 $filepath = $wgStyleDirectory . $path;
945 if( file_exists( $filepath ) ) {
946 return new ThumbnailImage( $wgStylePath . $path, 120, 120 );
949 return null;
953 * Validate thumbnail parameters and fill in the correct height
955 * @param integer &$width Specified width (input/output)
956 * @param integer &$height Height (output only)
957 * @return false to indicate that an error should be returned to the user.
959 function validateThumbParams( &$width, &$height ) {
960 global $wgSVGMaxSize, $wgMaxImageArea;
962 $this->load();
964 if ( ! $this->exists() )
966 # If there is no image, there will be no thumbnail
967 return false;
970 $width = intval( $width );
972 # Sanity check $width
973 if( $width <= 0 || $this->width <= 0) {
974 # BZZZT
975 return false;
978 # Don't thumbnail an image so big that it will fill hard drives and send servers into swap
979 # JPEG has the handy property of allowing thumbnailing without full decompression, so we make
980 # an exception for it.
981 if ( $this->getMediaType() == MEDIATYPE_BITMAP &&
982 $this->getMimeType() !== 'image/jpeg' &&
983 $this->width * $this->height > $wgMaxImageArea )
985 return false;
988 # Don't make an image bigger than the source, or wgMaxSVGSize for SVGs
989 if ( $this->mustRender() ) {
990 $width = min( $width, $wgSVGMaxSize );
991 } elseif ( $width > $this->width - 1 ) {
992 $width = $this->width;
993 $height = $this->height;
994 return true;
997 $height = self::scaleHeight( $this->width, $this->height, $width );
998 return true;
1002 * Create a thumbnail of the image having the specified width.
1003 * The thumbnail will not be created if the width is larger than the
1004 * image's width. Let the browser do the scaling in this case.
1005 * The thumbnail is stored on disk and is only computed if the thumbnail
1006 * file does not exist OR if it is older than the image.
1007 * Returns an object which can return the pathname, URL, and physical
1008 * pixel size of the thumbnail -- or null on failure.
1010 * @return ThumbnailImage or null on failure
1011 * @private
1013 function renderThumb( $width, $useScript = true ) {
1014 global $wgUseSquid, $wgThumbnailEpoch;
1016 wfProfileIn( __METHOD__ );
1018 $this->load();
1019 $height = -1;
1020 if ( !$this->validateThumbParams( $width, $height ) ) {
1021 # Validation error
1022 wfProfileOut( __METHOD__ );
1023 return null;
1026 if ( !$this->mustRender() && $width == $this->width && $height == $this->height ) {
1027 # validateThumbParams (or the user) wants us to return the unscaled image
1028 $thumb = new ThumbnailImage( $this->getURL(), $width, $height );
1029 wfProfileOut( __METHOD__ );
1030 return $thumb;
1033 list( $isScriptUrl, $url ) = $this->thumbUrl( $width );
1034 if ( $isScriptUrl && $useScript ) {
1035 // Use thumb.php to render the image
1036 $thumb = new ThumbnailImage( $url, $width, $height );
1037 wfProfileOut( __METHOD__ );
1038 return $thumb;
1041 $thumbName = $this->thumbName( $width, $this->fromSharedDirectory );
1042 $thumbDir = wfImageThumbDir( $this->name, $this->fromSharedDirectory );
1043 $thumbPath = $thumbDir.'/'.$thumbName;
1045 if ( is_dir( $thumbPath ) ) {
1046 // Directory where file should be
1047 // This happened occasionally due to broken migration code in 1.5
1048 // Rename to broken-*
1049 global $wgUploadDirectory;
1050 for ( $i = 0; $i < 100 ; $i++ ) {
1051 $broken = "$wgUploadDirectory/broken-$i-$thumbName";
1052 if ( !file_exists( $broken ) ) {
1053 rename( $thumbPath, $broken );
1054 break;
1057 // Code below will ask if it exists, and the answer is now no
1058 clearstatcache();
1061 $done = true;
1062 if ( !file_exists( $thumbPath ) ||
1063 filemtime( $thumbPath ) < wfTimestamp( TS_UNIX, $wgThumbnailEpoch ) )
1065 // Create the directory if it doesn't exist
1066 if ( is_file( $thumbDir ) ) {
1067 // File where thumb directory should be, destroy if possible
1068 @unlink( $thumbDir );
1070 wfMkdirParents( $thumbDir );
1072 $oldThumbPath = wfDeprecatedThumbDir( $thumbName, 'thumb', $this->fromSharedDirectory ).
1073 '/'.$thumbName;
1074 $done = false;
1076 // Migration from old directory structure
1077 if ( is_file( $oldThumbPath ) ) {
1078 if ( filemtime($oldThumbPath) >= filemtime($this->imagePath) ) {
1079 if ( file_exists( $thumbPath ) ) {
1080 if ( !is_dir( $thumbPath ) ) {
1081 // Old image in the way of rename
1082 unlink( $thumbPath );
1083 } else {
1084 // This should have been dealt with already
1085 throw new MWException( "Directory where image should be: $thumbPath" );
1088 // Rename the old image into the new location
1089 rename( $oldThumbPath, $thumbPath );
1090 $done = true;
1091 } else {
1092 unlink( $oldThumbPath );
1095 if ( !$done ) {
1096 $this->lastError = self::reallyRenderThumb( $this->imagePath, $thumbPath, $this->mime,
1097 $width, $height, $this->page );
1098 if ( $this->lastError === true ) {
1099 $done = true;
1100 } elseif( $GLOBALS['wgIgnoreImageErrors'] ) {
1101 // Log the error but output anyway.
1102 // With luck it's a transitory error...
1103 $done = true;
1106 # Purge squid
1107 # This has to be done after the image is updated and present for all machines on NFS,
1108 # or else the old version might be stored into the squid again
1109 if ( $wgUseSquid ) {
1110 $urlArr = array( $url );
1111 wfPurgeSquidServers($urlArr);
1116 if ( $done ) {
1117 $thumb = new ThumbnailImage( $url, $width, $height, $thumbPath );
1118 } else {
1119 $thumb = null;
1121 wfProfileOut( __METHOD__ );
1122 return $thumb;
1123 } // END OF function renderThumb
1126 * Really render a thumbnail
1127 * Call this only for images for which canRender() returns true.
1129 * @param string $source Source filename
1130 * @param string $destination Destination filename
1131 * @param string $mime MIME type of source
1132 * @param integer $width Destination width in pixels
1133 * @param integer $height Destination height in pixels
1134 * @param integer $page Which page of a multi-page document to display. Ignored
1135 * for source MIME types which do not support multiple pages.
1137 static function reallyRenderThumb( $source, $destination, $mime, $width, $height, $page = false ) {
1138 global $wgSVGConverters, $wgSVGConverter;
1139 global $wgUseImageMagick, $wgImageMagickConvertCommand;
1140 global $wgCustomConvertCommand;
1141 global $wgDjvuRenderer, $wgDjvuPostProcessor;
1143 $err = false;
1144 $cmd = "";
1145 $retval = 0;
1147 if( $mime == "image/svg" || $mime == 'image/svg+xml' ) {
1148 #Right now we have only SVG
1150 global $wgSVGConverters, $wgSVGConverter;
1151 if( isset( $wgSVGConverters[$wgSVGConverter] ) ) {
1152 global $wgSVGConverterPath;
1153 $cmd = str_replace(
1154 array( '$path/', '$width', '$height', '$input', '$output' ),
1155 array( $wgSVGConverterPath ? wfEscapeShellArg( "$wgSVGConverterPath/" ) : "",
1156 intval( $width ),
1157 intval( $height ),
1158 wfEscapeShellArg( $source ),
1159 wfEscapeShellArg( $destination ) ),
1160 $wgSVGConverters[$wgSVGConverter] ) . " 2>&1";
1161 wfProfileIn( 'rsvg' );
1162 wfDebug( "reallyRenderThumb SVG: $cmd\n" );
1163 $err = wfShellExec( $cmd, $retval );
1164 wfProfileOut( 'rsvg' );
1166 } elseif ( $mime === "image/vnd.djvu" && $wgDjvuRenderer ) {
1167 // DJVU image
1168 // The file contains several images. First, extract the
1169 // page in hi-res, if it doesn't yet exist. Then, thumbnail
1170 // it.
1172 $cmd = wfEscapeShellArg( $wgDjvuRenderer ) . " -format=ppm -page={$page} -size=${width}x${height} " .
1173 wfEscapeShellArg( $source );
1174 if ( $wgDjvuPostProcessor ) {
1175 $cmd .= " | {$wgDjvuPostProcessor}";
1177 $cmd .= ' > ' . wfEscapeShellArg($destination);
1178 wfProfileIn( 'ddjvu' );
1179 wfDebug( "reallyRenderThumb DJVU: $cmd\n" );
1180 $err = wfShellExec( $cmd, $retval );
1181 wfProfileOut( 'ddjvu' );
1183 } elseif ( $wgUseImageMagick ) {
1184 # use ImageMagick
1186 if ( $mime == 'image/jpeg' ) {
1187 $quality = "-quality 80"; // 80%
1188 } elseif ( $mime == 'image/png' ) {
1189 $quality = "-quality 95"; // zlib 9, adaptive filtering
1190 } else {
1191 $quality = ''; // default
1194 # Specify white background color, will be used for transparent images
1195 # in Internet Explorer/Windows instead of default black.
1197 # Note, we specify "-size {$width}" and NOT "-size {$width}x{$height}".
1198 # It seems that ImageMagick has a bug wherein it produces thumbnails of
1199 # the wrong size in the second case.
1201 $cmd = wfEscapeShellArg($wgImageMagickConvertCommand) .
1202 " {$quality} -background white -size {$width} ".
1203 wfEscapeShellArg($source) .
1204 // Coalesce is needed to scale animated GIFs properly (bug 1017).
1205 ' -coalesce ' .
1206 // For the -resize option a "!" is needed to force exact size,
1207 // or ImageMagick may decide your ratio is wrong and slice off
1208 // a pixel.
1209 " -thumbnail " . wfEscapeShellArg( "{$width}x{$height}!" ) .
1210 " -depth 8 " .
1211 wfEscapeShellArg($destination) . " 2>&1";
1212 wfDebug("reallyRenderThumb: running ImageMagick: $cmd\n");
1213 wfProfileIn( 'convert' );
1214 $err = wfShellExec( $cmd, $retval );
1215 wfProfileOut( 'convert' );
1216 } elseif( $wgCustomConvertCommand ) {
1217 # Use a custom convert command
1218 # Variables: %s %d %w %h
1219 $src = wfEscapeShellArg( $source );
1220 $dst = wfEscapeShellArg( $destination );
1221 $cmd = $wgCustomConvertCommand;
1222 $cmd = str_replace( '%s', $src, str_replace( '%d', $dst, $cmd ) ); # Filenames
1223 $cmd = str_replace( '%h', $height, str_replace( '%w', $width, $cmd ) ); # Size
1224 wfDebug( "reallyRenderThumb: Running custom convert command $cmd\n" );
1225 wfProfileIn( 'convert' );
1226 $err = wfShellExec( $cmd, $retval );
1227 wfProfileOut( 'convert' );
1228 } else {
1229 # Use PHP's builtin GD library functions.
1231 # First find out what kind of file this is, and select the correct
1232 # input routine for this.
1234 $typemap = array(
1235 'image/gif' => array( 'imagecreatefromgif', 'palette', 'imagegif' ),
1236 'image/jpeg' => array( 'imagecreatefromjpeg', 'truecolor', array( __CLASS__, 'imageJpegWrapper' ) ),
1237 'image/png' => array( 'imagecreatefrompng', 'bits', 'imagepng' ),
1238 'image/vnd.wap.wmbp' => array( 'imagecreatefromwbmp', 'palette', 'imagewbmp' ),
1239 'image/xbm' => array( 'imagecreatefromxbm', 'palette', 'imagexbm' ),
1241 if( !isset( $typemap[$mime] ) ) {
1242 $err = 'Image type not supported';
1243 wfDebug( "$err\n" );
1244 return $err;
1246 list( $loader, $colorStyle, $saveType ) = $typemap[$mime];
1248 if( !function_exists( $loader ) ) {
1249 $err = "Incomplete GD library configuration: missing function $loader";
1250 wfDebug( "$err\n" );
1251 return $err;
1254 $src_image = call_user_func( $loader, $source );
1255 $dst_image = imagecreatetruecolor( $width, $height );
1256 imagecopyresampled( $dst_image, $src_image,
1257 0,0,0,0,
1258 $width, $height, imagesx( $src_image ), imagesy( $src_image ) );
1259 call_user_func( $saveType, $dst_image, $destination );
1260 imagedestroy( $dst_image );
1261 imagedestroy( $src_image );
1265 # Check for zero-sized thumbnails. Those can be generated when
1266 # no disk space is available or some other error occurs
1268 $removed = false;
1269 if( file_exists( $destination ) ) {
1270 $thumbstat = stat( $destination );
1271 if( $thumbstat['size'] == 0 || $retval != 0 ) {
1272 wfDebugLog( 'thumbnail',
1273 sprintf( 'Removing bad %d-byte thumbnail "%s"',
1274 $thumbstat['size'], $destination ) );
1275 unlink( $destination );
1276 $removed = true;
1279 if ( $retval != 0 || $removed ) {
1280 wfDebugLog( 'thumbnail',
1281 sprintf( 'thumbnail failed on %s: error %d "%s" from "%s"',
1282 wfHostname(), $retval, trim($err), $cmd ) );
1283 return wfMsg( 'thumbnail_error', $err );
1284 } else {
1285 return true;
1289 function getLastError() {
1290 return $this->lastError;
1293 static function imageJpegWrapper( $dst_image, $thumbPath ) {
1294 imageinterlace( $dst_image );
1295 imagejpeg( $dst_image, $thumbPath, 95 );
1299 * Get all thumbnail names previously generated for this image
1301 function getThumbnails( $shared = false ) {
1302 if ( Image::isHashed( $shared ) ) {
1303 $this->load();
1304 $files = array();
1305 $dir = wfImageThumbDir( $this->name, $shared );
1307 if ( is_dir( $dir ) ) {
1308 $handle = opendir( $dir );
1310 if ( $handle ) {
1311 while ( false !== ( $file = readdir($handle) ) ) {
1312 if ( $file{0} != '.' ) {
1313 $files[] = $file;
1316 closedir( $handle );
1319 } else {
1320 $files = array();
1323 return $files;
1327 * Refresh metadata in memcached, but don't touch thumbnails or squid
1329 function purgeMetadataCache() {
1330 clearstatcache();
1331 $this->loadFromFile();
1332 $this->saveToCache();
1336 * Delete all previously generated thumbnails, refresh metadata in memcached and purge the squid
1338 function purgeCache( $archiveFiles = array(), $shared = false ) {
1339 global $wgUseSquid;
1341 // Refresh metadata cache
1342 $this->purgeMetadataCache();
1344 // Delete thumbnails
1345 $files = $this->getThumbnails( $shared );
1346 $dir = wfImageThumbDir( $this->name, $shared );
1347 $urls = array();
1348 foreach ( $files as $file ) {
1349 $m = array();
1350 if ( preg_match( '/^(\d+)px/', $file, $m ) ) {
1351 list( /* $isScriptUrl */, $url ) = $this->thumbUrl( $m[1] );
1352 $urls[] = $url;
1353 @unlink( "$dir/$file" );
1357 // Purge the squid
1358 if ( $wgUseSquid ) {
1359 $urls[] = $this->getURL();
1360 foreach ( $archiveFiles as $file ) {
1361 $urls[] = wfImageArchiveUrl( $file );
1363 wfPurgeSquidServers( $urls );
1368 * Purge the image description page, but don't go after
1369 * pages using the image. Use when modifying file history
1370 * but not the current data.
1372 function purgeDescription() {
1373 $page = Title::makeTitle( NS_IMAGE, $this->name );
1374 $page->invalidateCache();
1375 $page->purgeSquid();
1379 * Purge metadata and all affected pages when the image is created,
1380 * deleted, or majorly updated. A set of additional URLs may be
1381 * passed to purge, such as specific image files which have changed.
1382 * @param $urlArray array
1384 function purgeEverything( $urlArr=array() ) {
1385 // Delete thumbnails and refresh image metadata cache
1386 $this->purgeCache();
1387 $this->purgeDescription();
1389 // Purge cache of all pages using this image
1390 $update = new HTMLCacheUpdate( $this->getTitle(), 'imagelinks' );
1391 $update->doUpdate();
1394 function checkDBSchema(&$db) {
1395 static $checkDone = false;
1396 global $wgCheckDBSchema;
1397 if (!$wgCheckDBSchema || $checkDone) {
1398 return;
1400 # img_name must be unique
1401 if ( !$db->indexUnique( 'image', 'img_name' ) && !$db->indexExists('image','PRIMARY') ) {
1402 throw new MWException( 'Database schema not up to date, please run maintenance/archives/patch-image_name_unique.sql' );
1404 $checkDone = true;
1406 # new fields must exist
1408 # Not really, there's hundreds of checks like this that we could do and they're all pointless, because
1409 # if the fields are missing, the database will loudly report a query error, the first time you try to do
1410 # something. The only reason I put the above schema check in was because the absence of that particular
1411 # index would lead to an annoying subtle bug. No error message, just some very odd behaviour on duplicate
1412 # uploads. -- TS
1414 if ( !$db->fieldExists( 'image', 'img_media_type' )
1415 || !$db->fieldExists( 'image', 'img_metadata' )
1416 || !$db->fieldExists( 'image', 'img_width' ) ) {
1418 throw new MWException( 'Database schema not up to date, please run maintenance/update.php' );
1424 * Return the image history of this image, line by line.
1425 * starts with current version, then old versions.
1426 * uses $this->historyLine to check which line to return:
1427 * 0 return line for current version
1428 * 1 query for old versions, return first one
1429 * 2, ... return next old version from above query
1431 * @public
1433 function nextHistoryLine() {
1434 $dbr = wfGetDB( DB_SLAVE );
1436 $this->checkDBSchema($dbr);
1438 if ( $this->historyLine == 0 ) {// called for the first time, return line from cur
1439 $this->historyRes = $dbr->select( 'image',
1440 array(
1441 'img_size',
1442 'img_description',
1443 'img_user','img_user_text',
1444 'img_timestamp',
1445 'img_width',
1446 'img_height',
1447 "'' AS oi_archive_name"
1449 array( 'img_name' => $this->title->getDBkey() ),
1450 __METHOD__
1452 if ( 0 == $dbr->numRows( $this->historyRes ) ) {
1453 return FALSE;
1455 } else if ( $this->historyLine == 1 ) {
1456 $this->historyRes = $dbr->select( 'oldimage',
1457 array(
1458 'oi_size AS img_size',
1459 'oi_description AS img_description',
1460 'oi_user AS img_user',
1461 'oi_user_text AS img_user_text',
1462 'oi_timestamp AS img_timestamp',
1463 'oi_width as img_width',
1464 'oi_height as img_height',
1465 'oi_archive_name'
1467 array( 'oi_name' => $this->title->getDBkey() ),
1468 __METHOD__,
1469 array( 'ORDER BY' => 'oi_timestamp DESC' )
1472 $this->historyLine ++;
1474 return $dbr->fetchObject( $this->historyRes );
1478 * Reset the history pointer to the first element of the history
1479 * @public
1481 function resetHistory() {
1482 $this->historyLine = 0;
1486 * Return the full filesystem path to the file. Note that this does
1487 * not mean that a file actually exists under that location.
1489 * This path depends on whether directory hashing is active or not,
1490 * i.e. whether the images are all found in the same directory,
1491 * or in hashed paths like /images/3/3c.
1493 * @public
1494 * @param boolean $fromSharedDirectory Return the path to the file
1495 * in a shared repository (see $wgUseSharedRepository and related
1496 * options in DefaultSettings.php) instead of a local one.
1499 function getFullPath( $fromSharedRepository = false ) {
1500 global $wgUploadDirectory, $wgSharedUploadDirectory;
1502 $dir = $fromSharedRepository ? $wgSharedUploadDirectory :
1503 $wgUploadDirectory;
1505 // $wgSharedUploadDirectory may be false, if thumb.php is used
1506 if ( $dir ) {
1507 $fullpath = $dir . wfGetHashPath($this->name, $fromSharedRepository) . $this->name;
1508 } else {
1509 $fullpath = false;
1512 return $fullpath;
1516 * @return bool
1517 * @static
1519 public static function isHashed( $shared ) {
1520 global $wgHashedUploadDirectory, $wgHashedSharedUploadDirectory;
1521 return $shared ? $wgHashedSharedUploadDirectory : $wgHashedUploadDirectory;
1525 * Record an image upload in the upload log and the image table
1527 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '', $watch = false ) {
1528 global $wgUser, $wgUseCopyrightUpload;
1530 $dbw = wfGetDB( DB_MASTER );
1532 $this->checkDBSchema($dbw);
1534 // Delete thumbnails and refresh the metadata cache
1535 $this->purgeCache();
1537 // Fail now if the image isn't there
1538 if ( !$this->fileExists || $this->fromSharedDirectory ) {
1539 wfDebug( "Image::recordUpload: File ".$this->imagePath." went missing!\n" );
1540 return false;
1543 if ( $wgUseCopyrightUpload ) {
1544 if ( $license != '' ) {
1545 $licensetxt = '== ' . wfMsgForContent( 'license' ) . " ==\n" . '{{' . $license . '}}' . "\n";
1547 $textdesc = '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $desc . "\n" .
1548 '== ' . wfMsgForContent ( 'filestatus' ) . " ==\n" . $copyStatus . "\n" .
1549 "$licensetxt" .
1550 '== ' . wfMsgForContent ( 'filesource' ) . " ==\n" . $source ;
1551 } else {
1552 if ( $license != '' ) {
1553 $filedesc = $desc == '' ? '' : '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $desc . "\n";
1554 $textdesc = $filedesc .
1555 '== ' . wfMsgForContent ( 'license' ) . " ==\n" . '{{' . $license . '}}' . "\n";
1556 } else {
1557 $textdesc = $desc;
1561 $now = $dbw->timestamp();
1563 #split mime type
1564 if (strpos($this->mime,'/')!==false) {
1565 list($major,$minor)= explode('/',$this->mime,2);
1567 else {
1568 $major= $this->mime;
1569 $minor= "unknown";
1572 # Test to see if the row exists using INSERT IGNORE
1573 # This avoids race conditions by locking the row until the commit, and also
1574 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
1575 $dbw->insert( 'image',
1576 array(
1577 'img_name' => $this->name,
1578 'img_size'=> $this->size,
1579 'img_width' => intval( $this->width ),
1580 'img_height' => intval( $this->height ),
1581 'img_bits' => $this->bits,
1582 'img_media_type' => $this->type,
1583 'img_major_mime' => $major,
1584 'img_minor_mime' => $minor,
1585 'img_timestamp' => $now,
1586 'img_description' => $desc,
1587 'img_user' => $wgUser->getID(),
1588 'img_user_text' => $wgUser->getName(),
1589 'img_metadata' => $this->metadata,
1591 __METHOD__,
1592 'IGNORE'
1595 if( $dbw->affectedRows() == 0 ) {
1596 # Collision, this is an update of an image
1597 # Insert previous contents into oldimage
1598 $dbw->insertSelect( 'oldimage', 'image',
1599 array(
1600 'oi_name' => 'img_name',
1601 'oi_archive_name' => $dbw->addQuotes( $oldver ),
1602 'oi_size' => 'img_size',
1603 'oi_width' => 'img_width',
1604 'oi_height' => 'img_height',
1605 'oi_bits' => 'img_bits',
1606 'oi_timestamp' => 'img_timestamp',
1607 'oi_description' => 'img_description',
1608 'oi_user' => 'img_user',
1609 'oi_user_text' => 'img_user_text',
1610 ), array( 'img_name' => $this->name ), __METHOD__
1613 # Update the current image row
1614 $dbw->update( 'image',
1615 array( /* SET */
1616 'img_size' => $this->size,
1617 'img_width' => intval( $this->width ),
1618 'img_height' => intval( $this->height ),
1619 'img_bits' => $this->bits,
1620 'img_media_type' => $this->type,
1621 'img_major_mime' => $major,
1622 'img_minor_mime' => $minor,
1623 'img_timestamp' => $now,
1624 'img_description' => $desc,
1625 'img_user' => $wgUser->getID(),
1626 'img_user_text' => $wgUser->getName(),
1627 'img_metadata' => $this->metadata,
1628 ), array( /* WHERE */
1629 'img_name' => $this->name
1630 ), __METHOD__
1632 } else {
1633 # This is a new image
1634 # Update the image count
1635 $site_stats = $dbw->tableName( 'site_stats' );
1636 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images+1", __METHOD__ );
1639 $descTitle = $this->getTitle();
1640 $article = new Article( $descTitle );
1641 $minor = false;
1642 $watch = $watch || $wgUser->isWatched( $descTitle );
1643 $suppressRC = true; // There's already a log entry, so don't double the RC load
1645 if( $descTitle->exists() ) {
1646 // TODO: insert a null revision into the page history for this update.
1647 if( $watch ) {
1648 $wgUser->addWatch( $descTitle );
1651 # Invalidate the cache for the description page
1652 $descTitle->invalidateCache();
1653 $descTitle->purgeSquid();
1654 } else {
1655 // New image; create the description page.
1656 $article->insertNewArticle( $textdesc, $desc, $minor, $watch, $suppressRC );
1659 # Add the log entry
1660 $log = new LogPage( 'upload' );
1661 $log->addEntry( 'upload', $descTitle, $desc );
1663 # Commit the transaction now, in case something goes wrong later
1664 # The most important thing is that images don't get lost, especially archives
1665 $dbw->immediateCommit();
1667 # Invalidate cache for all pages using this image
1668 $update = new HTMLCacheUpdate( $this->getTitle(), 'imagelinks' );
1669 $update->doUpdate();
1671 return true;
1675 * Get an array of Title objects which are articles which use this image
1676 * Also adds their IDs to the link cache
1678 * This is mostly copied from Title::getLinksTo()
1680 * @deprecated Use HTMLCacheUpdate, this function uses too much memory
1682 function getLinksTo( $options = '' ) {
1683 wfProfileIn( __METHOD__ );
1685 if ( $options ) {
1686 $db = wfGetDB( DB_MASTER );
1687 } else {
1688 $db = wfGetDB( DB_SLAVE );
1690 $linkCache =& LinkCache::singleton();
1692 list( $page, $imagelinks ) = $db->tableNamesN( 'page', 'imagelinks' );
1693 $encName = $db->addQuotes( $this->name );
1694 $sql = "SELECT page_namespace,page_title,page_id FROM $page,$imagelinks WHERE page_id=il_from AND il_to=$encName $options";
1695 $res = $db->query( $sql, __METHOD__ );
1697 $retVal = array();
1698 if ( $db->numRows( $res ) ) {
1699 while ( $row = $db->fetchObject( $res ) ) {
1700 if ( $titleObj = Title::makeTitle( $row->page_namespace, $row->page_title ) ) {
1701 $linkCache->addGoodLinkObj( $row->page_id, $titleObj );
1702 $retVal[] = $titleObj;
1706 $db->freeResult( $res );
1707 wfProfileOut( __METHOD__ );
1708 return $retVal;
1712 * Retrive Exif data from the file and prune unrecognized tags
1713 * and/or tags with invalid contents
1715 * @param $filename
1716 * @return array
1718 private function retrieveExifData( $filename ) {
1719 global $wgShowEXIF;
1722 if ( $this->getMimeType() !== "image/jpeg" )
1723 return array();
1726 if( $wgShowEXIF && file_exists( $filename ) ) {
1727 $exif = new Exif( $filename );
1728 return $exif->getFilteredData();
1731 return array();
1734 function getExifData() {
1735 global $wgRequest;
1736 if ( $this->metadata === '0' || $this->mime == 'image/vnd.djvu' )
1737 return array();
1739 $purge = $wgRequest->getVal( 'action' ) == 'purge';
1740 $ret = unserialize( $this->metadata );
1742 $oldver = isset( $ret['MEDIAWIKI_EXIF_VERSION'] ) ? $ret['MEDIAWIKI_EXIF_VERSION'] : 0;
1743 $newver = Exif::version();
1745 if ( !count( $ret ) || $purge || $oldver != $newver ) {
1746 $this->purgeMetadataCache();
1747 $this->updateExifData( $newver );
1749 if ( isset( $ret['MEDIAWIKI_EXIF_VERSION'] ) )
1750 unset( $ret['MEDIAWIKI_EXIF_VERSION'] );
1751 $format = new FormatExif( $ret );
1753 return $format->getFormattedData();
1756 function updateExifData( $version ) {
1757 if ( $this->getImagePath() === false ) # Not a local image
1758 return;
1760 # Get EXIF data from image
1761 $exif = $this->retrieveExifData( $this->imagePath );
1762 if ( count( $exif ) ) {
1763 $exif['MEDIAWIKI_EXIF_VERSION'] = $version;
1764 $this->metadata = serialize( $exif );
1765 } else {
1766 $this->metadata = '0';
1769 # Update EXIF data in database
1770 $dbw = wfGetDB( DB_MASTER );
1772 $this->checkDBSchema($dbw);
1774 $dbw->update( 'image',
1775 array( 'img_metadata' => $this->metadata ),
1776 array( 'img_name' => $this->name ),
1777 __METHOD__
1782 * Returns true if the image does not come from the shared
1783 * image repository.
1785 * @return bool
1787 function isLocal() {
1788 return !$this->fromSharedDirectory;
1792 * Was this image ever deleted from the wiki?
1794 * @return bool
1796 function wasDeleted() {
1797 $title = Title::makeTitle( NS_IMAGE, $this->name );
1798 return ( $title->isDeleted() > 0 );
1802 * Delete all versions of the image.
1804 * Moves the files into an archive directory (or deletes them)
1805 * and removes the database rows.
1807 * Cache purging is done; logging is caller's responsibility.
1809 * @param $reason
1810 * @return true on success, false on some kind of failure
1812 function delete( $reason, $suppress=false ) {
1813 $transaction = new FSTransaction();
1814 $urlArr = array( $this->getURL() );
1816 if( !FileStore::lock() ) {
1817 wfDebug( __METHOD__.": failed to acquire file store lock, aborting\n" );
1818 return false;
1821 try {
1822 $dbw = wfGetDB( DB_MASTER );
1823 $dbw->begin();
1825 // Delete old versions
1826 $result = $dbw->select( 'oldimage',
1827 array( 'oi_archive_name' ),
1828 array( 'oi_name' => $this->name ) );
1830 while( $row = $dbw->fetchObject( $result ) ) {
1831 $oldName = $row->oi_archive_name;
1833 $transaction->add( $this->prepareDeleteOld( $oldName, $reason, $suppress ) );
1835 // We'll need to purge this URL from caches...
1836 $urlArr[] = wfImageArchiveUrl( $oldName );
1838 $dbw->freeResult( $result );
1840 // And the current version...
1841 $transaction->add( $this->prepareDeleteCurrent( $reason, $suppress ) );
1843 $dbw->immediateCommit();
1844 } catch( MWException $e ) {
1845 wfDebug( __METHOD__.": db error, rolling back file transactions\n" );
1846 $transaction->rollback();
1847 FileStore::unlock();
1848 throw $e;
1851 wfDebug( __METHOD__.": deleted db items, applying file transactions\n" );
1852 $transaction->commit();
1853 FileStore::unlock();
1856 // Update site_stats
1857 $site_stats = $dbw->tableName( 'site_stats' );
1858 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images-1", __METHOD__ );
1860 $this->purgeEverything( $urlArr );
1862 return true;
1867 * Delete an old version of the image.
1869 * Moves the file into an archive directory (or deletes it)
1870 * and removes the database row.
1872 * Cache purging is done; logging is caller's responsibility.
1874 * @param $reason
1875 * @throws MWException or FSException on database or filestore failure
1876 * @return true on success, false on some kind of failure
1878 function deleteOld( $archiveName, $reason, $suppress=false ) {
1879 $transaction = new FSTransaction();
1880 $urlArr = array();
1882 if( !FileStore::lock() ) {
1883 wfDebug( __METHOD__.": failed to acquire file store lock, aborting\n" );
1884 return false;
1887 $transaction = new FSTransaction();
1888 try {
1889 $dbw = wfGetDB( DB_MASTER );
1890 $dbw->begin();
1891 $transaction->add( $this->prepareDeleteOld( $archiveName, $reason, $suppress ) );
1892 $dbw->immediateCommit();
1893 } catch( MWException $e ) {
1894 wfDebug( __METHOD__.": db error, rolling back file transaction\n" );
1895 $transaction->rollback();
1896 FileStore::unlock();
1897 throw $e;
1900 wfDebug( __METHOD__.": deleted db items, applying file transaction\n" );
1901 $transaction->commit();
1902 FileStore::unlock();
1904 $this->purgeDescription();
1906 // Squid purging
1907 global $wgUseSquid;
1908 if ( $wgUseSquid ) {
1909 $urlArr = array(
1910 wfImageArchiveUrl( $archiveName ),
1912 wfPurgeSquidServers( $urlArr );
1914 return true;
1918 * Delete the current version of a file.
1919 * May throw a database error.
1920 * @return true on success, false on failure
1922 private function prepareDeleteCurrent( $reason, $suppress=false ) {
1923 return $this->prepareDeleteVersion(
1924 $this->getFullPath(),
1925 $reason,
1926 'image',
1927 array(
1928 'fa_name' => 'img_name',
1929 'fa_archive_name' => 'NULL',
1930 'fa_size' => 'img_size',
1931 'fa_width' => 'img_width',
1932 'fa_height' => 'img_height',
1933 'fa_metadata' => 'img_metadata',
1934 'fa_bits' => 'img_bits',
1935 'fa_media_type' => 'img_media_type',
1936 'fa_major_mime' => 'img_major_mime',
1937 'fa_minor_mime' => 'img_minor_mime',
1938 'fa_description' => 'img_description',
1939 'fa_user' => 'img_user',
1940 'fa_user_text' => 'img_user_text',
1941 'fa_timestamp' => 'img_timestamp' ),
1942 array( 'img_name' => $this->name ),
1943 $suppress,
1944 __METHOD__ );
1948 * Delete a given older version of a file.
1949 * May throw a database error.
1950 * @return true on success, false on failure
1952 private function prepareDeleteOld( $archiveName, $reason, $suppress=false ) {
1953 $oldpath = wfImageArchiveDir( $this->name ) .
1954 DIRECTORY_SEPARATOR . $archiveName;
1955 return $this->prepareDeleteVersion(
1956 $oldpath,
1957 $reason,
1958 'oldimage',
1959 array(
1960 'fa_name' => 'oi_name',
1961 'fa_archive_name' => 'oi_archive_name',
1962 'fa_size' => 'oi_size',
1963 'fa_width' => 'oi_width',
1964 'fa_height' => 'oi_height',
1965 'fa_metadata' => 'NULL',
1966 'fa_bits' => 'oi_bits',
1967 'fa_media_type' => 'NULL',
1968 'fa_major_mime' => 'NULL',
1969 'fa_minor_mime' => 'NULL',
1970 'fa_description' => 'oi_description',
1971 'fa_user' => 'oi_user',
1972 'fa_user_text' => 'oi_user_text',
1973 'fa_timestamp' => 'oi_timestamp' ),
1974 array(
1975 'oi_name' => $this->name,
1976 'oi_archive_name' => $archiveName ),
1977 $suppress,
1978 __METHOD__ );
1982 * Do the dirty work of backing up an image row and its file
1983 * (if $wgSaveDeletedFiles is on) and removing the originals.
1985 * Must be run while the file store is locked and a database
1986 * transaction is open to avoid race conditions.
1988 * @return FSTransaction
1990 private function prepareDeleteVersion( $path, $reason, $table, $fieldMap, $where, $suppress=false, $fname ) {
1991 global $wgUser, $wgSaveDeletedFiles;
1993 // Dupe the file into the file store
1994 if( file_exists( $path ) ) {
1995 if( $wgSaveDeletedFiles ) {
1996 $group = 'deleted';
1998 $store = FileStore::get( $group );
1999 $key = FileStore::calculateKey( $path, $this->extension );
2000 $transaction = $store->insert( $key, $path,
2001 FileStore::DELETE_ORIGINAL );
2002 } else {
2003 $group = null;
2004 $key = null;
2005 $transaction = FileStore::deleteFile( $path );
2007 } else {
2008 wfDebug( __METHOD__." deleting already-missing '$path'; moving on to database\n" );
2009 $group = null;
2010 $key = null;
2011 $transaction = new FSTransaction(); // empty
2014 if( $transaction === false ) {
2015 // Fail to restore?
2016 wfDebug( __METHOD__.": import to file store failed, aborting\n" );
2017 throw new MWException( "Could not archive and delete file $path" );
2018 return false;
2021 // Bitfields to further supress the image content
2022 // Note that currently, live images are stored elsewhere
2023 // and cannot be partially deleted
2024 $bitfield = 0;
2025 if ( $suppress ) {
2026 $bitfield |= self::DELETED_FILE;
2027 $bitfield |= self::DELETED_COMMENT;
2028 $bitfield |= self::DELETED_USER;
2029 $bitfield |= self::DELETED_RESTRICTED;
2032 $dbw = wfGetDB( DB_MASTER );
2033 $storageMap = array(
2034 'fa_storage_group' => $dbw->addQuotes( $group ),
2035 'fa_storage_key' => $dbw->addQuotes( $key ),
2037 'fa_deleted_user' => $dbw->addQuotes( $wgUser->getId() ),
2038 'fa_deleted_timestamp' => $dbw->timestamp(),
2039 'fa_deleted_reason' => $dbw->addQuotes( $reason ),
2040 'fa_deleted' => $bitfield);
2041 $allFields = array_merge( $storageMap, $fieldMap );
2043 try {
2044 if( $wgSaveDeletedFiles ) {
2045 $dbw->insertSelect( 'filearchive', $table, $allFields, $where, $fname );
2047 $dbw->delete( $table, $where, $fname );
2048 } catch( DBQueryError $e ) {
2049 // Something went horribly wrong!
2050 // Leave the file as it was...
2051 wfDebug( __METHOD__.": database error, rolling back file transaction\n" );
2052 $transaction->rollback();
2053 throw $e;
2056 return $transaction;
2060 * Restore all or specified deleted revisions to the given file.
2061 * Permissions and logging are left to the caller.
2063 * May throw database exceptions on error.
2065 * @param $versions set of record ids of deleted items to restore,
2066 * or empty to restore all revisions.
2067 * @return the number of file revisions restored if successful,
2068 * or false on failure
2070 function restore( $versions=array(), $Unsuppress=false ) {
2071 global $wgUser;
2073 if( !FileStore::lock() ) {
2074 wfDebug( __METHOD__." could not acquire filestore lock\n" );
2075 return false;
2078 $transaction = new FSTransaction();
2079 try {
2080 $dbw = wfGetDB( DB_MASTER );
2081 $dbw->begin();
2083 // Re-confirm whether this image presently exists;
2084 // if no we'll need to create an image record for the
2085 // first item we restore.
2086 $exists = $dbw->selectField( 'image', '1',
2087 array( 'img_name' => $this->name ),
2088 __METHOD__ );
2090 // Fetch all or selected archived revisions for the file,
2091 // sorted from the most recent to the oldest.
2092 $conditions = array( 'fa_name' => $this->name );
2093 if( $versions ) {
2094 $conditions['fa_id'] = $versions;
2097 $result = $dbw->select( 'filearchive', '*',
2098 $conditions,
2099 __METHOD__,
2100 array( 'ORDER BY' => 'fa_timestamp DESC' ) );
2102 if( $dbw->numRows( $result ) < count( $versions ) ) {
2103 // There's some kind of conflict or confusion;
2104 // we can't restore everything we were asked to.
2105 wfDebug( __METHOD__.": couldn't find requested items\n" );
2106 $dbw->rollback();
2107 FileStore::unlock();
2108 return false;
2111 if( $dbw->numRows( $result ) == 0 ) {
2112 // Nothing to do.
2113 wfDebug( __METHOD__.": nothing to do\n" );
2114 $dbw->rollback();
2115 FileStore::unlock();
2116 return true;
2119 $revisions = 0;
2120 while( $row = $dbw->fetchObject( $result ) ) {
2121 if ( $Unsuppress ) {
2122 // Currently, fa_deleted flags fall off upon restore, lets be careful about this
2123 } else if ( ($row->fa_deleted & Revision::DELETED_RESTRICTED) && !$wgUser->isAllowed('hiderevision') ) {
2124 // Skip restoring file revisions that the user cannot restore
2125 continue;
2127 $revisions++;
2128 $store = FileStore::get( $row->fa_storage_group );
2129 if( !$store ) {
2130 wfDebug( __METHOD__.": skipping row with no file.\n" );
2131 continue;
2134 if( $revisions == 1 && !$exists ) {
2135 $destDir = wfImageDir( $row->fa_name );
2136 if ( !is_dir( $destDir ) ) {
2137 wfMkdirParents( $destDir );
2139 $destPath = $destDir . DIRECTORY_SEPARATOR . $row->fa_name;
2141 // We may have to fill in data if this was originally
2142 // an archived file revision.
2143 if( is_null( $row->fa_metadata ) ) {
2144 $tempFile = $store->filePath( $row->fa_storage_key );
2145 $metadata = serialize( $this->retrieveExifData( $tempFile ) );
2147 $magic = MimeMagic::singleton();
2148 $mime = $magic->guessMimeType( $tempFile, true );
2149 $media_type = $magic->getMediaType( $tempFile, $mime );
2150 list( $major_mime, $minor_mime ) = self::splitMime( $mime );
2151 } else {
2152 $metadata = $row->fa_metadata;
2153 $major_mime = $row->fa_major_mime;
2154 $minor_mime = $row->fa_minor_mime;
2155 $media_type = $row->fa_media_type;
2158 $table = 'image';
2159 $fields = array(
2160 'img_name' => $row->fa_name,
2161 'img_size' => $row->fa_size,
2162 'img_width' => $row->fa_width,
2163 'img_height' => $row->fa_height,
2164 'img_metadata' => $metadata,
2165 'img_bits' => $row->fa_bits,
2166 'img_media_type' => $media_type,
2167 'img_major_mime' => $major_mime,
2168 'img_minor_mime' => $minor_mime,
2169 'img_description' => $row->fa_description,
2170 'img_user' => $row->fa_user,
2171 'img_user_text' => $row->fa_user_text,
2172 'img_timestamp' => $row->fa_timestamp );
2173 } else {
2174 $archiveName = $row->fa_archive_name;
2175 if( $archiveName == '' ) {
2176 // This was originally a current version; we
2177 // have to devise a new archive name for it.
2178 // Format is <timestamp of archiving>!<name>
2179 $archiveName =
2180 wfTimestamp( TS_MW, $row->fa_deleted_timestamp ) .
2181 '!' . $row->fa_name;
2183 $destDir = wfImageArchiveDir( $row->fa_name );
2184 if ( !is_dir( $destDir ) ) {
2185 wfMkdirParents( $destDir );
2187 $destPath = $destDir . DIRECTORY_SEPARATOR . $archiveName;
2189 $table = 'oldimage';
2190 $fields = array(
2191 'oi_name' => $row->fa_name,
2192 'oi_archive_name' => $archiveName,
2193 'oi_size' => $row->fa_size,
2194 'oi_width' => $row->fa_width,
2195 'oi_height' => $row->fa_height,
2196 'oi_bits' => $row->fa_bits,
2197 'oi_description' => $row->fa_description,
2198 'oi_user' => $row->fa_user,
2199 'oi_user_text' => $row->fa_user_text,
2200 'oi_timestamp' => $row->fa_timestamp );
2203 $dbw->insert( $table, $fields, __METHOD__ );
2204 /// @fixme this delete is not totally safe, potentially
2205 $dbw->delete( 'filearchive',
2206 array( 'fa_id' => $row->fa_id ),
2207 __METHOD__ );
2209 // Check if any other stored revisions use this file;
2210 // if so, we shouldn't remove the file from the deletion
2211 // archives so they will still work.
2212 $useCount = $dbw->selectField( 'filearchive',
2213 'COUNT(*)',
2214 array(
2215 'fa_storage_group' => $row->fa_storage_group,
2216 'fa_storage_key' => $row->fa_storage_key ),
2217 __METHOD__ );
2218 if( $useCount == 0 ) {
2219 wfDebug( __METHOD__.": nothing else using {$row->fa_storage_key}, will deleting after\n" );
2220 $flags = FileStore::DELETE_ORIGINAL;
2221 } else {
2222 $flags = 0;
2225 $transaction->add( $store->export( $row->fa_storage_key,
2226 $destPath, $flags ) );
2229 $dbw->immediateCommit();
2230 } catch( MWException $e ) {
2231 wfDebug( __METHOD__." caught error, aborting\n" );
2232 $transaction->rollback();
2233 throw $e;
2236 $transaction->commit();
2237 FileStore::unlock();
2239 if( $revisions > 0 ) {
2240 if( !$exists ) {
2241 wfDebug( __METHOD__." restored $revisions items, creating a new current\n" );
2243 // Update site_stats
2244 $site_stats = $dbw->tableName( 'site_stats' );
2245 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images+1", __METHOD__ );
2247 $this->purgeEverything();
2248 } else {
2249 wfDebug( __METHOD__." restored $revisions as archived versions\n" );
2250 $this->purgeDescription();
2254 return $revisions;
2258 * Select a page from a multipage document. Determines the page used for
2259 * rendering thumbnails.
2261 * @param $page Integer: page number, starting with 1
2263 function selectPage( $page ) {
2264 if( $this->initializeMultiPageXML() ) {
2265 wfDebug( __METHOD__." selecting page $page \n" );
2266 $this->page = $page;
2267 $o = $this->multiPageXML->BODY[0]->OBJECT[$page-1];
2268 $this->height = intval( $o['height'] );
2269 $this->width = intval( $o['width'] );
2270 } else {
2271 wfDebug( __METHOD__." selectPage($page) for bogus multipage xml on '$this->name'\n" );
2272 return;
2277 * Lazy-initialize multipage XML metadata for DjVu files.
2278 * @return bool true if $this->multiPageXML is set up and ready;
2279 * false if corrupt or otherwise failing
2281 function initializeMultiPageXML() {
2282 $this->load();
2283 if ( isset( $this->multiPageXML ) ) {
2284 return true;
2288 # Check for files uploaded prior to DJVU support activation,
2289 # or damaged.
2291 if( empty( $this->metadata ) || $this->metadata == serialize( array() ) ) {
2292 $deja = new DjVuImage( $this->imagePath );
2293 $this->metadata = $deja->retrieveMetaData();
2294 $this->purgeMetadataCache();
2296 # Update metadata in the database
2297 $dbw = wfGetDB( DB_MASTER );
2298 $dbw->update( 'image',
2299 array( 'img_metadata' => $this->metadata ),
2300 array( 'img_name' => $this->name ),
2301 __METHOD__
2304 wfSuppressWarnings();
2305 try {
2306 $this->multiPageXML = new SimpleXMLElement( $this->metadata );
2307 } catch( Exception $e ) {
2308 wfDebug( "Bogus multipage XML metadata on '$this->name'\n" );
2309 $this->multiPageXML = null;
2311 wfRestoreWarnings();
2312 return isset( $this->multiPageXML );
2316 * Returns 'true' if this image is a multipage document, e.g. a DJVU
2317 * document.
2319 * @return Bool
2321 function isMultipage() {
2322 return ( $this->mime == 'image/vnd.djvu' );
2326 * Returns the number of pages of a multipage document, or NULL for
2327 * documents which aren't multipage documents
2329 function pageCount() {
2330 if ( ! $this->isMultipage() ) {
2331 return null;
2333 if( $this->initializeMultiPageXML() ) {
2334 return count( $this->multiPageXML->xpath( '//OBJECT' ) );
2335 } else {
2336 wfDebug( "Requested pageCount() for bogus multi-page metadata for '$this->name'\n" );
2337 return null;
2341 static function getCommonsDB() {
2342 static $dbc;
2343 global $wgLoadBalancer, $wgSharedUploadDBname;
2344 if ( !isset( $dbc ) ) {
2345 $i = $wgLoadBalancer->getGroupIndex( 'commons' );
2346 $dbinfo = $wgLoadBalancer->mServers[$i];
2347 $dbc = new Database( $dbinfo['host'], $dbinfo['user'],
2348 $dbinfo['password'], $wgSharedUploadDBname );
2350 return $dbc;
2354 * Calculate the height of a thumbnail using the source and destination width
2356 static function scaleHeight( $srcWidth, $srcHeight, $dstWidth ) {
2357 // Exact integer multiply followed by division
2358 return round( $srcHeight * $dstWidth / $srcWidth );
2362 * Get an image size array like that returned by getimagesize(), or false if it
2363 * can't be determined.
2365 * @param string $fileName The filename
2366 * @param string $mimeType The MIME type of the file
2367 * @param object $deja Filled with a DjVu object if the mime type is image/vnd.djvu
2368 * @return array
2370 static function getImageSize( $fileName, $mimeType, &$deja ) {
2371 $magic =& MimeMagic::singleton();
2372 if( $mimeType == 'image/svg' || $mimeType == 'image/svg+xml' ) {
2373 $gis = wfGetSVGsize( $fileName );
2374 } elseif( $mimeType == 'image/vnd.djvu' ) {
2375 wfSuppressWarnings();
2376 $deja = new DjVuImage( $fileName );
2377 $gis = $deja->getImageSize();
2378 wfRestoreWarnings();
2379 } elseif ( !$magic->isPHPImageType( $mimeType ) ) {
2380 # Don't try to get the width and height of sound and video files, that's bad for performance
2381 $gis = false;
2382 } else {
2383 wfSuppressWarnings();
2384 $gis = getimagesize( $fileName );
2385 wfRestoreWarnings();
2387 return $gis;
2391 * Get the thumbnail extension and MIME type for a given source MIME type
2392 * @return array thumbnail extension and MIME type
2394 static function getThumbType( $ext, $mime ) {
2395 switch ( $mime ) {
2396 case 'image/svg':
2397 case 'image/svg+xml':
2398 $ext = 'png';
2399 $mime = 'image/png';
2400 break;
2401 case 'image/vnd.djvu':
2402 $ext = $GLOBALS['wgDjvuOutputExtension'];
2403 $magic = MimeMagic::singleton();
2404 $mime = $magic->guessTypesForExtension( $ext );
2405 break;
2407 return array( $ext, $mime );
2411 } //class
2413 class ArchivedFile
2416 * Returns a file object from the filearchive table
2417 * In the future, all current and old image storage
2418 * may use FileStore. There will be a "old" storage
2419 * for current and previous file revisions as well as
2420 * the "deleted" group for archived revisions
2421 * @param $title, the corresponding image page title
2422 * @param $id, the image id, a unique key
2423 * @param $key, optional storage key
2424 * @return ResultWrapper
2426 function ArchivedFile( $title, $id=0, $key='' ) {
2427 if( !is_object( $title ) ) {
2428 throw new MWException( 'Image constructor given bogus title.' );
2430 $conds = ($id) ? "fa_id = $id" : "fa_storage_key = '$key'";
2431 if( $title->getNamespace() == NS_IMAGE ) {
2432 $dbr = wfGetDB( DB_SLAVE );
2433 $res = $dbr->select( 'filearchive',
2434 array(
2435 'fa_id',
2436 'fa_name',
2437 'fa_storage_key',
2438 'fa_storage_group',
2439 'fa_size',
2440 'fa_bits',
2441 'fa_width',
2442 'fa_height',
2443 'fa_metadata',
2444 'fa_media_type',
2445 'fa_major_mime',
2446 'fa_minor_mime',
2447 'fa_description',
2448 'fa_user',
2449 'fa_user_text',
2450 'fa_timestamp',
2451 'fa_deleted' ),
2452 array(
2453 'fa_name' => $title->getDbKey(),
2454 $conds ),
2455 __METHOD__,
2456 array( 'ORDER BY' => 'fa_timestamp DESC' ) );
2458 if ( $dbr->numRows( $res ) == 0 ) {
2459 // this revision does not exist?
2460 return;
2462 $ret = $dbr->resultObject( $res );
2463 $row = $ret->fetchObject();
2465 // initialize fields for filestore image object
2466 $this->mId = intval($row->fa_id);
2467 $this->mName = $row->fa_name;
2468 $this->mGroup = $row->fa_storage_group;
2469 $this->mKey = $row->fa_storage_key;
2470 $this->mSize = $row->fa_size;
2471 $this->mBits = $row->fa_bits;
2472 $this->mWidth = $row->fa_width;
2473 $this->mHeight = $row->fa_height;
2474 $this->mMetaData = $row->fa_metadata;
2475 $this->mMime = "$row->fa_major_mime/$row->fa_minor_mime";
2476 $this->mType = $row->fa_media_type;
2477 $this->mDescription = $row->fa_description;
2478 $this->mUser = $row->fa_user;
2479 $this->mUserText = $row->fa_user_text;
2480 $this->mTimestamp = $row->fa_timestamp;
2481 $this->mDeleted = $row->fa_deleted;
2482 } else {
2483 throw new MWException( 'This title does not correspond to an image page.' );
2484 return;
2486 return true;
2490 * int $field one of DELETED_* bitfield constants
2491 * for file or revision rows
2492 * @return bool
2494 function isDeleted( $field ) {
2495 return ($this->mDeleted & $field) == $field;
2499 * Determine if the current user is allowed to view a particular
2500 * field of this FileStore image file, if it's marked as deleted.
2501 * @param int $field
2502 * @return bool
2504 function userCan( $field ) {
2505 if( isset($this->mDeleted) && ($this->mDeleted & $field) == $field ) {
2506 // images
2507 global $wgUser;
2508 $permission = ( $this->mDeleted & Revision::DELETED_RESTRICTED ) == Revision::DELETED_RESTRICTED
2509 ? 'hiderevision'
2510 : 'deleterevision';
2511 wfDebug( "Checking for $permission due to $field match on $this->mDeleted\n" );
2512 return $wgUser->isAllowed( $permission );
2513 } else {
2514 return true;
2520 * Wrapper class for thumbnail images
2522 class ThumbnailImage {
2524 * @param string $path Filesystem path to the thumb
2525 * @param string $url URL path to the thumb
2526 * @private
2528 function ThumbnailImage( $url, $width, $height, $path = false ) {
2529 $this->url = $url;
2530 $this->width = round( $width );
2531 $this->height = round( $height );
2532 # These should be integers when they get here.
2533 # If not, there's a bug somewhere. But let's at
2534 # least produce valid HTML code regardless.
2535 $this->path = $path;
2539 * @return string The thumbnail URL
2541 function getUrl() {
2542 return $this->url;
2546 * Return HTML <img ... /> tag for the thumbnail, will include
2547 * width and height attributes and a blank alt text (as required).
2549 * You can set or override additional attributes by passing an
2550 * associative array of name => data pairs. The data will be escaped
2551 * for HTML output, so should be in plaintext.
2553 * @param array $attribs
2554 * @return string
2555 * @public
2557 function toHtml( $attribs = array() ) {
2558 $attribs['src'] = $this->url;
2559 $attribs['width'] = $this->width;
2560 $attribs['height'] = $this->height;
2561 if( !isset( $attribs['alt'] ) ) $attribs['alt'] = '';
2563 $html = '<img ';
2564 foreach( $attribs as $name => $data ) {
2565 $html .= $name . '="' . htmlspecialchars( $data ) . '" ';
2567 $html .= '/>';
2568 return $html;
2574 * Aliases for backwards compatibility with 1.6
2576 define( 'MW_IMG_DELETED_FILE', Image::DELETED_FILE );
2577 define( 'MW_IMG_DELETED_COMMENT', Image::DELETED_COMMENT );
2578 define( 'MW_IMG_DELETED_USER', Image::DELETED_USER );
2579 define( 'MW_IMG_DELETED_RESTRICTED', Image::DELETED_RESTRICTED );