b18304078c8c4eb072fdcbbc0ee8bfd5a09e505d
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;
66 // Audience options for File::getDescription()
68 const FOR_THIS_USER
= 2;
72 * Some member variables can be lazy-initialised using __get(). The
73 * initialisation function for these variables is always a function named
74 * like getVar(), where Var is the variable name with upper-case first
77 * The following variables are initialised in this way in this base class:
78 * name, extension, handler, path, canRender, isSafeFile,
79 * transformScript, hashPath, pageCount, url
81 * Code within this class should generally use the accessor function
82 * directly, since __get() isn't re-entrant and therefore causes bugs that
83 * depend on initialisation order.
87 * The following member variables are not lazy-initialised
100 var $lastError, $redirected, $redirectedTitle;
103 * @var FSFile|bool False if undefined
115 protected $url, $extension, $name, $path, $hashPath, $pageCount, $transformScript;
117 protected $redirectTitle;
122 protected $canRender, $isSafeFile;
125 * @var string Required Repository class type
127 protected $repoClass = 'FileRepo';
130 * Call this constructor from child classes.
132 * Both $title and $repo are optional, though some functions
133 * may return false or throw exceptions if they are not set.
134 * Most subclasses will want to call assertRepoDefined() here.
136 * @param $title Title|string|bool
137 * @param $repo FileRepo|bool
139 function __construct( $title, $repo ) {
140 if ( $title !== false ) { // subclasses may not use MW titles
141 $title = self
::normalizeTitle( $title, 'exception' );
143 $this->title
= $title;
148 * Given a string or Title object return either a
149 * valid Title object with namespace NS_FILE or null
151 * @param $title Title|string
152 * @param $exception string|bool Use 'exception' to throw an error on bad titles
153 * @throws MWException
156 static function normalizeTitle( $title, $exception = false ) {
158 if ( $ret instanceof Title
) {
159 # Normalize NS_MEDIA -> NS_FILE
160 if ( $ret->getNamespace() == NS_MEDIA
) {
161 $ret = Title
::makeTitleSafe( NS_FILE
, $ret->getDBkey() );
162 # Sanity check the title namespace
163 } elseif ( $ret->getNamespace() !== NS_FILE
) {
167 # Convert strings to Title objects
168 $ret = Title
::makeTitleSafe( NS_FILE
, (string)$ret );
170 if ( !$ret && $exception !== false ) {
171 throw new MWException( "`$title` is not a valid file title." );
176 function __get( $name ) {
177 $function = array( $this, 'get' . ucfirst( $name ) );
178 if ( !is_callable( $function ) ) {
181 $this->$name = call_user_func( $function );
187 * Normalize a file extension to the common form, and ensure it's clean.
188 * Extensions with non-alphanumeric characters will be discarded.
190 * @param $ext string (without the .)
193 static function normalizeExtension( $ext ) {
194 $lower = strtolower( $ext );
201 if( isset( $squish[$lower] ) ) {
202 return $squish[$lower];
203 } elseif( preg_match( '/^[0-9a-z]+$/', $lower ) ) {
211 * Checks if file extensions are compatible
213 * @param $old File Old file
214 * @param $new string New name
218 static function checkExtensionCompatibility( File
$old, $new ) {
219 $oldMime = $old->getMimeType();
220 $n = strrpos( $new, '.' );
221 $newExt = self
::normalizeExtension( $n ?
substr( $new, $n +
1 ) : '' );
222 $mimeMagic = MimeMagic
::singleton();
223 return $mimeMagic->isMatchingExtension( $newExt, $oldMime );
227 * Upgrade the database row if there is one
228 * Called by ImagePage
231 function upgradeRow() {}
234 * Split an internet media type into its two components; if not
235 * a two-part name, set the minor type to 'unknown'.
237 * @param string $mime "text/html" etc
238 * @return array ("text", "html") etc
240 public static function splitMime( $mime ) {
241 if( strpos( $mime, '/' ) !== false ) {
242 return explode( '/', $mime, 2 );
244 return array( $mime, 'unknown' );
249 * Callback for usort() to do file sorts by name
254 * @return Integer: result of name comparison
256 public static function compare( File
$a, File
$b ) {
257 return strcmp( $a->getName(), $b->getName() );
261 * Return the name of this file
265 public function getName() {
266 if ( !isset( $this->name
) ) {
267 $this->assertRepoDefined();
268 $this->name
= $this->repo
->getNameFromTitle( $this->title
);
274 * Get the file extension, e.g. "svg"
278 function getExtension() {
279 if ( !isset( $this->extension
) ) {
280 $n = strrpos( $this->getName(), '.' );
281 $this->extension
= self
::normalizeExtension(
282 $n ?
substr( $this->getName(), $n +
1 ) : '' );
284 return $this->extension
;
288 * Return the associated title object
292 public function getTitle() {
297 * Return the title used to find this file
301 public function getOriginalTitle() {
302 if ( $this->redirected
) {
303 return $this->getRedirectedTitle();
309 * Return the URL of the file
313 public function getUrl() {
314 if ( !isset( $this->url
) ) {
315 $this->assertRepoDefined();
316 $this->url
= $this->repo
->getZoneUrl( 'public' ) . '/' . $this->getUrlRel();
322 * Return a fully-qualified URL to the file.
323 * Upload URL paths _may or may not_ be fully qualified, so
324 * we check. Local paths are assumed to belong on $wgServer.
328 public function getFullUrl() {
329 return wfExpandUrl( $this->getUrl(), PROTO_RELATIVE
);
335 public function getCanonicalUrl() {
336 return wfExpandUrl( $this->getUrl(), PROTO_CANONICAL
);
342 function getViewURL() {
343 if ( $this->mustRender() ) {
344 if ( $this->canRender() ) {
345 return $this->createThumb( $this->getWidth() );
347 wfDebug( __METHOD__
.': supposed to render ' . $this->getName() .
348 ' (' . $this->getMimeType() . "), but can't!\n" );
349 return $this->getURL(); #hm... return NULL?
352 return $this->getURL();
357 * Return the storage path to the file. Note that this does
358 * not mean that a file actually exists under that location.
360 * This path depends on whether directory hashing is active or not,
361 * i.e. whether the files are all found in the same directory,
362 * or in hashed paths like /images/3/3c.
364 * Most callers don't check the return value, but ForeignAPIFile::getPath
367 * @return string|bool ForeignAPIFile::getPath can return false
369 public function getPath() {
370 if ( !isset( $this->path
) ) {
371 $this->assertRepoDefined();
372 $this->path
= $this->repo
->getZonePath( 'public' ) . '/' . $this->getRel();
378 * Get an FS copy or original of this file and return the path.
379 * Returns false on failure. Callers must not alter the file.
380 * Temporary files are cleared automatically.
382 * @return string|bool False on failure
384 public function getLocalRefPath() {
385 $this->assertRepoDefined();
386 if ( !isset( $this->fsFile
) ) {
387 $this->fsFile
= $this->repo
->getLocalReference( $this->getPath() );
388 if ( !$this->fsFile
) {
389 $this->fsFile
= false; // null => false; cache negative hits
392 return ( $this->fsFile
)
393 ?
$this->fsFile
->getPath()
398 * Return the width of the image. Returns false if the width is unknown
402 * Overridden by LocalFile, UnregisteredLocalFile
408 public function getWidth( $page = 1 ) {
413 * Return the height of the image. Returns false if the height is unknown
417 * Overridden by LocalFile, UnregisteredLocalFile
421 * @return bool|number False on failure
423 public function getHeight( $page = 1 ) {
428 * Returns ID or name of user who uploaded the file
431 * @param $type string 'text' or 'id'
435 public function getUser( $type = 'text' ) {
440 * Get the duration of a media file in seconds
444 public function getLength() {
445 $handler = $this->getHandler();
447 return $handler->getLength( $this );
454 * Return true if the file is vectorized
458 public function isVectorized() {
459 $handler = $this->getHandler();
461 return $handler->isVectorized( $this );
468 * Get handler-specific metadata
469 * Overridden by LocalFile, UnregisteredLocalFile
473 public function getMetadata() {
478 * get versioned metadata
480 * @param $metadata Mixed Array or String of (serialized) metadata
481 * @param $version integer version number.
482 * @return Array containing metadata, or what was passed to it on fail (unserializing if not array)
484 public function convertMetadataVersion($metadata, $version) {
485 $handler = $this->getHandler();
486 if ( !is_array( $metadata ) ) {
487 // Just to make the return type consistent
488 $metadata = unserialize( $metadata );
491 return $handler->convertMetadataVersion( $metadata, $version );
498 * Return the bit depth of the file
499 * Overridden by LocalFile
503 public function getBitDepth() {
508 * Return the size of the image file, in bytes
509 * Overridden by LocalFile, UnregisteredLocalFile
513 public function getSize() {
518 * Returns the mime type of the file.
519 * Overridden by LocalFile, UnregisteredLocalFile
524 function getMimeType() {
525 return 'unknown/unknown';
529 * Return the type of the media in the file.
530 * Use the value returned by this function with the MEDIATYPE_xxx constants.
531 * Overridden by LocalFile,
535 function getMediaType() {
536 return MEDIATYPE_UNKNOWN
;
540 * Checks if the output of transform() for this file is likely
541 * to be valid. If this is false, various user elements will
542 * display a placeholder instead.
544 * Currently, this checks if the file is an image format
545 * that can be converted to a format
546 * supported by all browsers (namely GIF, PNG and JPEG),
547 * or if it is an SVG image and SVG conversion is enabled.
551 function canRender() {
552 if ( !isset( $this->canRender
) ) {
553 $this->canRender
= $this->getHandler() && $this->handler
->canRender( $this );
555 return $this->canRender
;
559 * Accessor for __get()
562 protected function getCanRender() {
563 return $this->canRender();
567 * Return true if the file is of a type that can't be directly
568 * rendered by typical browsers and needs to be re-rasterized.
570 * This returns true for everything but the bitmap types
571 * supported by all browsers, i.e. JPEG; GIF and PNG. It will
572 * also return true for any non-image formats.
576 function mustRender() {
577 return $this->getHandler() && $this->handler
->mustRender( $this );
581 * Alias for canRender()
585 function allowInlineDisplay() {
586 return $this->canRender();
590 * Determines if this media file is in a format that is unlikely to
591 * contain viruses or malicious content. It uses the global
592 * $wgTrustedMediaFormats list to determine if the file is safe.
594 * This is used to show a warning on the description page of non-safe files.
595 * It may also be used to disallow direct [[media:...]] links to such files.
597 * Note that this function will always return true if allowInlineDisplay()
598 * or isTrustedFile() is true for this file.
602 function isSafeFile() {
603 if ( !isset( $this->isSafeFile
) ) {
604 $this->isSafeFile
= $this->_getIsSafeFile();
606 return $this->isSafeFile
;
610 * Accessor for __get()
614 protected function getIsSafeFile() {
615 return $this->isSafeFile();
623 protected function _getIsSafeFile() {
624 global $wgTrustedMediaFormats;
626 if ( $this->allowInlineDisplay() ) {
629 if ($this->isTrustedFile()) {
633 $type = $this->getMediaType();
634 $mime = $this->getMimeType();
635 #wfDebug("LocalFile::isSafeFile: type= $type, mime= $mime\n");
637 if ( !$type ||
$type === MEDIATYPE_UNKNOWN
) {
638 return false; #unknown type, not trusted
640 if ( in_array( $type, $wgTrustedMediaFormats ) ) {
644 if ( $mime === "unknown/unknown" ) {
645 return false; #unknown type, not trusted
647 if ( in_array( $mime, $wgTrustedMediaFormats) ) {
655 * Returns true if the file is flagged as trusted. Files flagged that way
656 * can be linked to directly, even if that is not allowed for this type of
659 * This is a dummy function right now and always returns false. It could be
660 * implemented to extract a flag from the database. The trusted flag could be
661 * set on upload, if the user has sufficient privileges, to bypass script-
662 * and html-filters. It may even be coupled with cryptographics signatures
667 function isTrustedFile() {
668 #this could be implemented to check a flag in the database,
669 #look for signatures, etc
674 * Returns true if file exists in the repository.
676 * Overridden by LocalFile to avoid unnecessary stat calls.
678 * @return boolean Whether file exists in the repository.
680 public function exists() {
681 return $this->getPath() && $this->repo
->fileExists( $this->path
);
685 * Returns true if file exists in the repository and can be included in a page.
686 * It would be unsafe to include private images, making public thumbnails inadvertently
688 * @return boolean Whether file exists in the repository and is includable.
690 public function isVisible() {
691 return $this->exists();
697 function getTransformScript() {
698 if ( !isset( $this->transformScript
) ) {
699 $this->transformScript
= false;
701 $script = $this->repo
->getThumbScriptUrl();
703 $this->transformScript
= "$script?f=" . urlencode( $this->getName() );
707 return $this->transformScript
;
711 * Get a ThumbnailImage which is the same size as the source
713 * @param $handlerParams array
717 function getUnscaledThumb( $handlerParams = array() ) {
718 $hp =& $handlerParams;
719 $page = isset( $hp['page'] ) ?
$hp['page'] : false;
720 $width = $this->getWidth( $page );
722 return $this->iconThumb();
724 $hp['width'] = $width;
725 return $this->transform( $hp );
729 * Return the file name of a thumbnail with the specified parameters
731 * @param $params Array: handler-specific parameters
736 function thumbName( $params ) {
737 return $this->generateThumbName( $this->getName(), $params );
741 * Generate a thumbnail file name from a name and specified parameters
743 * @param string $name
744 * @param array $params Parameters which will be passed to MediaHandler::makeParamString
748 function generateThumbName( $name, $params ) {
749 if ( !$this->getHandler() ) {
752 $extension = $this->getExtension();
753 list( $thumbExt, $thumbMime ) = $this->handler
->getThumbType(
754 $extension, $this->getMimeType(), $params );
755 $thumbName = $this->handler
->makeParamString( $params ) . '-' . $name;
756 if ( $thumbExt != $extension ) {
757 $thumbName .= ".$thumbExt";
763 * Create a thumbnail of the image having the specified width/height.
764 * The thumbnail will not be created if the width is larger than the
765 * image's width. Let the browser do the scaling in this case.
766 * The thumbnail is stored on disk and is only computed if the thumbnail
767 * file does not exist OR if it is older than the image.
770 * Keeps aspect ratio of original image. If both width and height are
771 * specified, the generated image will be no bigger than width x height,
772 * and will also have correct aspect ratio.
774 * @param $width Integer: maximum width of the generated thumbnail
775 * @param $height Integer: maximum height of the image (optional)
779 public function createThumb( $width, $height = -1 ) {
780 $params = array( 'width' => $width );
781 if ( $height != -1 ) {
782 $params['height'] = $height;
784 $thumb = $this->transform( $params );
785 if ( is_null( $thumb ) ||
$thumb->isError() ) {
788 return $thumb->getUrl();
792 * Return either a MediaTransformError or placeholder thumbnail (if $wgIgnoreImageErrors)
794 * @param $thumbPath string Thumbnail storage path
795 * @param $thumbUrl string Thumbnail URL
796 * @param $params Array
797 * @param $flags integer
798 * @return MediaTransformOutput
800 protected function transformErrorOutput( $thumbPath, $thumbUrl, $params, $flags ) {
801 global $wgIgnoreImageErrors;
803 if ( $wgIgnoreImageErrors && !( $flags & self
::RENDER_NOW
) ) {
804 return $this->handler
->getTransform( $this, $thumbPath, $thumbUrl, $params );
806 return new MediaTransformError( 'thumbnail_error',
807 $params['width'], 0, wfMsg( 'thumbnail-dest-create' ) );
812 * Transform a media file
814 * @param $params Array: an associative array of handler-specific parameters.
815 * Typical keys are width, height and page.
816 * @param $flags Integer: a bitfield, may contain self::RENDER_NOW to force rendering
817 * @return MediaTransformOutput|bool False on failure
819 function transform( $params, $flags = 0 ) {
820 global $wgUseSquid, $wgIgnoreImageErrors, $wgThumbnailEpoch;
822 wfProfileIn( __METHOD__
);
824 if ( !$this->canRender() ) {
825 $thumb = $this->iconThumb();
826 break; // not a bitmap or renderable image, don't try
829 // Get the descriptionUrl to embed it as comment into the thumbnail. Bug 19791.
830 $descriptionUrl = $this->getDescriptionUrl();
831 if ( $descriptionUrl ) {
832 $params['descriptionUrl'] = wfExpandUrl( $descriptionUrl, PROTO_CANONICAL
);
835 $script = $this->getTransformScript();
836 if ( $script && !( $flags & self
::RENDER_NOW
) ) {
837 // Use a script to transform on client request, if possible
838 $thumb = $this->handler
->getScriptedTransform( $this, $script, $params );
844 $normalisedParams = $params;
845 $this->handler
->normaliseParams( $this, $normalisedParams );
847 $thumbName = $this->thumbName( $normalisedParams );
848 $thumbUrl = $this->getThumbUrl( $thumbName );
849 $thumbPath = $this->getThumbPath( $thumbName ); // final thumb path
852 // Defer rendering if a 404 handler is set up...
853 if ( $this->repo
->canTransformVia404() && !( $flags & self
::RENDER_NOW
) ) {
854 wfDebug( __METHOD__
. " transformation deferred." );
855 // XXX: Pass in the storage path even though we are not rendering anything
856 // and the path is supposed to be an FS path. This is due to getScalerType()
857 // getting called on the path and clobbering $thumb->getUrl() if it's false.
858 $thumb = $this->handler
->getTransform( $this, $thumbPath, $thumbUrl, $params );
861 // Clean up broken thumbnails as needed
862 $this->migrateThumbFile( $thumbName );
863 // Check if an up-to-date thumbnail already exists...
864 wfDebug( __METHOD__
.": Doing stat for $thumbPath\n" );
865 if ( $this->repo
->fileExists( $thumbPath ) && !( $flags & self
::RENDER_FORCE
) ) {
866 $timestamp = $this->repo
->getFileTimestamp( $thumbPath );
867 if ( $timestamp !== false && $timestamp >= $wgThumbnailEpoch ) {
868 // XXX: Pass in the storage path even though we are not rendering anything
869 // and the path is supposed to be an FS path. This is due to getScalerType()
870 // getting called on the path and clobbering $thumb->getUrl() if it's false.
871 $thumb = $this->handler
->getTransform( $this, $thumbPath, $thumbUrl, $params );
872 $thumb->setStoragePath( $thumbPath );
875 } elseif ( $flags & self
::RENDER_FORCE
) {
876 wfDebug( __METHOD__
. " forcing rendering per flag File::RENDER_FORCE\n" );
880 // If the backend is ready-only, don't keep generating thumbnails
881 // only to return transformation errors, just return the error now.
882 if ( $this->repo
->getReadOnlyReason() !== false ) {
883 $thumb = $this->transformErrorOutput( $thumbPath, $thumbUrl, $params, $flags );
887 // Create a temp FS file with the same extension and the thumbnail
888 $thumbExt = FileBackend
::extensionFromPath( $thumbPath );
889 $tmpFile = TempFSFile
::factory( 'transform_', $thumbExt );
891 $thumb = $this->transformErrorOutput( $thumbPath, $thumbUrl, $params, $flags );
894 $tmpThumbPath = $tmpFile->getPath(); // path of 0-byte temp file
896 // Actually render the thumbnail...
897 wfProfileIn( __METHOD__
. '-doTransform' );
898 $thumb = $this->handler
->doTransform( $this, $tmpThumbPath, $thumbUrl, $params );
899 wfProfileOut( __METHOD__
. '-doTransform' );
900 $tmpFile->bind( $thumb ); // keep alive with $thumb
902 if ( !$thumb ) { // bad params?
904 } elseif ( $thumb->isError() ) { // transform error
905 $this->lastError
= $thumb->toText();
906 // Ignore errors if requested
907 if ( $wgIgnoreImageErrors && !( $flags & self
::RENDER_NOW
) ) {
908 $thumb = $this->handler
->getTransform( $this, $tmpThumbPath, $thumbUrl, $params );
910 } elseif ( $this->repo
&& $thumb->hasFile() && !$thumb->fileIsSource() ) {
911 // Copy the thumbnail from the file system into storage...
912 $status = $this->repo
->quickImport( $tmpThumbPath, $thumbPath );
913 if ( $status->isOK() ) {
914 $thumb->setStoragePath( $thumbPath );
916 $thumb = $this->transformErrorOutput( $thumbPath, $thumbUrl, $params, $flags );
918 // Give extensions a chance to do something with this thumbnail...
919 wfRunHooks( 'FileTransformed', array( $this, $thumb, $tmpThumbPath, $thumbPath ) );
922 // Purge. Useful in the event of Core -> Squid connection failure or squid
923 // purge collisions from elsewhere during failure. Don't keep triggering for
924 // "thumbs" which have the main image URL though (bug 13776)
926 if ( !$thumb ||
$thumb->isError() ||
$thumb->getUrl() != $this->getURL() ) {
927 SquidUpdate
::purge( array( $thumbUrl ) );
932 wfProfileOut( __METHOD__
);
933 return is_object( $thumb ) ?
$thumb : false;
937 * Hook into transform() to allow migration of thumbnail files
939 * Overridden by LocalFile
941 function migrateThumbFile( $thumbName ) {}
944 * Get a MediaHandler instance for this file
946 * @return MediaHandler
948 function getHandler() {
949 if ( !isset( $this->handler
) ) {
950 $this->handler
= MediaHandler
::getHandler( $this->getMimeType() );
952 return $this->handler
;
956 * Get a ThumbnailImage representing a file type icon
958 * @return ThumbnailImage
960 function iconThumb() {
961 global $wgStylePath, $wgStyleDirectory;
963 $try = array( 'fileicon-' . $this->getExtension() . '.png', 'fileicon.png' );
964 foreach ( $try as $icon ) {
965 $path = '/common/images/icons/' . $icon;
966 $filepath = $wgStyleDirectory . $path;
967 if ( file_exists( $filepath ) ) { // always FS
968 return new ThumbnailImage( $this, $wgStylePath . $path, 120, 120 );
975 * Get last thumbnailing error.
978 function getLastError() {
979 return $this->lastError
;
983 * Get all thumbnail names previously generated for this file
985 * Overridden by LocalFile
988 function getThumbnails() {
993 * Purge shared caches such as thumbnails and DB data caching
995 * Overridden by LocalFile
996 * @param $options Array Options, which include:
997 * 'forThumbRefresh' : The purging is only to refresh thumbnails
999 function purgeCache( $options = array() ) {}
1002 * Purge the file description page, but don't go after
1003 * pages using the file. Use when modifying file history
1004 * but not the current data.
1006 function purgeDescription() {
1007 $title = $this->getTitle();
1009 $title->invalidateCache();
1010 $title->purgeSquid();
1015 * Purge metadata and all affected pages when the file is created,
1016 * deleted, or majorly updated.
1018 function purgeEverything() {
1019 // Delete thumbnails and refresh file metadata cache
1020 $this->purgeCache();
1021 $this->purgeDescription();
1023 // Purge cache of all pages using this file
1024 $title = $this->getTitle();
1026 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
1027 $update->doUpdate();
1032 * Return a fragment of the history of file.
1035 * @param $limit integer Limit of rows to return
1036 * @param $start string timestamp Only revisions older than $start will be returned
1037 * @param $end string timestamp Only revisions newer than $end will be returned
1038 * @param $inc bool Include the endpoints of the time range
1042 function getHistory( $limit = null, $start = null, $end = null, $inc=true ) {
1047 * Return the history of this file, line by line. Starts with current version,
1048 * then old versions. Should return an object similar to an image/oldimage
1052 * Overridden in LocalFile
1055 public function nextHistoryLine() {
1060 * Reset the history pointer to the first element of the history.
1061 * Always call this function after using nextHistoryLine() to free db resources
1063 * Overridden in LocalFile.
1065 public function resetHistory() {}
1068 * Get the filename hash component of the directory including trailing slash,
1070 * If the repository is not hashed, returns an empty string.
1074 function getHashPath() {
1075 if ( !isset( $this->hashPath
) ) {
1076 $this->assertRepoDefined();
1077 $this->hashPath
= $this->repo
->getHashPath( $this->getName() );
1079 return $this->hashPath
;
1083 * Get the path of the file relative to the public zone root.
1084 * This function is overriden in OldLocalFile to be like getArchiveRel().
1089 return $this->getHashPath() . $this->getName();
1093 * Get the path of an archived file relative to the public zone root
1095 * @param $suffix bool|string if not false, the name of an archived thumbnail file
1099 function getArchiveRel( $suffix = false ) {
1100 $path = 'archive/' . $this->getHashPath();
1101 if ( $suffix === false ) {
1102 $path = substr( $path, 0, -1 );
1110 * Get the path, relative to the thumbnail zone root, of the
1111 * thumbnail directory or a particular file if $suffix is specified
1113 * @param $suffix bool|string if not false, the name of a thumbnail file
1117 function getThumbRel( $suffix = false ) {
1118 $path = $this->getRel();
1119 if ( $suffix !== false ) {
1120 $path .= '/' . $suffix;
1126 * Get urlencoded path of the file relative to the public zone root.
1127 * This function is overriden in OldLocalFile to be like getArchiveUrl().
1131 function getUrlRel() {
1132 return $this->getHashPath() . rawurlencode( $this->getName() );
1136 * Get the path, relative to the thumbnail zone root, for an archived file's thumbs directory
1137 * or a specific thumb if the $suffix is given.
1139 * @param $archiveName string the timestamped name of an archived image
1140 * @param $suffix bool|string if not false, the name of a thumbnail file
1144 function getArchiveThumbRel( $archiveName, $suffix = false ) {
1145 $path = 'archive/' . $this->getHashPath() . $archiveName . "/";
1146 if ( $suffix === false ) {
1147 $path = substr( $path, 0, -1 );
1155 * Get the path of the archived file.
1157 * @param $suffix bool|string if not false, the name of an archived file.
1161 function getArchivePath( $suffix = false ) {
1162 $this->assertRepoDefined();
1163 return $this->repo
->getZonePath( 'public' ) . '/' . $this->getArchiveRel( $suffix );
1167 * Get the path of an 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 getArchiveThumbPath( $archiveName, $suffix = false ) {
1175 $this->assertRepoDefined();
1176 return $this->repo
->getZonePath( 'thumb' ) . '/' .
1177 $this->getArchiveThumbRel( $archiveName, $suffix );
1181 * Get the path of the thumbnail directory, or a particular file if $suffix is specified
1183 * @param $suffix bool|string if not false, the name of a thumbnail file
1187 function getThumbPath( $suffix = false ) {
1188 $this->assertRepoDefined();
1189 return $this->repo
->getZonePath( 'thumb' ) . '/' . $this->getThumbRel( $suffix );
1193 * Get the URL of the archive directory, or a particular file if $suffix is specified
1195 * @param $suffix bool|string if not false, the name of an archived file
1199 function getArchiveUrl( $suffix = false ) {
1200 $this->assertRepoDefined();
1201 $path = $this->repo
->getZoneUrl( 'public' ) . '/archive/' . $this->getHashPath();
1202 if ( $suffix === false ) {
1203 $path = substr( $path, 0, -1 );
1205 $path .= rawurlencode( $suffix );
1211 * Get the URL of the archived file's thumbs, or a particular thumb if $suffix is specified
1213 * @param $archiveName string the timestamped name of an archived image
1214 * @param $suffix bool|string if not false, the name of a thumbnail file
1218 function getArchiveThumbUrl( $archiveName, $suffix = false ) {
1219 $this->assertRepoDefined();
1220 $path = $this->repo
->getZoneUrl( 'thumb' ) . '/archive/' .
1221 $this->getHashPath() . rawurlencode( $archiveName ) . "/";
1222 if ( $suffix === false ) {
1223 $path = substr( $path, 0, -1 );
1225 $path .= rawurlencode( $suffix );
1231 * Get the URL of the thumbnail directory, or a particular file if $suffix is specified
1233 * @param $suffix bool|string if not false, the name of a thumbnail file
1235 * @return string path
1237 function getThumbUrl( $suffix = false ) {
1238 $this->assertRepoDefined();
1239 $path = $this->repo
->getZoneUrl( 'thumb' ) . '/' . $this->getUrlRel();
1240 if ( $suffix !== false ) {
1241 $path .= '/' . rawurlencode( $suffix );
1247 * Get the public zone virtual URL for a current version source file
1249 * @param $suffix bool|string if not false, the name of a thumbnail file
1253 function getVirtualUrl( $suffix = false ) {
1254 $this->assertRepoDefined();
1255 $path = $this->repo
->getVirtualUrl() . '/public/' . $this->getUrlRel();
1256 if ( $suffix !== false ) {
1257 $path .= '/' . rawurlencode( $suffix );
1263 * Get the public zone virtual URL for an archived version source file
1265 * @param $suffix bool|string if not false, the name of a thumbnail file
1269 function getArchiveVirtualUrl( $suffix = false ) {
1270 $this->assertRepoDefined();
1271 $path = $this->repo
->getVirtualUrl() . '/public/archive/' . $this->getHashPath();
1272 if ( $suffix === false ) {
1273 $path = substr( $path, 0, -1 );
1275 $path .= rawurlencode( $suffix );
1281 * Get the virtual URL for a thumbnail file or directory
1283 * @param $suffix bool|string if not false, the name of a thumbnail file
1287 function getThumbVirtualUrl( $suffix = false ) {
1288 $this->assertRepoDefined();
1289 $path = $this->repo
->getVirtualUrl() . '/thumb/' . $this->getUrlRel();
1290 if ( $suffix !== false ) {
1291 $path .= '/' . rawurlencode( $suffix );
1299 function isHashed() {
1300 $this->assertRepoDefined();
1301 return (bool)$this->repo
->getHashLevels();
1305 * @throws MWException
1307 function readOnlyError() {
1308 throw new MWException( get_class($this) . ': write operations are not supported' );
1312 * Record a file upload in the upload log and the image table
1314 * Overridden by LocalFile
1317 * @param $license string
1318 * @param $copyStatus string
1319 * @param $source string
1320 * @param $watch bool
1322 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '', $watch = false ) {
1323 $this->readOnlyError();
1327 * Move or copy a file to its public location. If a file exists at the
1328 * destination, move it to an archive. Returns a FileRepoStatus object with
1329 * the archive name in the "value" member on success.
1331 * The archive name should be passed through to recordUpload for database
1334 * @param $srcPath String: local filesystem path to the source image
1335 * @param $flags Integer: a bitwise combination of:
1336 * File::DELETE_SOURCE Delete the source file, i.e. move
1338 * @return FileRepoStatus object. On success, the value member contains the
1339 * archive name, or an empty string if it was a new file.
1342 * Overridden by LocalFile
1344 function publish( $srcPath, $flags = 0 ) {
1345 $this->readOnlyError();
1351 function formatMetadata() {
1352 if ( !$this->getHandler() ) {
1355 return $this->getHandler()->formatMetadata( $this, $this->getMetadata() );
1359 * Returns true if the file comes from the local file repository.
1363 function isLocal() {
1364 return $this->repo
&& $this->repo
->isLocal();
1368 * Returns the name of the repository.
1372 function getRepoName() {
1373 return $this->repo ?
$this->repo
->getName() : 'unknown';
1377 * Returns the repository
1379 * @return FileRepo|bool
1381 function getRepo() {
1386 * Returns true if the image is an old version
1396 * Is this file a "deleted" file in a private archive?
1403 function isDeleted( $field ) {
1408 * Return the deletion bitfield
1412 function getVisibility() {
1417 * Was this file ever deleted from the wiki?
1421 function wasDeleted() {
1422 $title = $this->getTitle();
1423 return $title && $title->isDeletedQuick();
1427 * Move file to the new title
1429 * Move current, old version and all thumbnails
1430 * to the new filename. Old file is deleted.
1432 * Cache purging is done; checks for validity
1433 * and logging are caller's responsibility
1435 * @param $target Title New file name
1436 * @return FileRepoStatus object.
1438 function move( $target ) {
1439 $this->readOnlyError();
1443 * Delete all versions of the file.
1445 * Moves the files into an archive directory (or deletes them)
1446 * and removes the database rows.
1448 * Cache purging is done; logging is caller's responsibility.
1450 * @param $reason String
1451 * @param $suppress Boolean: hide content from sysops?
1452 * @return bool on success, false on some kind of failure
1454 * Overridden by LocalFile
1456 function delete( $reason, $suppress = false ) {
1457 $this->readOnlyError();
1461 * Restore all or specified deleted revisions to the given file.
1462 * Permissions and logging are left to the caller.
1464 * May throw database exceptions on error.
1466 * @param $versions array set of record ids of deleted items to restore,
1467 * or empty to restore all revisions.
1468 * @param $unsuppress bool remove restrictions on content upon restoration?
1469 * @return int|bool the number of file revisions restored if successful,
1470 * or false on failure
1472 * Overridden by LocalFile
1474 function restore( $versions = array(), $unsuppress = false ) {
1475 $this->readOnlyError();
1479 * Returns 'true' if this file is a type which supports multiple pages,
1480 * e.g. DJVU or PDF. Note that this may be true even if the file in
1481 * question only has a single page.
1485 function isMultipage() {
1486 return $this->getHandler() && $this->handler
->isMultiPage( $this );
1490 * Returns the number of pages of a multipage document, or false for
1491 * documents which aren't multipage documents
1495 function pageCount() {
1496 if ( !isset( $this->pageCount
) ) {
1497 if ( $this->getHandler() && $this->handler
->isMultiPage( $this ) ) {
1498 $this->pageCount
= $this->handler
->pageCount( $this );
1500 $this->pageCount
= false;
1503 return $this->pageCount
;
1507 * Calculate the height of a thumbnail using the source and destination width
1515 static function scaleHeight( $srcWidth, $srcHeight, $dstWidth ) {
1516 // Exact integer multiply followed by division
1517 if ( $srcWidth == 0 ) {
1520 return round( $srcHeight * $dstWidth / $srcWidth );
1525 * Get an image size array like that returned by getImageSize(), or false if it
1526 * can't be determined.
1528 * @param $fileName String: The filename
1531 function getImageSize( $fileName ) {
1532 if ( !$this->getHandler() ) {
1535 return $this->handler
->getImageSize( $this, $fileName );
1539 * Get the URL of the image description page. May return false if it is
1540 * unknown or not applicable.
1544 function getDescriptionUrl() {
1545 if ( $this->repo
) {
1546 return $this->repo
->getDescriptionUrl( $this->getName() );
1553 * Get the HTML text of the description page, if available
1557 function getDescriptionText() {
1558 global $wgMemc, $wgLang;
1559 if ( !$this->repo ||
!$this->repo
->fetchDescription
) {
1562 $renderUrl = $this->repo
->getDescriptionRenderUrl( $this->getName(), $wgLang->getCode() );
1564 if ( $this->repo
->descriptionCacheExpiry
> 0 ) {
1565 wfDebug("Attempting to get the description from cache...");
1566 $key = $this->repo
->getLocalCacheKey( 'RemoteFileDescription', 'url', $wgLang->getCode(),
1568 $obj = $wgMemc->get($key);
1570 wfDebug("success!\n");
1575 wfDebug( "Fetching shared description from $renderUrl\n" );
1576 $res = Http
::get( $renderUrl );
1577 if ( $res && $this->repo
->descriptionCacheExpiry
> 0 ) {
1578 $wgMemc->set( $key, $res, $this->repo
->descriptionCacheExpiry
);
1587 * Get description of file revision
1590 * @param $audience Integer: one of:
1591 * File::FOR_PUBLIC to be displayed to all users
1592 * File::FOR_THIS_USER to be displayed to the given user
1593 * File::RAW get the description regardless of permissions
1594 * @param $user User object to check for, only if FOR_THIS_USER is passed
1595 * to the $audience parameter
1598 function getDescription( $audience = self
::FOR_PUBLIC
, User
$user = null ) {
1603 * Get the 14-character timestamp of the file upload
1605 * @return string|bool TS_MW timestamp or false on failure
1607 function getTimestamp() {
1608 $this->assertRepoDefined();
1609 return $this->repo
->getFileTimestamp( $this->getPath() );
1613 * Get the SHA-1 base 36 hash of the file
1617 function getSha1() {
1618 $this->assertRepoDefined();
1619 return $this->repo
->getFileSha1( $this->getPath() );
1623 * Get the deletion archive key, "<sha1>.<ext>"
1627 function getStorageKey() {
1628 $hash = $this->getSha1();
1632 $ext = $this->getExtension();
1633 $dotExt = $ext === '' ?
'' : ".$ext";
1634 return $hash . $dotExt;
1638 * Determine if the current user is allowed to view a particular
1639 * field of this file, if it's marked as deleted.
1641 * @param $field Integer
1642 * @param $user User object to check, or null to use $wgUser
1645 function userCan( $field, User
$user = null ) {
1650 * Get an associative array containing information about a file in the local filesystem.
1652 * @param $path String: absolute local filesystem path
1653 * @param $ext Mixed: the file extension, or true to extract it from the filename.
1654 * Set it to false to ignore the extension.
1658 static function getPropsFromPath( $path, $ext = true ) {
1659 wfDebug( __METHOD__
.": Getting file info for $path\n" );
1660 wfDeprecated( __METHOD__
, '1.19' );
1662 $fsFile = new FSFile( $path );
1663 return $fsFile->getProps();
1667 * Get a SHA-1 hash of a file in the local filesystem, in base-36 lower case
1668 * encoding, zero padded to 31 digits.
1670 * 160 log 2 / log 36 = 30.95, so the 160-bit hash fills 31 digits in base 36
1673 * @param $path string
1675 * @return bool|string False on failure
1677 static function sha1Base36( $path ) {
1678 wfDeprecated( __METHOD__
, '1.19' );
1680 $fsFile = new FSFile( $path );
1681 return $fsFile->getSha1Base36();
1687 function getLongDesc() {
1688 $handler = $this->getHandler();
1690 return $handler->getLongDesc( $this );
1692 return MediaHandler
::getGeneralLongDesc( $this );
1699 function getShortDesc() {
1700 $handler = $this->getHandler();
1702 return $handler->getShortDesc( $this );
1704 return MediaHandler
::getGeneralShortDesc( $this );
1711 function getDimensionsString() {
1712 $handler = $this->getHandler();
1714 return $handler->getDimensionsString( $this );
1723 function getRedirected() {
1724 return $this->redirected
;
1730 function getRedirectedTitle() {
1731 if ( $this->redirected
) {
1732 if ( !$this->redirectTitle
) {
1733 $this->redirectTitle
= Title
::makeTitle( NS_FILE
, $this->redirected
);
1735 return $this->redirectTitle
;
1743 function redirectedFrom( $from ) {
1744 $this->redirected
= $from;
1750 function isMissing() {
1755 * Check if this file object is small and can be cached
1758 public function isCacheable() {
1763 * Assert that $this->repo is set to a valid FileRepo instance
1764 * @throws MWException
1766 protected function assertRepoDefined() {
1767 if ( !( $this->repo
instanceof $this->repoClass
) ) {
1768 throw new MWException( "A {$this->repoClass} object is not set for this File.\n" );
1773 * Assert that $this->title is set to a Title
1774 * @throws MWException
1776 protected function assertTitleDefined() {
1777 if ( !( $this->title
instanceof Title
) ) {
1778 throw new MWException( "A Title object is not set for this File.\n" );