3 * @defgroup FileAbstraction File abstraction
6 * Represents files in a repository.
10 * Base code for files.
12 * This program is free software; you can redistribute it and/or modify
13 * it under the terms of the GNU General Public License as published by
14 * the Free Software Foundation; either version 2 of the License, or
15 * (at your option) any later version.
17 * This program is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 * GNU General Public License for more details.
22 * You should have received a copy of the GNU General Public License along
23 * with this program; if not, write to the Free Software Foundation, Inc.,
24 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
25 * http://www.gnu.org/copyleft/gpl.html
28 * @ingroup FileAbstraction
32 * Implements some public methods and some protected utility functions which
33 * are required by multiple child classes. Contains stub functionality for
34 * unimplemented public methods.
36 * Stub functions which should be overridden are marked with STUB. Some more
37 * concrete functions are also typically overridden by child classes.
39 * Note that only the repo object knows what its file class is called. You should
40 * never name a file class explictly outside of the repo class. Instead use the
41 * repo's factory functions to generate file objects, for example:
43 * RepoGroup::singleton()->getLocalRepo()->newFile($title);
45 * The convenience functions wfLocalFile() and wfFindFile() should be sufficient
48 * @ingroup FileAbstraction
51 const DELETED_FILE
= 1;
52 const DELETED_COMMENT
= 2;
53 const DELETED_USER
= 4;
54 const DELETED_RESTRICTED
= 8;
56 /** Force rendering in the current process */
59 * Force rendering even if thumbnail already exist and using RENDER_NOW
60 * I.e. you have to pass both flags: File::RENDER_NOW | File::RENDER_FORCE
62 const RENDER_FORCE
= 2;
64 const DELETE_SOURCE
= 1;
67 * Some member variables can be lazy-initialised using __get(). The
68 * initialisation function for these variables is always a function named
69 * like getVar(), where Var is the variable name with upper-case first
72 * The following variables are initialised in this way in this base class:
73 * name, extension, handler, path, canRender, isSafeFile,
74 * transformScript, hashPath, pageCount, url
76 * Code within this class should generally use the accessor function
77 * directly, since __get() isn't re-entrant and therefore causes bugs that
78 * depend on initialisation order.
82 * The following member variables are not lazy-initialised
95 var $lastError, $redirected, $redirectedTitle;
98 * @var FSFile|bool False if undefined
110 protected $url, $extension, $name, $path, $hashPath, $pageCount, $transformScript;
115 protected $canRender, $isSafeFile;
118 * @var string Required Repository class type
120 protected $repoClass = 'FileRepo';
123 * Call this constructor from child classes.
125 * Both $title and $repo are optional, though some functions
126 * may return false or throw exceptions if they are not set.
127 * Most subclasses will want to call assertRepoDefined() here.
129 * @param $title Title|string|bool
130 * @param $repo FileRepo|bool
132 function __construct( $title, $repo ) {
133 if ( $title !== false ) { // subclasses may not use MW titles
134 $title = self
::normalizeTitle( $title, 'exception' );
136 $this->title
= $title;
141 * Given a string or Title object return either a
142 * valid Title object with namespace NS_FILE or null
144 * @param $title Title|string
145 * @param $exception string|bool Use 'exception' to throw an error on bad titles
148 static function normalizeTitle( $title, $exception = false ) {
150 if ( $ret instanceof Title
) {
151 # Normalize NS_MEDIA -> NS_FILE
152 if ( $ret->getNamespace() == NS_MEDIA
) {
153 $ret = Title
::makeTitleSafe( NS_FILE
, $ret->getDBkey() );
154 # Sanity check the title namespace
155 } elseif ( $ret->getNamespace() !== NS_FILE
) {
159 # Convert strings to Title objects
160 $ret = Title
::makeTitleSafe( NS_FILE
, (string)$ret );
162 if ( !$ret && $exception !== false ) {
163 throw new MWException( "`$title` is not a valid file title." );
168 function __get( $name ) {
169 $function = array( $this, 'get' . ucfirst( $name ) );
170 if ( !is_callable( $function ) ) {
173 $this->$name = call_user_func( $function );
179 * Normalize a file extension to the common form, and ensure it's clean.
180 * Extensions with non-alphanumeric characters will be discarded.
182 * @param $ext string (without the .)
185 static function normalizeExtension( $ext ) {
186 $lower = strtolower( $ext );
193 if( isset( $squish[$lower] ) ) {
194 return $squish[$lower];
195 } elseif( preg_match( '/^[0-9a-z]+$/', $lower ) ) {
203 * Checks if file extensions are compatible
205 * @param $old File Old file
206 * @param $new string New name
210 static function checkExtensionCompatibility( File
$old, $new ) {
211 $oldMime = $old->getMimeType();
212 $n = strrpos( $new, '.' );
213 $newExt = self
::normalizeExtension( $n ?
substr( $new, $n +
1 ) : '' );
214 $mimeMagic = MimeMagic
::singleton();
215 return $mimeMagic->isMatchingExtension( $newExt, $oldMime );
219 * Upgrade the database row if there is one
220 * Called by ImagePage
223 function upgradeRow() {}
226 * Split an internet media type into its two components; if not
227 * a two-part name, set the minor type to 'unknown'.
229 * @param string $mime "text/html" etc
230 * @return array ("text", "html") etc
232 public static function splitMime( $mime ) {
233 if( strpos( $mime, '/' ) !== false ) {
234 return explode( '/', $mime, 2 );
236 return array( $mime, 'unknown' );
241 * Return the name of this file
245 public function getName() {
246 if ( !isset( $this->name
) ) {
247 $this->assertRepoDefined();
248 $this->name
= $this->repo
->getNameFromTitle( $this->title
);
254 * Get the file extension, e.g. "svg"
258 function getExtension() {
259 if ( !isset( $this->extension
) ) {
260 $n = strrpos( $this->getName(), '.' );
261 $this->extension
= self
::normalizeExtension(
262 $n ?
substr( $this->getName(), $n +
1 ) : '' );
264 return $this->extension
;
268 * Return the associated title object
272 public function getTitle() {
277 * Return the title used to find this file
281 public function getOriginalTitle() {
282 if ( $this->redirected
) {
283 return $this->getRedirectedTitle();
289 * Return the URL of the file
293 public function getUrl() {
294 if ( !isset( $this->url
) ) {
295 $this->assertRepoDefined();
296 $this->url
= $this->repo
->getZoneUrl( 'public' ) . '/' . $this->getUrlRel();
302 * Return a fully-qualified URL to the file.
303 * Upload URL paths _may or may not_ be fully qualified, so
304 * we check. Local paths are assumed to belong on $wgServer.
308 public function getFullUrl() {
309 return wfExpandUrl( $this->getUrl(), PROTO_RELATIVE
);
315 public function getCanonicalUrl() {
316 return wfExpandUrl( $this->getUrl(), PROTO_CANONICAL
);
322 function getViewURL() {
323 if ( $this->mustRender() ) {
324 if ( $this->canRender() ) {
325 return $this->createThumb( $this->getWidth() );
327 wfDebug( __METHOD__
.': supposed to render ' . $this->getName() .
328 ' (' . $this->getMimeType() . "), but can't!\n" );
329 return $this->getURL(); #hm... return NULL?
332 return $this->getURL();
337 * Return the storage path to the file. Note that this does
338 * not mean that a file actually exists under that location.
340 * This path depends on whether directory hashing is active or not,
341 * i.e. whether the files are all found in the same directory,
342 * or in hashed paths like /images/3/3c.
344 * Most callers don't check the return value, but ForeignAPIFile::getPath
347 * @return string|bool ForeignAPIFile::getPath can return false
349 public function getPath() {
350 if ( !isset( $this->path
) ) {
351 $this->assertRepoDefined();
352 $this->path
= $this->repo
->getZonePath( 'public' ) . '/' . $this->getRel();
358 * Get an FS copy or original of this file and return the path.
359 * Returns false on failure. Callers must not alter the file.
360 * Temporary files are cleared automatically.
362 * @return string|bool False on failure
364 public function getLocalRefPath() {
365 $this->assertRepoDefined();
366 if ( !isset( $this->fsFile
) ) {
367 $this->fsFile
= $this->repo
->getLocalReference( $this->getPath() );
368 if ( !$this->fsFile
) {
369 $this->fsFile
= false; // null => false; cache negative hits
372 return ( $this->fsFile
)
373 ?
$this->fsFile
->getPath()
378 * Return the width of the image. Returns false if the width is unknown
382 * Overridden by LocalFile, UnregisteredLocalFile
388 public function getWidth( $page = 1 ) {
393 * Return the height of the image. Returns false if the height is unknown
397 * Overridden by LocalFile, UnregisteredLocalFile
401 * @return bool|number False on failure
403 public function getHeight( $page = 1 ) {
408 * Returns ID or name of user who uploaded the file
411 * @param $type string 'text' or 'id'
415 public function getUser( $type = 'text' ) {
420 * Get the duration of a media file in seconds
424 public function getLength() {
425 $handler = $this->getHandler();
427 return $handler->getLength( $this );
434 * Return true if the file is vectorized
438 public function isVectorized() {
439 $handler = $this->getHandler();
441 return $handler->isVectorized( $this );
448 * Get handler-specific metadata
449 * Overridden by LocalFile, UnregisteredLocalFile
453 public function getMetadata() {
458 * get versioned metadata
460 * @param $metadata Mixed Array or String of (serialized) metadata
461 * @param $version integer version number.
462 * @return Array containing metadata, or what was passed to it on fail (unserializing if not array)
464 public function convertMetadataVersion($metadata, $version) {
465 $handler = $this->getHandler();
466 if ( !is_array( $metadata ) ) {
467 // Just to make the return type consistent
468 $metadata = unserialize( $metadata );
471 return $handler->convertMetadataVersion( $metadata, $version );
478 * Return the bit depth of the file
479 * Overridden by LocalFile
483 public function getBitDepth() {
488 * Return the size of the image file, in bytes
489 * Overridden by LocalFile, UnregisteredLocalFile
493 public function getSize() {
498 * Returns the mime type of the file.
499 * Overridden by LocalFile, UnregisteredLocalFile
504 function getMimeType() {
505 return 'unknown/unknown';
509 * Return the type of the media in the file.
510 * Use the value returned by this function with the MEDIATYPE_xxx constants.
511 * Overridden by LocalFile,
515 function getMediaType() {
516 return MEDIATYPE_UNKNOWN
;
520 * Checks if the output of transform() for this file is likely
521 * to be valid. If this is false, various user elements will
522 * display a placeholder instead.
524 * Currently, this checks if the file is an image format
525 * that can be converted to a format
526 * supported by all browsers (namely GIF, PNG and JPEG),
527 * or if it is an SVG image and SVG conversion is enabled.
531 function canRender() {
532 if ( !isset( $this->canRender
) ) {
533 $this->canRender
= $this->getHandler() && $this->handler
->canRender( $this );
535 return $this->canRender
;
539 * Accessor for __get()
542 protected function getCanRender() {
543 return $this->canRender();
547 * Return true if the file is of a type that can't be directly
548 * rendered by typical browsers and needs to be re-rasterized.
550 * This returns true for everything but the bitmap types
551 * supported by all browsers, i.e. JPEG; GIF and PNG. It will
552 * also return true for any non-image formats.
556 function mustRender() {
557 return $this->getHandler() && $this->handler
->mustRender( $this );
561 * Alias for canRender()
565 function allowInlineDisplay() {
566 return $this->canRender();
570 * Determines if this media file is in a format that is unlikely to
571 * contain viruses or malicious content. It uses the global
572 * $wgTrustedMediaFormats list to determine if the file is safe.
574 * This is used to show a warning on the description page of non-safe files.
575 * It may also be used to disallow direct [[media:...]] links to such files.
577 * Note that this function will always return true if allowInlineDisplay()
578 * or isTrustedFile() is true for this file.
582 function isSafeFile() {
583 if ( !isset( $this->isSafeFile
) ) {
584 $this->isSafeFile
= $this->_getIsSafeFile();
586 return $this->isSafeFile
;
590 * Accessor for __get()
594 protected function getIsSafeFile() {
595 return $this->isSafeFile();
603 protected function _getIsSafeFile() {
604 global $wgTrustedMediaFormats;
606 if ( $this->allowInlineDisplay() ) {
609 if ($this->isTrustedFile()) {
613 $type = $this->getMediaType();
614 $mime = $this->getMimeType();
615 #wfDebug("LocalFile::isSafeFile: type= $type, mime= $mime\n");
617 if ( !$type ||
$type === MEDIATYPE_UNKNOWN
) {
618 return false; #unknown type, not trusted
620 if ( in_array( $type, $wgTrustedMediaFormats ) ) {
624 if ( $mime === "unknown/unknown" ) {
625 return false; #unknown type, not trusted
627 if ( in_array( $mime, $wgTrustedMediaFormats) ) {
635 * Returns true if the file is flagged as trusted. Files flagged that way
636 * can be linked to directly, even if that is not allowed for this type of
639 * This is a dummy function right now and always returns false. It could be
640 * implemented to extract a flag from the database. The trusted flag could be
641 * set on upload, if the user has sufficient privileges, to bypass script-
642 * and html-filters. It may even be coupled with cryptographics signatures
647 function isTrustedFile() {
648 #this could be implemented to check a flag in the database,
649 #look for signatures, etc
654 * Returns true if file exists in the repository.
656 * Overridden by LocalFile to avoid unnecessary stat calls.
658 * @return boolean Whether file exists in the repository.
660 public function exists() {
661 return $this->getPath() && $this->repo
->fileExists( $this->path
);
665 * Returns true if file exists in the repository and can be included in a page.
666 * It would be unsafe to include private images, making public thumbnails inadvertently
668 * @return boolean Whether file exists in the repository and is includable.
670 public function isVisible() {
671 return $this->exists();
677 function getTransformScript() {
678 if ( !isset( $this->transformScript
) ) {
679 $this->transformScript
= false;
681 $script = $this->repo
->getThumbScriptUrl();
683 $this->transformScript
= "$script?f=" . urlencode( $this->getName() );
687 return $this->transformScript
;
691 * Get a ThumbnailImage which is the same size as the source
693 * @param $handlerParams array
697 function getUnscaledThumb( $handlerParams = array() ) {
698 $hp =& $handlerParams;
699 $page = isset( $hp['page'] ) ?
$hp['page'] : false;
700 $width = $this->getWidth( $page );
702 return $this->iconThumb();
704 $hp['width'] = $width;
705 return $this->transform( $hp );
709 * Return the file name of a thumbnail with the specified parameters
711 * @param $params Array: handler-specific parameters
716 function thumbName( $params ) {
717 return $this->generateThumbName( $this->getName(), $params );
721 * Generate a thumbnail file name from a name and specified parameters
723 * @param string $name
724 * @param array $params Parameters which will be passed to MediaHandler::makeParamString
728 function generateThumbName( $name, $params ) {
729 if ( !$this->getHandler() ) {
732 $extension = $this->getExtension();
733 list( $thumbExt, $thumbMime ) = $this->handler
->getThumbType(
734 $extension, $this->getMimeType(), $params );
735 $thumbName = $this->handler
->makeParamString( $params ) . '-' . $name;
736 if ( $thumbExt != $extension ) {
737 $thumbName .= ".$thumbExt";
743 * Create a thumbnail of the image having the specified width/height.
744 * The thumbnail will not be created if the width is larger than the
745 * image's width. Let the browser do the scaling in this case.
746 * The thumbnail is stored on disk and is only computed if the thumbnail
747 * file does not exist OR if it is older than the image.
750 * Keeps aspect ratio of original image. If both width and height are
751 * specified, the generated image will be no bigger than width x height,
752 * and will also have correct aspect ratio.
754 * @param $width Integer: maximum width of the generated thumbnail
755 * @param $height Integer: maximum height of the image (optional)
759 public function createThumb( $width, $height = -1 ) {
760 $params = array( 'width' => $width );
761 if ( $height != -1 ) {
762 $params['height'] = $height;
764 $thumb = $this->transform( $params );
765 if ( is_null( $thumb ) ||
$thumb->isError() ) {
768 return $thumb->getUrl();
772 * Return either a MediaTransformError or placeholder thumbnail (if $wgIgnoreImageErrors)
774 * @param $thumbPath string Thumbnail storage path
775 * @param $thumbUrl string Thumbnail URL
776 * @param $params Array
777 * @param $flags integer
778 * @return MediaTransformOutput
780 protected function transformErrorOutput( $thumbPath, $thumbUrl, $params, $flags ) {
781 global $wgIgnoreImageErrors;
783 if ( $wgIgnoreImageErrors && !( $flags & self
::RENDER_NOW
) ) {
784 return $this->handler
->getTransform( $this, $thumbPath, $thumbUrl, $params );
786 return new MediaTransformError( 'thumbnail_error',
787 $params['width'], 0, wfMsg( 'thumbnail-dest-create' ) );
792 * Transform a media file
794 * @param $params Array: an associative array of handler-specific parameters.
795 * Typical keys are width, height and page.
796 * @param $flags Integer: a bitfield, may contain self::RENDER_NOW to force rendering
797 * @return MediaTransformOutput|bool False on failure
799 function transform( $params, $flags = 0 ) {
800 global $wgUseSquid, $wgIgnoreImageErrors, $wgThumbnailEpoch;
802 wfProfileIn( __METHOD__
);
804 if ( !$this->canRender() ) {
805 $thumb = $this->iconThumb();
806 break; // not a bitmap or renderable image, don't try
809 // Get the descriptionUrl to embed it as comment into the thumbnail. Bug 19791.
810 $descriptionUrl = $this->getDescriptionUrl();
811 if ( $descriptionUrl ) {
812 $params['descriptionUrl'] = wfExpandUrl( $descriptionUrl, PROTO_CANONICAL
);
815 $script = $this->getTransformScript();
816 if ( $script && !( $flags & self
::RENDER_NOW
) ) {
817 // Use a script to transform on client request, if possible
818 $thumb = $this->handler
->getScriptedTransform( $this, $script, $params );
824 $normalisedParams = $params;
825 $this->handler
->normaliseParams( $this, $normalisedParams );
827 $thumbName = $this->thumbName( $normalisedParams );
828 $thumbUrl = $this->getThumbUrl( $thumbName );
829 $thumbPath = $this->getThumbPath( $thumbName ); // final thumb path
832 // Defer rendering if a 404 handler is set up...
833 if ( $this->repo
->canTransformVia404() && !( $flags & self
::RENDER_NOW
) ) {
834 wfDebug( __METHOD__
. " transformation deferred." );
835 // XXX: Pass in the storage path even though we are not rendering anything
836 // and the path is supposed to be an FS path. This is due to getScalerType()
837 // getting called on the path and clobbering $thumb->getUrl() if it's false.
838 $thumb = $this->handler
->getTransform( $this, $thumbPath, $thumbUrl, $params );
841 // Clean up broken thumbnails as needed
842 $this->migrateThumbFile( $thumbName );
843 // Check if an up-to-date thumbnail already exists...
844 wfDebug( __METHOD__
.": Doing stat for $thumbPath\n" );
845 if ( $this->repo
->fileExists( $thumbPath ) && !( $flags & self
::RENDER_FORCE
) ) {
846 $timestamp = $this->repo
->getFileTimestamp( $thumbPath );
847 if ( $timestamp !== false && $timestamp >= $wgThumbnailEpoch ) {
848 // XXX: Pass in the storage path even though we are not rendering anything
849 // and the path is supposed to be an FS path. This is due to getScalerType()
850 // getting called on the path and clobbering $thumb->getUrl() if it's false.
851 $thumb = $this->handler
->getTransform( $this, $thumbPath, $thumbUrl, $params );
852 $thumb->setStoragePath( $thumbPath );
855 } elseif ( $flags & self
::RENDER_FORCE
) {
856 wfDebug( __METHOD__
. " forcing rendering per flag File::RENDER_FORCE\n" );
860 // If the backend is ready-only, don't keep generating thumbnails
861 // only to return transformation errors, just return the error now.
862 if ( $this->repo
->getReadOnlyReason() !== false ) {
863 $thumb = $this->transformErrorOutput( $thumbPath, $thumbUrl, $params, $flags );
867 // Create a temp FS file with the same extension and the thumbnail
868 $thumbExt = FileBackend
::extensionFromPath( $thumbPath );
869 $tmpFile = TempFSFile
::factory( 'transform_', $thumbExt );
871 $thumb = $this->transformErrorOutput( $thumbPath, $thumbUrl, $params, $flags );
874 $tmpThumbPath = $tmpFile->getPath(); // path of 0-byte temp file
876 // Actually render the thumbnail...
877 $thumb = $this->handler
->doTransform( $this, $tmpThumbPath, $thumbUrl, $params );
878 $tmpFile->bind( $thumb ); // keep alive with $thumb
880 if ( !$thumb ) { // bad params?
882 } elseif ( $thumb->isError() ) { // transform error
883 $this->lastError
= $thumb->toText();
884 // Ignore errors if requested
885 if ( $wgIgnoreImageErrors && !( $flags & self
::RENDER_NOW
) ) {
886 $thumb = $this->handler
->getTransform( $this, $tmpThumbPath, $thumbUrl, $params );
888 } elseif ( $this->repo
&& $thumb->hasFile() && !$thumb->fileIsSource() ) {
889 // Copy the thumbnail from the file system into storage...
890 $status = $this->repo
->quickImport( $tmpThumbPath, $thumbPath );
891 if ( $status->isOK() ) {
892 $thumb->setStoragePath( $thumbPath );
894 $thumb = $this->transformErrorOutput( $thumbPath, $thumbUrl, $params, $flags );
896 // Give extensions a chance to do something with this thumbnail...
897 wfRunHooks( 'FileTransformed', array( $this, $thumb, $tmpThumbPath, $thumbPath ) );
900 // Purge. Useful in the event of Core -> Squid connection failure or squid
901 // purge collisions from elsewhere during failure. Don't keep triggering for
902 // "thumbs" which have the main image URL though (bug 13776)
904 if ( !$thumb ||
$thumb->isError() ||
$thumb->getUrl() != $this->getURL() ) {
905 SquidUpdate
::purge( array( $thumbUrl ) );
910 wfProfileOut( __METHOD__
);
911 return is_object( $thumb ) ?
$thumb : false;
915 * Hook into transform() to allow migration of thumbnail files
917 * Overridden by LocalFile
919 function migrateThumbFile( $thumbName ) {}
922 * Get a MediaHandler instance for this file
924 * @return MediaHandler
926 function getHandler() {
927 if ( !isset( $this->handler
) ) {
928 $this->handler
= MediaHandler
::getHandler( $this->getMimeType() );
930 return $this->handler
;
934 * Get a ThumbnailImage representing a file type icon
936 * @return ThumbnailImage
938 function iconThumb() {
939 global $wgStylePath, $wgStyleDirectory;
941 $try = array( 'fileicon-' . $this->getExtension() . '.png', 'fileicon.png' );
942 foreach ( $try as $icon ) {
943 $path = '/common/images/icons/' . $icon;
944 $filepath = $wgStyleDirectory . $path;
945 if ( file_exists( $filepath ) ) { // always FS
946 return new ThumbnailImage( $this, $wgStylePath . $path, 120, 120 );
953 * Get last thumbnailing error.
956 function getLastError() {
957 return $this->lastError
;
961 * Get all thumbnail names previously generated for this file
963 * Overridden by LocalFile
966 function getThumbnails() {
971 * Purge shared caches such as thumbnails and DB data caching
973 * Overridden by LocalFile
974 * @param $options Array Options, which include:
975 * 'forThumbRefresh' : The purging is only to refresh thumbnails
977 function purgeCache( $options = array() ) {}
980 * Purge the file description page, but don't go after
981 * pages using the file. Use when modifying file history
982 * but not the current data.
984 function purgeDescription() {
985 $title = $this->getTitle();
987 $title->invalidateCache();
988 $title->purgeSquid();
993 * Purge metadata and all affected pages when the file is created,
994 * deleted, or majorly updated.
996 function purgeEverything() {
997 // Delete thumbnails and refresh file metadata cache
999 $this->purgeDescription();
1001 // Purge cache of all pages using this file
1002 $title = $this->getTitle();
1004 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
1005 $update->doUpdate();
1010 * Return a fragment of the history of file.
1013 * @param $limit integer Limit of rows to return
1014 * @param $start string timestamp Only revisions older than $start will be returned
1015 * @param $end string timestamp Only revisions newer than $end will be returned
1016 * @param $inc bool Include the endpoints of the time range
1020 function getHistory($limit = null, $start = null, $end = null, $inc=true) {
1025 * Return the history of this file, line by line. Starts with current version,
1026 * then old versions. Should return an object similar to an image/oldimage
1030 * Overridden in LocalFile
1033 public function nextHistoryLine() {
1038 * Reset the history pointer to the first element of the history.
1039 * Always call this function after using nextHistoryLine() to free db resources
1041 * Overridden in LocalFile.
1043 public function resetHistory() {}
1046 * Get the filename hash component of the directory including trailing slash,
1048 * If the repository is not hashed, returns an empty string.
1052 function getHashPath() {
1053 if ( !isset( $this->hashPath
) ) {
1054 $this->assertRepoDefined();
1055 $this->hashPath
= $this->repo
->getHashPath( $this->getName() );
1057 return $this->hashPath
;
1061 * Get the path of the file relative to the public zone root.
1062 * This function is overriden in OldLocalFile to be like getArchiveRel().
1067 return $this->getHashPath() . $this->getName();
1071 * Get the path of an archived file relative to the public zone root
1073 * @param $suffix bool|string if not false, the name of an archived thumbnail file
1077 function getArchiveRel( $suffix = false ) {
1078 $path = 'archive/' . $this->getHashPath();
1079 if ( $suffix === false ) {
1080 $path = substr( $path, 0, -1 );
1088 * Get the path, relative to the thumbnail zone root, of the
1089 * thumbnail directory or a particular file if $suffix is specified
1091 * @param $suffix bool|string if not false, the name of a thumbnail file
1095 function getThumbRel( $suffix = false ) {
1096 $path = $this->getRel();
1097 if ( $suffix !== false ) {
1098 $path .= '/' . $suffix;
1104 * Get urlencoded path of the file relative to the public zone root.
1105 * This function is overriden in OldLocalFile to be like getArchiveUrl().
1109 function getUrlRel() {
1110 return $this->getHashPath() . rawurlencode( $this->getName() );
1114 * Get the path, relative to the thumbnail zone root, for an archived file's thumbs directory
1115 * or a specific thumb if the $suffix is given.
1117 * @param $archiveName string the timestamped name of an archived image
1118 * @param $suffix bool|string if not false, the name of a thumbnail file
1122 function getArchiveThumbRel( $archiveName, $suffix = false ) {
1123 $path = 'archive/' . $this->getHashPath() . $archiveName . "/";
1124 if ( $suffix === false ) {
1125 $path = substr( $path, 0, -1 );
1133 * Get the path of the archived file.
1135 * @param $suffix bool|string if not false, the name of an archived file.
1139 function getArchivePath( $suffix = false ) {
1140 $this->assertRepoDefined();
1141 return $this->repo
->getZonePath( 'public' ) . '/' . $this->getArchiveRel( $suffix );
1145 * Get the path of an archived file's thumbs, or a particular thumb if $suffix is specified
1147 * @param $archiveName string the timestamped name of an archived image
1148 * @param $suffix bool|string if not false, the name of a thumbnail file
1152 function getArchiveThumbPath( $archiveName, $suffix = false ) {
1153 $this->assertRepoDefined();
1154 return $this->repo
->getZonePath( 'thumb' ) . '/' .
1155 $this->getArchiveThumbRel( $archiveName, $suffix );
1159 * Get the path of the thumbnail directory, or a particular file if $suffix is specified
1161 * @param $suffix bool|string if not false, the name of a thumbnail file
1165 function getThumbPath( $suffix = false ) {
1166 $this->assertRepoDefined();
1167 return $this->repo
->getZonePath( 'thumb' ) . '/' . $this->getThumbRel( $suffix );
1171 * Get the URL of the archive directory, or a particular file if $suffix is specified
1173 * @param $suffix bool|string if not false, the name of an archived file
1177 function getArchiveUrl( $suffix = false ) {
1178 $this->assertRepoDefined();
1179 $path = $this->repo
->getZoneUrl( 'public' ) . '/archive/' . $this->getHashPath();
1180 if ( $suffix === false ) {
1181 $path = substr( $path, 0, -1 );
1183 $path .= rawurlencode( $suffix );
1189 * Get the URL of the archived file's thumbs, or a particular thumb if $suffix is specified
1191 * @param $archiveName string the timestamped name of an archived image
1192 * @param $suffix bool|string if not false, the name of a thumbnail file
1196 function getArchiveThumbUrl( $archiveName, $suffix = false ) {
1197 $this->assertRepoDefined();
1198 $path = $this->repo
->getZoneUrl( 'thumb' ) . '/archive/' .
1199 $this->getHashPath() . rawurlencode( $archiveName ) . "/";
1200 if ( $suffix === false ) {
1201 $path = substr( $path, 0, -1 );
1203 $path .= rawurlencode( $suffix );
1209 * Get the URL of the thumbnail directory, or a particular file if $suffix is specified
1211 * @param $suffix bool|string if not false, the name of a thumbnail file
1213 * @return string path
1215 function getThumbUrl( $suffix = false ) {
1216 $this->assertRepoDefined();
1217 $path = $this->repo
->getZoneUrl( 'thumb' ) . '/' . $this->getUrlRel();
1218 if ( $suffix !== false ) {
1219 $path .= '/' . rawurlencode( $suffix );
1225 * Get the public zone virtual URL for a current version source file
1227 * @param $suffix bool|string if not false, the name of a thumbnail file
1231 function getVirtualUrl( $suffix = false ) {
1232 $this->assertRepoDefined();
1233 $path = $this->repo
->getVirtualUrl() . '/public/' . $this->getUrlRel();
1234 if ( $suffix !== false ) {
1235 $path .= '/' . rawurlencode( $suffix );
1241 * Get the public zone virtual URL for an archived version source file
1243 * @param $suffix bool|string if not false, the name of a thumbnail file
1247 function getArchiveVirtualUrl( $suffix = false ) {
1248 $this->assertRepoDefined();
1249 $path = $this->repo
->getVirtualUrl() . '/public/archive/' . $this->getHashPath();
1250 if ( $suffix === false ) {
1251 $path = substr( $path, 0, -1 );
1253 $path .= rawurlencode( $suffix );
1259 * Get the virtual URL for a thumbnail file or directory
1261 * @param $suffix bool|string if not false, the name of a thumbnail file
1265 function getThumbVirtualUrl( $suffix = false ) {
1266 $this->assertRepoDefined();
1267 $path = $this->repo
->getVirtualUrl() . '/thumb/' . $this->getUrlRel();
1268 if ( $suffix !== false ) {
1269 $path .= '/' . rawurlencode( $suffix );
1277 function isHashed() {
1278 $this->assertRepoDefined();
1279 return (bool)$this->repo
->getHashLevels();
1283 * @throws MWException
1285 function readOnlyError() {
1286 throw new MWException( get_class($this) . ': write operations are not supported' );
1290 * Record a file upload in the upload log and the image table
1292 * Overridden by LocalFile
1295 * @param $license string
1296 * @param $copyStatus string
1297 * @param $source string
1298 * @param $watch bool
1300 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '', $watch = false ) {
1301 $this->readOnlyError();
1305 * Move or copy a file to its public location. If a file exists at the
1306 * destination, move it to an archive. Returns a FileRepoStatus object with
1307 * the archive name in the "value" member on success.
1309 * The archive name should be passed through to recordUpload for database
1312 * @param $srcPath String: local filesystem path to the source image
1313 * @param $flags Integer: a bitwise combination of:
1314 * File::DELETE_SOURCE Delete the source file, i.e. move
1316 * @return FileRepoStatus object. On success, the value member contains the
1317 * archive name, or an empty string if it was a new file.
1320 * Overridden by LocalFile
1322 function publish( $srcPath, $flags = 0 ) {
1323 $this->readOnlyError();
1329 function formatMetadata() {
1330 if ( !$this->getHandler() ) {
1333 return $this->getHandler()->formatMetadata( $this, $this->getMetadata() );
1337 * Returns true if the file comes from the local file repository.
1341 function isLocal() {
1342 return $this->repo
&& $this->repo
->isLocal();
1346 * Returns the name of the repository.
1350 function getRepoName() {
1351 return $this->repo ?
$this->repo
->getName() : 'unknown';
1355 * Returns the repository
1357 * @return FileRepo|bool
1359 function getRepo() {
1364 * Returns true if the image is an old version
1374 * Is this file a "deleted" file in a private archive?
1381 function isDeleted( $field ) {
1386 * Return the deletion bitfield
1390 function getVisibility() {
1395 * Was this file ever deleted from the wiki?
1399 function wasDeleted() {
1400 $title = $this->getTitle();
1401 return $title && $title->isDeletedQuick();
1405 * Move file to the new title
1407 * Move current, old version and all thumbnails
1408 * to the new filename. Old file is deleted.
1410 * Cache purging is done; checks for validity
1411 * and logging are caller's responsibility
1413 * @param $target Title New file name
1414 * @return FileRepoStatus object.
1416 function move( $target ) {
1417 $this->readOnlyError();
1421 * Delete all versions of the file.
1423 * Moves the files into an archive directory (or deletes them)
1424 * and removes the database rows.
1426 * Cache purging is done; logging is caller's responsibility.
1428 * @param $reason String
1429 * @param $suppress Boolean: hide content from sysops?
1430 * @return bool on success, false on some kind of failure
1432 * Overridden by LocalFile
1434 function delete( $reason, $suppress = false ) {
1435 $this->readOnlyError();
1439 * Restore all or specified deleted revisions to the given file.
1440 * Permissions and logging are left to the caller.
1442 * May throw database exceptions on error.
1444 * @param $versions array set of record ids of deleted items to restore,
1445 * or empty to restore all revisions.
1446 * @param $unsuppress bool remove restrictions on content upon restoration?
1447 * @return int|bool the number of file revisions restored if successful,
1448 * or false on failure
1450 * Overridden by LocalFile
1452 function restore( $versions = array(), $unsuppress = false ) {
1453 $this->readOnlyError();
1457 * Returns 'true' if this file is a type which supports multiple pages,
1458 * e.g. DJVU or PDF. Note that this may be true even if the file in
1459 * question only has a single page.
1463 function isMultipage() {
1464 return $this->getHandler() && $this->handler
->isMultiPage( $this );
1468 * Returns the number of pages of a multipage document, or false for
1469 * documents which aren't multipage documents
1473 function pageCount() {
1474 if ( !isset( $this->pageCount
) ) {
1475 if ( $this->getHandler() && $this->handler
->isMultiPage( $this ) ) {
1476 $this->pageCount
= $this->handler
->pageCount( $this );
1478 $this->pageCount
= false;
1481 return $this->pageCount
;
1485 * Calculate the height of a thumbnail using the source and destination width
1493 static function scaleHeight( $srcWidth, $srcHeight, $dstWidth ) {
1494 // Exact integer multiply followed by division
1495 if ( $srcWidth == 0 ) {
1498 return round( $srcHeight * $dstWidth / $srcWidth );
1503 * Get an image size array like that returned by getImageSize(), or false if it
1504 * can't be determined.
1506 * @param $fileName String: The filename
1509 function getImageSize( $fileName ) {
1510 if ( !$this->getHandler() ) {
1513 return $this->handler
->getImageSize( $this, $fileName );
1517 * Get the URL of the image description page. May return false if it is
1518 * unknown or not applicable.
1522 function getDescriptionUrl() {
1523 if ( $this->repo
) {
1524 return $this->repo
->getDescriptionUrl( $this->getName() );
1531 * Get the HTML text of the description page, if available
1535 function getDescriptionText() {
1536 global $wgMemc, $wgLang;
1537 if ( !$this->repo ||
!$this->repo
->fetchDescription
) {
1540 $renderUrl = $this->repo
->getDescriptionRenderUrl( $this->getName(), $wgLang->getCode() );
1542 if ( $this->repo
->descriptionCacheExpiry
> 0 ) {
1543 wfDebug("Attempting to get the description from cache...");
1544 $key = $this->repo
->getLocalCacheKey( 'RemoteFileDescription', 'url', $wgLang->getCode(),
1546 $obj = $wgMemc->get($key);
1548 wfDebug("success!\n");
1553 wfDebug( "Fetching shared description from $renderUrl\n" );
1554 $res = Http
::get( $renderUrl );
1555 if ( $res && $this->repo
->descriptionCacheExpiry
> 0 ) {
1556 $wgMemc->set( $key, $res, $this->repo
->descriptionCacheExpiry
);
1565 * Get discription of file revision
1570 function getDescription() {
1575 * Get the 14-character timestamp of the file upload
1577 * @return string|bool TS_MW timestamp or false on failure
1579 function getTimestamp() {
1580 $this->assertRepoDefined();
1581 return $this->repo
->getFileTimestamp( $this->getPath() );
1585 * Get the SHA-1 base 36 hash of the file
1589 function getSha1() {
1590 $this->assertRepoDefined();
1591 return $this->repo
->getFileSha1( $this->getPath() );
1595 * Get the deletion archive key, <sha1>.<ext>
1599 function getStorageKey() {
1600 $hash = $this->getSha1();
1604 $ext = $this->getExtension();
1605 $dotExt = $ext === '' ?
'' : ".$ext";
1606 return $hash . $dotExt;
1610 * Determine if the current user is allowed to view a particular
1611 * field of this file, if it's marked as deleted.
1613 * @param $field Integer
1614 * @param $user User object to check, or null to use $wgUser
1617 function userCan( $field, User
$user = null ) {
1622 * Get an associative array containing information about a file in the local filesystem.
1624 * @param $path String: absolute local filesystem path
1625 * @param $ext Mixed: the file extension, or true to extract it from the filename.
1626 * Set it to false to ignore the extension.
1630 static function getPropsFromPath( $path, $ext = true ) {
1631 wfDebug( __METHOD__
.": Getting file info for $path\n" );
1632 wfDeprecated( __METHOD__
, '1.19' );
1634 $fsFile = new FSFile( $path );
1635 return $fsFile->getProps();
1639 * Get a SHA-1 hash of a file in the local filesystem, in base-36 lower case
1640 * encoding, zero padded to 31 digits.
1642 * 160 log 2 / log 36 = 30.95, so the 160-bit hash fills 31 digits in base 36
1645 * @param $path string
1647 * @return bool|string False on failure
1649 static function sha1Base36( $path ) {
1650 wfDeprecated( __METHOD__
, '1.19' );
1652 $fsFile = new FSFile( $path );
1653 return $fsFile->getSha1Base36();
1659 function getLongDesc() {
1660 $handler = $this->getHandler();
1662 return $handler->getLongDesc( $this );
1664 return MediaHandler
::getGeneralLongDesc( $this );
1671 function getShortDesc() {
1672 $handler = $this->getHandler();
1674 return $handler->getShortDesc( $this );
1676 return MediaHandler
::getGeneralShortDesc( $this );
1683 function getDimensionsString() {
1684 $handler = $this->getHandler();
1686 return $handler->getDimensionsString( $this );
1695 function getRedirected() {
1696 return $this->redirected
;
1702 function getRedirectedTitle() {
1703 if ( $this->redirected
) {
1704 if ( !$this->redirectTitle
) {
1705 $this->redirectTitle
= Title
::makeTitle( NS_FILE
, $this->redirected
);
1707 return $this->redirectTitle
;
1715 function redirectedFrom( $from ) {
1716 $this->redirected
= $from;
1722 function isMissing() {
1727 * Check if this file object is small and can be cached
1730 public function isCacheable() {
1735 * Assert that $this->repo is set to a valid FileRepo instance
1736 * @throws MWException
1738 protected function assertRepoDefined() {
1739 if ( !( $this->repo
instanceof $this->repoClass
) ) {
1740 throw new MWException( "A {$this->repoClass} object is not set for this File.\n" );
1745 * Assert that $this->title is set to a Title
1746 * @throws MWException
1748 protected function assertTitleDefined() {
1749 if ( !( $this->title
instanceof Title
) ) {
1750 throw new MWException( "A Title object is not set for this File.\n" );