3 * @defgroup FileAbstraction File abstraction
6 * Represents files in a repository.
10 * Base code for files.
13 * @ingroup FileAbstraction
17 * Implements some public methods and some protected utility functions which
18 * are required by multiple child classes. Contains stub functionality for
19 * unimplemented public methods.
21 * Stub functions which should be overridden are marked with STUB. Some more
22 * concrete functions are also typically overridden by child classes.
24 * Note that only the repo object knows what its file class is called. You should
25 * never name a file class explictly outside of the repo class. Instead use the
26 * repo's factory functions to generate file objects, for example:
28 * RepoGroup::singleton()->getLocalRepo()->newFile($title);
30 * The convenience functions wfLocalFile() and wfFindFile() should be sufficient
33 * @ingroup FileAbstraction
36 const DELETED_FILE
= 1;
37 const DELETED_COMMENT
= 2;
38 const DELETED_USER
= 4;
39 const DELETED_RESTRICTED
= 8;
41 /** Force rendering in the current process */
44 * Force rendering even if thumbnail already exist and using RENDER_NOW
45 * I.e. you have to pass both flags: File::RENDER_NOW | File::RENDER_FORCE
47 const RENDER_FORCE
= 2;
49 const DELETE_SOURCE
= 1;
52 * Some member variables can be lazy-initialised using __get(). The
53 * initialisation function for these variables is always a function named
54 * like getVar(), where Var is the variable name with upper-case first
57 * The following variables are initialised in this way in this base class:
58 * name, extension, handler, path, canRender, isSafeFile,
59 * transformScript, hashPath, pageCount, url
61 * Code within this class should generally use the accessor function
62 * directly, since __get() isn't re-entrant and therefore causes bugs that
63 * depend on initialisation order.
67 * The following member variables are not lazy-initialised
80 var $lastError, $redirected, $redirectedTitle;
83 * @var FSFile|bool False if undefined
95 protected $url, $extension, $name, $path, $hashPath, $pageCount, $transformScript;
100 protected $canRender, $isSafeFile;
103 * @var string Required Repository class type
105 protected $repoClass = 'FileRepo';
108 * Call this constructor from child classes.
110 * Both $title and $repo are optional, though some functions
111 * may return false or throw exceptions if they are not set.
112 * Most subclasses will want to call assertRepoDefined() here.
114 * @param $title Title|string|bool
115 * @param $repo FileRepo|bool
117 function __construct( $title, $repo ) {
118 if ( $title !== false ) { // subclasses may not use MW titles
119 $title = self
::normalizeTitle( $title, 'exception' );
121 $this->title
= $title;
126 * Given a string or Title object return either a
127 * valid Title object with namespace NS_FILE or null
129 * @param $title Title|string
130 * @param $exception string|bool Use 'exception' to throw an error on bad titles
133 static function normalizeTitle( $title, $exception = false ) {
135 if ( $ret instanceof Title
) {
136 # Normalize NS_MEDIA -> NS_FILE
137 if ( $ret->getNamespace() == NS_MEDIA
) {
138 $ret = Title
::makeTitleSafe( NS_FILE
, $ret->getDBkey() );
139 # Sanity check the title namespace
140 } elseif ( $ret->getNamespace() !== NS_FILE
) {
144 # Convert strings to Title objects
145 $ret = Title
::makeTitleSafe( NS_FILE
, (string)$ret );
147 if ( !$ret && $exception !== false ) {
148 throw new MWException( "`$title` is not a valid file title." );
153 function __get( $name ) {
154 $function = array( $this, 'get' . ucfirst( $name ) );
155 if ( !is_callable( $function ) ) {
158 $this->$name = call_user_func( $function );
164 * Normalize a file extension to the common form, and ensure it's clean.
165 * Extensions with non-alphanumeric characters will be discarded.
167 * @param $ext string (without the .)
170 static function normalizeExtension( $ext ) {
171 $lower = strtolower( $ext );
178 if( isset( $squish[$lower] ) ) {
179 return $squish[$lower];
180 } elseif( preg_match( '/^[0-9a-z]+$/', $lower ) ) {
188 * Checks if file extensions are compatible
190 * @param $old File Old file
191 * @param $new string New name
195 static function checkExtensionCompatibility( File
$old, $new ) {
196 $oldMime = $old->getMimeType();
197 $n = strrpos( $new, '.' );
198 $newExt = self
::normalizeExtension( $n ?
substr( $new, $n +
1 ) : '' );
199 $mimeMagic = MimeMagic
::singleton();
200 return $mimeMagic->isMatchingExtension( $newExt, $oldMime );
204 * Upgrade the database row if there is one
205 * Called by ImagePage
208 function upgradeRow() {}
211 * Split an internet media type into its two components; if not
212 * a two-part name, set the minor type to 'unknown'.
214 * @param string $mime "text/html" etc
215 * @return array ("text", "html") etc
217 public static function splitMime( $mime ) {
218 if( strpos( $mime, '/' ) !== false ) {
219 return explode( '/', $mime, 2 );
221 return array( $mime, 'unknown' );
226 * Return the name of this file
230 public function getName() {
231 if ( !isset( $this->name
) ) {
232 $this->assertRepoDefined();
233 $this->name
= $this->repo
->getNameFromTitle( $this->title
);
239 * Get the file extension, e.g. "svg"
243 function getExtension() {
244 if ( !isset( $this->extension
) ) {
245 $n = strrpos( $this->getName(), '.' );
246 $this->extension
= self
::normalizeExtension(
247 $n ?
substr( $this->getName(), $n +
1 ) : '' );
249 return $this->extension
;
253 * Return the associated title object
257 public function getTitle() {
262 * Return the title used to find this file
266 public function getOriginalTitle() {
267 if ( $this->redirected
) {
268 return $this->getRedirectedTitle();
274 * Return the URL of the file
278 public function getUrl() {
279 if ( !isset( $this->url
) ) {
280 $this->assertRepoDefined();
281 $this->url
= $this->repo
->getZoneUrl( 'public' ) . '/' . $this->getUrlRel();
287 * Return a fully-qualified URL to the file.
288 * Upload URL paths _may or may not_ be fully qualified, so
289 * we check. Local paths are assumed to belong on $wgServer.
293 public function getFullUrl() {
294 return wfExpandUrl( $this->getUrl(), PROTO_RELATIVE
);
300 public function getCanonicalUrl() {
301 return wfExpandUrl( $this->getUrl(), PROTO_CANONICAL
);
307 function getViewURL() {
308 if ( $this->mustRender() ) {
309 if ( $this->canRender() ) {
310 return $this->createThumb( $this->getWidth() );
312 wfDebug( __METHOD__
.': supposed to render ' . $this->getName() .
313 ' (' . $this->getMimeType() . "), but can't!\n" );
314 return $this->getURL(); #hm... return NULL?
317 return $this->getURL();
322 * Return the storage path to the file. Note that this does
323 * not mean that a file actually exists under that location.
325 * This path depends on whether directory hashing is active or not,
326 * i.e. whether the files are all found in the same directory,
327 * or in hashed paths like /images/3/3c.
329 * Most callers don't check the return value, but ForeignAPIFile::getPath
332 * @return string|bool ForeignAPIFile::getPath can return false
334 public function getPath() {
335 if ( !isset( $this->path
) ) {
336 $this->assertRepoDefined();
337 $this->path
= $this->repo
->getZonePath( 'public' ) . '/' . $this->getRel();
343 * Get an FS copy or original of this file and return the path.
344 * Returns false on failure. Callers must not alter the file.
345 * Temporary files are cleared automatically.
347 * @return string|bool False on failure
349 public function getLocalRefPath() {
350 $this->assertRepoDefined();
351 if ( !isset( $this->fsFile
) ) {
352 $this->fsFile
= $this->repo
->getLocalReference( $this->getPath() );
353 if ( !$this->fsFile
) {
354 $this->fsFile
= false; // null => false; cache negative hits
357 return ( $this->fsFile
)
358 ?
$this->fsFile
->getPath()
363 * Return the width of the image. Returns false if the width is unknown
367 * Overridden by LocalFile, UnregisteredLocalFile
373 public function getWidth( $page = 1 ) {
378 * Return the height of the image. Returns false if the height is unknown
382 * Overridden by LocalFile, UnregisteredLocalFile
386 * @return bool|number False on failure
388 public function getHeight( $page = 1 ) {
393 * Returns ID or name of user who uploaded the file
396 * @param $type string 'text' or 'id'
400 public function getUser( $type = 'text' ) {
405 * Get the duration of a media file in seconds
409 public function getLength() {
410 $handler = $this->getHandler();
412 return $handler->getLength( $this );
419 * Return true if the file is vectorized
423 public function isVectorized() {
424 $handler = $this->getHandler();
426 return $handler->isVectorized( $this );
433 * Get handler-specific metadata
434 * Overridden by LocalFile, UnregisteredLocalFile
438 public function getMetadata() {
443 * get versioned metadata
445 * @param $metadata Mixed Array or String of (serialized) metadata
446 * @param $version integer version number.
447 * @return Array containing metadata, or what was passed to it on fail (unserializing if not array)
449 public function convertMetadataVersion($metadata, $version) {
450 $handler = $this->getHandler();
451 if ( !is_array( $metadata ) ) {
452 // Just to make the return type consistent
453 $metadata = unserialize( $metadata );
456 return $handler->convertMetadataVersion( $metadata, $version );
463 * Return the bit depth of the file
464 * Overridden by LocalFile
468 public function getBitDepth() {
473 * Return the size of the image file, in bytes
474 * Overridden by LocalFile, UnregisteredLocalFile
478 public function getSize() {
483 * Returns the mime type of the file.
484 * Overridden by LocalFile, UnregisteredLocalFile
489 function getMimeType() {
490 return 'unknown/unknown';
494 * Return the type of the media in the file.
495 * Use the value returned by this function with the MEDIATYPE_xxx constants.
496 * Overridden by LocalFile,
500 function getMediaType() {
501 return MEDIATYPE_UNKNOWN
;
505 * Checks if the output of transform() for this file is likely
506 * to be valid. If this is false, various user elements will
507 * display a placeholder instead.
509 * Currently, this checks if the file is an image format
510 * that can be converted to a format
511 * supported by all browsers (namely GIF, PNG and JPEG),
512 * or if it is an SVG image and SVG conversion is enabled.
516 function canRender() {
517 if ( !isset( $this->canRender
) ) {
518 $this->canRender
= $this->getHandler() && $this->handler
->canRender( $this );
520 return $this->canRender
;
524 * Accessor for __get()
527 protected function getCanRender() {
528 return $this->canRender();
532 * Return true if the file is of a type that can't be directly
533 * rendered by typical browsers and needs to be re-rasterized.
535 * This returns true for everything but the bitmap types
536 * supported by all browsers, i.e. JPEG; GIF and PNG. It will
537 * also return true for any non-image formats.
541 function mustRender() {
542 return $this->getHandler() && $this->handler
->mustRender( $this );
546 * Alias for canRender()
550 function allowInlineDisplay() {
551 return $this->canRender();
555 * Determines if this media file is in a format that is unlikely to
556 * contain viruses or malicious content. It uses the global
557 * $wgTrustedMediaFormats list to determine if the file is safe.
559 * This is used to show a warning on the description page of non-safe files.
560 * It may also be used to disallow direct [[media:...]] links to such files.
562 * Note that this function will always return true if allowInlineDisplay()
563 * or isTrustedFile() is true for this file.
567 function isSafeFile() {
568 if ( !isset( $this->isSafeFile
) ) {
569 $this->isSafeFile
= $this->_getIsSafeFile();
571 return $this->isSafeFile
;
575 * Accessor for __get()
579 protected function getIsSafeFile() {
580 return $this->isSafeFile();
588 protected function _getIsSafeFile() {
589 global $wgTrustedMediaFormats;
591 if ( $this->allowInlineDisplay() ) {
594 if ($this->isTrustedFile()) {
598 $type = $this->getMediaType();
599 $mime = $this->getMimeType();
600 #wfDebug("LocalFile::isSafeFile: type= $type, mime= $mime\n");
602 if ( !$type ||
$type === MEDIATYPE_UNKNOWN
) {
603 return false; #unknown type, not trusted
605 if ( in_array( $type, $wgTrustedMediaFormats ) ) {
609 if ( $mime === "unknown/unknown" ) {
610 return false; #unknown type, not trusted
612 if ( in_array( $mime, $wgTrustedMediaFormats) ) {
620 * Returns true if the file is flagged as trusted. Files flagged that way
621 * can be linked to directly, even if that is not allowed for this type of
624 * This is a dummy function right now and always returns false. It could be
625 * implemented to extract a flag from the database. The trusted flag could be
626 * set on upload, if the user has sufficient privileges, to bypass script-
627 * and html-filters. It may even be coupled with cryptographics signatures
632 function isTrustedFile() {
633 #this could be implemented to check a flag in the database,
634 #look for signatures, etc
639 * Returns true if file exists in the repository.
641 * Overridden by LocalFile to avoid unnecessary stat calls.
643 * @return boolean Whether file exists in the repository.
645 public function exists() {
646 return $this->getPath() && $this->repo
->fileExists( $this->path
);
650 * Returns true if file exists in the repository and can be included in a page.
651 * It would be unsafe to include private images, making public thumbnails inadvertently
653 * @return boolean Whether file exists in the repository and is includable.
655 public function isVisible() {
656 return $this->exists();
662 function getTransformScript() {
663 if ( !isset( $this->transformScript
) ) {
664 $this->transformScript
= false;
666 $script = $this->repo
->getThumbScriptUrl();
668 $this->transformScript
= "$script?f=" . urlencode( $this->getName() );
672 return $this->transformScript
;
676 * Get a ThumbnailImage which is the same size as the source
678 * @param $handlerParams array
682 function getUnscaledThumb( $handlerParams = array() ) {
683 $hp =& $handlerParams;
684 $page = isset( $hp['page'] ) ?
$hp['page'] : false;
685 $width = $this->getWidth( $page );
687 return $this->iconThumb();
689 $hp['width'] = $width;
690 return $this->transform( $hp );
694 * Return the file name of a thumbnail with the specified parameters
696 * @param $params Array: handler-specific parameters
701 function thumbName( $params ) {
702 return $this->generateThumbName( $this->getName(), $params );
706 * Generate a thumbnail file name from a name and specified parameters
708 * @param string $name
709 * @param array $params Parameters which will be passed to MediaHandler::makeParamString
713 function generateThumbName( $name, $params ) {
714 if ( !$this->getHandler() ) {
717 $extension = $this->getExtension();
718 list( $thumbExt, $thumbMime ) = $this->handler
->getThumbType(
719 $extension, $this->getMimeType(), $params );
720 $thumbName = $this->handler
->makeParamString( $params ) . '-' . $name;
721 if ( $thumbExt != $extension ) {
722 $thumbName .= ".$thumbExt";
728 * Create a thumbnail of the image having the specified width/height.
729 * The thumbnail will not be created if the width is larger than the
730 * image's width. Let the browser do the scaling in this case.
731 * The thumbnail is stored on disk and is only computed if the thumbnail
732 * file does not exist OR if it is older than the image.
735 * Keeps aspect ratio of original image. If both width and height are
736 * specified, the generated image will be no bigger than width x height,
737 * and will also have correct aspect ratio.
739 * @param $width Integer: maximum width of the generated thumbnail
740 * @param $height Integer: maximum height of the image (optional)
744 public function createThumb( $width, $height = -1 ) {
745 $params = array( 'width' => $width );
746 if ( $height != -1 ) {
747 $params['height'] = $height;
749 $thumb = $this->transform( $params );
750 if ( is_null( $thumb ) ||
$thumb->isError() ) {
753 return $thumb->getUrl();
757 * Return either a MediaTransformError or placeholder thumbnail (if $wgIgnoreImageErrors)
759 * @param $thumbPath string Thumbnail storage path
760 * @param $thumbUrl string Thumbnail URL
761 * @param $params Array
762 * @param $flags integer
763 * @return MediaTransformOutput
765 protected function transformErrorOutput( $thumbPath, $thumbUrl, $params, $flags ) {
766 global $wgIgnoreImageErrors;
768 if ( $wgIgnoreImageErrors && !( $flags & self
::RENDER_NOW
) ) {
769 return $this->handler
->getTransform( $this, $thumbPath, $thumbUrl, $params );
771 return new MediaTransformError( 'thumbnail_error',
772 $params['width'], 0, wfMsg( 'thumbnail-dest-create' ) );
777 * Transform a media file
779 * @param $params Array: an associative array of handler-specific parameters.
780 * Typical keys are width, height and page.
781 * @param $flags Integer: a bitfield, may contain self::RENDER_NOW to force rendering
782 * @return MediaTransformOutput|bool False on failure
784 function transform( $params, $flags = 0 ) {
785 global $wgUseSquid, $wgIgnoreImageErrors, $wgThumbnailEpoch;
787 wfProfileIn( __METHOD__
);
789 if ( !$this->canRender() ) {
790 $thumb = $this->iconThumb();
791 break; // not a bitmap or renderable image, don't try
794 // Get the descriptionUrl to embed it as comment into the thumbnail. Bug 19791.
795 $descriptionUrl = $this->getDescriptionUrl();
796 if ( $descriptionUrl ) {
797 $params['descriptionUrl'] = wfExpandUrl( $descriptionUrl, PROTO_CANONICAL
);
800 $script = $this->getTransformScript();
801 if ( $script && !( $flags & self
::RENDER_NOW
) ) {
802 // Use a script to transform on client request, if possible
803 $thumb = $this->handler
->getScriptedTransform( $this, $script, $params );
809 $normalisedParams = $params;
810 $this->handler
->normaliseParams( $this, $normalisedParams );
812 $thumbName = $this->thumbName( $normalisedParams );
813 $thumbUrl = $this->getThumbUrl( $thumbName );
814 $thumbPath = $this->getThumbPath( $thumbName ); // final thumb path
817 // Defer rendering if a 404 handler is set up...
818 if ( $this->repo
->canTransformVia404() && !( $flags & self
::RENDER_NOW
) ) {
819 wfDebug( __METHOD__
. " transformation deferred." );
820 // XXX: Pass in the storage path even though we are not rendering anything
821 // and the path is supposed to be an FS path. This is due to getScalerType()
822 // getting called on the path and clobbering $thumb->getUrl() if it's false.
823 $thumb = $this->handler
->getTransform( $this, $thumbPath, $thumbUrl, $params );
826 // Clean up broken thumbnails as needed
827 $this->migrateThumbFile( $thumbName );
828 // Check if an up-to-date thumbnail already exists...
829 wfDebug( __METHOD__
.": Doing stat for $thumbPath\n" );
830 if ( $this->repo
->fileExists( $thumbPath ) && !( $flags & self
::RENDER_FORCE
) ) {
831 $timestamp = $this->repo
->getFileTimestamp( $thumbPath );
832 if ( $timestamp !== false && $timestamp >= $wgThumbnailEpoch ) {
833 // XXX: Pass in the storage path even though we are not rendering anything
834 // and the path is supposed to be an FS path. This is due to getScalerType()
835 // getting called on the path and clobbering $thumb->getUrl() if it's false.
836 $thumb = $this->handler
->getTransform( $this, $thumbPath, $thumbUrl, $params );
837 $thumb->setStoragePath( $thumbPath );
840 } elseif ( $flags & self
::RENDER_FORCE
) {
841 wfDebug( __METHOD__
. " forcing rendering per flag File::RENDER_FORCE\n" );
845 // Create a temp FS file with the same extension and the thumbnail
846 $thumbExt = FileBackend
::extensionFromPath( $thumbPath );
847 $tmpFile = TempFSFile
::factory( 'transform_', $thumbExt );
849 $thumb = $this->transformErrorOutput( $thumbPath, $thumbUrl, $params, $flags );
852 $tmpThumbPath = $tmpFile->getPath(); // path of 0-byte temp file
854 // Actually render the thumbnail...
855 $thumb = $this->handler
->doTransform( $this, $tmpThumbPath, $thumbUrl, $params );
856 $tmpFile->bind( $thumb ); // keep alive with $thumb
858 if ( !$thumb ) { // bad params?
860 } elseif ( $thumb->isError() ) { // transform error
861 $this->lastError
= $thumb->toText();
862 // Ignore errors if requested
863 if ( $wgIgnoreImageErrors && !( $flags & self
::RENDER_NOW
) ) {
864 $thumb = $this->handler
->getTransform( $this, $tmpThumbPath, $thumbUrl, $params );
866 } elseif ( $this->repo
&& $thumb->hasFile() && !$thumb->fileIsSource() ) {
867 // Copy the thumbnail from the file system into storage...
868 $status = $this->repo
->quickImport( $tmpThumbPath, $thumbPath );
869 if ( $status->isOK() ) {
870 $thumb->setStoragePath( $thumbPath );
872 $thumb = $this->transformErrorOutput( $thumbPath, $thumbUrl, $params, $flags );
874 // Give extensions a chance to do something with this thumbnail...
875 wfRunHooks( 'FileTransformed', array( $this, $thumb, $tmpThumbPath, $thumbPath ) );
878 // Purge. Useful in the event of Core -> Squid connection failure or squid
879 // purge collisions from elsewhere during failure. Don't keep triggering for
880 // "thumbs" which have the main image URL though (bug 13776)
882 if ( !$thumb ||
$thumb->isError() ||
$thumb->getUrl() != $this->getURL() ) {
883 SquidUpdate
::purge( array( $thumbUrl ) );
888 wfProfileOut( __METHOD__
);
889 return is_object( $thumb ) ?
$thumb : false;
893 * Hook into transform() to allow migration of thumbnail files
895 * Overridden by LocalFile
897 function migrateThumbFile( $thumbName ) {}
900 * Get a MediaHandler instance for this file
902 * @return MediaHandler
904 function getHandler() {
905 if ( !isset( $this->handler
) ) {
906 $this->handler
= MediaHandler
::getHandler( $this->getMimeType() );
908 return $this->handler
;
912 * Get a ThumbnailImage representing a file type icon
914 * @return ThumbnailImage
916 function iconThumb() {
917 global $wgStylePath, $wgStyleDirectory;
919 $try = array( 'fileicon-' . $this->getExtension() . '.png', 'fileicon.png' );
920 foreach ( $try as $icon ) {
921 $path = '/common/images/icons/' . $icon;
922 $filepath = $wgStyleDirectory . $path;
923 if ( file_exists( $filepath ) ) { // always FS
924 return new ThumbnailImage( $this, $wgStylePath . $path, 120, 120 );
931 * Get last thumbnailing error.
934 function getLastError() {
935 return $this->lastError
;
939 * Get all thumbnail names previously generated for this file
941 * Overridden by LocalFile
944 function getThumbnails() {
949 * Purge shared caches such as thumbnails and DB data caching
951 * Overridden by LocalFile
952 * @param $options Array Options, which include:
953 * 'forThumbRefresh' : The purging is only to refresh thumbnails
955 function purgeCache( $options = array() ) {}
958 * Purge the file description page, but don't go after
959 * pages using the file. Use when modifying file history
960 * but not the current data.
962 function purgeDescription() {
963 $title = $this->getTitle();
965 $title->invalidateCache();
966 $title->purgeSquid();
971 * Purge metadata and all affected pages when the file is created,
972 * deleted, or majorly updated.
974 function purgeEverything() {
975 // Delete thumbnails and refresh file metadata cache
977 $this->purgeDescription();
979 // Purge cache of all pages using this file
980 $title = $this->getTitle();
982 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
988 * Return a fragment of the history of file.
991 * @param $limit integer Limit of rows to return
992 * @param $start string timestamp Only revisions older than $start will be returned
993 * @param $end string timestamp Only revisions newer than $end will be returned
994 * @param $inc bool Include the endpoints of the time range
998 function getHistory($limit = null, $start = null, $end = null, $inc=true) {
1003 * Return the history of this file, line by line. Starts with current version,
1004 * then old versions. Should return an object similar to an image/oldimage
1008 * Overridden in LocalFile
1011 public function nextHistoryLine() {
1016 * Reset the history pointer to the first element of the history.
1017 * Always call this function after using nextHistoryLine() to free db resources
1019 * Overridden in LocalFile.
1021 public function resetHistory() {}
1024 * Get the filename hash component of the directory including trailing slash,
1026 * If the repository is not hashed, returns an empty string.
1030 function getHashPath() {
1031 if ( !isset( $this->hashPath
) ) {
1032 $this->assertRepoDefined();
1033 $this->hashPath
= $this->repo
->getHashPath( $this->getName() );
1035 return $this->hashPath
;
1039 * Get the path of the file relative to the public zone root.
1040 * This function is overriden in OldLocalFile to be like getArchiveRel().
1045 return $this->getHashPath() . $this->getName();
1049 * Get the path of an archived file relative to the public zone root
1051 * @param $suffix bool|string if not false, the name of an archived thumbnail file
1055 function getArchiveRel( $suffix = false ) {
1056 $path = 'archive/' . $this->getHashPath();
1057 if ( $suffix === false ) {
1058 $path = substr( $path, 0, -1 );
1066 * Get the path, relative to the thumbnail zone root, of the
1067 * thumbnail directory or a particular file if $suffix is specified
1069 * @param $suffix bool|string if not false, the name of a thumbnail file
1073 function getThumbRel( $suffix = false ) {
1074 $path = $this->getRel();
1075 if ( $suffix !== false ) {
1076 $path .= '/' . $suffix;
1082 * Get urlencoded path of the file relative to the public zone root.
1083 * This function is overriden in OldLocalFile to be like getArchiveUrl().
1087 function getUrlRel() {
1088 return $this->getHashPath() . rawurlencode( $this->getName() );
1092 * Get the path, relative to the thumbnail zone root, for an archived file's thumbs directory
1093 * or a specific thumb if the $suffix is given.
1095 * @param $archiveName string the timestamped name of an archived image
1096 * @param $suffix bool|string if not false, the name of a thumbnail file
1100 function getArchiveThumbRel( $archiveName, $suffix = false ) {
1101 $path = 'archive/' . $this->getHashPath() . $archiveName . "/";
1102 if ( $suffix === false ) {
1103 $path = substr( $path, 0, -1 );
1111 * Get the path of the archived file.
1113 * @param $suffix bool|string if not false, the name of an archived file.
1117 function getArchivePath( $suffix = false ) {
1118 $this->assertRepoDefined();
1119 return $this->repo
->getZonePath( 'public' ) . '/' . $this->getArchiveRel( $suffix );
1123 * Get the path of an archived file's thumbs, or a particular thumb if $suffix is specified
1125 * @param $archiveName string the timestamped name of an archived image
1126 * @param $suffix bool|string if not false, the name of a thumbnail file
1130 function getArchiveThumbPath( $archiveName, $suffix = false ) {
1131 $this->assertRepoDefined();
1132 return $this->repo
->getZonePath( 'thumb' ) . '/' .
1133 $this->getArchiveThumbRel( $archiveName, $suffix );
1137 * Get the path of the thumbnail directory, or a particular file if $suffix is specified
1139 * @param $suffix bool|string if not false, the name of a thumbnail file
1143 function getThumbPath( $suffix = false ) {
1144 $this->assertRepoDefined();
1145 return $this->repo
->getZonePath( 'thumb' ) . '/' . $this->getThumbRel( $suffix );
1149 * Get the URL of the archive directory, or a particular file if $suffix is specified
1151 * @param $suffix bool|string if not false, the name of an archived file
1155 function getArchiveUrl( $suffix = false ) {
1156 $this->assertRepoDefined();
1157 $path = $this->repo
->getZoneUrl( 'public' ) . '/archive/' . $this->getHashPath();
1158 if ( $suffix === false ) {
1159 $path = substr( $path, 0, -1 );
1161 $path .= rawurlencode( $suffix );
1167 * Get the URL of the archived file's thumbs, or a particular thumb if $suffix is specified
1169 * @param $archiveName string the timestamped name of an archived image
1170 * @param $suffix bool|string if not false, the name of a thumbnail file
1174 function getArchiveThumbUrl( $archiveName, $suffix = false ) {
1175 $this->assertRepoDefined();
1176 $path = $this->repo
->getZoneUrl( 'thumb' ) . '/archive/' .
1177 $this->getHashPath() . rawurlencode( $archiveName ) . "/";
1178 if ( $suffix === false ) {
1179 $path = substr( $path, 0, -1 );
1181 $path .= rawurlencode( $suffix );
1187 * Get the URL of the thumbnail directory, or a particular file if $suffix is specified
1189 * @param $suffix bool|string if not false, the name of a thumbnail file
1191 * @return string path
1193 function getThumbUrl( $suffix = false ) {
1194 $this->assertRepoDefined();
1195 $path = $this->repo
->getZoneUrl( 'thumb' ) . '/' . $this->getUrlRel();
1196 if ( $suffix !== false ) {
1197 $path .= '/' . rawurlencode( $suffix );
1203 * Get the public zone virtual URL for a current version source file
1205 * @param $suffix bool|string if not false, the name of a thumbnail file
1209 function getVirtualUrl( $suffix = false ) {
1210 $this->assertRepoDefined();
1211 $path = $this->repo
->getVirtualUrl() . '/public/' . $this->getUrlRel();
1212 if ( $suffix !== false ) {
1213 $path .= '/' . rawurlencode( $suffix );
1219 * Get the public zone virtual URL for an archived version source file
1221 * @param $suffix bool|string if not false, the name of a thumbnail file
1225 function getArchiveVirtualUrl( $suffix = false ) {
1226 $this->assertRepoDefined();
1227 $path = $this->repo
->getVirtualUrl() . '/public/archive/' . $this->getHashPath();
1228 if ( $suffix === false ) {
1229 $path = substr( $path, 0, -1 );
1231 $path .= rawurlencode( $suffix );
1237 * Get the virtual URL for a thumbnail file or directory
1239 * @param $suffix bool|string if not false, the name of a thumbnail file
1243 function getThumbVirtualUrl( $suffix = false ) {
1244 $this->assertRepoDefined();
1245 $path = $this->repo
->getVirtualUrl() . '/thumb/' . $this->getUrlRel();
1246 if ( $suffix !== false ) {
1247 $path .= '/' . rawurlencode( $suffix );
1255 function isHashed() {
1256 $this->assertRepoDefined();
1257 return (bool)$this->repo
->getHashLevels();
1261 * @throws MWException
1263 function readOnlyError() {
1264 throw new MWException( get_class($this) . ': write operations are not supported' );
1268 * Record a file upload in the upload log and the image table
1270 * Overridden by LocalFile
1273 * @param $license string
1274 * @param $copyStatus string
1275 * @param $source string
1276 * @param $watch bool
1278 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '', $watch = false ) {
1279 $this->readOnlyError();
1283 * Move or copy a file to its public location. If a file exists at the
1284 * destination, move it to an archive. Returns a FileRepoStatus object with
1285 * the archive name in the "value" member on success.
1287 * The archive name should be passed through to recordUpload for database
1290 * @param $srcPath String: local filesystem path to the source image
1291 * @param $flags Integer: a bitwise combination of:
1292 * File::DELETE_SOURCE Delete the source file, i.e. move
1294 * @return FileRepoStatus object. On success, the value member contains the
1295 * archive name, or an empty string if it was a new file.
1298 * Overridden by LocalFile
1300 function publish( $srcPath, $flags = 0 ) {
1301 $this->readOnlyError();
1307 function formatMetadata() {
1308 if ( !$this->getHandler() ) {
1311 return $this->getHandler()->formatMetadata( $this, $this->getMetadata() );
1315 * Returns true if the file comes from the local file repository.
1319 function isLocal() {
1320 return $this->repo
&& $this->repo
->isLocal();
1324 * Returns the name of the repository.
1328 function getRepoName() {
1329 return $this->repo ?
$this->repo
->getName() : 'unknown';
1333 * Returns the repository
1335 * @return FileRepo|bool
1337 function getRepo() {
1342 * Returns true if the image is an old version
1352 * Is this file a "deleted" file in a private archive?
1359 function isDeleted( $field ) {
1364 * Return the deletion bitfield
1368 function getVisibility() {
1373 * Was this file ever deleted from the wiki?
1377 function wasDeleted() {
1378 $title = $this->getTitle();
1379 return $title && $title->isDeletedQuick();
1383 * Move file to the new title
1385 * Move current, old version and all thumbnails
1386 * to the new filename. Old file is deleted.
1388 * Cache purging is done; checks for validity
1389 * and logging are caller's responsibility
1391 * @param $target Title New file name
1392 * @return FileRepoStatus object.
1394 function move( $target ) {
1395 $this->readOnlyError();
1399 * Delete all versions of the file.
1401 * Moves the files into an archive directory (or deletes them)
1402 * and removes the database rows.
1404 * Cache purging is done; logging is caller's responsibility.
1406 * @param $reason String
1407 * @param $suppress Boolean: hide content from sysops?
1408 * @return bool on success, false on some kind of failure
1410 * Overridden by LocalFile
1412 function delete( $reason, $suppress = false ) {
1413 $this->readOnlyError();
1417 * Restore all or specified deleted revisions to the given file.
1418 * Permissions and logging are left to the caller.
1420 * May throw database exceptions on error.
1422 * @param $versions array set of record ids of deleted items to restore,
1423 * or empty to restore all revisions.
1424 * @param $unsuppress bool remove restrictions on content upon restoration?
1425 * @return int|bool the number of file revisions restored if successful,
1426 * or false on failure
1428 * Overridden by LocalFile
1430 function restore( $versions = array(), $unsuppress = false ) {
1431 $this->readOnlyError();
1435 * Returns 'true' if this file is a type which supports multiple pages,
1436 * e.g. DJVU or PDF. Note that this may be true even if the file in
1437 * question only has a single page.
1441 function isMultipage() {
1442 return $this->getHandler() && $this->handler
->isMultiPage( $this );
1446 * Returns the number of pages of a multipage document, or false for
1447 * documents which aren't multipage documents
1451 function pageCount() {
1452 if ( !isset( $this->pageCount
) ) {
1453 if ( $this->getHandler() && $this->handler
->isMultiPage( $this ) ) {
1454 $this->pageCount
= $this->handler
->pageCount( $this );
1456 $this->pageCount
= false;
1459 return $this->pageCount
;
1463 * Calculate the height of a thumbnail using the source and destination width
1471 static function scaleHeight( $srcWidth, $srcHeight, $dstWidth ) {
1472 // Exact integer multiply followed by division
1473 if ( $srcWidth == 0 ) {
1476 return round( $srcHeight * $dstWidth / $srcWidth );
1481 * Get an image size array like that returned by getImageSize(), or false if it
1482 * can't be determined.
1484 * @param $fileName String: The filename
1487 function getImageSize( $fileName ) {
1488 if ( !$this->getHandler() ) {
1491 return $this->handler
->getImageSize( $this, $fileName );
1495 * Get the URL of the image description page. May return false if it is
1496 * unknown or not applicable.
1500 function getDescriptionUrl() {
1501 if ( $this->repo
) {
1502 return $this->repo
->getDescriptionUrl( $this->getName() );
1509 * Get the HTML text of the description page, if available
1513 function getDescriptionText() {
1514 global $wgMemc, $wgLang;
1515 if ( !$this->repo ||
!$this->repo
->fetchDescription
) {
1518 $renderUrl = $this->repo
->getDescriptionRenderUrl( $this->getName(), $wgLang->getCode() );
1520 if ( $this->repo
->descriptionCacheExpiry
> 0 ) {
1521 wfDebug("Attempting to get the description from cache...");
1522 $key = $this->repo
->getLocalCacheKey( 'RemoteFileDescription', 'url', $wgLang->getCode(),
1524 $obj = $wgMemc->get($key);
1526 wfDebug("success!\n");
1531 wfDebug( "Fetching shared description from $renderUrl\n" );
1532 $res = Http
::get( $renderUrl );
1533 if ( $res && $this->repo
->descriptionCacheExpiry
> 0 ) {
1534 $wgMemc->set( $key, $res, $this->repo
->descriptionCacheExpiry
);
1543 * Get discription of file revision
1548 function getDescription() {
1553 * Get the 14-character timestamp of the file upload
1555 * @return string|bool TS_MW timestamp or false on failure
1557 function getTimestamp() {
1558 $this->assertRepoDefined();
1559 return $this->repo
->getFileTimestamp( $this->getPath() );
1563 * Get the SHA-1 base 36 hash of the file
1567 function getSha1() {
1568 $this->assertRepoDefined();
1569 return $this->repo
->getFileSha1( $this->getPath() );
1573 * Get the deletion archive key, <sha1>.<ext>
1577 function getStorageKey() {
1578 $hash = $this->getSha1();
1582 $ext = $this->getExtension();
1583 $dotExt = $ext === '' ?
'' : ".$ext";
1584 return $hash . $dotExt;
1588 * Determine if the current user is allowed to view a particular
1589 * field of this file, if it's marked as deleted.
1591 * @param $field Integer
1592 * @param $user User object to check, or null to use $wgUser
1595 function userCan( $field, User
$user = null ) {
1600 * Get an associative array containing information about a file in the local filesystem.
1602 * @param $path String: absolute local filesystem path
1603 * @param $ext Mixed: the file extension, or true to extract it from the filename.
1604 * Set it to false to ignore the extension.
1608 static function getPropsFromPath( $path, $ext = true ) {
1609 wfDebug( __METHOD__
.": Getting file info for $path\n" );
1610 wfDeprecated( __METHOD__
, '1.19' );
1612 $fsFile = new FSFile( $path );
1613 return $fsFile->getProps();
1617 * Get a SHA-1 hash of a file in the local filesystem, in base-36 lower case
1618 * encoding, zero padded to 31 digits.
1620 * 160 log 2 / log 36 = 30.95, so the 160-bit hash fills 31 digits in base 36
1623 * @param $path string
1625 * @return bool|string False on failure
1627 static function sha1Base36( $path ) {
1628 wfDeprecated( __METHOD__
, '1.19' );
1630 $fsFile = new FSFile( $path );
1631 return $fsFile->getSha1Base36();
1637 function getLongDesc() {
1638 $handler = $this->getHandler();
1640 return $handler->getLongDesc( $this );
1642 return MediaHandler
::getGeneralLongDesc( $this );
1649 function getShortDesc() {
1650 $handler = $this->getHandler();
1652 return $handler->getShortDesc( $this );
1654 return MediaHandler
::getGeneralShortDesc( $this );
1661 function getDimensionsString() {
1662 $handler = $this->getHandler();
1664 return $handler->getDimensionsString( $this );
1673 function getRedirected() {
1674 return $this->redirected
;
1680 function getRedirectedTitle() {
1681 if ( $this->redirected
) {
1682 if ( !$this->redirectTitle
) {
1683 $this->redirectTitle
= Title
::makeTitle( NS_FILE
, $this->redirected
);
1685 return $this->redirectTitle
;
1693 function redirectedFrom( $from ) {
1694 $this->redirected
= $from;
1700 function isMissing() {
1705 * Check if this file object is small and can be cached
1708 public function isCacheable() {
1713 * Assert that $this->repo is set to a valid FileRepo instance
1714 * @throws MWException
1716 protected function assertRepoDefined() {
1717 if ( !( $this->repo
instanceof $this->repoClass
) ) {
1718 throw new MWException( "A {$this->repoClass} object is not set for this File.\n" );
1723 * Assert that $this->title is set to a Title
1724 * @throws MWException
1726 protected function assertTitleDefined() {
1727 if ( !( $this->title
instanceof Title
) ) {
1728 throw new MWException( "A Title object is not set for this File.\n" );