4 * Base file class. Do not instantiate.
6 * Implements some public methods and some protected utility functions which
7 * are required by multiple child classes. Contains stub functionality for
8 * unimplemented public methods.
10 * Stub functions which should be overridden are marked with STUB. Some more
11 * concrete functions are also typically overridden by child classes.
13 * Note that only the repo object knows what its file class is called. You should
14 * never name a file class explictly outside of the repo class. Instead use the
15 * repo's factory functions to generate file objects, for example:
17 * RepoGroup::singleton()->getLocalRepo()->newFile($title);
19 * The convenience functions wfLocalFile() and wfFindFile() should be sufficient
22 * @addtogroup FileRepo
25 const DELETED_FILE
= 1;
26 const DELETED_COMMENT
= 2;
27 const DELETED_USER
= 4;
28 const DELETED_RESTRICTED
= 8;
31 const DELETE_SOURCE
= 1;
34 * Some member variables can be lazy-initialised using __get(). The
35 * initialisation function for these variables is always a function named
36 * like getVar(), where Var is the variable name with upper-case first
39 * The following variables are initialised in this way in this base class:
40 * name, extension, handler, path, canRender, isSafeFile,
41 * transformScript, hashPath, pageCount, url
43 * Code within this class should generally use the accessor function
44 * directly, since __get() isn't re-entrant and therefore causes bugs that
45 * depend on initialisation order.
49 * The following member variables are not lazy-initialised
51 var $repo, $title, $lastError;
54 * Call this constructor from child classes
56 function __construct( $title, $repo ) {
57 $this->title
= $title;
61 function __get( $name ) {
62 $function = array( $this, 'get' . ucfirst( $name ) );
63 if ( !is_callable( $function ) ) {
66 $this->$name = call_user_func( $function );
72 * Normalize a file extension to the common form, and ensure it's clean.
73 * Extensions with non-alphanumeric characters will be discarded.
75 * @param $ext string (without the .)
78 static function normalizeExtension( $ext ) {
79 $lower = strtolower( $ext );
85 if( isset( $squish[$lower] ) ) {
86 return $squish[$lower];
87 } elseif( preg_match( '/^[0-9a-z]+$/', $lower ) ) {
95 * Upgrade the database row if there is one
99 function upgradeRow() {}
102 * Split an internet media type into its two components; if not
103 * a two-part name, set the minor type to 'unknown'.
105 * @param $mime "text/html" etc
106 * @return array ("text", "html") etc
108 static function splitMime( $mime ) {
109 if( strpos( $mime, '/' ) !== false ) {
110 return explode( '/', $mime, 2 );
112 return array( $mime, 'unknown' );
117 * Return the name of this file
121 if ( !isset( $this->name
) ) {
122 $this->name
= $this->repo
->getNameFromTitle( $this->title
);
128 * Get the file extension, e.g. "svg"
130 function getExtension() {
131 if ( !isset( $this->extension
) ) {
132 $n = strrpos( $this->getName(), '.' );
133 $this->extension
= self
::normalizeExtension(
134 $n ?
substr( $this->getName(), $n +
1 ) : '' );
136 return $this->extension
;
140 * Return the associated title object
143 function getTitle() { return $this->title
; }
146 * Return the URL of the file
150 if ( !isset( $this->url
) ) {
151 $this->url
= $this->repo
->getZoneUrl( 'public' ) . '/' . $this->getUrlRel();
156 function getViewURL() {
157 if( $this->mustRender()) {
158 if( $this->canRender() ) {
159 return $this->createThumb( $this->getWidth() );
162 wfDebug(__METHOD__
.': supposed to render '.$this->getName().' ('.$this->getMimeType()."), but can't!\n");
163 return $this->getURL(); #hm... return NULL?
166 return $this->getURL();
171 * Return the full filesystem path to the file. Note that this does
172 * not mean that a file actually exists under that location.
174 * This path depends on whether directory hashing is active or not,
175 * i.e. whether the files are all found in the same directory,
176 * or in hashed paths like /images/3/3c.
178 * May return false if the file is not locally accessible.
183 if ( !isset( $this->path
) ) {
184 $this->path
= $this->repo
->getZonePath('public') . '/' . $this->getRel();
190 * Alias for getPath()
193 function getFullPath() {
194 return $this->getPath();
198 * Return the width of the image. Returns false if the width is unknown
202 * Overridden by LocalFile, UnregisteredLocalFile
205 function getWidth( $page = 1 ) { return false; }
208 * Return the height of the image. Returns false if the height is unknown
212 * Overridden by LocalFile, UnregisteredLocalFile
215 function getHeight( $page = 1 ) { return false; }
218 * Get handler-specific metadata
219 * Overridden by LocalFile, UnregisteredLocalFile
222 function getMetadata() { return false; }
225 * Return the size of the image file, in bytes
226 * Overridden by LocalFile, UnregisteredLocalFile
230 function getSize() { return false; }
233 * Returns the mime type of the file.
234 * Overridden by LocalFile, UnregisteredLocalFile
237 function getMimeType() { return 'unknown/unknown'; }
240 * Return the type of the media in the file.
241 * Use the value returned by this function with the MEDIATYPE_xxx constants.
242 * Overridden by LocalFile,
245 function getMediaType() { return MEDIATYPE_UNKNOWN
; }
248 * Checks if the file can be presented to the browser as a bitmap.
250 * Currently, this checks if the file is an image format
251 * that can be converted to a format
252 * supported by all browsers (namely GIF, PNG and JPEG),
253 * or if it is an SVG image and SVG conversion is enabled.
255 function canRender() {
256 if ( !isset( $this->canRender
) ) {
257 $this->canRender
= $this->getHandler() && $this->handler
->canRender();
259 return $this->canRender
;
263 * Accessor for __get()
265 protected function getCanRender() {
266 return $this->canRender();
270 * Return true if the file is of a type that can't be directly
271 * rendered by typical browsers and needs to be re-rasterized.
273 * This returns true for everything but the bitmap types
274 * supported by all browsers, i.e. JPEG; GIF and PNG. It will
275 * also return true for any non-image formats.
279 function mustRender() {
280 return $this->getHandler() && $this->handler
->mustRender();
284 * Determines if this media file may be shown inline on a page.
286 * This is currently synonymous to canRender(), but this could be
287 * extended to also allow inline display of other media,
288 * like flash animations or videos. If you do so, please keep in mind that
289 * that could be a security risk.
291 function allowInlineDisplay() {
292 return $this->canRender();
296 * Determines if this media file is in a format that is unlikely to
297 * contain viruses or malicious content. It uses the global
298 * $wgTrustedMediaFormats list to determine if the file is safe.
300 * This is used to show a warning on the description page of non-safe files.
301 * It may also be used to disallow direct [[media:...]] links to such files.
303 * Note that this function will always return true if allowInlineDisplay()
304 * or isTrustedFile() is true for this file.
306 function isSafeFile() {
307 if ( !isset( $this->isSafeFile
) ) {
308 $this->isSafeFile
= $this->_getIsSafeFile();
310 return $this->isSafeFile
;
313 /** Accessor for __get() */
314 protected function getIsSafeFile() {
315 return $this->isSafeFile();
318 /** Uncached accessor */
319 protected function _getIsSafeFile() {
320 if ($this->allowInlineDisplay()) return true;
321 if ($this->isTrustedFile()) return true;
323 global $wgTrustedMediaFormats;
325 $type= $this->getMediaType();
326 $mime= $this->getMimeType();
327 #wfDebug("LocalFile::isSafeFile: type= $type, mime= $mime\n");
329 if (!$type ||
$type===MEDIATYPE_UNKNOWN
) return false; #unknown type, not trusted
330 if ( in_array( $type, $wgTrustedMediaFormats) ) return true;
332 if ($mime==="unknown/unknown") return false; #unknown type, not trusted
333 if ( in_array( $mime, $wgTrustedMediaFormats) ) return true;
338 /** Returns true if the file is flagged as trusted. Files flagged that way
339 * can be linked to directly, even if that is not allowed for this type of
342 * This is a dummy function right now and always returns false. It could be
343 * implemented to extract a flag from the database. The trusted flag could be
344 * set on upload, if the user has sufficient privileges, to bypass script-
345 * and html-filters. It may even be coupled with cryptographics signatures
348 function isTrustedFile() {
349 #this could be implemented to check a flag in the databas,
350 #look for signatures, etc
355 * Returns true if file exists in the repository.
357 * Overridden by LocalFile to avoid unnecessary stat calls.
359 * @return boolean Whether file exists in the repository.
363 return $this->getPath() && file_exists( $this->path
);
366 function getTransformScript() {
367 if ( !isset( $this->transformScript
) ) {
368 $this->transformScript
= false;
370 $script = $this->repo
->getThumbScriptUrl();
372 $this->transformScript
= "$script?f=" . urlencode( $this->getName() );
376 return $this->transformScript
;
380 * Get a ThumbnailImage which is the same size as the source
382 function getUnscaledThumb( $page = false ) {
383 $width = $this->getWidth( $page );
385 return $this->iconThumb();
390 'width' => $this->getWidth( $page )
393 $params = array( 'width' => $this->getWidth() );
395 return $this->transform( $params );
399 * Return the file name of a thumbnail with the specified parameters
401 * @param array $params Handler-specific parameters
404 function thumbName( $params ) {
405 if ( !$this->getHandler() ) {
408 $extension = $this->getExtension();
409 list( $thumbExt, $thumbMime ) = $this->handler
->getThumbType( $extension, $this->getMimeType() );
410 $thumbName = $this->handler
->makeParamString( $params ) . '-' . $this->getName();
411 if ( $thumbExt != $extension ) {
412 $thumbName .= ".$thumbExt";
418 * Create a thumbnail of the image having the specified width/height.
419 * The thumbnail will not be created if the width is larger than the
420 * image's width. Let the browser do the scaling in this case.
421 * The thumbnail is stored on disk and is only computed if the thumbnail
422 * file does not exist OR if it is older than the image.
425 * Keeps aspect ratio of original image. If both width and height are
426 * specified, the generated image will be no bigger than width x height,
427 * and will also have correct aspect ratio.
429 * @param integer $width maximum width of the generated thumbnail
430 * @param integer $height maximum height of the image (optional)
433 function createThumb( $width, $height = -1 ) {
434 $params = array( 'width' => $width );
435 if ( $height != -1 ) {
436 $params['height'] = $height;
438 $thumb = $this->transform( $params );
439 if( is_null( $thumb ) ||
$thumb->isError() ) return '';
440 return $thumb->getUrl();
444 * As createThumb, but returns a ThumbnailImage object. This can
445 * provide access to the actual file, the real size of the thumb,
446 * and can produce a convenient <img> tag for you.
448 * For non-image formats, this may return a filetype-specific icon.
450 * @param integer $width maximum width of the generated thumbnail
451 * @param integer $height maximum height of the image (optional)
452 * @param boolean $render True to render the thumbnail if it doesn't exist,
453 * false to just return the URL
455 * @return ThumbnailImage or null on failure
458 * @deprecated use transform()
460 function getThumbnail( $width, $height=-1, $render = true ) {
461 $params = array( 'width' => $width );
462 if ( $height != -1 ) {
463 $params['height'] = $height;
465 $flags = $render ? self
::RENDER_NOW
: 0;
466 return $this->transform( $params, $flags );
470 * Transform a media file
472 * @param array $params An associative array of handler-specific parameters. Typical
473 * keys are width, height and page.
474 * @param integer $flags A bitfield, may contain self::RENDER_NOW to force rendering
475 * @return MediaTransformOutput
477 function transform( $params, $flags = 0 ) {
478 global $wgUseSquid, $wgIgnoreImageErrors;
480 wfProfileIn( __METHOD__
);
482 if ( !$this->getHandler() ||
!$this->handler
->canRender() ) {
483 // not a bitmap or renderable image, don't try.
484 $thumb = $this->iconThumb();
488 $script = $this->getTransformScript();
489 if ( $script && !($flags & self
::RENDER_NOW
) ) {
490 // Use a script to transform on client request
491 $thumb = $this->handler
->getScriptedTransform( $this, $script, $params );
495 $normalisedParams = $params;
496 $this->handler
->normaliseParams( $this, $normalisedParams );
497 $thumbName = $this->thumbName( $normalisedParams );
498 $thumbPath = $this->getThumbPath( $thumbName );
499 $thumbUrl = $this->getThumbUrl( $thumbName );
501 if ( $this->repo
->canTransformVia404() && !($flags & self
::RENDER_NOW
) ) {
502 $thumb = $this->handler
->getTransform( $this, $thumbPath, $thumbUrl, $params );
506 wfDebug( "Doing stat for $thumbPath\n" );
507 $this->migrateThumbFile( $thumbName );
508 if ( file_exists( $thumbPath ) ) {
509 $thumb = $this->handler
->getTransform( $this, $thumbPath, $thumbUrl, $params );
512 $thumb = $this->handler
->doTransform( $this, $thumbPath, $thumbUrl, $params );
514 // Ignore errors if requested
517 } elseif ( $thumb->isError() ) {
518 $this->lastError
= $thumb->toText();
519 if ( $wgIgnoreImageErrors && !($flags & self
::RENDER_NOW
) ) {
520 $thumb = $this->handler
->getTransform( $this, $thumbPath, $thumbUrl, $params );
525 wfPurgeSquidServers( array( $thumbUrl ) );
529 wfProfileOut( __METHOD__
);
534 * Hook into transform() to allow migration of thumbnail files
536 * Overridden by LocalFile
538 function migrateThumbFile() {}
541 * Get a MediaHandler instance for this file
543 function getHandler() {
544 if ( !isset( $this->handler
) ) {
545 $this->handler
= MediaHandler
::getHandler( $this->getMimeType() );
547 return $this->handler
;
551 * Get a ThumbnailImage representing a file type icon
552 * @return ThumbnailImage
554 function iconThumb() {
555 global $wgStylePath, $wgStyleDirectory;
557 $try = array( 'fileicon-' . $this->getExtension() . '.png', 'fileicon.png' );
558 foreach( $try as $icon ) {
559 $path = '/common/images/icons/' . $icon;
560 $filepath = $wgStyleDirectory . $path;
561 if( file_exists( $filepath ) ) {
562 return new ThumbnailImage( $wgStylePath . $path, 120, 120 );
569 * Get last thumbnailing error.
572 function getLastError() {
573 return $this->lastError
;
577 * Get all thumbnail names previously generated for this file
579 * Overridden by LocalFile
581 function getThumbnails() { return array(); }
584 * Purge shared caches such as thumbnails and DB data caching
586 * Overridden by LocalFile
588 function purgeCache( $archiveFiles = array() ) {}
591 * Purge the file description page, but don't go after
592 * pages using the file. Use when modifying file history
593 * but not the current data.
595 function purgeDescription() {
596 $title = $this->getTitle();
598 $title->invalidateCache();
599 $title->purgeSquid();
604 * Purge metadata and all affected pages when the file is created,
605 * deleted, or majorly updated. A set of additional URLs may be
606 * passed to purge, such as specific file files which have changed.
607 * @param $urlArray array
609 function purgeEverything( $urlArr=array() ) {
610 // Delete thumbnails and refresh file metadata cache
612 $this->purgeDescription();
614 // Purge cache of all pages using this file
615 $title = $this->getTitle();
617 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
623 * Return the history of this file, line by line. Starts with current version,
624 * then old versions. Should return an object similar to an image/oldimage
629 * Overridden in LocalFile
631 function nextHistoryLine() {
636 * Reset the history pointer to the first element of the history
639 * Overridden in LocalFile.
641 function resetHistory() {}
644 * Get the filename hash component of the directory including trailing slash,
646 * If the repository is not hashed, returns an empty string.
648 function getHashPath() {
649 if ( !isset( $this->hashPath
) ) {
650 $this->hashPath
= $this->repo
->getHashPath( $this->getName() );
652 return $this->hashPath
;
656 * Get the path of the file relative to the public zone root
659 return $this->getHashPath() . $this->getName();
663 * Get urlencoded relative path of the file
665 function getUrlRel() {
666 return $this->getHashPath() . urlencode( $this->getName() );
669 /** Get the path of the archive directory, or a particular file if $suffix is specified */
670 function getArchivePath( $suffix = false ) {
671 $path = $this->repo
->getZonePath('public') . '/archive/' . $this->getHashPath();
672 if ( $suffix !== false ) {
673 $path .= '/' . $suffix;
678 /** Get the path of the thumbnail directory, or a particular file if $suffix is specified */
679 function getThumbPath( $suffix = false ) {
680 $path = $this->repo
->getZonePath('public') . '/thumb/' . $this->getRel();
681 if ( $suffix !== false ) {
682 $path .= '/' . $suffix;
687 /** Get the URL of the archive directory, or a particular file if $suffix is specified */
688 function getArchiveUrl( $suffix = false ) {
689 $path = $this->repo
->getZoneUrl('public') . '/archive/' . $this->getHashPath();
690 if ( $suffix !== false ) {
691 $path .= '/' . urlencode( $suffix );
696 /** Get the URL of the thumbnail directory, or a particular file if $suffix is specified */
697 function getThumbUrl( $suffix = false ) {
698 $path = $this->repo
->getZoneUrl('public') . '/thumb/' . $this->getUrlRel();
699 if ( $suffix !== false ) {
700 $path .= '/' . urlencode( $suffix );
705 /** Get the virtual URL for an archive file or directory */
706 function getArchiveVirtualUrl( $suffix = false ) {
707 $path = $this->repo
->getVirtualUrl() . '/public/archive/' . $this->getHashPath();
708 if ( $suffix !== false ) {
709 $path .= '/' . urlencode( $suffix );
714 /** Get the virtual URL for a thumbnail file or directory */
715 function getThumbVirtualUrl( $suffix = false ) {
716 $path = $this->repo
->getVirtualUrl() . '/public/thumb/' . $this->getHashPath();
717 if ( $suffix !== false ) {
718 $path .= '/' . urlencode( $suffix );
726 function isHashed() {
727 return $this->repo
->isHashed();
730 function readOnlyError() {
731 throw new MWException( get_class($this) . ': write operations are not supported' );
735 * Record a file upload in the upload log and the image table
737 * Overridden by LocalFile
739 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '', $watch = false ) {
740 $this->readOnlyError();
744 * Move or copy a file to its public location. If a file exists at the
745 * destination, move it to an archive. Returns the archive name on success
746 * or an empty string if it was a new file, and a wikitext-formatted
747 * WikiError object on failure.
749 * The archive name should be passed through to recordUpload for database
752 * @param string $sourcePath Local filesystem path to the source image
753 * @param integer $flags A bitwise combination of:
754 * File::DELETE_SOURCE Delete the source file, i.e. move
756 * @return The archive name on success or an empty string if it was a new
757 * file, and a wikitext-formatted WikiError object on failure.
760 * Overridden by LocalFile
762 function publish( $srcPath, $flags = 0 ) {
763 $this->readOnlyError();
767 * Get an array of Title objects which are articles which use this file
768 * Also adds their IDs to the link cache
770 * This is mostly copied from Title::getLinksTo()
772 * @deprecated Use HTMLCacheUpdate, this function uses too much memory
774 function getLinksTo( $options = '' ) {
775 wfProfileIn( __METHOD__
);
777 // Note: use local DB not repo DB, we want to know local links
779 $db = wfGetDB( DB_MASTER
);
781 $db = wfGetDB( DB_SLAVE
);
783 $linkCache =& LinkCache
::singleton();
785 list( $page, $imagelinks ) = $db->tableNamesN( 'page', 'imagelinks' );
786 $encName = $db->addQuotes( $this->getName() );
787 $sql = "SELECT page_namespace,page_title,page_id FROM $page,$imagelinks WHERE page_id=il_from AND il_to=$encName $options";
788 $res = $db->query( $sql, __METHOD__
);
791 if ( $db->numRows( $res ) ) {
792 while ( $row = $db->fetchObject( $res ) ) {
793 if ( $titleObj = Title
::makeTitle( $row->page_namespace
, $row->page_title
) ) {
794 $linkCache->addGoodLinkObj( $row->page_id
, $titleObj );
795 $retVal[] = $titleObj;
799 $db->freeResult( $res );
800 wfProfileOut( __METHOD__
);
804 function getExifData() {
805 if ( !$this->getHandler() ||
$this->handler
->getMetadataType( $this ) != 'exif' ) {
808 $metadata = $this->getMetadata();
812 $exif = unserialize( $metadata );
816 unset( $exif['MEDIAWIKI_EXIF_VERSION'] );
817 $format = new FormatExif( $exif );
819 return $format->getFormattedData();
823 * Returns true if the file comes from the local file repository.
828 return $this->repo
&& $this->repo
->getName() == 'local';
832 * Returns true if the image is an old version
840 * Is this file a "deleted" file in a private archive?
843 function isDeleted( $field ) {
848 * Was this file ever deleted from the wiki?
852 function wasDeleted() {
853 $title = $this->getTitle();
854 return $title && $title->isDeleted() > 0;
858 * Delete all versions of the file.
860 * Moves the files into an archive directory (or deletes them)
861 * and removes the database rows.
863 * Cache purging is done; logging is caller's responsibility.
866 * @return true on success, false on some kind of failure
868 * Overridden by LocalFile
870 function delete( $reason, $suppress=false ) {
871 $this->readOnlyError();
875 * Restore all or specified deleted revisions to the given file.
876 * Permissions and logging are left to the caller.
878 * May throw database exceptions on error.
880 * @param $versions set of record ids of deleted items to restore,
881 * or empty to restore all revisions.
882 * @return the number of file revisions restored if successful,
883 * or false on failure
885 * Overridden by LocalFile
887 function restore( $versions=array(), $Unsuppress=false ) {
888 $this->readOnlyError();
892 * Returns 'true' if this image is a multipage document, e.g. a DJVU
897 function isMultipage() {
898 return $this->getHandler() && $this->handler
->isMultiPage();
902 * Returns the number of pages of a multipage document, or NULL for
903 * documents which aren't multipage documents
905 function pageCount() {
906 if ( !isset( $this->pageCount
) ) {
907 if ( $this->getHandler() && $this->handler
->isMultiPage() ) {
908 $this->pageCount
= $this->handler
->pageCount( $this );
910 $this->pageCount
= false;
913 return $this->pageCount
;
917 * Calculate the height of a thumbnail using the source and destination width
919 static function scaleHeight( $srcWidth, $srcHeight, $dstWidth ) {
920 // Exact integer multiply followed by division
921 if ( $srcWidth == 0 ) {
924 return round( $srcHeight * $dstWidth / $srcWidth );
929 * Get an image size array like that returned by getimagesize(), or false if it
930 * can't be determined.
932 * @param string $fileName The filename
935 function getImageSize( $fileName ) {
936 if ( !$this->getHandler() ) {
939 return $this->handler
->getImageSize( $this, $fileName );
943 * Get the URL of the image description page. May return false if it is
944 * unknown or not applicable.
946 function getDescriptionUrl() {
947 return $this->repo
->getDescriptionUrl( $this->getName() );
951 * Get the HTML text of the description page, if available
953 function getDescriptionText() {
954 if ( !$this->repo
->fetchDescription
) {
957 $renderUrl = $this->repo
->getDescriptionRenderUrl( $this->getName() );
959 wfDebug( "Fetching shared description from $renderUrl\n" );
960 return Http
::get( $renderUrl );
967 * Get the 14-character timestamp of the file upload, or false if
969 function getTimestmap() {
970 $path = $this->getPath();
971 if ( !file_exists( $path ) ) {
974 return wfTimestamp( filemtime( $path ) );
978 * Determine if the current user is allowed to view a particular
979 * field of this file, if it's marked as deleted.
984 function userCan( $field ) {