6 * NOTE FOR WINDOWS USERS:
7 * To enable EXIF functions, add the folloing lines to the
8 * "Windows extensions" section of php.ini:
10 * extension=extensions/php_mbstring.dll
11 * extension=extensions/php_exif.dll
15 * Bump this number when serialized cache records may be incompatible.
17 define( 'MW_IMAGE_VERSION', 2 );
20 * Class to represent an image
22 * Provides methods to retrieve paths (physical, logical, URL),
23 * to generate thumbnails or for uploading.
29 const DELETED_FILE
= 1;
30 const DELETED_COMMENT
= 2;
31 const DELETED_USER
= 4;
32 const DELETED_RESTRICTED
= 8;
38 var $name, # name of the image (constructor)
39 $imagePath, # Path of the image (loadFromXxx)
40 $url, # Image URL (accessor)
41 $title, # Title object for this image (constructor)
42 $fileExists, # does the image file exist on disk? (loadFromXxx)
43 $fromSharedDirectory, # load this image from $wgSharedUploadDirectory (loadFromXxx)
44 $historyLine, # Number of line to return by nextHistoryLine() (constructor)
45 $historyRes, # result of the query for the image's history (nextHistoryLine)
48 $bits, # --- returned by getimagesize (loadFromXxx)
50 $type, # MEDIATYPE_xxx (bitmap, drawing, audio...)
51 $mime, # MIME type, determined by MimeMagic::guessMimeType
52 $extension, # The file extension (constructor)
53 $size, # Size in bytes (loadFromXxx)
55 $dataLoaded, # Whether or not all this has been loaded from the database (loadFromXxx)
56 $page, # Page to render when creating thumbnails
57 $lastError; # Error string associated with a thumbnail display error
63 * Create an Image object from an image name
65 * @param string $name name of the image, used to create a title object using Title::makeTitleSafe
68 public static function newFromName( $name ) {
69 $title = Title
::makeTitleSafe( NS_IMAGE
, $name );
70 if ( is_object( $title ) ) {
71 return new Image( $title );
78 * Obsolete factory function, use constructor
81 function newFromTitle( $title ) {
82 return new Image( $title );
85 function Image( $title ) {
86 if( !is_object( $title ) ) {
87 throw new MWException( 'Image constructor given bogus title.' );
89 $this->title
=& $title;
90 $this->name
= $title->getDBkey();
93 $n = strrpos( $this->name
, '.' );
94 $this->extension
= Image
::normalizeExtension( $n ?
95 substr( $this->name
, $n +
1 ) : '' );
96 $this->historyLine
= 0;
98 $this->dataLoaded
= false;
102 * Normalize a file extension to the common form, and ensure it's clean.
103 * Extensions with non-alphanumeric characters will be discarded.
105 * @param $ext string (without the .)
108 static function normalizeExtension( $ext ) {
109 $lower = strtolower( $ext );
115 if( isset( $squish[$lower] ) ) {
116 return $squish[$lower];
117 } elseif( preg_match( '/^[0-9a-z]+$/', $lower ) ) {
125 * Get the memcached keys
126 * Returns an array, first element is the local cache key, second is the shared cache key, if there is one
128 function getCacheKeys( ) {
129 global $wgUseSharedUploads, $wgSharedUploadDBname, $wgCacheSharedUploads;
131 $hashedName = md5($this->name
);
132 $keys = array( wfMemcKey( 'Image', $hashedName ) );
133 if ( $wgUseSharedUploads && $wgSharedUploadDBname && $wgCacheSharedUploads ) {
134 $keys[] = wfForeignMemcKey( $wgSharedUploadDBname, false, 'Image', $hashedName );
140 * Try to load image metadata from memcached. Returns true on success.
142 function loadFromCache() {
143 global $wgUseSharedUploads, $wgMemc;
144 wfProfileIn( __METHOD__
);
145 $this->dataLoaded
= false;
146 $keys = $this->getCacheKeys();
147 $cachedValues = $wgMemc->get( $keys[0] );
149 // Check if the key existed and belongs to this version of MediaWiki
150 if (!empty($cachedValues) && is_array($cachedValues)
151 && isset($cachedValues['version']) && ( $cachedValues['version'] == MW_IMAGE_VERSION
)
152 && isset( $cachedValues['mime'] ) && isset( $cachedValues['metadata'] ) )
154 if ( $wgUseSharedUploads && $cachedValues['fromShared']) {
155 # if this is shared file, we need to check if image
156 # in shared repository has not changed
157 if ( isset( $keys[1] ) ) {
158 $commonsCachedValues = $wgMemc->get( $keys[1] );
159 if (!empty($commonsCachedValues) && is_array($commonsCachedValues)
160 && isset($commonsCachedValues['version'])
161 && ( $commonsCachedValues['version'] == MW_IMAGE_VERSION
)
162 && isset($commonsCachedValues['mime'])) {
163 wfDebug( "Pulling image metadata from shared repository cache\n" );
164 $this->name
= $commonsCachedValues['name'];
165 $this->imagePath
= $commonsCachedValues['imagePath'];
166 $this->fileExists
= $commonsCachedValues['fileExists'];
167 $this->width
= $commonsCachedValues['width'];
168 $this->height
= $commonsCachedValues['height'];
169 $this->bits
= $commonsCachedValues['bits'];
170 $this->type
= $commonsCachedValues['type'];
171 $this->mime
= $commonsCachedValues['mime'];
172 $this->metadata
= $commonsCachedValues['metadata'];
173 $this->size
= $commonsCachedValues['size'];
174 $this->fromSharedDirectory
= true;
175 $this->dataLoaded
= true;
176 $this->imagePath
= $this->getFullPath(true);
180 wfDebug( "Pulling image metadata from local cache\n" );
181 $this->name
= $cachedValues['name'];
182 $this->imagePath
= $cachedValues['imagePath'];
183 $this->fileExists
= $cachedValues['fileExists'];
184 $this->width
= $cachedValues['width'];
185 $this->height
= $cachedValues['height'];
186 $this->bits
= $cachedValues['bits'];
187 $this->type
= $cachedValues['type'];
188 $this->mime
= $cachedValues['mime'];
189 $this->metadata
= $cachedValues['metadata'];
190 $this->size
= $cachedValues['size'];
191 $this->fromSharedDirectory
= false;
192 $this->dataLoaded
= true;
193 $this->imagePath
= $this->getFullPath();
196 if ( $this->dataLoaded
) {
197 wfIncrStats( 'image_cache_hit' );
199 wfIncrStats( 'image_cache_miss' );
202 wfProfileOut( __METHOD__
);
203 return $this->dataLoaded
;
207 * Save the image metadata to memcached
209 function saveToCache() {
210 global $wgMemc, $wgUseSharedUploads;
212 $keys = $this->getCacheKeys();
213 // We can't cache negative metadata for non-existent files,
214 // because if the file later appears in commons, the local
215 // keys won't be purged.
216 if ( $this->fileExists ||
!$wgUseSharedUploads ) {
217 $cachedValues = array(
218 'version' => MW_IMAGE_VERSION
,
219 'name' => $this->name
,
220 'imagePath' => $this->imagePath
,
221 'fileExists' => $this->fileExists
,
222 'fromShared' => $this->fromSharedDirectory
,
223 'width' => $this->width
,
224 'height' => $this->height
,
225 'bits' => $this->bits
,
226 'type' => $this->type
,
227 'mime' => $this->mime
,
228 'metadata' => $this->metadata
,
229 'size' => $this->size
);
231 $wgMemc->set( $keys[0], $cachedValues, 60 * 60 * 24 * 7 ); // A week
233 // However we should clear them, so they aren't leftover
234 // if we've deleted the file.
235 $wgMemc->delete( $keys[0] );
240 * Load metadata from the file itself
242 function loadFromFile() {
243 global $wgUseSharedUploads, $wgSharedUploadDirectory, $wgContLang;
244 wfProfileIn( __METHOD__
);
245 $this->imagePath
= $this->getFullPath();
246 $this->fileExists
= file_exists( $this->imagePath
);
247 $this->fromSharedDirectory
= false;
250 if (!$this->fileExists
) wfDebug(__METHOD__
.': '.$this->imagePath
." not found locally!\n");
252 # If the file is not found, and a shared upload directory is used, look for it there.
253 if (!$this->fileExists
&& $wgUseSharedUploads && $wgSharedUploadDirectory) {
254 # In case we're on a wgCapitalLinks=false wiki, we
255 # capitalize the first letter of the filename before
256 # looking it up in the shared repository.
257 $sharedImage = Image
::newFromName( $wgContLang->ucfirst($this->name
) );
258 $this->fileExists
= $sharedImage && file_exists( $sharedImage->getFullPath(true) );
259 if ( $this->fileExists
) {
260 $this->name
= $sharedImage->name
;
261 $this->imagePath
= $this->getFullPath(true);
262 $this->fromSharedDirectory
= true;
267 if ( $this->fileExists
) {
268 $magic=& MimeMagic
::singleton();
270 $this->mime
= $magic->guessMimeType($this->imagePath
,true);
271 $this->type
= $magic->getMediaType($this->imagePath
,$this->mime
);
272 $handler = MediaHandler
::getHandler( $this->mime
);
275 $this->size
= filesize( $this->imagePath
);
277 # Height, width and metadata
279 $gis = $handler->getImageSize( $this, $this->imagePath
);
280 $this->metadata
= $handler->getMetadata( $this, $this->imagePath
);
283 $this->metadata
= '';
286 wfDebug(__METHOD__
.': '.$this->imagePath
." loaded, ".$this->size
." bytes, ".$this->mime
.".\n");
290 $this->type
= MEDIATYPE_UNKNOWN
;
291 $this->metadata
= '';
292 wfDebug(__METHOD__
.': '.$this->imagePath
." NOT FOUND!\n");
296 $this->width
= $gis[0];
297 $this->height
= $gis[1];
303 #NOTE: $gis[2] contains a code for the image type. This is no longer used.
305 #NOTE: we have to set this flag early to avoid load() to be called
306 # be some of the functions below. This may lead to recursion or other bad things!
307 # as ther's only one thread of execution, this should be safe anyway.
308 $this->dataLoaded
= true;
310 if ( isset( $gis['bits'] ) ) $this->bits
= $gis['bits'];
311 else $this->bits
= 0;
313 wfProfileOut( __METHOD__
);
317 * Load image metadata from the DB
319 function loadFromDB() {
320 global $wgUseSharedUploads, $wgSharedUploadDBname, $wgSharedUploadDBprefix, $wgContLang;
321 wfProfileIn( __METHOD__
);
323 $dbr = wfGetDB( DB_SLAVE
);
324 $this->checkDBSchema($dbr);
326 $row = $dbr->selectRow( 'image',
327 array( 'img_size', 'img_width', 'img_height', 'img_bits',
328 'img_media_type', 'img_major_mime', 'img_minor_mime', 'img_metadata' ),
329 array( 'img_name' => $this->name
), __METHOD__
);
331 $this->fromSharedDirectory
= false;
332 $this->fileExists
= true;
333 $this->loadFromRow( $row );
334 $this->imagePath
= $this->getFullPath();
335 // Check for rows from a previous schema, quietly upgrade them
336 $this->maybeUpgradeRow();
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",
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__
);
350 $this->fromSharedDirectory
= true;
351 $this->fileExists
= true;
352 $this->imagePath
= $this->getFullPath(true);
354 $this->loadFromRow( $row );
356 // Check for rows from a previous schema, quietly upgrade them
357 $this->maybeUpgradeRow();
367 $this->fileExists
= false;
368 $this->fromSharedDirectory
= false;
369 $this->metadata
= '';
373 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
374 $this->dataLoaded
= true;
375 wfProfileOut( __METHOD__
);
379 * Load image metadata from a DB result row
381 function loadFromRow( &$row ) {
382 $this->size
= $row->img_size
;
383 $this->width
= $row->img_width
;
384 $this->height
= $row->img_height
;
385 $this->bits
= $row->img_bits
;
386 $this->type
= $row->img_media_type
;
388 $major= $row->img_major_mime
;
389 $minor= $row->img_minor_mime
;
391 if (!$major) $this->mime
= "unknown/unknown";
393 if (!$minor) $minor= "unknown";
394 $this->mime
= $major.'/'.$minor;
396 $this->metadata
= $row->img_metadata
;
398 $this->dataLoaded
= true;
402 * Load image metadata from cache or DB, unless already loaded
405 global $wgSharedUploadDBname, $wgUseSharedUploads;
406 if ( !$this->dataLoaded
) {
407 if ( !$this->loadFromCache() ) {
409 if ( !$wgSharedUploadDBname && $wgUseSharedUploads ) {
410 $this->loadFromFile();
411 } elseif ( $this->fileExists ||
!$wgUseSharedUploads ) {
412 // We can do negative caching for local images, because the cache
413 // will be purged on upload. But we can't do it when shared images
414 // are enabled, since updates to that won't purge foreign caches.
415 $this->saveToCache();
418 $this->dataLoaded
= true;
423 * Upgrade a row if it needs it
425 function maybeUpgradeRow() {
426 if ( is_null($this->type
) ||
$this->mime
== 'image/svg' ) {
429 $handler = $this->getHandler();
430 if ( $handler && !$handler->isMetadataValid( $this, $this->metadata
) ) {
437 * Fix assorted version-related problems with the image row by reloading it from the file
439 function upgradeRow() {
440 global $wgDBname, $wgSharedUploadDBname;
441 wfProfileIn( __METHOD__
);
443 $this->loadFromFile();
445 if ( $this->fromSharedDirectory
) {
446 if ( !$wgSharedUploadDBname ) {
447 wfProfileOut( __METHOD__
);
451 // Write to the other DB using selectDB, not database selectors
452 // This avoids breaking replication in MySQL
453 $dbw = Image
::getCommonsDB();
455 $dbw = wfGetDB( DB_MASTER
);
458 $this->checkDBSchema($dbw);
460 list( $major, $minor ) = self
::splitMime( $this->mime
);
462 wfDebug(__METHOD__
.': upgrading '.$this->name
." to the current schema\n");
464 $dbw->update( 'image',
466 'img_width' => $this->width
,
467 'img_height' => $this->height
,
468 'img_bits' => $this->bits
,
469 'img_media_type' => $this->type
,
470 'img_major_mime' => $major,
471 'img_minor_mime' => $minor,
472 'img_metadata' => $this->metadata
,
473 ), array( 'img_name' => $this->name
), __METHOD__
475 if ( $this->fromSharedDirectory
) {
476 $dbw->selectDB( $wgDBname );
478 wfProfileOut( __METHOD__
);
482 * Split an internet media type into its two components; if not
483 * a two-part name, set the minor type to 'unknown'.
485 * @param $mime "text/html" etc
486 * @return array ("text", "html") etc
488 static function splitMime( $mime ) {
489 if( strpos( $mime, '/' ) !== false ) {
490 return explode( '/', $mime, 2 );
492 return array( $mime, 'unknown' );
497 * Return the name of this image
505 * Return the associated title object
508 function getTitle() {
513 * Return the URL of the image file
519 if($this->fileExists
) {
520 $this->url
= Image
::imageUrl( $this->name
, $this->fromSharedDirectory
);
528 function getViewURL() {
529 if( $this->mustRender()) {
530 if( $this->canRender() ) {
531 return $this->createThumb( $this->getWidth() );
534 wfDebug('Image::getViewURL(): supposed to render '.$this->name
.' ('.$this->mime
."), but can't!\n");
535 return $this->getURL(); #hm... return NULL?
538 return $this->getURL();
543 * Return the image path of the image in the
544 * local file system as an absolute path
547 function getImagePath() {
549 return $this->imagePath
;
553 * Return the width of the image
555 * Returns false on error
558 function getWidth( $page = 1 ) {
560 if ( $this->isMultipage() ) {
561 $dim = $this->getHandler()->getPageDimensions( $this, $page );
563 return $dim['width'];
573 * Return the height of the image
575 * Returns false on error
578 function getHeight( $page = 1 ) {
580 if ( $this->isMultipage() ) {
581 $dim = $this->getHandler()->getPageDimensions( $this, $page );
583 return $dim['height'];
588 return $this->height
;
593 * Get handler-specific metadata
595 function getMetadata() {
597 return $this->metadata
;
601 * Return the size of the image file, in bytes
610 * Returns the mime type of the file.
612 function getMimeType() {
618 * Return the type of the media in the file.
619 * Use the value returned by this function with the MEDIATYPE_xxx constants.
621 function getMediaType() {
627 * Checks if the file can be presented to the browser as a bitmap.
629 * Currently, this checks if the file is an image format
630 * that can be converted to a format
631 * supported by all browsers (namely GIF, PNG and JPEG),
632 * or if it is an SVG image and SVG conversion is enabled.
634 * @todo remember the result of this check.
636 function canRender() {
637 $handler = $this->getHandler();
638 return $handler && $handler->canRender();
642 * Return true if the file is of a type that can't be directly
643 * rendered by typical browsers and needs to be re-rasterized.
645 * This returns true for everything but the bitmap types
646 * supported by all browsers, i.e. JPEG; GIF and PNG. It will
647 * also return true for any non-image formats.
651 function mustRender() {
652 $handler = $this->getHandler();
653 return $handler && $handler->mustRender();
657 * Determines if this media file may be shown inline on a page.
659 * This is currently synonymous to canRender(), but this could be
660 * extended to also allow inline display of other media,
661 * like flash animations or videos. If you do so, please keep in mind that
662 * that could be a security risk.
664 function allowInlineDisplay() {
665 return $this->canRender();
669 * Determines if this media file is in a format that is unlikely to
670 * contain viruses or malicious content. It uses the global
671 * $wgTrustedMediaFormats list to determine if the file is safe.
673 * This is used to show a warning on the description page of non-safe files.
674 * It may also be used to disallow direct [[media:...]] links to such files.
676 * Note that this function will always return true if allowInlineDisplay()
677 * or isTrustedFile() is true for this file.
679 function isSafeFile() {
680 if ($this->allowInlineDisplay()) return true;
681 if ($this->isTrustedFile()) return true;
683 global $wgTrustedMediaFormats;
685 $type= $this->getMediaType();
686 $mime= $this->getMimeType();
687 #wfDebug("Image::isSafeFile: type= $type, mime= $mime\n");
689 if (!$type ||
$type===MEDIATYPE_UNKNOWN
) return false; #unknown type, not trusted
690 if ( in_array( $type, $wgTrustedMediaFormats) ) return true;
692 if ($mime==="unknown/unknown") return false; #unknown type, not trusted
693 if ( in_array( $mime, $wgTrustedMediaFormats) ) return true;
698 /** Returns true if the file is flagged as trusted. Files flagged that way
699 * can be linked to directly, even if that is not allowed for this type of
702 * This is a dummy function right now and always returns false. It could be
703 * implemented to extract a flag from the database. The trusted flag could be
704 * set on upload, if the user has sufficient privileges, to bypass script-
705 * and html-filters. It may even be coupled with cryptographics signatures
708 function isTrustedFile() {
709 #this could be implemented to check a flag in the databas,
710 #look for signatures, etc
715 * Return the escapeLocalURL of this image
718 function getEscapeLocalURL( $query=false) {
719 return $this->getTitle()->escapeLocalURL( $query );
723 * Return the escapeFullURL of this image
726 function getEscapeFullURL() {
728 return $this->title
->escapeFullURL();
732 * Return the URL of an image, provided its name.
734 * @param string $name Name of the image, without the leading "Image:"
735 * @param boolean $fromSharedDirectory Should this be in $wgSharedUploadPath?
736 * @return string URL of $name image
740 function imageUrl( $name, $fromSharedDirectory = false ) {
741 global $wgUploadPath,$wgUploadBaseUrl,$wgSharedUploadPath;
742 if($fromSharedDirectory) {
744 $path = $wgSharedUploadPath;
746 $base = $wgUploadBaseUrl;
747 $path = $wgUploadPath;
749 $url = "{$base}{$path}" . wfGetHashPath($name, $fromSharedDirectory) . "{$name}";
750 return wfUrlencode( $url );
754 * Returns true if the image file exists on disk.
755 * @return boolean Whether image file exist on disk.
760 return $this->fileExists
;
767 function thumbUrl( $thumbName ) {
768 global $wgUploadPath, $wgUploadBaseUrl, $wgSharedUploadPath;
769 if($this->fromSharedDirectory
) {
771 $path = $wgSharedUploadPath;
773 $base = $wgUploadBaseUrl;
774 $path = $wgUploadPath;
776 if ( Image
::isHashed( $this->fromSharedDirectory
) ) {
777 $subdir = wfGetHashPath($this->name
, $this->fromSharedDirectory
) .
778 wfUrlencode( $this->name
);
782 $url = "{$base}{$path}/thumb{$subdir}/" . wfUrlencode( $thumbName );
786 function getTransformScript() {
787 global $wgSharedThumbnailScriptPath, $wgThumbnailScriptPath;
788 if ( $this->fromSharedDirectory
) {
789 $script = $wgSharedThumbnailScriptPath;
791 $script = $wgThumbnailScriptPath;
794 return "$script?f=" . urlencode( $this->name
);
801 * Get a ThumbnailImage which is the same size as the source
803 function getUnscaledThumb( $page = false ) {
807 'width' => $this->getWidth( $page )
810 $params = array( 'width' => $this->getWidth() );
812 return $this->transform( $params );
816 * Return the file name of a thumbnail with the specified parameters
818 * @param array $params Handler-specific parameters
821 function thumbName( $params ) {
822 $handler = $this->getHandler();
826 list( $thumbExt, $thumbMime ) = self
::getThumbType( $this->extension
, $this->mime
);
827 $thumbName = $handler->makeParamString( $params ) . '-' . $this->name
;
828 if ( $thumbExt != $this->extension
) {
829 $thumbName .= ".$thumbExt";
835 * Create a thumbnail of the image having the specified width/height.
836 * The thumbnail will not be created if the width is larger than the
837 * image's width. Let the browser do the scaling in this case.
838 * The thumbnail is stored on disk and is only computed if the thumbnail
839 * file does not exist OR if it is older than the image.
842 * Keeps aspect ratio of original image. If both width and height are
843 * specified, the generated image will be no bigger than width x height,
844 * and will also have correct aspect ratio.
846 * @param integer $width maximum width of the generated thumbnail
847 * @param integer $height maximum height of the image (optional)
850 function createThumb( $width, $height = -1 ) {
851 $params = array( 'width' => $width );
852 if ( $height != -1 ) {
853 $params['height'] = $height;
855 $thumb = $this->transform( $params );
856 if( is_null( $thumb ) ||
$thumb->isError() ) return '';
857 return $thumb->getUrl();
861 * As createThumb, but returns a ThumbnailImage object. This can
862 * provide access to the actual file, the real size of the thumb,
863 * and can produce a convenient <img> tag for you.
865 * For non-image formats, this may return a filetype-specific icon.
867 * @param integer $width maximum width of the generated thumbnail
868 * @param integer $height maximum height of the image (optional)
869 * @param boolean $render True to render the thumbnail if it doesn't exist,
870 * false to just return the URL
872 * @return ThumbnailImage or null on failure
875 * @deprecated use transform()
877 function getThumbnail( $width, $height=-1, $render = true ) {
878 $params = array( 'width' => $width );
879 if ( $height != -1 ) {
880 $params['height'] = $height;
882 $flags = $render ? self
::RENDER_NOW
: 0;
883 return $this->transform( $params, $flags );
887 * Transform a media file
889 * @param array $params An associative array of handler-specific parameters. Typical
890 * keys are width, height and page.
891 * @param integer $flags A bitfield, may contain self::RENDER_NOW to force rendering
892 * @return MediaTransformOutput
894 function transform( $params, $flags = 0 ) {
895 global $wgGenerateThumbnailOnParse, $wgUseSquid, $wgIgnoreImageErrors;
897 wfProfileIn( __METHOD__
);
899 $handler = $this->getHandler();
900 if ( !$handler ||
!$handler->canRender() ) {
901 // not a bitmap or renderable image, don't try.
902 $thumb = $this->iconThumb();
906 $script = $this->getTransformScript();
907 if ( $script && !($flags & self
::RENDER_NOW
) ) {
908 // Use a script to transform on client request
909 $thumb = $handler->getScriptedTransform( $this, $script, $params );
913 $normalisedParams = $params;
914 $handler->normaliseParams( $this, $normalisedParams );
915 list( $thumbExt, $thumbMime ) = self
::getThumbType( $this->extension
, $this->mime
);
916 $thumbName = $this->thumbName( $normalisedParams );
917 $thumbPath = wfImageThumbDir( $this->name
, $this->fromSharedDirectory
) . "/$thumbName";
918 $thumbUrl = $this->thumbUrl( $thumbName );
920 $this->migrateThumbFile( $thumbName );
922 if ( file_exists( $thumbPath ) ) {
923 $thumb = $handler->getTransform( $this, $thumbPath, $thumbUrl, $params );
927 if ( !$wgGenerateThumbnailOnParse && !($flags & self
::RENDER_NOW
) ) {
928 $thumb = $handler->getTransform( $this, $thumbPath, $thumbUrl, $params );
931 $thumb = $handler->doTransform( $this, $thumbPath, $thumbUrl, $params );
933 // Ignore errors if requested
936 } elseif ( $thumb->isError() ) {
937 $this->lastError
= $thumb->toText();
938 if ( $wgIgnoreImageErrors && !($flags & self
::RENDER_NOW
) ) {
939 $thumb = $handler->getTransform( $this, $thumbPath, $thumbUrl, $params );
944 wfPurgeSquidServers( array( $thumbUrl ) );
948 wfProfileOut( __METHOD__
);
953 * Fix thumbnail files from 1.4 or before, with extreme prejudice
955 function migrateThumbFile( $thumbName ) {
956 $thumbDir = wfImageThumbDir( $this->name
, $this->fromSharedDirectory
);
957 $thumbPath = "$thumbDir/$thumbName";
958 if ( is_dir( $thumbPath ) ) {
959 // Directory where file should be
960 // This happened occasionally due to broken migration code in 1.5
961 // Rename to broken-*
962 global $wgUploadDirectory;
963 for ( $i = 0; $i < 100 ; $i++
) {
964 $broken = "$wgUploadDirectory/broken-$i-$thumbName";
965 if ( !file_exists( $broken ) ) {
966 rename( $thumbPath, $broken );
970 // Doesn't exist anymore
973 if ( is_file( $thumbDir ) ) {
974 // File where directory should be
976 // Doesn't exist anymore
982 * Get a MediaHandler instance for this image
984 function getHandler() {
985 return MediaHandler
::getHandler( $this->getMimeType() );
989 * Get a ThumbnailImage representing a file type icon
990 * @return ThumbnailImage
992 function iconThumb() {
993 global $wgStylePath, $wgStyleDirectory;
995 $try = array( 'fileicon-' . $this->extension
. '.png', 'fileicon.png' );
996 foreach( $try as $icon ) {
997 $path = '/common/images/icons/' . $icon;
998 $filepath = $wgStyleDirectory . $path;
999 if( file_exists( $filepath ) ) {
1000 return new ThumbnailImage( $wgStylePath . $path, 120, 120 );
1007 * Get last thumbnailing error.
1010 function getLastError() {
1011 return $this->lastError
;
1015 * Get all thumbnail names previously generated for this image
1017 function getThumbnails( $shared = false ) {
1018 if ( Image
::isHashed( $shared ) ) {
1021 $dir = wfImageThumbDir( $this->name
, $shared );
1023 if ( is_dir( $dir ) ) {
1024 $handle = opendir( $dir );
1027 while ( false !== ( $file = readdir($handle) ) ) {
1028 if ( $file{0} != '.' ) {
1032 closedir( $handle );
1043 * Refresh metadata in memcached, but don't touch thumbnails or squid
1045 function purgeMetadataCache() {
1047 $this->upgradeRow();
1048 $this->saveToCache();
1052 * Delete all previously generated thumbnails, refresh metadata in memcached and purge the squid
1054 function purgeCache( $archiveFiles = array(), $shared = false ) {
1057 // Refresh metadata cache
1058 $this->purgeMetadataCache();
1060 // Delete thumbnails
1061 $files = $this->getThumbnails( $shared );
1062 $dir = wfImageThumbDir( $this->name
, $shared );
1064 foreach ( $files as $file ) {
1066 if ( preg_match( '/^(\d+)px/', $file, $m ) ) {
1067 $url = $this->thumbUrl( $m[1] );
1069 @unlink
( "$dir/$file" );
1074 if ( $wgUseSquid ) {
1075 $urls[] = $this->getURL();
1076 foreach ( $archiveFiles as $file ) {
1077 $urls[] = wfImageArchiveUrl( $file );
1079 wfPurgeSquidServers( $urls );
1084 * Purge the image description page, but don't go after
1085 * pages using the image. Use when modifying file history
1086 * but not the current data.
1088 function purgeDescription() {
1089 $page = Title
::makeTitle( NS_IMAGE
, $this->name
);
1090 $page->invalidateCache();
1091 $page->purgeSquid();
1095 * Purge metadata and all affected pages when the image is created,
1096 * deleted, or majorly updated. A set of additional URLs may be
1097 * passed to purge, such as specific image files which have changed.
1098 * @param $urlArray array
1100 function purgeEverything( $urlArr=array() ) {
1101 // Delete thumbnails and refresh image metadata cache
1102 $this->purgeCache();
1103 $this->purgeDescription();
1105 // Purge cache of all pages using this image
1106 $update = new HTMLCacheUpdate( $this->getTitle(), 'imagelinks' );
1107 $update->doUpdate();
1111 * Check the image table schema on the given connection for subtle problems
1113 function checkDBSchema(&$db) {
1114 static $checkDone = false;
1115 global $wgCheckDBSchema;
1116 if (!$wgCheckDBSchema ||
$checkDone) {
1119 # img_name must be unique
1120 if ( !$db->indexUnique( 'image', 'img_name' ) && !$db->indexExists('image','PRIMARY') ) {
1121 throw new MWException( 'Database schema not up to date, please run maintenance/archives/patch-image_name_unique.sql' );
1125 # new fields must exist
1127 # Not really, there's hundreds of checks like this that we could do and they're all pointless, because
1128 # if the fields are missing, the database will loudly report a query error, the first time you try to do
1129 # something. The only reason I put the above schema check in was because the absence of that particular
1130 # index would lead to an annoying subtle bug. No error message, just some very odd behaviour on duplicate
1133 if ( !$db->fieldExists( 'image', 'img_media_type' )
1134 || !$db->fieldExists( 'image', 'img_metadata' )
1135 || !$db->fieldExists( 'image', 'img_width' ) ) {
1137 throw new MWException( 'Database schema not up to date, please run maintenance/update.php' );
1143 * Return the image history of this image, line by line.
1144 * starts with current version, then old versions.
1145 * uses $this->historyLine to check which line to return:
1146 * 0 return line for current version
1147 * 1 query for old versions, return first one
1148 * 2, ... return next old version from above query
1152 function nextHistoryLine() {
1153 $dbr = wfGetDB( DB_SLAVE
);
1155 $this->checkDBSchema($dbr);
1157 if ( $this->historyLine
== 0 ) {// called for the first time, return line from cur
1158 $this->historyRes
= $dbr->select( 'image',
1162 'img_user','img_user_text',
1166 "'' AS oi_archive_name"
1168 array( 'img_name' => $this->title
->getDBkey() ),
1171 if ( 0 == $dbr->numRows( $this->historyRes
) ) {
1174 } else if ( $this->historyLine
== 1 ) {
1175 $this->historyRes
= $dbr->select( 'oldimage',
1177 'oi_size AS img_size',
1178 'oi_description AS img_description',
1179 'oi_user AS img_user',
1180 'oi_user_text AS img_user_text',
1181 'oi_timestamp AS img_timestamp',
1182 'oi_width as img_width',
1183 'oi_height as img_height',
1186 array( 'oi_name' => $this->title
->getDBkey() ),
1188 array( 'ORDER BY' => 'oi_timestamp DESC' )
1191 $this->historyLine ++
;
1193 return $dbr->fetchObject( $this->historyRes
);
1197 * Reset the history pointer to the first element of the history
1200 function resetHistory() {
1201 $this->historyLine
= 0;
1205 * Return the full filesystem path to the file. Note that this does
1206 * not mean that a file actually exists under that location.
1208 * This path depends on whether directory hashing is active or not,
1209 * i.e. whether the images are all found in the same directory,
1210 * or in hashed paths like /images/3/3c.
1213 * @param boolean $fromSharedDirectory Return the path to the file
1214 * in a shared repository (see $wgUseSharedRepository and related
1215 * options in DefaultSettings.php) instead of a local one.
1218 function getFullPath( $fromSharedRepository = false ) {
1219 global $wgUploadDirectory, $wgSharedUploadDirectory;
1221 $dir = $fromSharedRepository ?
$wgSharedUploadDirectory :
1224 // $wgSharedUploadDirectory may be false, if thumb.php is used
1226 $fullpath = $dir . wfGetHashPath($this->name
, $fromSharedRepository) . $this->name
;
1238 public static function isHashed( $shared ) {
1239 global $wgHashedUploadDirectory, $wgHashedSharedUploadDirectory;
1240 return $shared ?
$wgHashedSharedUploadDirectory : $wgHashedUploadDirectory;
1244 * Record an image upload in the upload log and the image table
1246 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '', $watch = false ) {
1247 global $wgUser, $wgUseCopyrightUpload;
1249 $dbw = wfGetDB( DB_MASTER
);
1251 $this->checkDBSchema($dbw);
1253 // Delete thumbnails and refresh the metadata cache
1254 $this->purgeCache();
1256 // Fail now if the image isn't there
1257 if ( !$this->fileExists ||
$this->fromSharedDirectory
) {
1258 wfDebug( "Image::recordUpload: File ".$this->imagePath
." went missing!\n" );
1262 if ( $wgUseCopyrightUpload ) {
1263 if ( $license != '' ) {
1264 $licensetxt = '== ' . wfMsgForContent( 'license' ) . " ==\n" . '{{' . $license . '}}' . "\n";
1266 $textdesc = '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $desc . "\n" .
1267 '== ' . wfMsgForContent ( 'filestatus' ) . " ==\n" . $copyStatus . "\n" .
1269 '== ' . wfMsgForContent ( 'filesource' ) . " ==\n" . $source ;
1271 if ( $license != '' ) {
1272 $filedesc = $desc == '' ?
'' : '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $desc . "\n";
1273 $textdesc = $filedesc .
1274 '== ' . wfMsgForContent ( 'license' ) . " ==\n" . '{{' . $license . '}}' . "\n";
1280 $now = $dbw->timestamp();
1283 if (strpos($this->mime
,'/')!==false) {
1284 list($major,$minor)= explode('/',$this->mime
,2);
1287 $major= $this->mime
;
1291 # Test to see if the row exists using INSERT IGNORE
1292 # This avoids race conditions by locking the row until the commit, and also
1293 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
1294 $dbw->insert( 'image',
1296 'img_name' => $this->name
,
1297 'img_size'=> $this->size
,
1298 'img_width' => intval( $this->width
),
1299 'img_height' => intval( $this->height
),
1300 'img_bits' => $this->bits
,
1301 'img_media_type' => $this->type
,
1302 'img_major_mime' => $major,
1303 'img_minor_mime' => $minor,
1304 'img_timestamp' => $now,
1305 'img_description' => $desc,
1306 'img_user' => $wgUser->getID(),
1307 'img_user_text' => $wgUser->getName(),
1308 'img_metadata' => $this->metadata
,
1314 if( $dbw->affectedRows() == 0 ) {
1315 # Collision, this is an update of an image
1316 # Insert previous contents into oldimage
1317 $dbw->insertSelect( 'oldimage', 'image',
1319 'oi_name' => 'img_name',
1320 'oi_archive_name' => $dbw->addQuotes( $oldver ),
1321 'oi_size' => 'img_size',
1322 'oi_width' => 'img_width',
1323 'oi_height' => 'img_height',
1324 'oi_bits' => 'img_bits',
1325 'oi_timestamp' => 'img_timestamp',
1326 'oi_description' => 'img_description',
1327 'oi_user' => 'img_user',
1328 'oi_user_text' => 'img_user_text',
1329 ), array( 'img_name' => $this->name
), __METHOD__
1332 # Update the current image row
1333 $dbw->update( 'image',
1335 'img_size' => $this->size
,
1336 'img_width' => intval( $this->width
),
1337 'img_height' => intval( $this->height
),
1338 'img_bits' => $this->bits
,
1339 'img_media_type' => $this->type
,
1340 'img_major_mime' => $major,
1341 'img_minor_mime' => $minor,
1342 'img_timestamp' => $now,
1343 'img_description' => $desc,
1344 'img_user' => $wgUser->getID(),
1345 'img_user_text' => $wgUser->getName(),
1346 'img_metadata' => $this->metadata
,
1347 ), array( /* WHERE */
1348 'img_name' => $this->name
1352 # This is a new image
1353 # Update the image count
1354 $site_stats = $dbw->tableName( 'site_stats' );
1355 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images+1", __METHOD__
);
1358 $descTitle = $this->getTitle();
1359 $article = new Article( $descTitle );
1361 $watch = $watch ||
$wgUser->isWatched( $descTitle );
1362 $suppressRC = true; // There's already a log entry, so don't double the RC load
1364 if( $descTitle->exists() ) {
1365 // TODO: insert a null revision into the page history for this update.
1367 $wgUser->addWatch( $descTitle );
1370 # Invalidate the cache for the description page
1371 $descTitle->invalidateCache();
1372 $descTitle->purgeSquid();
1374 // New image; create the description page.
1375 $article->insertNewArticle( $textdesc, $desc, $minor, $watch, $suppressRC );
1378 # Hooks, hooks, the magic of hooks...
1379 wfRunHooks( 'FileUpload', array( $this ) );
1382 $log = new LogPage( 'upload' );
1383 $log->addEntry( 'upload', $descTitle, $desc );
1385 # Commit the transaction now, in case something goes wrong later
1386 # The most important thing is that images don't get lost, especially archives
1387 $dbw->immediateCommit();
1389 # Invalidate cache for all pages using this image
1390 $update = new HTMLCacheUpdate( $this->getTitle(), 'imagelinks' );
1391 $update->doUpdate();
1397 * Get an array of Title objects which are articles which use this image
1398 * Also adds their IDs to the link cache
1400 * This is mostly copied from Title::getLinksTo()
1402 * @deprecated Use HTMLCacheUpdate, this function uses too much memory
1404 function getLinksTo( $options = '' ) {
1405 wfProfileIn( __METHOD__
);
1408 $db = wfGetDB( DB_MASTER
);
1410 $db = wfGetDB( DB_SLAVE
);
1412 $linkCache =& LinkCache
::singleton();
1414 list( $page, $imagelinks ) = $db->tableNamesN( 'page', 'imagelinks' );
1415 $encName = $db->addQuotes( $this->name
);
1416 $sql = "SELECT page_namespace,page_title,page_id FROM $page,$imagelinks WHERE page_id=il_from AND il_to=$encName $options";
1417 $res = $db->query( $sql, __METHOD__
);
1420 if ( $db->numRows( $res ) ) {
1421 while ( $row = $db->fetchObject( $res ) ) {
1422 if ( $titleObj = Title
::makeTitle( $row->page_namespace
, $row->page_title
) ) {
1423 $linkCache->addGoodLinkObj( $row->page_id
, $titleObj );
1424 $retVal[] = $titleObj;
1428 $db->freeResult( $res );
1429 wfProfileOut( __METHOD__
);
1433 function getExifData() {
1435 $handler = $this->getHandler();
1436 if ( !$handler ||
$handler->getMetadataType( $this ) != 'exif' ) {
1439 if ( !$this->metadata
) {
1442 $exif = unserialize( $this->metadata
);
1446 unset( $exif['MEDIAWIKI_EXIF_VERSION'] );
1447 $format = new FormatExif( $exif );
1449 return $format->getFormattedData();
1453 * Returns true if the image does not come from the shared
1458 function isLocal() {
1459 return !$this->fromSharedDirectory
;
1463 * Was this image ever deleted from the wiki?
1467 function wasDeleted() {
1468 $title = Title
::makeTitle( NS_IMAGE
, $this->name
);
1469 return ( $title->isDeleted() > 0 );
1473 * Delete all versions of the image.
1475 * Moves the files into an archive directory (or deletes them)
1476 * and removes the database rows.
1478 * Cache purging is done; logging is caller's responsibility.
1481 * @return true on success, false on some kind of failure
1483 function delete( $reason, $suppress=false ) {
1484 $transaction = new FSTransaction();
1485 $urlArr = array( $this->getURL() );
1487 if( !FileStore
::lock() ) {
1488 wfDebug( __METHOD__
.": failed to acquire file store lock, aborting\n" );
1493 $dbw = wfGetDB( DB_MASTER
);
1496 // Delete old versions
1497 $result = $dbw->select( 'oldimage',
1498 array( 'oi_archive_name' ),
1499 array( 'oi_name' => $this->name
) );
1501 while( $row = $dbw->fetchObject( $result ) ) {
1502 $oldName = $row->oi_archive_name
;
1504 $transaction->add( $this->prepareDeleteOld( $oldName, $reason, $suppress ) );
1506 // We'll need to purge this URL from caches...
1507 $urlArr[] = wfImageArchiveUrl( $oldName );
1509 $dbw->freeResult( $result );
1511 // And the current version...
1512 $transaction->add( $this->prepareDeleteCurrent( $reason, $suppress ) );
1514 $dbw->immediateCommit();
1515 } catch( MWException
$e ) {
1516 wfDebug( __METHOD__
.": db error, rolling back file transactions\n" );
1517 $transaction->rollback();
1518 FileStore
::unlock();
1522 wfDebug( __METHOD__
.": deleted db items, applying file transactions\n" );
1523 $transaction->commit();
1524 FileStore
::unlock();
1527 // Update site_stats
1528 $site_stats = $dbw->tableName( 'site_stats' );
1529 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images-1", __METHOD__
);
1531 $this->purgeEverything( $urlArr );
1538 * Delete an old version of the image.
1540 * Moves the file into an archive directory (or deletes it)
1541 * and removes the database row.
1543 * Cache purging is done; logging is caller's responsibility.
1546 * @throws MWException or FSException on database or filestore failure
1547 * @return true on success, false on some kind of failure
1549 function deleteOld( $archiveName, $reason, $suppress=false ) {
1550 $transaction = new FSTransaction();
1553 if( !FileStore
::lock() ) {
1554 wfDebug( __METHOD__
.": failed to acquire file store lock, aborting\n" );
1558 $transaction = new FSTransaction();
1560 $dbw = wfGetDB( DB_MASTER
);
1562 $transaction->add( $this->prepareDeleteOld( $archiveName, $reason, $suppress ) );
1563 $dbw->immediateCommit();
1564 } catch( MWException
$e ) {
1565 wfDebug( __METHOD__
.": db error, rolling back file transaction\n" );
1566 $transaction->rollback();
1567 FileStore
::unlock();
1571 wfDebug( __METHOD__
.": deleted db items, applying file transaction\n" );
1572 $transaction->commit();
1573 FileStore
::unlock();
1575 $this->purgeDescription();
1579 if ( $wgUseSquid ) {
1581 wfImageArchiveUrl( $archiveName ),
1583 wfPurgeSquidServers( $urlArr );
1589 * Delete the current version of a file.
1590 * May throw a database error.
1591 * @return true on success, false on failure
1593 private function prepareDeleteCurrent( $reason, $suppress=false ) {
1594 return $this->prepareDeleteVersion(
1595 $this->getFullPath(),
1599 'fa_name' => 'img_name',
1600 'fa_archive_name' => 'NULL',
1601 'fa_size' => 'img_size',
1602 'fa_width' => 'img_width',
1603 'fa_height' => 'img_height',
1604 'fa_metadata' => 'img_metadata',
1605 'fa_bits' => 'img_bits',
1606 'fa_media_type' => 'img_media_type',
1607 'fa_major_mime' => 'img_major_mime',
1608 'fa_minor_mime' => 'img_minor_mime',
1609 'fa_description' => 'img_description',
1610 'fa_user' => 'img_user',
1611 'fa_user_text' => 'img_user_text',
1612 'fa_timestamp' => 'img_timestamp' ),
1613 array( 'img_name' => $this->name
),
1619 * Delete a given older version of a file.
1620 * May throw a database error.
1621 * @return true on success, false on failure
1623 private function prepareDeleteOld( $archiveName, $reason, $suppress=false ) {
1624 $oldpath = wfImageArchiveDir( $this->name
) .
1625 DIRECTORY_SEPARATOR
. $archiveName;
1626 return $this->prepareDeleteVersion(
1631 'fa_name' => 'oi_name',
1632 'fa_archive_name' => 'oi_archive_name',
1633 'fa_size' => 'oi_size',
1634 'fa_width' => 'oi_width',
1635 'fa_height' => 'oi_height',
1636 'fa_metadata' => 'NULL',
1637 'fa_bits' => 'oi_bits',
1638 'fa_media_type' => 'NULL',
1639 'fa_major_mime' => 'NULL',
1640 'fa_minor_mime' => 'NULL',
1641 'fa_description' => 'oi_description',
1642 'fa_user' => 'oi_user',
1643 'fa_user_text' => 'oi_user_text',
1644 'fa_timestamp' => 'oi_timestamp' ),
1646 'oi_name' => $this->name
,
1647 'oi_archive_name' => $archiveName ),
1653 * Do the dirty work of backing up an image row and its file
1654 * (if $wgSaveDeletedFiles is on) and removing the originals.
1656 * Must be run while the file store is locked and a database
1657 * transaction is open to avoid race conditions.
1659 * @return FSTransaction
1661 private function prepareDeleteVersion( $path, $reason, $table, $fieldMap, $where, $suppress=false, $fname ) {
1662 global $wgUser, $wgSaveDeletedFiles;
1664 // Dupe the file into the file store
1665 if( file_exists( $path ) ) {
1666 if( $wgSaveDeletedFiles ) {
1669 $store = FileStore
::get( $group );
1670 $key = FileStore
::calculateKey( $path, $this->extension
);
1671 $transaction = $store->insert( $key, $path,
1672 FileStore
::DELETE_ORIGINAL
);
1676 $transaction = FileStore
::deleteFile( $path );
1679 wfDebug( __METHOD__
." deleting already-missing '$path'; moving on to database\n" );
1682 $transaction = new FSTransaction(); // empty
1685 if( $transaction === false ) {
1687 wfDebug( __METHOD__
.": import to file store failed, aborting\n" );
1688 throw new MWException( "Could not archive and delete file $path" );
1692 // Bitfields to further supress the image content
1693 // Note that currently, live images are stored elsewhere
1694 // and cannot be partially deleted
1697 $bitfield |
= self
::DELETED_FILE
;
1698 $bitfield |
= self
::DELETED_COMMENT
;
1699 $bitfield |
= self
::DELETED_USER
;
1700 $bitfield |
= self
::DELETED_RESTRICTED
;
1703 $dbw = wfGetDB( DB_MASTER
);
1704 $storageMap = array(
1705 'fa_storage_group' => $dbw->addQuotes( $group ),
1706 'fa_storage_key' => $dbw->addQuotes( $key ),
1708 'fa_deleted_user' => $dbw->addQuotes( $wgUser->getId() ),
1709 'fa_deleted_timestamp' => $dbw->timestamp(),
1710 'fa_deleted_reason' => $dbw->addQuotes( $reason ),
1711 'fa_deleted' => $bitfield);
1712 $allFields = array_merge( $storageMap, $fieldMap );
1715 if( $wgSaveDeletedFiles ) {
1716 $dbw->insertSelect( 'filearchive', $table, $allFields, $where, $fname );
1718 $dbw->delete( $table, $where, $fname );
1719 } catch( DBQueryError
$e ) {
1720 // Something went horribly wrong!
1721 // Leave the file as it was...
1722 wfDebug( __METHOD__
.": database error, rolling back file transaction\n" );
1723 $transaction->rollback();
1727 return $transaction;
1731 * Restore all or specified deleted revisions to the given file.
1732 * Permissions and logging are left to the caller.
1734 * May throw database exceptions on error.
1736 * @param $versions set of record ids of deleted items to restore,
1737 * or empty to restore all revisions.
1738 * @return the number of file revisions restored if successful,
1739 * or false on failure
1741 function restore( $versions=array(), $Unsuppress=false ) {
1744 if( !FileStore
::lock() ) {
1745 wfDebug( __METHOD__
." could not acquire filestore lock\n" );
1749 $transaction = new FSTransaction();
1751 $dbw = wfGetDB( DB_MASTER
);
1754 // Re-confirm whether this image presently exists;
1755 // if no we'll need to create an image record for the
1756 // first item we restore.
1757 $exists = $dbw->selectField( 'image', '1',
1758 array( 'img_name' => $this->name
),
1761 // Fetch all or selected archived revisions for the file,
1762 // sorted from the most recent to the oldest.
1763 $conditions = array( 'fa_name' => $this->name
);
1765 $conditions['fa_id'] = $versions;
1768 $result = $dbw->select( 'filearchive', '*',
1771 array( 'ORDER BY' => 'fa_timestamp DESC' ) );
1773 if( $dbw->numRows( $result ) < count( $versions ) ) {
1774 // There's some kind of conflict or confusion;
1775 // we can't restore everything we were asked to.
1776 wfDebug( __METHOD__
.": couldn't find requested items\n" );
1778 FileStore
::unlock();
1782 if( $dbw->numRows( $result ) == 0 ) {
1784 wfDebug( __METHOD__
.": nothing to do\n" );
1786 FileStore
::unlock();
1791 while( $row = $dbw->fetchObject( $result ) ) {
1792 if ( $Unsuppress ) {
1793 // Currently, fa_deleted flags fall off upon restore, lets be careful about this
1794 } else if ( ($row->fa_deleted
& Revision
::DELETED_RESTRICTED
) && !$wgUser->isAllowed('hiderevision') ) {
1795 // Skip restoring file revisions that the user cannot restore
1799 $store = FileStore
::get( $row->fa_storage_group
);
1801 wfDebug( __METHOD__
.": skipping row with no file.\n" );
1805 if( $revisions == 1 && !$exists ) {
1806 $destDir = wfImageDir( $row->fa_name
);
1807 if ( !is_dir( $destDir ) ) {
1808 wfMkdirParents( $destDir );
1810 $destPath = $destDir . DIRECTORY_SEPARATOR
. $row->fa_name
;
1812 // We may have to fill in data if this was originally
1813 // an archived file revision.
1814 if( is_null( $row->fa_metadata
) ) {
1815 $tempFile = $store->filePath( $row->fa_storage_key
);
1817 $magic = MimeMagic
::singleton();
1818 $mime = $magic->guessMimeType( $tempFile, true );
1819 $media_type = $magic->getMediaType( $tempFile, $mime );
1820 list( $major_mime, $minor_mime ) = self
::splitMime( $mime );
1821 $handler = MediaHandler
::getHandler( $mime );
1823 $metadata = $handler->getMetadata( $image, $tempFile );
1828 $metadata = $row->fa_metadata
;
1829 $major_mime = $row->fa_major_mime
;
1830 $minor_mime = $row->fa_minor_mime
;
1831 $media_type = $row->fa_media_type
;
1836 'img_name' => $row->fa_name
,
1837 'img_size' => $row->fa_size
,
1838 'img_width' => $row->fa_width
,
1839 'img_height' => $row->fa_height
,
1840 'img_metadata' => $metadata,
1841 'img_bits' => $row->fa_bits
,
1842 'img_media_type' => $media_type,
1843 'img_major_mime' => $major_mime,
1844 'img_minor_mime' => $minor_mime,
1845 'img_description' => $row->fa_description
,
1846 'img_user' => $row->fa_user
,
1847 'img_user_text' => $row->fa_user_text
,
1848 'img_timestamp' => $row->fa_timestamp
);
1850 $archiveName = $row->fa_archive_name
;
1851 if( $archiveName == '' ) {
1852 // This was originally a current version; we
1853 // have to devise a new archive name for it.
1854 // Format is <timestamp of archiving>!<name>
1856 wfTimestamp( TS_MW
, $row->fa_deleted_timestamp
) .
1857 '!' . $row->fa_name
;
1859 $destDir = wfImageArchiveDir( $row->fa_name
);
1860 if ( !is_dir( $destDir ) ) {
1861 wfMkdirParents( $destDir );
1863 $destPath = $destDir . DIRECTORY_SEPARATOR
. $archiveName;
1865 $table = 'oldimage';
1867 'oi_name' => $row->fa_name
,
1868 'oi_archive_name' => $archiveName,
1869 'oi_size' => $row->fa_size
,
1870 'oi_width' => $row->fa_width
,
1871 'oi_height' => $row->fa_height
,
1872 'oi_bits' => $row->fa_bits
,
1873 'oi_description' => $row->fa_description
,
1874 'oi_user' => $row->fa_user
,
1875 'oi_user_text' => $row->fa_user_text
,
1876 'oi_timestamp' => $row->fa_timestamp
);
1879 $dbw->insert( $table, $fields, __METHOD__
);
1880 // @todo this delete is not totally safe, potentially
1881 $dbw->delete( 'filearchive',
1882 array( 'fa_id' => $row->fa_id
),
1885 // Check if any other stored revisions use this file;
1886 // if so, we shouldn't remove the file from the deletion
1887 // archives so they will still work.
1888 $useCount = $dbw->selectField( 'filearchive',
1891 'fa_storage_group' => $row->fa_storage_group
,
1892 'fa_storage_key' => $row->fa_storage_key
),
1894 if( $useCount == 0 ) {
1895 wfDebug( __METHOD__
.": nothing else using {$row->fa_storage_key}, will deleting after\n" );
1896 $flags = FileStore
::DELETE_ORIGINAL
;
1901 $transaction->add( $store->export( $row->fa_storage_key
,
1902 $destPath, $flags ) );
1905 $dbw->immediateCommit();
1906 } catch( MWException
$e ) {
1907 wfDebug( __METHOD__
." caught error, aborting\n" );
1908 $transaction->rollback();
1912 $transaction->commit();
1913 FileStore
::unlock();
1915 if( $revisions > 0 ) {
1917 wfDebug( __METHOD__
." restored $revisions items, creating a new current\n" );
1919 // Update site_stats
1920 $site_stats = $dbw->tableName( 'site_stats' );
1921 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images+1", __METHOD__
);
1923 $this->purgeEverything();
1925 wfDebug( __METHOD__
." restored $revisions as archived versions\n" );
1926 $this->purgeDescription();
1934 * Returns 'true' if this image is a multipage document, e.g. a DJVU
1939 function isMultipage() {
1940 $handler = $this->getHandler();
1941 return $handler && $handler->isMultiPage();
1945 * Returns the number of pages of a multipage document, or NULL for
1946 * documents which aren't multipage documents
1948 function pageCount() {
1949 $handler = $this->getHandler();
1950 if ( $handler && $handler->isMultiPage() ) {
1951 return $handler->pageCount( $this );
1957 static function getCommonsDB() {
1959 global $wgLoadBalancer, $wgSharedUploadDBname;
1960 if ( !isset( $dbc ) ) {
1961 $i = $wgLoadBalancer->getGroupIndex( 'commons' );
1962 $dbinfo = $wgLoadBalancer->mServers
[$i];
1963 $dbc = new Database( $dbinfo['host'], $dbinfo['user'],
1964 $dbinfo['password'], $wgSharedUploadDBname );
1970 * Calculate the height of a thumbnail using the source and destination width
1972 static function scaleHeight( $srcWidth, $srcHeight, $dstWidth ) {
1973 // Exact integer multiply followed by division
1974 if ( $srcWidth == 0 ) {
1977 return round( $srcHeight * $dstWidth / $srcWidth );
1982 * Get an image size array like that returned by getimagesize(), or false if it
1983 * can't be determined.
1985 * @param string $fileName The filename
1988 function getImageSize( $fileName ) {
1989 $handler = $this->getHandler();
1990 return $handler->getImageSize( $this, $fileName );
1994 * Get the thumbnail extension and MIME type for a given source MIME type
1995 * @return array thumbnail extension and MIME type
1997 static function getThumbType( $ext, $mime ) {
1998 $handler = MediaHandler
::getHandler( $mime );
2000 return $handler->getThumbType( $ext, $mime );
2002 return array( $ext, $mime );
2015 * Returns a file object from the filearchive table
2016 * In the future, all current and old image storage
2017 * may use FileStore. There will be a "old" storage
2018 * for current and previous file revisions as well as
2019 * the "deleted" group for archived revisions
2020 * @param $title, the corresponding image page title
2021 * @param $id, the image id, a unique key
2022 * @param $key, optional storage key
2023 * @return ResultWrapper
2025 function ArchivedFile( $title, $id=0, $key='' ) {
2026 if( !is_object( $title ) ) {
2027 throw new MWException( 'Image constructor given bogus title.' );
2029 $conds = ($id) ?
"fa_id = $id" : "fa_storage_key = '$key'";
2030 if( $title->getNamespace() == NS_IMAGE
) {
2031 $dbr = wfGetDB( DB_SLAVE
);
2032 $res = $dbr->select( 'filearchive',
2052 'fa_name' => $title->getDbKey(),
2055 array( 'ORDER BY' => 'fa_timestamp DESC' ) );
2057 if ( $dbr->numRows( $res ) == 0 ) {
2058 // this revision does not exist?
2061 $ret = $dbr->resultObject( $res );
2062 $row = $ret->fetchObject();
2064 // initialize fields for filestore image object
2065 $this->mId
= intval($row->fa_id
);
2066 $this->mName
= $row->fa_name
;
2067 $this->mGroup
= $row->fa_storage_group
;
2068 $this->mKey
= $row->fa_storage_key
;
2069 $this->mSize
= $row->fa_size
;
2070 $this->mBits
= $row->fa_bits
;
2071 $this->mWidth
= $row->fa_width
;
2072 $this->mHeight
= $row->fa_height
;
2073 $this->mMetaData
= $row->fa_metadata
;
2074 $this->mMime
= "$row->fa_major_mime/$row->fa_minor_mime";
2075 $this->mType
= $row->fa_media_type
;
2076 $this->mDescription
= $row->fa_description
;
2077 $this->mUser
= $row->fa_user
;
2078 $this->mUserText
= $row->fa_user_text
;
2079 $this->mTimestamp
= $row->fa_timestamp
;
2080 $this->mDeleted
= $row->fa_deleted
;
2082 throw new MWException( 'This title does not correspond to an image page.' );
2089 * int $field one of DELETED_* bitfield constants
2090 * for file or revision rows
2093 function isDeleted( $field ) {
2094 return ($this->mDeleted
& $field) == $field;
2098 * Determine if the current user is allowed to view a particular
2099 * field of this FileStore image file, if it's marked as deleted.
2103 function userCan( $field ) {
2104 if( isset($this->mDeleted
) && ($this->mDeleted
& $field) == $field ) {
2107 $permission = ( $this->mDeleted
& Revision
::DELETED_RESTRICTED
) == Revision
::DELETED_RESTRICTED
2110 wfDebug( "Checking for $permission due to $field match on $this->mDeleted\n" );
2111 return $wgUser->isAllowed( $permission );
2119 * Aliases for backwards compatibility with 1.6
2121 define( 'MW_IMG_DELETED_FILE', Image
::DELETED_FILE
);
2122 define( 'MW_IMG_DELETED_COMMENT', Image
::DELETED_COMMENT
);
2123 define( 'MW_IMG_DELETED_USER', Image
::DELETED_USER
);
2124 define( 'MW_IMG_DELETED_RESTRICTED', Image
::DELETED_RESTRICTED
);