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', 1 );
20 * Class to represent an image
22 * Provides methods to retrieve paths (physical, logical, URL),
23 * to generate thumbnails or for uploading.
27 const DELETED_FILE
= 1;
28 const DELETED_COMMENT
= 2;
29 const DELETED_USER
= 4;
30 const DELETED_RESTRICTED
= 8;
36 var $name, # name of the image (constructor)
37 $imagePath, # Path of the image (loadFromXxx)
38 $url, # Image URL (accessor)
39 $title, # Title object for this image (constructor)
40 $fileExists, # does the image file exist on disk? (loadFromXxx)
41 $fromSharedDirectory, # load this image from $wgSharedUploadDirectory (loadFromXxx)
42 $historyLine, # Number of line to return by nextHistoryLine() (constructor)
43 $historyRes, # result of the query for the image's history (nextHistoryLine)
46 $bits, # --- returned by getimagesize (loadFromXxx)
48 $type, # MEDIATYPE_xxx (bitmap, drawing, audio...)
49 $mime, # MIME type, determined by MimeMagic::guessMimeType
50 $extension, # The file extension (constructor)
51 $size, # Size in bytes (loadFromXxx)
53 $dataLoaded, # Whether or not all this has been loaded from the database (loadFromXxx)
54 $page, # Page to render when creating thumbnails
55 $lastError; # Error string associated with a thumbnail display error
61 * Create an Image object from an image name
63 * @param string $name name of the image, used to create a title object using Title::makeTitleSafe
66 public static function newFromName( $name ) {
67 $title = Title
::makeTitleSafe( NS_IMAGE
, $name );
68 if ( is_object( $title ) ) {
69 return new Image( $title );
76 * Obsolete factory function, use constructor
79 function newFromTitle( $title ) {
80 return new Image( $title );
83 function Image( $title ) {
84 if( !is_object( $title ) ) {
85 throw new MWException( 'Image constructor given bogus title.' );
87 $this->title
=& $title;
88 $this->name
= $title->getDBkey();
91 $n = strrpos( $this->name
, '.' );
92 $this->extension
= Image
::normalizeExtension( $n ?
93 substr( $this->name
, $n +
1 ) : '' );
94 $this->historyLine
= 0;
96 $this->dataLoaded
= false;
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 .)
106 static function normalizeExtension( $ext ) {
107 $lower = strtolower( $ext );
113 if( isset( $squish[$lower] ) ) {
114 return $squish[$lower];
115 } elseif( preg_match( '/^[0-9a-z]+$/', $lower ) ) {
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 );
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);
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' );
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;
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
231 // However we should clear them, so they aren't leftover
232 // if we've deleted the file.
233 $wgMemc->delete( $keys[0] );
238 * Load metadata from the file itself
240 function loadFromFile() {
241 global $wgUseSharedUploads, $wgSharedUploadDirectory, $wgContLang;
242 wfProfileIn( __METHOD__
);
243 $this->imagePath
= $this->getFullPath();
244 $this->fileExists
= file_exists( $this->imagePath
);
245 $this->fromSharedDirectory
= false;
248 if (!$this->fileExists
) wfDebug(__METHOD__
.': '.$this->imagePath
." not found locally!\n");
250 # If the file is not found, and a shared upload directory is used, look for it there.
251 if (!$this->fileExists
&& $wgUseSharedUploads && $wgSharedUploadDirectory) {
252 # In case we're on a wgCapitalLinks=false wiki, we
253 # capitalize the first letter of the filename before
254 # looking it up in the shared repository.
255 $sharedImage = Image
::newFromName( $wgContLang->ucfirst($this->name
) );
256 $this->fileExists
= $sharedImage && file_exists( $sharedImage->getFullPath(true) );
257 if ( $this->fileExists
) {
258 $this->name
= $sharedImage->name
;
259 $this->imagePath
= $this->getFullPath(true);
260 $this->fromSharedDirectory
= true;
265 if ( $this->fileExists
) {
266 $magic=& MimeMagic
::singleton();
268 $this->mime
= $magic->guessMimeType($this->imagePath
,true);
269 $this->type
= $magic->getMediaType($this->imagePath
,$this->mime
);
270 $handler = MediaHandler
::getHandler( $this->mime
);
273 $this->size
= filesize( $this->imagePath
);
275 # Height, width and metadata
277 $gis = $handler->getImageSize( $this, $this->imagePath
);
278 $this->metadata
= $handler->getMetadata( $this, $this->imagePath
);
281 $this->metadata
= '';
284 wfDebug(__METHOD__
.': '.$this->imagePath
." loaded, ".$this->size
." bytes, ".$this->mime
.".\n");
288 $this->type
= MEDIATYPE_UNKNOWN
;
289 $this->metadata
= '';
290 wfDebug(__METHOD__
.': '.$this->imagePath
." NOT FOUND!\n");
294 $this->width
= $gis[0];
295 $this->height
= $gis[1];
301 #NOTE: $gis[2] contains a code for the image type. This is no longer used.
303 #NOTE: we have to set this flag early to avoid load() to be called
304 # be some of the functions below. This may lead to recursion or other bad things!
305 # as ther's only one thread of execution, this should be safe anyway.
306 $this->dataLoaded
= true;
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__
);
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 $this->maybeUpgradeRow();
335 } elseif ( $wgUseSharedUploads && $wgSharedUploadDBname ) {
336 # In case we're on a wgCapitalLinks=false wiki, we
337 # capitalize the first letter of the filename before
338 # looking it up in the shared repository.
339 $name = $wgContLang->ucfirst($this->name
);
340 $dbc = Image
::getCommonsDB();
342 $row = $dbc->selectRow( "`$wgSharedUploadDBname`.{$wgSharedUploadDBprefix}image",
344 'img_size', 'img_width', 'img_height', 'img_bits',
345 'img_media_type', 'img_major_mime', 'img_minor_mime', 'img_metadata' ),
346 array( 'img_name' => $name ), __METHOD__
);
348 $this->fromSharedDirectory
= true;
349 $this->fileExists
= true;
350 $this->imagePath
= $this->getFullPath(true);
352 $this->loadFromRow( $row );
354 // Check for rows from a previous schema, quietly upgrade them
355 $this->maybeUpgradeRow();
365 $this->fileExists
= false;
366 $this->fromSharedDirectory
= false;
367 $this->metadata
= '';
371 # Unconditionally set loaded=true, we don't want the accessors constantly rechecking
372 $this->dataLoaded
= true;
373 wfProfileOut( __METHOD__
);
377 * Load image metadata from a DB result row
379 function loadFromRow( &$row ) {
380 $this->size
= $row->img_size
;
381 $this->width
= $row->img_width
;
382 $this->height
= $row->img_height
;
383 $this->bits
= $row->img_bits
;
384 $this->type
= $row->img_media_type
;
386 $major= $row->img_major_mime
;
387 $minor= $row->img_minor_mime
;
389 if (!$major) $this->mime
= "unknown/unknown";
391 if (!$minor) $minor= "unknown";
392 $this->mime
= $major.'/'.$minor;
394 $this->metadata
= $row->img_metadata
;
396 $this->dataLoaded
= true;
400 * Load image metadata from cache or DB, unless already loaded
403 global $wgSharedUploadDBname, $wgUseSharedUploads;
404 if ( !$this->dataLoaded
) {
405 if ( !$this->loadFromCache() ) {
407 if ( !$wgSharedUploadDBname && $wgUseSharedUploads ) {
408 $this->loadFromFile();
409 } elseif ( $this->fileExists ||
!$wgUseSharedUploads ) {
410 // We can do negative caching for local images, because the cache
411 // will be purged on upload. But we can't do it when shared images
412 // are enabled, since updates to that won't purge foreign caches.
413 $this->saveToCache();
416 $this->dataLoaded
= true;
421 * Upgrade a row if it needs it
423 function maybeUpgradeRow() {
424 if ( is_null($this->type
) ||
$this->mime
== 'image/svg' ) {
427 $handler = $this->getHandler();
428 if ( $handler && !$handler->isMetadataValid( $this, $this->metadata
) ) {
435 * Fix assorted version-related problems with the image row by reloading it from the file
437 function upgradeRow() {
438 global $wgDBname, $wgSharedUploadDBname;
439 wfProfileIn( __METHOD__
);
441 $this->loadFromFile();
443 if ( $this->fromSharedDirectory
) {
444 if ( !$wgSharedUploadDBname ) {
445 wfProfileOut( __METHOD__
);
449 // Write to the other DB using selectDB, not database selectors
450 // This avoids breaking replication in MySQL
451 $dbw = Image
::getCommonsDB();
453 $dbw = wfGetDB( DB_MASTER
);
456 $this->checkDBSchema($dbw);
458 list( $major, $minor ) = self
::splitMime( $this->mime
);
460 wfDebug(__METHOD__
.': upgrading '.$this->name
." to the current schema\n");
462 $dbw->update( 'image',
464 'img_width' => $this->width
,
465 'img_height' => $this->height
,
466 'img_bits' => $this->bits
,
467 'img_media_type' => $this->type
,
468 'img_major_mime' => $major,
469 'img_minor_mime' => $minor,
470 'img_metadata' => $this->metadata
,
471 ), array( 'img_name' => $this->name
), __METHOD__
473 if ( $this->fromSharedDirectory
) {
474 $dbw->selectDB( $wgDBname );
476 wfProfileOut( __METHOD__
);
480 * Split an internet media type into its two components; if not
481 * a two-part name, set the minor type to 'unknown'.
483 * @param $mime "text/html" etc
484 * @return array ("text", "html") etc
486 static function splitMime( $mime ) {
487 if( strpos( $mime, '/' ) !== false ) {
488 return explode( '/', $mime, 2 );
490 return array( $mime, 'unknown' );
495 * Return the name of this image
503 * Return the associated title object
506 function getTitle() {
511 * Return the URL of the image file
517 if($this->fileExists
) {
518 $this->url
= Image
::imageUrl( $this->name
, $this->fromSharedDirectory
);
526 function getViewURL() {
527 if( $this->mustRender()) {
528 if( $this->canRender() ) {
529 return $this->createThumb( $this->getWidth() );
532 wfDebug('Image::getViewURL(): supposed to render '.$this->name
.' ('.$this->mime
."), but can't!\n");
533 return $this->getURL(); #hm... return NULL?
536 return $this->getURL();
541 * Return the image path of the image in the
542 * local file system as an absolute path
545 function getImagePath() {
547 return $this->imagePath
;
551 * Return the width of the image
553 * Returns false on error
556 function getWidth( $page = 1 ) {
558 if ( $this->isMultipage() ) {
559 $dim = $this->getHandler()->getPageDimensions( $this, $page );
561 return $dim['width'];
571 * Return the height of the image
573 * Returns false on error
576 function getHeight( $page = 1 ) {
578 if ( $this->isMultipage() ) {
579 $dim = $this->getHandler()->getPageDimensions( $this, $page );
581 return $dim['height'];
586 return $this->height
;
591 * Get handler-specific metadata
593 function getMetadata() {
595 return $this->metadata
;
599 * Return the size of the image file, in bytes
608 * Returns the mime type of the file.
610 function getMimeType() {
616 * Return the type of the media in the file.
617 * Use the value returned by this function with the MEDIATYPE_xxx constants.
619 function getMediaType() {
625 * Checks if the file can be presented to the browser as a bitmap.
627 * Currently, this checks if the file is an image format
628 * that can be converted to a format
629 * supported by all browsers (namely GIF, PNG and JPEG),
630 * or if it is an SVG image and SVG conversion is enabled.
632 * @todo remember the result of this check.
634 function canRender() {
635 $handler = $this->getHandler();
636 return $handler && $handler->canRender();
640 * Return true if the file is of a type that can't be directly
641 * rendered by typical browsers and needs to be re-rasterized.
643 * This returns true for everything but the bitmap types
644 * supported by all browsers, i.e. JPEG; GIF and PNG. It will
645 * also return true for any non-image formats.
649 function mustRender() {
650 $handler = $this->getHandler();
651 return $handler && $handler->mustRender();
655 * Determines if this media file may be shown inline on a page.
657 * This is currently synonymous to canRender(), but this could be
658 * extended to also allow inline display of other media,
659 * like flash animations or videos. If you do so, please keep in mind that
660 * that could be a security risk.
662 function allowInlineDisplay() {
663 return $this->canRender();
667 * Determines if this media file is in a format that is unlikely to
668 * contain viruses or malicious content. It uses the global
669 * $wgTrustedMediaFormats list to determine if the file is safe.
671 * This is used to show a warning on the description page of non-safe files.
672 * It may also be used to disallow direct [[media:...]] links to such files.
674 * Note that this function will always return true if allowInlineDisplay()
675 * or isTrustedFile() is true for this file.
677 function isSafeFile() {
678 if ($this->allowInlineDisplay()) return true;
679 if ($this->isTrustedFile()) return true;
681 global $wgTrustedMediaFormats;
683 $type= $this->getMediaType();
684 $mime= $this->getMimeType();
685 #wfDebug("Image::isSafeFile: type= $type, mime= $mime\n");
687 if (!$type ||
$type===MEDIATYPE_UNKNOWN
) return false; #unknown type, not trusted
688 if ( in_array( $type, $wgTrustedMediaFormats) ) return true;
690 if ($mime==="unknown/unknown") return false; #unknown type, not trusted
691 if ( in_array( $mime, $wgTrustedMediaFormats) ) return true;
696 /** Returns true if the file is flagged as trusted. Files flagged that way
697 * can be linked to directly, even if that is not allowed for this type of
700 * This is a dummy function right now and always returns false. It could be
701 * implemented to extract a flag from the database. The trusted flag could be
702 * set on upload, if the user has sufficient privileges, to bypass script-
703 * and html-filters. It may even be coupled with cryptographics signatures
706 function isTrustedFile() {
707 #this could be implemented to check a flag in the databas,
708 #look for signatures, etc
713 * Return the escapeLocalURL of this image
716 function getEscapeLocalURL( $query=false) {
717 return $this->getTitle()->escapeLocalURL( $query );
721 * Return the escapeFullURL of this image
724 function getEscapeFullURL() {
726 return $this->title
->escapeFullURL();
730 * Return the URL of an image, provided its name.
732 * @param string $name Name of the image, without the leading "Image:"
733 * @param boolean $fromSharedDirectory Should this be in $wgSharedUploadPath?
734 * @return string URL of $name image
738 function imageUrl( $name, $fromSharedDirectory = false ) {
739 global $wgUploadPath,$wgUploadBaseUrl,$wgSharedUploadPath;
740 if($fromSharedDirectory) {
742 $path = $wgSharedUploadPath;
744 $base = $wgUploadBaseUrl;
745 $path = $wgUploadPath;
747 $url = "{$base}{$path}" . wfGetHashPath($name, $fromSharedDirectory) . "{$name}";
748 return wfUrlencode( $url );
752 * Returns true if the image file exists on disk.
753 * @return boolean Whether image file exist on disk.
758 return $this->fileExists
;
765 function thumbUrl( $thumbName ) {
766 global $wgUploadPath, $wgUploadBaseUrl, $wgSharedUploadPath;
767 if($this->fromSharedDirectory
) {
769 $path = $wgSharedUploadPath;
771 $base = $wgUploadBaseUrl;
772 $path = $wgUploadPath;
774 if ( Image
::isHashed( $this->fromSharedDirectory
) ) {
775 $url = "{$base}{$path}/thumb" .
776 wfGetHashPath($this->name
, $this->fromSharedDirectory
)
777 . $this->name
.'/'.$thumbName;
778 $url = wfUrlencode( $url );
780 $url = "{$base}{$path}/thumb/{$thumbName}";
785 function getTransformScript() {
786 global $wgSharedThumbnailScriptPath, $wgThumbnailScriptPath;
787 if ( $this->fromSharedDirectory
) {
788 $script = $wgSharedThumbnailScriptPath;
790 $script = $wgThumbnailScriptPath;
793 return "$script?f=" . urlencode( $this->name
);
800 * Get a ThumbnailImage which is the same size as the source
802 function getUnscaledThumb( $page = false ) {
806 'width' => $this->getWidth( $page )
809 $params = array( 'width' => $this->getWidth() );
811 return $this->transform( $params );
815 * Return the file name of a thumbnail with the specified parameters
817 * @param array $params Handler-specific parameters
820 function thumbName( $params ) {
821 $handler = $this->getHandler();
825 list( $thumbExt, $thumbMime ) = self
::getThumbType( $this->extension
, $this->mime
);
826 $thumbName = $handler->makeParamString( $params ) . '-' . $this->name
;
827 if ( $thumbExt != $this->extension
) {
828 $thumbName .= ".$thumbExt";
834 * Create a thumbnail of the image having the specified width/height.
835 * The thumbnail will not be created if the width is larger than the
836 * image's width. Let the browser do the scaling in this case.
837 * The thumbnail is stored on disk and is only computed if the thumbnail
838 * file does not exist OR if it is older than the image.
841 * Keeps aspect ratio of original image. If both width and height are
842 * specified, the generated image will be no bigger than width x height,
843 * and will also have correct aspect ratio.
845 * @param integer $width maximum width of the generated thumbnail
846 * @param integer $height maximum height of the image (optional)
849 function createThumb( $width, $height = -1 ) {
850 $params = array( 'width' => $width );
851 if ( $height != -1 ) {
852 $params['height'] = $height;
854 $thumb = $this->transform( $params );
855 if( is_null( $thumb ) ||
$thumb->isError() ) return '';
856 return $thumb->getUrl();
860 * As createThumb, but returns a ThumbnailImage object. This can
861 * provide access to the actual file, the real size of the thumb,
862 * and can produce a convenient <img> tag for you.
864 * For non-image formats, this may return a filetype-specific icon.
866 * @param integer $width maximum width of the generated thumbnail
867 * @param integer $height maximum height of the image (optional)
868 * @param boolean $render True to render the thumbnail if it doesn't exist,
869 * false to just return the URL
871 * @return ThumbnailImage or null on failure
874 * @deprecated use transform()
876 function getThumbnail( $width, $height=-1, $render = true ) {
877 $params = array( 'width' => $width );
878 if ( $height != -1 ) {
879 $params['height'] = $height;
881 $flags = $render ? self
::RENDER_NOW
: 0;
882 return $this->transform( $params, $flags );
886 * Transform a media file
888 * @param array $params An associative array of handler-specific parameters. Typical
889 * keys are width, height and page.
890 * @param integer $flags A bitfield, may contain self::RENDER_NOW to force rendering
891 * @return MediaTransformOutput
893 function transform( $params, $flags = 0 ) {
894 global $wgGenerateThumbnailOnParse, $wgUseSquid, $wgIgnoreImageErrors;
896 wfProfileIn( __METHOD__
);
898 $handler = $this->getHandler();
899 if ( !$handler ||
!$handler->canRender() ) {
900 // not a bitmap or renderable image, don't try.
901 $thumb = $this->iconThumb();
905 $script = $this->getTransformScript();
906 if ( $script && !($flags & self
::RENDER_NOW
) ) {
907 // Use a script to transform on client request
908 $thumb = $handler->getScriptedTransform( $this, $script, $params );
912 $handler->normaliseParams( $this, $params );
913 list( $thumbExt, $thumbMime ) = self
::getThumbType( $this->extension
, $this->mime
);
914 $thumbName = $this->thumbName( $params );
915 $thumbPath = wfImageThumbDir( $this->name
, $this->fromSharedDirectory
) . "/$thumbName";
916 $thumbUrl = $this->thumbUrl( $thumbName );
918 $this->migrateThumbFile( $thumbName );
920 if ( file_exists( $thumbPath ) ) {
921 $thumb = $handler->getTransform( $this, $thumbPath, $thumbUrl, $params );
925 if ( !$wgGenerateThumbnailOnParse && !($flags & self
::RENDER_NOW
) ) {
926 $thumb = $handler->getTransform( $this, $thumbPath, $thumbUrl, $params );
929 $thumb = $handler->doTransform( $this, $thumbPath, $thumbUrl, $params );
931 // Ignore errors if requested
934 } elseif ( $thumb->isError() ) {
935 $this->lastError
= $thumb->toText();
936 if ( $wgIgnoreImageErrors ) {
937 $thumb = $handler->getTransform( $this, $thumbPath, $thumbUrl, $params );
942 wfPurgeSquidServers( array( $thumbUrl ) );
946 wfProfileOut( __METHOD__
);
951 * Fix thumbnail files from 1.4 or before, with extreme prejudice
953 function migrateThumbFile( $thumbName ) {
954 $thumbDir = wfImageThumbDir( $this->name
, $this->fromSharedDirectory
);
955 $thumbPath = "$thumbDir/$thumbName";
956 if ( is_dir( $thumbPath ) ) {
957 // Directory where file should be
958 // This happened occasionally due to broken migration code in 1.5
959 // Rename to broken-*
960 global $wgUploadDirectory;
961 for ( $i = 0; $i < 100 ; $i++
) {
962 $broken = "$wgUploadDirectory/broken-$i-$thumbName";
963 if ( !file_exists( $broken ) ) {
964 rename( $thumbPath, $broken );
968 // Doesn't exist anymore
971 if ( is_file( $thumbDir ) ) {
972 // File where directory should be
974 // Doesn't exist anymore
980 * Get a MediaHandler instance for this image
982 function getHandler() {
983 return MediaHandler
::getHandler( $this->getMimeType() );
987 * Get a ThumbnailImage representing a file type icon
988 * @return ThumbnailImage
990 function iconThumb() {
991 global $wgStylePath, $wgStyleDirectory;
993 $try = array( 'fileicon-' . $this->extension
. '.png', 'fileicon.png' );
994 foreach( $try as $icon ) {
995 $path = '/common/images/icons/' . $icon;
996 $filepath = $wgStyleDirectory . $path;
997 if( file_exists( $filepath ) ) {
998 return new ThumbnailImage( $wgStylePath . $path, 120, 120 );
1005 * Get last thumbnailing error.
1008 function getLastError() {
1009 return $this->lastError
;
1013 * Get all thumbnail names previously generated for this image
1015 function getThumbnails( $shared = false ) {
1016 if ( Image
::isHashed( $shared ) ) {
1019 $dir = wfImageThumbDir( $this->name
, $shared );
1021 if ( is_dir( $dir ) ) {
1022 $handle = opendir( $dir );
1025 while ( false !== ( $file = readdir($handle) ) ) {
1026 if ( $file{0} != '.' ) {
1030 closedir( $handle );
1041 * Refresh metadata in memcached, but don't touch thumbnails or squid
1043 function purgeMetadataCache() {
1045 $this->upgradeRow();
1046 $this->saveToCache();
1050 * Delete all previously generated thumbnails, refresh metadata in memcached and purge the squid
1052 function purgeCache( $archiveFiles = array(), $shared = false ) {
1055 // Refresh metadata cache
1056 $this->purgeMetadataCache();
1058 // Delete thumbnails
1059 $files = $this->getThumbnails( $shared );
1060 $dir = wfImageThumbDir( $this->name
, $shared );
1062 foreach ( $files as $file ) {
1064 if ( preg_match( '/^(\d+)px/', $file, $m ) ) {
1065 $url = $this->thumbUrl( $m[1] );
1067 @unlink
( "$dir/$file" );
1072 if ( $wgUseSquid ) {
1073 $urls[] = $this->getURL();
1074 foreach ( $archiveFiles as $file ) {
1075 $urls[] = wfImageArchiveUrl( $file );
1077 wfPurgeSquidServers( $urls );
1082 * Purge the image description page, but don't go after
1083 * pages using the image. Use when modifying file history
1084 * but not the current data.
1086 function purgeDescription() {
1087 $page = Title
::makeTitle( NS_IMAGE
, $this->name
);
1088 $page->invalidateCache();
1089 $page->purgeSquid();
1093 * Purge metadata and all affected pages when the image is created,
1094 * deleted, or majorly updated. A set of additional URLs may be
1095 * passed to purge, such as specific image files which have changed.
1096 * @param $urlArray array
1098 function purgeEverything( $urlArr=array() ) {
1099 // Delete thumbnails and refresh image metadata cache
1100 $this->purgeCache();
1101 $this->purgeDescription();
1103 // Purge cache of all pages using this image
1104 $update = new HTMLCacheUpdate( $this->getTitle(), 'imagelinks' );
1105 $update->doUpdate();
1109 * Check the image table schema on the given connection for subtle problems
1111 function checkDBSchema(&$db) {
1112 static $checkDone = false;
1113 global $wgCheckDBSchema;
1114 if (!$wgCheckDBSchema ||
$checkDone) {
1117 # img_name must be unique
1118 if ( !$db->indexUnique( 'image', 'img_name' ) && !$db->indexExists('image','PRIMARY') ) {
1119 throw new MWException( 'Database schema not up to date, please run maintenance/archives/patch-image_name_unique.sql' );
1123 # new fields must exist
1125 # Not really, there's hundreds of checks like this that we could do and they're all pointless, because
1126 # if the fields are missing, the database will loudly report a query error, the first time you try to do
1127 # something. The only reason I put the above schema check in was because the absence of that particular
1128 # index would lead to an annoying subtle bug. No error message, just some very odd behaviour on duplicate
1131 if ( !$db->fieldExists( 'image', 'img_media_type' )
1132 || !$db->fieldExists( 'image', 'img_metadata' )
1133 || !$db->fieldExists( 'image', 'img_width' ) ) {
1135 throw new MWException( 'Database schema not up to date, please run maintenance/update.php' );
1141 * Return the image history of this image, line by line.
1142 * starts with current version, then old versions.
1143 * uses $this->historyLine to check which line to return:
1144 * 0 return line for current version
1145 * 1 query for old versions, return first one
1146 * 2, ... return next old version from above query
1150 function nextHistoryLine() {
1151 $dbr = wfGetDB( DB_SLAVE
);
1153 $this->checkDBSchema($dbr);
1155 if ( $this->historyLine
== 0 ) {// called for the first time, return line from cur
1156 $this->historyRes
= $dbr->select( 'image',
1160 'img_user','img_user_text',
1164 "'' AS oi_archive_name"
1166 array( 'img_name' => $this->title
->getDBkey() ),
1169 if ( 0 == $dbr->numRows( $this->historyRes
) ) {
1172 } else if ( $this->historyLine
== 1 ) {
1173 $this->historyRes
= $dbr->select( 'oldimage',
1175 'oi_size AS img_size',
1176 'oi_description AS img_description',
1177 'oi_user AS img_user',
1178 'oi_user_text AS img_user_text',
1179 'oi_timestamp AS img_timestamp',
1180 'oi_width as img_width',
1181 'oi_height as img_height',
1184 array( 'oi_name' => $this->title
->getDBkey() ),
1186 array( 'ORDER BY' => 'oi_timestamp DESC' )
1189 $this->historyLine ++
;
1191 return $dbr->fetchObject( $this->historyRes
);
1195 * Reset the history pointer to the first element of the history
1198 function resetHistory() {
1199 $this->historyLine
= 0;
1203 * Return the full filesystem path to the file. Note that this does
1204 * not mean that a file actually exists under that location.
1206 * This path depends on whether directory hashing is active or not,
1207 * i.e. whether the images are all found in the same directory,
1208 * or in hashed paths like /images/3/3c.
1211 * @param boolean $fromSharedDirectory Return the path to the file
1212 * in a shared repository (see $wgUseSharedRepository and related
1213 * options in DefaultSettings.php) instead of a local one.
1216 function getFullPath( $fromSharedRepository = false ) {
1217 global $wgUploadDirectory, $wgSharedUploadDirectory;
1219 $dir = $fromSharedRepository ?
$wgSharedUploadDirectory :
1222 // $wgSharedUploadDirectory may be false, if thumb.php is used
1224 $fullpath = $dir . wfGetHashPath($this->name
, $fromSharedRepository) . $this->name
;
1236 public static function isHashed( $shared ) {
1237 global $wgHashedUploadDirectory, $wgHashedSharedUploadDirectory;
1238 return $shared ?
$wgHashedSharedUploadDirectory : $wgHashedUploadDirectory;
1242 * Record an image upload in the upload log and the image table
1244 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '', $watch = false ) {
1245 global $wgUser, $wgUseCopyrightUpload;
1247 $dbw = wfGetDB( DB_MASTER
);
1249 $this->checkDBSchema($dbw);
1251 // Delete thumbnails and refresh the metadata cache
1252 $this->purgeCache();
1254 // Fail now if the image isn't there
1255 if ( !$this->fileExists ||
$this->fromSharedDirectory
) {
1256 wfDebug( "Image::recordUpload: File ".$this->imagePath
." went missing!\n" );
1260 if ( $wgUseCopyrightUpload ) {
1261 if ( $license != '' ) {
1262 $licensetxt = '== ' . wfMsgForContent( 'license' ) . " ==\n" . '{{' . $license . '}}' . "\n";
1264 $textdesc = '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $desc . "\n" .
1265 '== ' . wfMsgForContent ( 'filestatus' ) . " ==\n" . $copyStatus . "\n" .
1267 '== ' . wfMsgForContent ( 'filesource' ) . " ==\n" . $source ;
1269 if ( $license != '' ) {
1270 $filedesc = $desc == '' ?
'' : '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $desc . "\n";
1271 $textdesc = $filedesc .
1272 '== ' . wfMsgForContent ( 'license' ) . " ==\n" . '{{' . $license . '}}' . "\n";
1278 $now = $dbw->timestamp();
1281 if (strpos($this->mime
,'/')!==false) {
1282 list($major,$minor)= explode('/',$this->mime
,2);
1285 $major= $this->mime
;
1289 # Test to see if the row exists using INSERT IGNORE
1290 # This avoids race conditions by locking the row until the commit, and also
1291 # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition.
1292 $dbw->insert( 'image',
1294 'img_name' => $this->name
,
1295 'img_size'=> $this->size
,
1296 'img_width' => intval( $this->width
),
1297 'img_height' => intval( $this->height
),
1298 'img_bits' => $this->bits
,
1299 'img_media_type' => $this->type
,
1300 'img_major_mime' => $major,
1301 'img_minor_mime' => $minor,
1302 'img_timestamp' => $now,
1303 'img_description' => $desc,
1304 'img_user' => $wgUser->getID(),
1305 'img_user_text' => $wgUser->getName(),
1306 'img_metadata' => $this->metadata
,
1312 if( $dbw->affectedRows() == 0 ) {
1313 # Collision, this is an update of an image
1314 # Insert previous contents into oldimage
1315 $dbw->insertSelect( 'oldimage', 'image',
1317 'oi_name' => 'img_name',
1318 'oi_archive_name' => $dbw->addQuotes( $oldver ),
1319 'oi_size' => 'img_size',
1320 'oi_width' => 'img_width',
1321 'oi_height' => 'img_height',
1322 'oi_bits' => 'img_bits',
1323 'oi_timestamp' => 'img_timestamp',
1324 'oi_description' => 'img_description',
1325 'oi_user' => 'img_user',
1326 'oi_user_text' => 'img_user_text',
1327 ), array( 'img_name' => $this->name
), __METHOD__
1330 # Update the current image row
1331 $dbw->update( 'image',
1333 'img_size' => $this->size
,
1334 'img_width' => intval( $this->width
),
1335 'img_height' => intval( $this->height
),
1336 'img_bits' => $this->bits
,
1337 'img_media_type' => $this->type
,
1338 'img_major_mime' => $major,
1339 'img_minor_mime' => $minor,
1340 'img_timestamp' => $now,
1341 'img_description' => $desc,
1342 'img_user' => $wgUser->getID(),
1343 'img_user_text' => $wgUser->getName(),
1344 'img_metadata' => $this->metadata
,
1345 ), array( /* WHERE */
1346 'img_name' => $this->name
1350 # This is a new image
1351 # Update the image count
1352 $site_stats = $dbw->tableName( 'site_stats' );
1353 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images+1", __METHOD__
);
1356 $descTitle = $this->getTitle();
1357 $article = new Article( $descTitle );
1359 $watch = $watch ||
$wgUser->isWatched( $descTitle );
1360 $suppressRC = true; // There's already a log entry, so don't double the RC load
1362 if( $descTitle->exists() ) {
1363 // TODO: insert a null revision into the page history for this update.
1365 $wgUser->addWatch( $descTitle );
1368 # Invalidate the cache for the description page
1369 $descTitle->invalidateCache();
1370 $descTitle->purgeSquid();
1372 // New image; create the description page.
1373 $article->insertNewArticle( $textdesc, $desc, $minor, $watch, $suppressRC );
1376 # Hooks, hooks, the magic of hooks...
1377 wfRunHooks( 'FileUpload', array( $this ) );
1380 $log = new LogPage( 'upload' );
1381 $log->addEntry( 'upload', $descTitle, $desc );
1383 # Commit the transaction now, in case something goes wrong later
1384 # The most important thing is that images don't get lost, especially archives
1385 $dbw->immediateCommit();
1387 # Invalidate cache for all pages using this image
1388 $update = new HTMLCacheUpdate( $this->getTitle(), 'imagelinks' );
1389 $update->doUpdate();
1395 * Get an array of Title objects which are articles which use this image
1396 * Also adds their IDs to the link cache
1398 * This is mostly copied from Title::getLinksTo()
1400 * @deprecated Use HTMLCacheUpdate, this function uses too much memory
1402 function getLinksTo( $options = '' ) {
1403 wfProfileIn( __METHOD__
);
1406 $db = wfGetDB( DB_MASTER
);
1408 $db = wfGetDB( DB_SLAVE
);
1410 $linkCache =& LinkCache
::singleton();
1412 list( $page, $imagelinks ) = $db->tableNamesN( 'page', 'imagelinks' );
1413 $encName = $db->addQuotes( $this->name
);
1414 $sql = "SELECT page_namespace,page_title,page_id FROM $page,$imagelinks WHERE page_id=il_from AND il_to=$encName $options";
1415 $res = $db->query( $sql, __METHOD__
);
1418 if ( $db->numRows( $res ) ) {
1419 while ( $row = $db->fetchObject( $res ) ) {
1420 if ( $titleObj = Title
::makeTitle( $row->page_namespace
, $row->page_title
) ) {
1421 $linkCache->addGoodLinkObj( $row->page_id
, $titleObj );
1422 $retVal[] = $titleObj;
1426 $db->freeResult( $res );
1427 wfProfileOut( __METHOD__
);
1431 function getExifData() {
1433 $handler = $this->getHandler();
1434 if ( !$handler ||
$handler->getMetadataType( $this ) != 'exif' ) {
1437 if ( !$this->metadata
) {
1440 $exif = unserialize( $this->metadata
);
1444 $format = new FormatExif( $exif );
1446 return $format->getFormattedData();
1450 * Returns true if the image does not come from the shared
1455 function isLocal() {
1456 return !$this->fromSharedDirectory
;
1460 * Was this image ever deleted from the wiki?
1464 function wasDeleted() {
1465 $title = Title
::makeTitle( NS_IMAGE
, $this->name
);
1466 return ( $title->isDeleted() > 0 );
1470 * Delete all versions of the image.
1472 * Moves the files into an archive directory (or deletes them)
1473 * and removes the database rows.
1475 * Cache purging is done; logging is caller's responsibility.
1478 * @return true on success, false on some kind of failure
1480 function delete( $reason, $suppress=false ) {
1481 $transaction = new FSTransaction();
1482 $urlArr = array( $this->getURL() );
1484 if( !FileStore
::lock() ) {
1485 wfDebug( __METHOD__
.": failed to acquire file store lock, aborting\n" );
1490 $dbw = wfGetDB( DB_MASTER
);
1493 // Delete old versions
1494 $result = $dbw->select( 'oldimage',
1495 array( 'oi_archive_name' ),
1496 array( 'oi_name' => $this->name
) );
1498 while( $row = $dbw->fetchObject( $result ) ) {
1499 $oldName = $row->oi_archive_name
;
1501 $transaction->add( $this->prepareDeleteOld( $oldName, $reason, $suppress ) );
1503 // We'll need to purge this URL from caches...
1504 $urlArr[] = wfImageArchiveUrl( $oldName );
1506 $dbw->freeResult( $result );
1508 // And the current version...
1509 $transaction->add( $this->prepareDeleteCurrent( $reason, $suppress ) );
1511 $dbw->immediateCommit();
1512 } catch( MWException
$e ) {
1513 wfDebug( __METHOD__
.": db error, rolling back file transactions\n" );
1514 $transaction->rollback();
1515 FileStore
::unlock();
1519 wfDebug( __METHOD__
.": deleted db items, applying file transactions\n" );
1520 $transaction->commit();
1521 FileStore
::unlock();
1524 // Update site_stats
1525 $site_stats = $dbw->tableName( 'site_stats' );
1526 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images-1", __METHOD__
);
1528 $this->purgeEverything( $urlArr );
1535 * Delete an old version of the image.
1537 * Moves the file into an archive directory (or deletes it)
1538 * and removes the database row.
1540 * Cache purging is done; logging is caller's responsibility.
1543 * @throws MWException or FSException on database or filestore failure
1544 * @return true on success, false on some kind of failure
1546 function deleteOld( $archiveName, $reason, $suppress=false ) {
1547 $transaction = new FSTransaction();
1550 if( !FileStore
::lock() ) {
1551 wfDebug( __METHOD__
.": failed to acquire file store lock, aborting\n" );
1555 $transaction = new FSTransaction();
1557 $dbw = wfGetDB( DB_MASTER
);
1559 $transaction->add( $this->prepareDeleteOld( $archiveName, $reason, $suppress ) );
1560 $dbw->immediateCommit();
1561 } catch( MWException
$e ) {
1562 wfDebug( __METHOD__
.": db error, rolling back file transaction\n" );
1563 $transaction->rollback();
1564 FileStore
::unlock();
1568 wfDebug( __METHOD__
.": deleted db items, applying file transaction\n" );
1569 $transaction->commit();
1570 FileStore
::unlock();
1572 $this->purgeDescription();
1576 if ( $wgUseSquid ) {
1578 wfImageArchiveUrl( $archiveName ),
1580 wfPurgeSquidServers( $urlArr );
1586 * Delete the current version of a file.
1587 * May throw a database error.
1588 * @return true on success, false on failure
1590 private function prepareDeleteCurrent( $reason, $suppress=false ) {
1591 return $this->prepareDeleteVersion(
1592 $this->getFullPath(),
1596 'fa_name' => 'img_name',
1597 'fa_archive_name' => 'NULL',
1598 'fa_size' => 'img_size',
1599 'fa_width' => 'img_width',
1600 'fa_height' => 'img_height',
1601 'fa_metadata' => 'img_metadata',
1602 'fa_bits' => 'img_bits',
1603 'fa_media_type' => 'img_media_type',
1604 'fa_major_mime' => 'img_major_mime',
1605 'fa_minor_mime' => 'img_minor_mime',
1606 'fa_description' => 'img_description',
1607 'fa_user' => 'img_user',
1608 'fa_user_text' => 'img_user_text',
1609 'fa_timestamp' => 'img_timestamp' ),
1610 array( 'img_name' => $this->name
),
1616 * Delete a given older version of a file.
1617 * May throw a database error.
1618 * @return true on success, false on failure
1620 private function prepareDeleteOld( $archiveName, $reason, $suppress=false ) {
1621 $oldpath = wfImageArchiveDir( $this->name
) .
1622 DIRECTORY_SEPARATOR
. $archiveName;
1623 return $this->prepareDeleteVersion(
1628 'fa_name' => 'oi_name',
1629 'fa_archive_name' => 'oi_archive_name',
1630 'fa_size' => 'oi_size',
1631 'fa_width' => 'oi_width',
1632 'fa_height' => 'oi_height',
1633 'fa_metadata' => 'NULL',
1634 'fa_bits' => 'oi_bits',
1635 'fa_media_type' => 'NULL',
1636 'fa_major_mime' => 'NULL',
1637 'fa_minor_mime' => 'NULL',
1638 'fa_description' => 'oi_description',
1639 'fa_user' => 'oi_user',
1640 'fa_user_text' => 'oi_user_text',
1641 'fa_timestamp' => 'oi_timestamp' ),
1643 'oi_name' => $this->name
,
1644 'oi_archive_name' => $archiveName ),
1650 * Do the dirty work of backing up an image row and its file
1651 * (if $wgSaveDeletedFiles is on) and removing the originals.
1653 * Must be run while the file store is locked and a database
1654 * transaction is open to avoid race conditions.
1656 * @return FSTransaction
1658 private function prepareDeleteVersion( $path, $reason, $table, $fieldMap, $where, $suppress=false, $fname ) {
1659 global $wgUser, $wgSaveDeletedFiles;
1661 // Dupe the file into the file store
1662 if( file_exists( $path ) ) {
1663 if( $wgSaveDeletedFiles ) {
1666 $store = FileStore
::get( $group );
1667 $key = FileStore
::calculateKey( $path, $this->extension
);
1668 $transaction = $store->insert( $key, $path,
1669 FileStore
::DELETE_ORIGINAL
);
1673 $transaction = FileStore
::deleteFile( $path );
1676 wfDebug( __METHOD__
." deleting already-missing '$path'; moving on to database\n" );
1679 $transaction = new FSTransaction(); // empty
1682 if( $transaction === false ) {
1684 wfDebug( __METHOD__
.": import to file store failed, aborting\n" );
1685 throw new MWException( "Could not archive and delete file $path" );
1689 // Bitfields to further supress the image content
1690 // Note that currently, live images are stored elsewhere
1691 // and cannot be partially deleted
1694 $bitfield |
= self
::DELETED_FILE
;
1695 $bitfield |
= self
::DELETED_COMMENT
;
1696 $bitfield |
= self
::DELETED_USER
;
1697 $bitfield |
= self
::DELETED_RESTRICTED
;
1700 $dbw = wfGetDB( DB_MASTER
);
1701 $storageMap = array(
1702 'fa_storage_group' => $dbw->addQuotes( $group ),
1703 'fa_storage_key' => $dbw->addQuotes( $key ),
1705 'fa_deleted_user' => $dbw->addQuotes( $wgUser->getId() ),
1706 'fa_deleted_timestamp' => $dbw->timestamp(),
1707 'fa_deleted_reason' => $dbw->addQuotes( $reason ),
1708 'fa_deleted' => $bitfield);
1709 $allFields = array_merge( $storageMap, $fieldMap );
1712 if( $wgSaveDeletedFiles ) {
1713 $dbw->insertSelect( 'filearchive', $table, $allFields, $where, $fname );
1715 $dbw->delete( $table, $where, $fname );
1716 } catch( DBQueryError
$e ) {
1717 // Something went horribly wrong!
1718 // Leave the file as it was...
1719 wfDebug( __METHOD__
.": database error, rolling back file transaction\n" );
1720 $transaction->rollback();
1724 return $transaction;
1728 * Restore all or specified deleted revisions to the given file.
1729 * Permissions and logging are left to the caller.
1731 * May throw database exceptions on error.
1733 * @param $versions set of record ids of deleted items to restore,
1734 * or empty to restore all revisions.
1735 * @return the number of file revisions restored if successful,
1736 * or false on failure
1738 function restore( $versions=array(), $Unsuppress=false ) {
1741 if( !FileStore
::lock() ) {
1742 wfDebug( __METHOD__
." could not acquire filestore lock\n" );
1746 $transaction = new FSTransaction();
1748 $dbw = wfGetDB( DB_MASTER
);
1751 // Re-confirm whether this image presently exists;
1752 // if no we'll need to create an image record for the
1753 // first item we restore.
1754 $exists = $dbw->selectField( 'image', '1',
1755 array( 'img_name' => $this->name
),
1758 // Fetch all or selected archived revisions for the file,
1759 // sorted from the most recent to the oldest.
1760 $conditions = array( 'fa_name' => $this->name
);
1762 $conditions['fa_id'] = $versions;
1765 $result = $dbw->select( 'filearchive', '*',
1768 array( 'ORDER BY' => 'fa_timestamp DESC' ) );
1770 if( $dbw->numRows( $result ) < count( $versions ) ) {
1771 // There's some kind of conflict or confusion;
1772 // we can't restore everything we were asked to.
1773 wfDebug( __METHOD__
.": couldn't find requested items\n" );
1775 FileStore
::unlock();
1779 if( $dbw->numRows( $result ) == 0 ) {
1781 wfDebug( __METHOD__
.": nothing to do\n" );
1783 FileStore
::unlock();
1788 while( $row = $dbw->fetchObject( $result ) ) {
1789 if ( $Unsuppress ) {
1790 // Currently, fa_deleted flags fall off upon restore, lets be careful about this
1791 } else if ( ($row->fa_deleted
& Revision
::DELETED_RESTRICTED
) && !$wgUser->isAllowed('hiderevision') ) {
1792 // Skip restoring file revisions that the user cannot restore
1796 $store = FileStore
::get( $row->fa_storage_group
);
1798 wfDebug( __METHOD__
.": skipping row with no file.\n" );
1802 if( $revisions == 1 && !$exists ) {
1803 $destDir = wfImageDir( $row->fa_name
);
1804 if ( !is_dir( $destDir ) ) {
1805 wfMkdirParents( $destDir );
1807 $destPath = $destDir . DIRECTORY_SEPARATOR
. $row->fa_name
;
1809 // We may have to fill in data if this was originally
1810 // an archived file revision.
1811 if( is_null( $row->fa_metadata
) ) {
1812 $tempFile = $store->filePath( $row->fa_storage_key
);
1814 $magic = MimeMagic
::singleton();
1815 $mime = $magic->guessMimeType( $tempFile, true );
1816 $media_type = $magic->getMediaType( $tempFile, $mime );
1817 list( $major_mime, $minor_mime ) = self
::splitMime( $mime );
1818 $handler = MediaHandler
::getHandler( $mime );
1820 $metadata = $handler->getMetadata( $image, $tempFile );
1825 $metadata = $row->fa_metadata
;
1826 $major_mime = $row->fa_major_mime
;
1827 $minor_mime = $row->fa_minor_mime
;
1828 $media_type = $row->fa_media_type
;
1833 'img_name' => $row->fa_name
,
1834 'img_size' => $row->fa_size
,
1835 'img_width' => $row->fa_width
,
1836 'img_height' => $row->fa_height
,
1837 'img_metadata' => $metadata,
1838 'img_bits' => $row->fa_bits
,
1839 'img_media_type' => $media_type,
1840 'img_major_mime' => $major_mime,
1841 'img_minor_mime' => $minor_mime,
1842 'img_description' => $row->fa_description
,
1843 'img_user' => $row->fa_user
,
1844 'img_user_text' => $row->fa_user_text
,
1845 'img_timestamp' => $row->fa_timestamp
);
1847 $archiveName = $row->fa_archive_name
;
1848 if( $archiveName == '' ) {
1849 // This was originally a current version; we
1850 // have to devise a new archive name for it.
1851 // Format is <timestamp of archiving>!<name>
1853 wfTimestamp( TS_MW
, $row->fa_deleted_timestamp
) .
1854 '!' . $row->fa_name
;
1856 $destDir = wfImageArchiveDir( $row->fa_name
);
1857 if ( !is_dir( $destDir ) ) {
1858 wfMkdirParents( $destDir );
1860 $destPath = $destDir . DIRECTORY_SEPARATOR
. $archiveName;
1862 $table = 'oldimage';
1864 'oi_name' => $row->fa_name
,
1865 'oi_archive_name' => $archiveName,
1866 'oi_size' => $row->fa_size
,
1867 'oi_width' => $row->fa_width
,
1868 'oi_height' => $row->fa_height
,
1869 'oi_bits' => $row->fa_bits
,
1870 'oi_description' => $row->fa_description
,
1871 'oi_user' => $row->fa_user
,
1872 'oi_user_text' => $row->fa_user_text
,
1873 'oi_timestamp' => $row->fa_timestamp
);
1876 $dbw->insert( $table, $fields, __METHOD__
);
1877 // @todo this delete is not totally safe, potentially
1878 $dbw->delete( 'filearchive',
1879 array( 'fa_id' => $row->fa_id
),
1882 // Check if any other stored revisions use this file;
1883 // if so, we shouldn't remove the file from the deletion
1884 // archives so they will still work.
1885 $useCount = $dbw->selectField( 'filearchive',
1888 'fa_storage_group' => $row->fa_storage_group
,
1889 'fa_storage_key' => $row->fa_storage_key
),
1891 if( $useCount == 0 ) {
1892 wfDebug( __METHOD__
.": nothing else using {$row->fa_storage_key}, will deleting after\n" );
1893 $flags = FileStore
::DELETE_ORIGINAL
;
1898 $transaction->add( $store->export( $row->fa_storage_key
,
1899 $destPath, $flags ) );
1902 $dbw->immediateCommit();
1903 } catch( MWException
$e ) {
1904 wfDebug( __METHOD__
." caught error, aborting\n" );
1905 $transaction->rollback();
1909 $transaction->commit();
1910 FileStore
::unlock();
1912 if( $revisions > 0 ) {
1914 wfDebug( __METHOD__
." restored $revisions items, creating a new current\n" );
1916 // Update site_stats
1917 $site_stats = $dbw->tableName( 'site_stats' );
1918 $dbw->query( "UPDATE $site_stats SET ss_images=ss_images+1", __METHOD__
);
1920 $this->purgeEverything();
1922 wfDebug( __METHOD__
." restored $revisions as archived versions\n" );
1923 $this->purgeDescription();
1931 * Returns 'true' if this image is a multipage document, e.g. a DJVU
1936 function isMultipage() {
1937 $handler = $this->getHandler();
1938 return $handler && $handler->isMultiPage();
1942 * Returns the number of pages of a multipage document, or NULL for
1943 * documents which aren't multipage documents
1945 function pageCount() {
1946 $handler = $this->getHandler();
1947 if ( $handler && $handler->isMultiPage() ) {
1948 return $handler->pageCount( $this );
1954 static function getCommonsDB() {
1956 global $wgLoadBalancer, $wgSharedUploadDBname;
1957 if ( !isset( $dbc ) ) {
1958 $i = $wgLoadBalancer->getGroupIndex( 'commons' );
1959 $dbinfo = $wgLoadBalancer->mServers
[$i];
1960 $dbc = new Database( $dbinfo['host'], $dbinfo['user'],
1961 $dbinfo['password'], $wgSharedUploadDBname );
1967 * Calculate the height of a thumbnail using the source and destination width
1969 static function scaleHeight( $srcWidth, $srcHeight, $dstWidth ) {
1970 // Exact integer multiply followed by division
1971 if ( $srcWidth == 0 ) {
1974 return round( $srcHeight * $dstWidth / $srcWidth );
1979 * Get an image size array like that returned by getimagesize(), or false if it
1980 * can't be determined.
1982 * @param string $fileName The filename
1985 function getImageSize( $fileName ) {
1986 $handler = $this->getHandler();
1987 return $handler->getImageSize( $this, $fileName );
1991 * Get the thumbnail extension and MIME type for a given source MIME type
1992 * @return array thumbnail extension and MIME type
1994 static function getThumbType( $ext, $mime ) {
1995 $handler = MediaHandler
::getHandler( $mime );
1997 return $handler->getThumbType( $ext, $mime );
1999 return array( $ext, $mime );
2008 * Returns a file object from the filearchive table
2009 * In the future, all current and old image storage
2010 * may use FileStore. There will be a "old" storage
2011 * for current and previous file revisions as well as
2012 * the "deleted" group for archived revisions
2013 * @param $title, the corresponding image page title
2014 * @param $id, the image id, a unique key
2015 * @param $key, optional storage key
2016 * @return ResultWrapper
2018 function ArchivedFile( $title, $id=0, $key='' ) {
2019 if( !is_object( $title ) ) {
2020 throw new MWException( 'Image constructor given bogus title.' );
2022 $conds = ($id) ?
"fa_id = $id" : "fa_storage_key = '$key'";
2023 if( $title->getNamespace() == NS_IMAGE
) {
2024 $dbr = wfGetDB( DB_SLAVE
);
2025 $res = $dbr->select( 'filearchive',
2045 'fa_name' => $title->getDbKey(),
2048 array( 'ORDER BY' => 'fa_timestamp DESC' ) );
2050 if ( $dbr->numRows( $res ) == 0 ) {
2051 // this revision does not exist?
2054 $ret = $dbr->resultObject( $res );
2055 $row = $ret->fetchObject();
2057 // initialize fields for filestore image object
2058 $this->mId
= intval($row->fa_id
);
2059 $this->mName
= $row->fa_name
;
2060 $this->mGroup
= $row->fa_storage_group
;
2061 $this->mKey
= $row->fa_storage_key
;
2062 $this->mSize
= $row->fa_size
;
2063 $this->mBits
= $row->fa_bits
;
2064 $this->mWidth
= $row->fa_width
;
2065 $this->mHeight
= $row->fa_height
;
2066 $this->mMetaData
= $row->fa_metadata
;
2067 $this->mMime
= "$row->fa_major_mime/$row->fa_minor_mime";
2068 $this->mType
= $row->fa_media_type
;
2069 $this->mDescription
= $row->fa_description
;
2070 $this->mUser
= $row->fa_user
;
2071 $this->mUserText
= $row->fa_user_text
;
2072 $this->mTimestamp
= $row->fa_timestamp
;
2073 $this->mDeleted
= $row->fa_deleted
;
2075 throw new MWException( 'This title does not correspond to an image page.' );
2082 * int $field one of DELETED_* bitfield constants
2083 * for file or revision rows
2086 function isDeleted( $field ) {
2087 return ($this->mDeleted
& $field) == $field;
2091 * Determine if the current user is allowed to view a particular
2092 * field of this FileStore image file, if it's marked as deleted.
2096 function userCan( $field ) {
2097 if( isset($this->mDeleted
) && ($this->mDeleted
& $field) == $field ) {
2100 $permission = ( $this->mDeleted
& Revision
::DELETED_RESTRICTED
) == Revision
::DELETED_RESTRICTED
2103 wfDebug( "Checking for $permission due to $field match on $this->mDeleted\n" );
2104 return $wgUser->isAllowed( $permission );
2112 * Aliases for backwards compatibility with 1.6
2114 define( 'MW_IMG_DELETED_FILE', Image
::DELETED_FILE
);
2115 define( 'MW_IMG_DELETED_COMMENT', Image
::DELETED_COMMENT
);
2116 define( 'MW_IMG_DELETED_USER', Image
::DELETED_USER
);
2117 define( 'MW_IMG_DELETED_RESTRICTED', Image
::DELETED_RESTRICTED
);