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;
112 protected $redirectTitle;
117 protected $canRender, $isSafeFile;
120 * @var string Required Repository class type
122 protected $repoClass = 'FileRepo';
125 * Call this constructor from child classes.
127 * Both $title and $repo are optional, though some functions
128 * may return false or throw exceptions if they are not set.
129 * Most subclasses will want to call assertRepoDefined() here.
131 * @param $title Title|string|bool
132 * @param $repo FileRepo|bool
134 function __construct( $title, $repo ) {
135 if ( $title !== false ) { // subclasses may not use MW titles
136 $title = self
::normalizeTitle( $title, 'exception' );
138 $this->title
= $title;
143 * Given a string or Title object return either a
144 * valid Title object with namespace NS_FILE or null
146 * @param $title Title|string
147 * @param $exception string|bool Use 'exception' to throw an error on bad titles
148 * @throws MWException
151 static function normalizeTitle( $title, $exception = false ) {
153 if ( $ret instanceof Title
) {
154 # Normalize NS_MEDIA -> NS_FILE
155 if ( $ret->getNamespace() == NS_MEDIA
) {
156 $ret = Title
::makeTitleSafe( NS_FILE
, $ret->getDBkey() );
157 # Sanity check the title namespace
158 } elseif ( $ret->getNamespace() !== NS_FILE
) {
162 # Convert strings to Title objects
163 $ret = Title
::makeTitleSafe( NS_FILE
, (string)$ret );
165 if ( !$ret && $exception !== false ) {
166 throw new MWException( "`$title` is not a valid file title." );
171 function __get( $name ) {
172 $function = array( $this, 'get' . ucfirst( $name ) );
173 if ( !is_callable( $function ) ) {
176 $this->$name = call_user_func( $function );
182 * Normalize a file extension to the common form, and ensure it's clean.
183 * Extensions with non-alphanumeric characters will be discarded.
185 * @param $ext string (without the .)
188 static function normalizeExtension( $ext ) {
189 $lower = strtolower( $ext );
196 if( isset( $squish[$lower] ) ) {
197 return $squish[$lower];
198 } elseif( preg_match( '/^[0-9a-z]+$/', $lower ) ) {
206 * Checks if file extensions are compatible
208 * @param $old File Old file
209 * @param $new string New name
213 static function checkExtensionCompatibility( File
$old, $new ) {
214 $oldMime = $old->getMimeType();
215 $n = strrpos( $new, '.' );
216 $newExt = self
::normalizeExtension( $n ?
substr( $new, $n +
1 ) : '' );
217 $mimeMagic = MimeMagic
::singleton();
218 return $mimeMagic->isMatchingExtension( $newExt, $oldMime );
222 * Upgrade the database row if there is one
223 * Called by ImagePage
226 function upgradeRow() {}
229 * Split an internet media type into its two components; if not
230 * a two-part name, set the minor type to 'unknown'.
232 * @param string $mime "text/html" etc
233 * @return array ("text", "html") etc
235 public static function splitMime( $mime ) {
236 if( strpos( $mime, '/' ) !== false ) {
237 return explode( '/', $mime, 2 );
239 return array( $mime, 'unknown' );
244 * Return the name of this file
248 public function getName() {
249 if ( !isset( $this->name
) ) {
250 $this->assertRepoDefined();
251 $this->name
= $this->repo
->getNameFromTitle( $this->title
);
257 * Get the file extension, e.g. "svg"
261 function getExtension() {
262 if ( !isset( $this->extension
) ) {
263 $n = strrpos( $this->getName(), '.' );
264 $this->extension
= self
::normalizeExtension(
265 $n ?
substr( $this->getName(), $n +
1 ) : '' );
267 return $this->extension
;
271 * Return the associated title object
275 public function getTitle() {
280 * Return the title used to find this file
284 public function getOriginalTitle() {
285 if ( $this->redirected
) {
286 return $this->getRedirectedTitle();
292 * Return the URL of the file
296 public function getUrl() {
297 if ( !isset( $this->url
) ) {
298 $this->assertRepoDefined();
299 $this->url
= $this->repo
->getZoneUrl( 'public' ) . '/' . $this->getUrlRel();
305 * Return a fully-qualified URL to the file.
306 * Upload URL paths _may or may not_ be fully qualified, so
307 * we check. Local paths are assumed to belong on $wgServer.
311 public function getFullUrl() {
312 return wfExpandUrl( $this->getUrl(), PROTO_RELATIVE
);
318 public function getCanonicalUrl() {
319 return wfExpandUrl( $this->getUrl(), PROTO_CANONICAL
);
325 function getViewURL() {
326 if ( $this->mustRender() ) {
327 if ( $this->canRender() ) {
328 return $this->createThumb( $this->getWidth() );
330 wfDebug( __METHOD__
.': supposed to render ' . $this->getName() .
331 ' (' . $this->getMimeType() . "), but can't!\n" );
332 return $this->getURL(); #hm... return NULL?
335 return $this->getURL();
340 * Return the storage path to the file. Note that this does
341 * not mean that a file actually exists under that location.
343 * This path depends on whether directory hashing is active or not,
344 * i.e. whether the files are all found in the same directory,
345 * or in hashed paths like /images/3/3c.
347 * Most callers don't check the return value, but ForeignAPIFile::getPath
350 * @return string|bool ForeignAPIFile::getPath can return false
352 public function getPath() {
353 if ( !isset( $this->path
) ) {
354 $this->assertRepoDefined();
355 $this->path
= $this->repo
->getZonePath( 'public' ) . '/' . $this->getRel();
361 * Get an FS copy or original of this file and return the path.
362 * Returns false on failure. Callers must not alter the file.
363 * Temporary files are cleared automatically.
365 * @return string|bool False on failure
367 public function getLocalRefPath() {
368 $this->assertRepoDefined();
369 if ( !isset( $this->fsFile
) ) {
370 $this->fsFile
= $this->repo
->getLocalReference( $this->getPath() );
371 if ( !$this->fsFile
) {
372 $this->fsFile
= false; // null => false; cache negative hits
375 return ( $this->fsFile
)
376 ?
$this->fsFile
->getPath()
381 * Return the width of the image. Returns false if the width is unknown
385 * Overridden by LocalFile, UnregisteredLocalFile
391 public function getWidth( $page = 1 ) {
396 * Return the height of the image. Returns false if the height is unknown
400 * Overridden by LocalFile, UnregisteredLocalFile
404 * @return bool|number False on failure
406 public function getHeight( $page = 1 ) {
411 * Returns ID or name of user who uploaded the file
414 * @param $type string 'text' or 'id'
418 public function getUser( $type = 'text' ) {
423 * Get the duration of a media file in seconds
427 public function getLength() {
428 $handler = $this->getHandler();
430 return $handler->getLength( $this );
437 * Return true if the file is vectorized
441 public function isVectorized() {
442 $handler = $this->getHandler();
444 return $handler->isVectorized( $this );
451 * Get handler-specific metadata
452 * Overridden by LocalFile, UnregisteredLocalFile
456 public function getMetadata() {
461 * get versioned metadata
463 * @param $metadata Mixed Array or String of (serialized) metadata
464 * @param $version integer version number.
465 * @return Array containing metadata, or what was passed to it on fail (unserializing if not array)
467 public function convertMetadataVersion($metadata, $version) {
468 $handler = $this->getHandler();
469 if ( !is_array( $metadata ) ) {
470 // Just to make the return type consistent
471 $metadata = unserialize( $metadata );
474 return $handler->convertMetadataVersion( $metadata, $version );
481 * Return the bit depth of the file
482 * Overridden by LocalFile
486 public function getBitDepth() {
491 * Return the size of the image file, in bytes
492 * Overridden by LocalFile, UnregisteredLocalFile
496 public function getSize() {
501 * Returns the mime type of the file.
502 * Overridden by LocalFile, UnregisteredLocalFile
507 function getMimeType() {
508 return 'unknown/unknown';
512 * Return the type of the media in the file.
513 * Use the value returned by this function with the MEDIATYPE_xxx constants.
514 * Overridden by LocalFile,
518 function getMediaType() {
519 return MEDIATYPE_UNKNOWN
;
523 * Checks if the output of transform() for this file is likely
524 * to be valid. If this is false, various user elements will
525 * display a placeholder instead.
527 * Currently, this checks if the file is an image format
528 * that can be converted to a format
529 * supported by all browsers (namely GIF, PNG and JPEG),
530 * or if it is an SVG image and SVG conversion is enabled.
534 function canRender() {
535 if ( !isset( $this->canRender
) ) {
536 $this->canRender
= $this->getHandler() && $this->handler
->canRender( $this );
538 return $this->canRender
;
542 * Accessor for __get()
545 protected function getCanRender() {
546 return $this->canRender();
550 * Return true if the file is of a type that can't be directly
551 * rendered by typical browsers and needs to be re-rasterized.
553 * This returns true for everything but the bitmap types
554 * supported by all browsers, i.e. JPEG; GIF and PNG. It will
555 * also return true for any non-image formats.
559 function mustRender() {
560 return $this->getHandler() && $this->handler
->mustRender( $this );
564 * Alias for canRender()
568 function allowInlineDisplay() {
569 return $this->canRender();
573 * Determines if this media file is in a format that is unlikely to
574 * contain viruses or malicious content. It uses the global
575 * $wgTrustedMediaFormats list to determine if the file is safe.
577 * This is used to show a warning on the description page of non-safe files.
578 * It may also be used to disallow direct [[media:...]] links to such files.
580 * Note that this function will always return true if allowInlineDisplay()
581 * or isTrustedFile() is true for this file.
585 function isSafeFile() {
586 if ( !isset( $this->isSafeFile
) ) {
587 $this->isSafeFile
= $this->_getIsSafeFile();
589 return $this->isSafeFile
;
593 * Accessor for __get()
597 protected function getIsSafeFile() {
598 return $this->isSafeFile();
606 protected function _getIsSafeFile() {
607 global $wgTrustedMediaFormats;
609 if ( $this->allowInlineDisplay() ) {
612 if ($this->isTrustedFile()) {
616 $type = $this->getMediaType();
617 $mime = $this->getMimeType();
618 #wfDebug("LocalFile::isSafeFile: type= $type, mime= $mime\n");
620 if ( !$type ||
$type === MEDIATYPE_UNKNOWN
) {
621 return false; #unknown type, not trusted
623 if ( in_array( $type, $wgTrustedMediaFormats ) ) {
627 if ( $mime === "unknown/unknown" ) {
628 return false; #unknown type, not trusted
630 if ( in_array( $mime, $wgTrustedMediaFormats) ) {
638 * Returns true if the file is flagged as trusted. Files flagged that way
639 * can be linked to directly, even if that is not allowed for this type of
642 * This is a dummy function right now and always returns false. It could be
643 * implemented to extract a flag from the database. The trusted flag could be
644 * set on upload, if the user has sufficient privileges, to bypass script-
645 * and html-filters. It may even be coupled with cryptographics signatures
650 function isTrustedFile() {
651 #this could be implemented to check a flag in the database,
652 #look for signatures, etc
657 * Returns true if file exists in the repository.
659 * Overridden by LocalFile to avoid unnecessary stat calls.
661 * @return boolean Whether file exists in the repository.
663 public function exists() {
664 return $this->getPath() && $this->repo
->fileExists( $this->path
);
668 * Returns true if file exists in the repository and can be included in a page.
669 * It would be unsafe to include private images, making public thumbnails inadvertently
671 * @return boolean Whether file exists in the repository and is includable.
673 public function isVisible() {
674 return $this->exists();
680 function getTransformScript() {
681 if ( !isset( $this->transformScript
) ) {
682 $this->transformScript
= false;
684 $script = $this->repo
->getThumbScriptUrl();
686 $this->transformScript
= "$script?f=" . urlencode( $this->getName() );
690 return $this->transformScript
;
694 * Get a ThumbnailImage which is the same size as the source
696 * @param $handlerParams array
700 function getUnscaledThumb( $handlerParams = array() ) {
701 $hp =& $handlerParams;
702 $page = isset( $hp['page'] ) ?
$hp['page'] : false;
703 $width = $this->getWidth( $page );
705 return $this->iconThumb();
707 $hp['width'] = $width;
708 return $this->transform( $hp );
712 * Return the file name of a thumbnail with the specified parameters
714 * @param $params Array: handler-specific parameters
719 function thumbName( $params ) {
720 return $this->generateThumbName( $this->getName(), $params );
724 * Generate a thumbnail file name from a name and specified parameters
726 * @param string $name
727 * @param array $params Parameters which will be passed to MediaHandler::makeParamString
731 function generateThumbName( $name, $params ) {
732 if ( !$this->getHandler() ) {
735 $extension = $this->getExtension();
736 list( $thumbExt, $thumbMime ) = $this->handler
->getThumbType(
737 $extension, $this->getMimeType(), $params );
738 $thumbName = $this->handler
->makeParamString( $params ) . '-' . $name;
739 if ( $thumbExt != $extension ) {
740 $thumbName .= ".$thumbExt";
746 * Create a thumbnail of the image having the specified width/height.
747 * The thumbnail will not be created if the width is larger than the
748 * image's width. Let the browser do the scaling in this case.
749 * The thumbnail is stored on disk and is only computed if the thumbnail
750 * file does not exist OR if it is older than the image.
753 * Keeps aspect ratio of original image. If both width and height are
754 * specified, the generated image will be no bigger than width x height,
755 * and will also have correct aspect ratio.
757 * @param $width Integer: maximum width of the generated thumbnail
758 * @param $height Integer: maximum height of the image (optional)
762 public function createThumb( $width, $height = -1 ) {
763 $params = array( 'width' => $width );
764 if ( $height != -1 ) {
765 $params['height'] = $height;
767 $thumb = $this->transform( $params );
768 if ( is_null( $thumb ) ||
$thumb->isError() ) {
771 return $thumb->getUrl();
775 * Return either a MediaTransformError or placeholder thumbnail (if $wgIgnoreImageErrors)
777 * @param $thumbPath string Thumbnail storage path
778 * @param $thumbUrl string Thumbnail URL
779 * @param $params Array
780 * @param $flags integer
781 * @return MediaTransformOutput
783 protected function transformErrorOutput( $thumbPath, $thumbUrl, $params, $flags ) {
784 global $wgIgnoreImageErrors;
786 if ( $wgIgnoreImageErrors && !( $flags & self
::RENDER_NOW
) ) {
787 return $this->handler
->getTransform( $this, $thumbPath, $thumbUrl, $params );
789 return new MediaTransformError( 'thumbnail_error',
790 $params['width'], 0, wfMsg( 'thumbnail-dest-create' ) );
795 * Transform a media file
797 * @param $params Array: an associative array of handler-specific parameters.
798 * Typical keys are width, height and page.
799 * @param $flags Integer: a bitfield, may contain self::RENDER_NOW to force rendering
800 * @return MediaTransformOutput|bool False on failure
802 function transform( $params, $flags = 0 ) {
803 global $wgUseSquid, $wgIgnoreImageErrors, $wgThumbnailEpoch;
805 wfProfileIn( __METHOD__
);
807 if ( !$this->canRender() ) {
808 $thumb = $this->iconThumb();
809 break; // not a bitmap or renderable image, don't try
812 // Get the descriptionUrl to embed it as comment into the thumbnail. Bug 19791.
813 $descriptionUrl = $this->getDescriptionUrl();
814 if ( $descriptionUrl ) {
815 $params['descriptionUrl'] = wfExpandUrl( $descriptionUrl, PROTO_CANONICAL
);
818 $script = $this->getTransformScript();
819 if ( $script && !( $flags & self
::RENDER_NOW
) ) {
820 // Use a script to transform on client request, if possible
821 $thumb = $this->handler
->getScriptedTransform( $this, $script, $params );
827 $normalisedParams = $params;
828 $this->handler
->normaliseParams( $this, $normalisedParams );
830 $thumbName = $this->thumbName( $normalisedParams );
831 $thumbUrl = $this->getThumbUrl( $thumbName );
832 $thumbPath = $this->getThumbPath( $thumbName ); // final thumb path
835 // Defer rendering if a 404 handler is set up...
836 if ( $this->repo
->canTransformVia404() && !( $flags & self
::RENDER_NOW
) ) {
837 wfDebug( __METHOD__
. " transformation deferred." );
838 // XXX: Pass in the storage path even though we are not rendering anything
839 // and the path is supposed to be an FS path. This is due to getScalerType()
840 // getting called on the path and clobbering $thumb->getUrl() if it's false.
841 $thumb = $this->handler
->getTransform( $this, $thumbPath, $thumbUrl, $params );
844 // Clean up broken thumbnails as needed
845 $this->migrateThumbFile( $thumbName );
846 // Check if an up-to-date thumbnail already exists...
847 wfDebug( __METHOD__
.": Doing stat for $thumbPath\n" );
848 if ( $this->repo
->fileExists( $thumbPath ) && !( $flags & self
::RENDER_FORCE
) ) {
849 $timestamp = $this->repo
->getFileTimestamp( $thumbPath );
850 if ( $timestamp !== false && $timestamp >= $wgThumbnailEpoch ) {
851 // XXX: Pass in the storage path even though we are not rendering anything
852 // and the path is supposed to be an FS path. This is due to getScalerType()
853 // getting called on the path and clobbering $thumb->getUrl() if it's false.
854 $thumb = $this->handler
->getTransform( $this, $thumbPath, $thumbUrl, $params );
855 $thumb->setStoragePath( $thumbPath );
858 } elseif ( $flags & self
::RENDER_FORCE
) {
859 wfDebug( __METHOD__
. " forcing rendering per flag File::RENDER_FORCE\n" );
863 // If the backend is ready-only, don't keep generating thumbnails
864 // only to return transformation errors, just return the error now.
865 if ( $this->repo
->getReadOnlyReason() !== false ) {
866 $thumb = $this->transformErrorOutput( $thumbPath, $thumbUrl, $params, $flags );
870 // Create a temp FS file with the same extension and the thumbnail
871 $thumbExt = FileBackend
::extensionFromPath( $thumbPath );
872 $tmpFile = TempFSFile
::factory( 'transform_', $thumbExt );
874 $thumb = $this->transformErrorOutput( $thumbPath, $thumbUrl, $params, $flags );
877 $tmpThumbPath = $tmpFile->getPath(); // path of 0-byte temp file
879 // Actually render the thumbnail...
880 $thumb = $this->handler
->doTransform( $this, $tmpThumbPath, $thumbUrl, $params );
881 $tmpFile->bind( $thumb ); // keep alive with $thumb
883 if ( !$thumb ) { // bad params?
885 } elseif ( $thumb->isError() ) { // transform error
886 $this->lastError
= $thumb->toText();
887 // Ignore errors if requested
888 if ( $wgIgnoreImageErrors && !( $flags & self
::RENDER_NOW
) ) {
889 $thumb = $this->handler
->getTransform( $this, $tmpThumbPath, $thumbUrl, $params );
891 } elseif ( $this->repo
&& $thumb->hasFile() && !$thumb->fileIsSource() ) {
892 // Copy the thumbnail from the file system into storage...
893 $status = $this->repo
->quickImport( $tmpThumbPath, $thumbPath );
894 if ( $status->isOK() ) {
895 $thumb->setStoragePath( $thumbPath );
897 $thumb = $this->transformErrorOutput( $thumbPath, $thumbUrl, $params, $flags );
899 // Give extensions a chance to do something with this thumbnail...
900 wfRunHooks( 'FileTransformed', array( $this, $thumb, $tmpThumbPath, $thumbPath ) );
903 // Purge. Useful in the event of Core -> Squid connection failure or squid
904 // purge collisions from elsewhere during failure. Don't keep triggering for
905 // "thumbs" which have the main image URL though (bug 13776)
907 if ( !$thumb ||
$thumb->isError() ||
$thumb->getUrl() != $this->getURL() ) {
908 SquidUpdate
::purge( array( $thumbUrl ) );
913 wfProfileOut( __METHOD__
);
914 return is_object( $thumb ) ?
$thumb : false;
918 * Hook into transform() to allow migration of thumbnail files
920 * Overridden by LocalFile
922 function migrateThumbFile( $thumbName ) {}
925 * Get a MediaHandler instance for this file
927 * @return MediaHandler
929 function getHandler() {
930 if ( !isset( $this->handler
) ) {
931 $this->handler
= MediaHandler
::getHandler( $this->getMimeType() );
933 return $this->handler
;
937 * Get a ThumbnailImage representing a file type icon
939 * @return ThumbnailImage
941 function iconThumb() {
942 global $wgStylePath, $wgStyleDirectory;
944 $try = array( 'fileicon-' . $this->getExtension() . '.png', 'fileicon.png' );
945 foreach ( $try as $icon ) {
946 $path = '/common/images/icons/' . $icon;
947 $filepath = $wgStyleDirectory . $path;
948 if ( file_exists( $filepath ) ) { // always FS
949 return new ThumbnailImage( $this, $wgStylePath . $path, 120, 120 );
956 * Get last thumbnailing error.
959 function getLastError() {
960 return $this->lastError
;
964 * Get all thumbnail names previously generated for this file
966 * Overridden by LocalFile
969 function getThumbnails() {
974 * Purge shared caches such as thumbnails and DB data caching
976 * Overridden by LocalFile
977 * @param $options Array Options, which include:
978 * 'forThumbRefresh' : The purging is only to refresh thumbnails
980 function purgeCache( $options = array() ) {}
983 * Purge the file description page, but don't go after
984 * pages using the file. Use when modifying file history
985 * but not the current data.
987 function purgeDescription() {
988 $title = $this->getTitle();
990 $title->invalidateCache();
991 $title->purgeSquid();
996 * Purge metadata and all affected pages when the file is created,
997 * deleted, or majorly updated.
999 function purgeEverything() {
1000 // Delete thumbnails and refresh file metadata cache
1001 $this->purgeCache();
1002 $this->purgeDescription();
1004 // Purge cache of all pages using this file
1005 $title = $this->getTitle();
1007 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
1008 $update->doUpdate();
1013 * Return a fragment of the history of file.
1016 * @param $limit integer Limit of rows to return
1017 * @param $start string timestamp Only revisions older than $start will be returned
1018 * @param $end string timestamp Only revisions newer than $end will be returned
1019 * @param $inc bool Include the endpoints of the time range
1023 function getHistory( $limit = null, $start = null, $end = null, $inc=true ) {
1028 * Return the history of this file, line by line. Starts with current version,
1029 * then old versions. Should return an object similar to an image/oldimage
1033 * Overridden in LocalFile
1036 public function nextHistoryLine() {
1041 * Reset the history pointer to the first element of the history.
1042 * Always call this function after using nextHistoryLine() to free db resources
1044 * Overridden in LocalFile.
1046 public function resetHistory() {}
1049 * Get the filename hash component of the directory including trailing slash,
1051 * If the repository is not hashed, returns an empty string.
1055 function getHashPath() {
1056 if ( !isset( $this->hashPath
) ) {
1057 $this->assertRepoDefined();
1058 $this->hashPath
= $this->repo
->getHashPath( $this->getName() );
1060 return $this->hashPath
;
1064 * Get the path of the file relative to the public zone root.
1065 * This function is overriden in OldLocalFile to be like getArchiveRel().
1070 return $this->getHashPath() . $this->getName();
1074 * Get the path of an archived file relative to the public zone root
1076 * @param $suffix bool|string if not false, the name of an archived thumbnail file
1080 function getArchiveRel( $suffix = false ) {
1081 $path = 'archive/' . $this->getHashPath();
1082 if ( $suffix === false ) {
1083 $path = substr( $path, 0, -1 );
1091 * Get the path, relative to the thumbnail zone root, of the
1092 * thumbnail directory or a particular file if $suffix is specified
1094 * @param $suffix bool|string if not false, the name of a thumbnail file
1098 function getThumbRel( $suffix = false ) {
1099 $path = $this->getRel();
1100 if ( $suffix !== false ) {
1101 $path .= '/' . $suffix;
1107 * Get urlencoded path of the file relative to the public zone root.
1108 * This function is overriden in OldLocalFile to be like getArchiveUrl().
1112 function getUrlRel() {
1113 return $this->getHashPath() . rawurlencode( $this->getName() );
1117 * Get the path, relative to the thumbnail zone root, for an archived file's thumbs directory
1118 * or a specific thumb if the $suffix is given.
1120 * @param $archiveName string the timestamped name of an archived image
1121 * @param $suffix bool|string if not false, the name of a thumbnail file
1125 function getArchiveThumbRel( $archiveName, $suffix = false ) {
1126 $path = 'archive/' . $this->getHashPath() . $archiveName . "/";
1127 if ( $suffix === false ) {
1128 $path = substr( $path, 0, -1 );
1136 * Get the path of the archived file.
1138 * @param $suffix bool|string if not false, the name of an archived file.
1142 function getArchivePath( $suffix = false ) {
1143 $this->assertRepoDefined();
1144 return $this->repo
->getZonePath( 'public' ) . '/' . $this->getArchiveRel( $suffix );
1148 * Get the path of an archived file's thumbs, or a particular thumb if $suffix is specified
1150 * @param $archiveName string the timestamped name of an archived image
1151 * @param $suffix bool|string if not false, the name of a thumbnail file
1155 function getArchiveThumbPath( $archiveName, $suffix = false ) {
1156 $this->assertRepoDefined();
1157 return $this->repo
->getZonePath( 'thumb' ) . '/' .
1158 $this->getArchiveThumbRel( $archiveName, $suffix );
1162 * Get the path of the thumbnail directory, or a particular file if $suffix is specified
1164 * @param $suffix bool|string if not false, the name of a thumbnail file
1168 function getThumbPath( $suffix = false ) {
1169 $this->assertRepoDefined();
1170 return $this->repo
->getZonePath( 'thumb' ) . '/' . $this->getThumbRel( $suffix );
1174 * Get the URL of the archive directory, or a particular file if $suffix is specified
1176 * @param $suffix bool|string if not false, the name of an archived file
1180 function getArchiveUrl( $suffix = false ) {
1181 $this->assertRepoDefined();
1182 $path = $this->repo
->getZoneUrl( 'public' ) . '/archive/' . $this->getHashPath();
1183 if ( $suffix === false ) {
1184 $path = substr( $path, 0, -1 );
1186 $path .= rawurlencode( $suffix );
1192 * Get the URL of the archived file's thumbs, or a particular thumb if $suffix is specified
1194 * @param $archiveName string the timestamped name of an archived image
1195 * @param $suffix bool|string if not false, the name of a thumbnail file
1199 function getArchiveThumbUrl( $archiveName, $suffix = false ) {
1200 $this->assertRepoDefined();
1201 $path = $this->repo
->getZoneUrl( 'thumb' ) . '/archive/' .
1202 $this->getHashPath() . rawurlencode( $archiveName ) . "/";
1203 if ( $suffix === false ) {
1204 $path = substr( $path, 0, -1 );
1206 $path .= rawurlencode( $suffix );
1212 * Get the URL of the thumbnail directory, or a particular file if $suffix is specified
1214 * @param $suffix bool|string if not false, the name of a thumbnail file
1216 * @return string path
1218 function getThumbUrl( $suffix = false ) {
1219 $this->assertRepoDefined();
1220 $path = $this->repo
->getZoneUrl( 'thumb' ) . '/' . $this->getUrlRel();
1221 if ( $suffix !== false ) {
1222 $path .= '/' . rawurlencode( $suffix );
1228 * Get the public zone virtual URL for a current version source file
1230 * @param $suffix bool|string if not false, the name of a thumbnail file
1234 function getVirtualUrl( $suffix = false ) {
1235 $this->assertRepoDefined();
1236 $path = $this->repo
->getVirtualUrl() . '/public/' . $this->getUrlRel();
1237 if ( $suffix !== false ) {
1238 $path .= '/' . rawurlencode( $suffix );
1244 * Get the public zone virtual URL for an archived version source file
1246 * @param $suffix bool|string if not false, the name of a thumbnail file
1250 function getArchiveVirtualUrl( $suffix = false ) {
1251 $this->assertRepoDefined();
1252 $path = $this->repo
->getVirtualUrl() . '/public/archive/' . $this->getHashPath();
1253 if ( $suffix === false ) {
1254 $path = substr( $path, 0, -1 );
1256 $path .= rawurlencode( $suffix );
1262 * Get the virtual URL for a thumbnail file or directory
1264 * @param $suffix bool|string if not false, the name of a thumbnail file
1268 function getThumbVirtualUrl( $suffix = false ) {
1269 $this->assertRepoDefined();
1270 $path = $this->repo
->getVirtualUrl() . '/thumb/' . $this->getUrlRel();
1271 if ( $suffix !== false ) {
1272 $path .= '/' . rawurlencode( $suffix );
1280 function isHashed() {
1281 $this->assertRepoDefined();
1282 return (bool)$this->repo
->getHashLevels();
1286 * @throws MWException
1288 function readOnlyError() {
1289 throw new MWException( get_class($this) . ': write operations are not supported' );
1293 * Record a file upload in the upload log and the image table
1295 * Overridden by LocalFile
1298 * @param $license string
1299 * @param $copyStatus string
1300 * @param $source string
1301 * @param $watch bool
1303 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '', $watch = false ) {
1304 $this->readOnlyError();
1308 * Move or copy a file to its public location. If a file exists at the
1309 * destination, move it to an archive. Returns a FileRepoStatus object with
1310 * the archive name in the "value" member on success.
1312 * The archive name should be passed through to recordUpload for database
1315 * @param $srcPath String: local filesystem path to the source image
1316 * @param $flags Integer: a bitwise combination of:
1317 * File::DELETE_SOURCE Delete the source file, i.e. move
1319 * @return FileRepoStatus object. On success, the value member contains the
1320 * archive name, or an empty string if it was a new file.
1323 * Overridden by LocalFile
1325 function publish( $srcPath, $flags = 0 ) {
1326 $this->readOnlyError();
1332 function formatMetadata() {
1333 if ( !$this->getHandler() ) {
1336 return $this->getHandler()->formatMetadata( $this, $this->getMetadata() );
1340 * Returns true if the file comes from the local file repository.
1344 function isLocal() {
1345 return $this->repo
&& $this->repo
->isLocal();
1349 * Returns the name of the repository.
1353 function getRepoName() {
1354 return $this->repo ?
$this->repo
->getName() : 'unknown';
1358 * Returns the repository
1360 * @return FileRepo|bool
1362 function getRepo() {
1367 * Returns true if the image is an old version
1377 * Is this file a "deleted" file in a private archive?
1384 function isDeleted( $field ) {
1389 * Return the deletion bitfield
1393 function getVisibility() {
1398 * Was this file ever deleted from the wiki?
1402 function wasDeleted() {
1403 $title = $this->getTitle();
1404 return $title && $title->isDeletedQuick();
1408 * Move file to the new title
1410 * Move current, old version and all thumbnails
1411 * to the new filename. Old file is deleted.
1413 * Cache purging is done; checks for validity
1414 * and logging are caller's responsibility
1416 * @param $target Title New file name
1417 * @return FileRepoStatus object.
1419 function move( $target ) {
1420 $this->readOnlyError();
1424 * Delete all versions of the file.
1426 * Moves the files into an archive directory (or deletes them)
1427 * and removes the database rows.
1429 * Cache purging is done; logging is caller's responsibility.
1431 * @param $reason String
1432 * @param $suppress Boolean: hide content from sysops?
1433 * @return bool on success, false on some kind of failure
1435 * Overridden by LocalFile
1437 function delete( $reason, $suppress = false ) {
1438 $this->readOnlyError();
1442 * Restore all or specified deleted revisions to the given file.
1443 * Permissions and logging are left to the caller.
1445 * May throw database exceptions on error.
1447 * @param $versions array set of record ids of deleted items to restore,
1448 * or empty to restore all revisions.
1449 * @param $unsuppress bool remove restrictions on content upon restoration?
1450 * @return int|bool the number of file revisions restored if successful,
1451 * or false on failure
1453 * Overridden by LocalFile
1455 function restore( $versions = array(), $unsuppress = false ) {
1456 $this->readOnlyError();
1460 * Returns 'true' if this file is a type which supports multiple pages,
1461 * e.g. DJVU or PDF. Note that this may be true even if the file in
1462 * question only has a single page.
1466 function isMultipage() {
1467 return $this->getHandler() && $this->handler
->isMultiPage( $this );
1471 * Returns the number of pages of a multipage document, or false for
1472 * documents which aren't multipage documents
1476 function pageCount() {
1477 if ( !isset( $this->pageCount
) ) {
1478 if ( $this->getHandler() && $this->handler
->isMultiPage( $this ) ) {
1479 $this->pageCount
= $this->handler
->pageCount( $this );
1481 $this->pageCount
= false;
1484 return $this->pageCount
;
1488 * Calculate the height of a thumbnail using the source and destination width
1496 static function scaleHeight( $srcWidth, $srcHeight, $dstWidth ) {
1497 // Exact integer multiply followed by division
1498 if ( $srcWidth == 0 ) {
1501 return round( $srcHeight * $dstWidth / $srcWidth );
1506 * Get an image size array like that returned by getImageSize(), or false if it
1507 * can't be determined.
1509 * @param $fileName String: The filename
1512 function getImageSize( $fileName ) {
1513 if ( !$this->getHandler() ) {
1516 return $this->handler
->getImageSize( $this, $fileName );
1520 * Get the URL of the image description page. May return false if it is
1521 * unknown or not applicable.
1525 function getDescriptionUrl() {
1526 if ( $this->repo
) {
1527 return $this->repo
->getDescriptionUrl( $this->getName() );
1534 * Get the HTML text of the description page, if available
1538 function getDescriptionText() {
1539 global $wgMemc, $wgLang;
1540 if ( !$this->repo ||
!$this->repo
->fetchDescription
) {
1543 $renderUrl = $this->repo
->getDescriptionRenderUrl( $this->getName(), $wgLang->getCode() );
1545 if ( $this->repo
->descriptionCacheExpiry
> 0 ) {
1546 wfDebug("Attempting to get the description from cache...");
1547 $key = $this->repo
->getLocalCacheKey( 'RemoteFileDescription', 'url', $wgLang->getCode(),
1549 $obj = $wgMemc->get($key);
1551 wfDebug("success!\n");
1556 wfDebug( "Fetching shared description from $renderUrl\n" );
1557 $res = Http
::get( $renderUrl );
1558 if ( $res && $this->repo
->descriptionCacheExpiry
> 0 ) {
1559 $wgMemc->set( $key, $res, $this->repo
->descriptionCacheExpiry
);
1568 * Get discription of file revision
1573 function getDescription() {
1578 * Get the 14-character timestamp of the file upload
1580 * @return string|bool TS_MW timestamp or false on failure
1582 function getTimestamp() {
1583 $this->assertRepoDefined();
1584 return $this->repo
->getFileTimestamp( $this->getPath() );
1588 * Get the SHA-1 base 36 hash of the file
1592 function getSha1() {
1593 $this->assertRepoDefined();
1594 return $this->repo
->getFileSha1( $this->getPath() );
1598 * Get the deletion archive key, <sha1>.<ext>
1602 function getStorageKey() {
1603 $hash = $this->getSha1();
1607 $ext = $this->getExtension();
1608 $dotExt = $ext === '' ?
'' : ".$ext";
1609 return $hash . $dotExt;
1613 * Determine if the current user is allowed to view a particular
1614 * field of this file, if it's marked as deleted.
1616 * @param $field Integer
1617 * @param $user User object to check, or null to use $wgUser
1620 function userCan( $field, User
$user = null ) {
1625 * Get an associative array containing information about a file in the local filesystem.
1627 * @param $path String: absolute local filesystem path
1628 * @param $ext Mixed: the file extension, or true to extract it from the filename.
1629 * Set it to false to ignore the extension.
1633 static function getPropsFromPath( $path, $ext = true ) {
1634 wfDebug( __METHOD__
.": Getting file info for $path\n" );
1635 wfDeprecated( __METHOD__
, '1.19' );
1637 $fsFile = new FSFile( $path );
1638 return $fsFile->getProps();
1642 * Get a SHA-1 hash of a file in the local filesystem, in base-36 lower case
1643 * encoding, zero padded to 31 digits.
1645 * 160 log 2 / log 36 = 30.95, so the 160-bit hash fills 31 digits in base 36
1648 * @param $path string
1650 * @return bool|string False on failure
1652 static function sha1Base36( $path ) {
1653 wfDeprecated( __METHOD__
, '1.19' );
1655 $fsFile = new FSFile( $path );
1656 return $fsFile->getSha1Base36();
1662 function getLongDesc() {
1663 $handler = $this->getHandler();
1665 return $handler->getLongDesc( $this );
1667 return MediaHandler
::getGeneralLongDesc( $this );
1674 function getShortDesc() {
1675 $handler = $this->getHandler();
1677 return $handler->getShortDesc( $this );
1679 return MediaHandler
::getGeneralShortDesc( $this );
1686 function getDimensionsString() {
1687 $handler = $this->getHandler();
1689 return $handler->getDimensionsString( $this );
1698 function getRedirected() {
1699 return $this->redirected
;
1705 function getRedirectedTitle() {
1706 if ( $this->redirected
) {
1707 if ( !$this->redirectTitle
) {
1708 $this->redirectTitle
= Title
::makeTitle( NS_FILE
, $this->redirected
);
1710 return $this->redirectTitle
;
1718 function redirectedFrom( $from ) {
1719 $this->redirected
= $from;
1725 function isMissing() {
1730 * Check if this file object is small and can be cached
1733 public function isCacheable() {
1738 * Assert that $this->repo is set to a valid FileRepo instance
1739 * @throws MWException
1741 protected function assertRepoDefined() {
1742 if ( !( $this->repo
instanceof $this->repoClass
) ) {
1743 throw new MWException( "A {$this->repoClass} object is not set for this File.\n" );
1748 * Assert that $this->title is set to a Title
1749 * @throws MWException
1751 protected function assertTitleDefined() {
1752 if ( !( $this->title
instanceof Title
) ) {
1753 throw new MWException( "A Title object is not set for this File.\n" );