5d5647e5979ac1a6eadc1218c6f20a852a6583c1
3 * @defgroup FileAbstraction File abstraction
6 * Represents files in a repository.
10 * Base code for files.
13 * @ingroup FileAbstraction
17 * Implements some public methods and some protected utility functions which
18 * are required by multiple child classes. Contains stub functionality for
19 * unimplemented public methods.
21 * Stub functions which should be overridden are marked with STUB. Some more
22 * concrete functions are also typically overridden by child classes.
24 * Note that only the repo object knows what its file class is called. You should
25 * never name a file class explictly outside of the repo class. Instead use the
26 * repo's factory functions to generate file objects, for example:
28 * RepoGroup::singleton()->getLocalRepo()->newFile($title);
30 * The convenience functions wfLocalFile() and wfFindFile() should be sufficient
33 * @ingroup FileAbstraction
36 const DELETED_FILE
= 1;
37 const DELETED_COMMENT
= 2;
38 const DELETED_USER
= 4;
39 const DELETED_RESTRICTED
= 8;
41 /** Force rendering in the current process */
44 * Force rendering even if thumbnail already exist and using RENDER_NOW
45 * I.e. you have to pass both flags: File::RENDER_NOW | File::RENDER_FORCE
47 const RENDER_FORCE
= 2;
49 const DELETE_SOURCE
= 1;
52 * Some member variables can be lazy-initialised using __get(). The
53 * initialisation function for these variables is always a function named
54 * like getVar(), where Var is the variable name with upper-case first
57 * The following variables are initialised in this way in this base class:
58 * name, extension, handler, path, canRender, isSafeFile,
59 * transformScript, hashPath, pageCount, url
61 * Code within this class should generally use the accessor function
62 * directly, since __get() isn't re-entrant and therefore causes bugs that
63 * depend on initialisation order.
67 * The following member variables are not lazy-initialised
80 var $lastError, $redirected, $redirectedTitle;
95 protected $url, $extension, $name, $path, $hashPath, $pageCount, $transformScript;
100 protected $canRender, $isSafeFile;
103 * @var string Required Repository class type
105 protected $repoClass = 'FileRepo';
108 * Call this constructor from child classes.
110 * Both $title and $repo are optional, though some functions
111 * may return false or throw exceptions if they are not set.
112 * Most subclasses will want to call assertRepoDefined() here.
114 * @param $title Title|string|bool
115 * @param $repo FileRepo|bool
117 function __construct( $title, $repo ) {
118 if ( $title !== false ) { // subclasses may not use MW titles
119 $title = self
::normalizeTitle( $title, 'exception' );
121 $this->title
= $title;
126 * Given a string or Title object return either a
127 * valid Title object with namespace NS_FILE or null
129 * @param $title Title|string
130 * @param $exception string|bool Use 'exception' to throw an error on bad titles
133 static function normalizeTitle( $title, $exception = false ) {
135 if ( $ret instanceof Title
) {
136 # Normalize NS_MEDIA -> NS_FILE
137 if ( $ret->getNamespace() == NS_MEDIA
) {
138 $ret = Title
::makeTitleSafe( NS_FILE
, $ret->getDBkey() );
139 # Sanity check the title namespace
140 } elseif ( $ret->getNamespace() !== NS_FILE
) {
144 # Convert strings to Title objects
145 $ret = Title
::makeTitleSafe( NS_FILE
, (string)$ret );
147 if ( !$ret && $exception !== false ) {
148 throw new MWException( "`$title` is not a valid file title." );
153 function __get( $name ) {
154 $function = array( $this, 'get' . ucfirst( $name ) );
155 if ( !is_callable( $function ) ) {
158 $this->$name = call_user_func( $function );
164 * Normalize a file extension to the common form, and ensure it's clean.
165 * Extensions with non-alphanumeric characters will be discarded.
167 * @param $ext string (without the .)
170 static function normalizeExtension( $ext ) {
171 $lower = strtolower( $ext );
178 if( isset( $squish[$lower] ) ) {
179 return $squish[$lower];
180 } elseif( preg_match( '/^[0-9a-z]+$/', $lower ) ) {
188 * Checks if file extensions are compatible
190 * @param $old File Old file
191 * @param $new string New name
195 static function checkExtensionCompatibility( File
$old, $new ) {
196 $oldMime = $old->getMimeType();
197 $n = strrpos( $new, '.' );
198 $newExt = self
::normalizeExtension( $n ?
substr( $new, $n +
1 ) : '' );
199 $mimeMagic = MimeMagic
::singleton();
200 return $mimeMagic->isMatchingExtension( $newExt, $oldMime );
204 * Upgrade the database row if there is one
205 * Called by ImagePage
208 function upgradeRow() {}
211 * Split an internet media type into its two components; if not
212 * a two-part name, set the minor type to 'unknown'.
214 * @param string $mime "text/html" etc
215 * @return array ("text", "html") etc
217 public static function splitMime( $mime ) {
218 if( strpos( $mime, '/' ) !== false ) {
219 return explode( '/', $mime, 2 );
221 return array( $mime, 'unknown' );
226 * Return the name of this file
230 public function getName() {
231 if ( !isset( $this->name
) ) {
232 $this->assertRepoDefined();
233 $this->name
= $this->repo
->getNameFromTitle( $this->title
);
239 * Get the file extension, e.g. "svg"
243 function getExtension() {
244 if ( !isset( $this->extension
) ) {
245 $n = strrpos( $this->getName(), '.' );
246 $this->extension
= self
::normalizeExtension(
247 $n ?
substr( $this->getName(), $n +
1 ) : '' );
249 return $this->extension
;
253 * Return the associated title object
257 public function getTitle() {
262 * Return the title used to find this file
266 public function getOriginalTitle() {
267 if ( $this->redirected
) {
268 return $this->getRedirectedTitle();
274 * Return the URL of the file
278 public function getUrl() {
279 if ( !isset( $this->url
) ) {
280 $this->assertRepoDefined();
281 $this->url
= $this->repo
->getZoneUrl( 'public' ) . '/' . $this->getUrlRel();
287 * Return a fully-qualified URL to the file.
288 * Upload URL paths _may or may not_ be fully qualified, so
289 * we check. Local paths are assumed to belong on $wgServer.
293 public function getFullUrl() {
294 return wfExpandUrl( $this->getUrl(), PROTO_RELATIVE
);
300 public function getCanonicalUrl() {
301 return wfExpandUrl( $this->getUrl(), PROTO_CANONICAL
);
307 function getViewURL() {
308 if ( $this->mustRender() ) {
309 if ( $this->canRender() ) {
310 return $this->createThumb( $this->getWidth() );
312 wfDebug( __METHOD__
.': supposed to render ' . $this->getName() .
313 ' (' . $this->getMimeType() . "), but can't!\n" );
314 return $this->getURL(); #hm... return NULL?
317 return $this->getURL();
322 * Return the storage path to the file. Note that this does
323 * not mean that a file actually exists under that location.
325 * This path depends on whether directory hashing is active or not,
326 * i.e. whether the files are all found in the same directory,
327 * or in hashed paths like /images/3/3c.
329 * Most callers don't check the return value, but ForeignAPIFile::getPath
332 * @return string|bool
334 public function getPath() {
335 if ( !isset( $this->path
) ) {
336 $this->assertRepoDefined();
337 $this->path
= $this->repo
->getZonePath( 'public' ) . '/' . $this->getRel();
343 * Get an FS copy or original of this file and return the path.
344 * Returns false on failure. Callers must not alter the file.
345 * Temporary files are cleared automatically.
347 * @return string|bool
349 public function getLocalRefPath() {
350 $this->assertRepoDefined();
351 if ( !isset( $this->fsFile
) ) {
352 $this->fsFile
= $this->repo
->getLocalReference( $this->getPath() );
353 if ( !$this->fsFile
) {
354 $this->fsFile
= false; // null => false; cache negative hits
357 return ( $this->fsFile
)
358 ?
$this->fsFile
->getPath()
363 * Return the width of the image. Returns false if the width is unknown
367 * Overridden by LocalFile, UnregisteredLocalFile
373 public function getWidth( $page = 1 ) {
378 * Return the height of the image. Returns false if the height is unknown
382 * Overridden by LocalFile, UnregisteredLocalFile
386 * @return bool|number
388 public function getHeight( $page = 1 ) {
393 * Returns ID or name of user who uploaded the file
396 * @param $type string 'text' or 'id'
400 public function getUser( $type = 'text' ) {
405 * Get the duration of a media file in seconds
409 public function getLength() {
410 $handler = $this->getHandler();
412 return $handler->getLength( $this );
419 * Return true if the file is vectorized
423 public function isVectorized() {
424 $handler = $this->getHandler();
426 return $handler->isVectorized( $this );
433 * Get handler-specific metadata
434 * Overridden by LocalFile, UnregisteredLocalFile
437 public function getMetadata() {
442 * get versioned metadata
444 * @param $metadata Mixed Array or String of (serialized) metadata
445 * @param $version integer version number.
446 * @return Array containing metadata, or what was passed to it on fail (unserializing if not array)
448 public function convertMetadataVersion($metadata, $version) {
449 $handler = $this->getHandler();
450 if ( !is_array( $metadata ) ) {
451 // Just to make the return type consistent
452 $metadata = unserialize( $metadata );
455 return $handler->convertMetadataVersion( $metadata, $version );
462 * Return the bit depth of the file
463 * Overridden by LocalFile
466 public function getBitDepth() {
471 * Return the size of the image file, in bytes
472 * Overridden by LocalFile, UnregisteredLocalFile
475 public function getSize() {
480 * Returns the mime type of the file.
481 * Overridden by LocalFile, UnregisteredLocalFile
486 function getMimeType() {
487 return 'unknown/unknown';
491 * Return the type of the media in the file.
492 * Use the value returned by this function with the MEDIATYPE_xxx constants.
493 * Overridden by LocalFile,
496 function getMediaType() {
497 return MEDIATYPE_UNKNOWN
;
501 * Checks if the output of transform() for this file is likely
502 * to be valid. If this is false, various user elements will
503 * display a placeholder instead.
505 * Currently, this checks if the file is an image format
506 * that can be converted to a format
507 * supported by all browsers (namely GIF, PNG and JPEG),
508 * or if it is an SVG image and SVG conversion is enabled.
512 function canRender() {
513 if ( !isset( $this->canRender
) ) {
514 $this->canRender
= $this->getHandler() && $this->handler
->canRender( $this );
516 return $this->canRender
;
520 * Accessor for __get()
522 protected function getCanRender() {
523 return $this->canRender();
527 * Return true if the file is of a type that can't be directly
528 * rendered by typical browsers and needs to be re-rasterized.
530 * This returns true for everything but the bitmap types
531 * supported by all browsers, i.e. JPEG; GIF and PNG. It will
532 * also return true for any non-image formats.
536 function mustRender() {
537 return $this->getHandler() && $this->handler
->mustRender( $this );
541 * Alias for canRender()
545 function allowInlineDisplay() {
546 return $this->canRender();
550 * Determines if this media file is in a format that is unlikely to
551 * contain viruses or malicious content. It uses the global
552 * $wgTrustedMediaFormats list to determine if the file is safe.
554 * This is used to show a warning on the description page of non-safe files.
555 * It may also be used to disallow direct [[media:...]] links to such files.
557 * Note that this function will always return true if allowInlineDisplay()
558 * or isTrustedFile() is true for this file.
562 function isSafeFile() {
563 if ( !isset( $this->isSafeFile
) ) {
564 $this->isSafeFile
= $this->_getIsSafeFile();
566 return $this->isSafeFile
;
570 * Accessor for __get()
574 protected function getIsSafeFile() {
575 return $this->isSafeFile();
583 protected function _getIsSafeFile() {
584 global $wgTrustedMediaFormats;
586 if ( $this->allowInlineDisplay() ) {
589 if ($this->isTrustedFile()) {
593 $type = $this->getMediaType();
594 $mime = $this->getMimeType();
595 #wfDebug("LocalFile::isSafeFile: type= $type, mime= $mime\n");
597 if ( !$type ||
$type === MEDIATYPE_UNKNOWN
) {
598 return false; #unknown type, not trusted
600 if ( in_array( $type, $wgTrustedMediaFormats ) ) {
604 if ( $mime === "unknown/unknown" ) {
605 return false; #unknown type, not trusted
607 if ( in_array( $mime, $wgTrustedMediaFormats) ) {
615 * Returns true if the file is flagged as trusted. Files flagged that way
616 * can be linked to directly, even if that is not allowed for this type of
619 * This is a dummy function right now and always returns false. It could be
620 * implemented to extract a flag from the database. The trusted flag could be
621 * set on upload, if the user has sufficient privileges, to bypass script-
622 * and html-filters. It may even be coupled with cryptographics signatures
627 function isTrustedFile() {
628 #this could be implemented to check a flag in the database,
629 #look for signatures, etc
634 * Returns true if file exists in the repository.
636 * Overridden by LocalFile to avoid unnecessary stat calls.
638 * @return boolean Whether file exists in the repository.
640 public function exists() {
641 return $this->getPath() && $this->repo
->fileExists( $this->path
);
645 * Returns true if file exists in the repository and can be included in a page.
646 * It would be unsafe to include private images, making public thumbnails inadvertently
648 * @return boolean Whether file exists in the repository and is includable.
650 public function isVisible() {
651 return $this->exists();
657 function getTransformScript() {
658 if ( !isset( $this->transformScript
) ) {
659 $this->transformScript
= false;
661 $script = $this->repo
->getThumbScriptUrl();
663 $this->transformScript
= "$script?f=" . urlencode( $this->getName() );
667 return $this->transformScript
;
671 * Get a ThumbnailImage which is the same size as the source
673 * @param $handlerParams array
677 function getUnscaledThumb( $handlerParams = array() ) {
678 $hp =& $handlerParams;
679 $page = isset( $hp['page'] ) ?
$hp['page'] : false;
680 $width = $this->getWidth( $page );
682 return $this->iconThumb();
684 $hp['width'] = $width;
685 return $this->transform( $hp );
689 * Return the file name of a thumbnail with the specified parameters
691 * @param $params Array: handler-specific parameters
696 function thumbName( $params ) {
697 return $this->generateThumbName( $this->getName(), $params );
701 * Generate a thumbnail file name from a name and specified parameters
703 * @param string $name
704 * @param array $params Parameters which will be passed to MediaHandler::makeParamString
708 function generateThumbName( $name, $params ) {
709 if ( !$this->getHandler() ) {
712 $extension = $this->getExtension();
713 list( $thumbExt, $thumbMime ) = $this->handler
->getThumbType(
714 $extension, $this->getMimeType(), $params );
715 $thumbName = $this->handler
->makeParamString( $params ) . '-' . $name;
716 if ( $thumbExt != $extension ) {
717 $thumbName .= ".$thumbExt";
723 * Create a thumbnail of the image having the specified width/height.
724 * The thumbnail will not be created if the width is larger than the
725 * image's width. Let the browser do the scaling in this case.
726 * The thumbnail is stored on disk and is only computed if the thumbnail
727 * file does not exist OR if it is older than the image.
730 * Keeps aspect ratio of original image. If both width and height are
731 * specified, the generated image will be no bigger than width x height,
732 * and will also have correct aspect ratio.
734 * @param $width Integer: maximum width of the generated thumbnail
735 * @param $height Integer: maximum height of the image (optional)
739 public function createThumb( $width, $height = -1 ) {
740 $params = array( 'width' => $width );
741 if ( $height != -1 ) {
742 $params['height'] = $height;
744 $thumb = $this->transform( $params );
745 if ( is_null( $thumb ) ||
$thumb->isError() ) {
748 return $thumb->getUrl();
752 * Return either a MediaTransformError or placeholder thumbnail (if $wgIgnoreImageErrors)
754 * @param $thumbPath string Thumbnail storage path
755 * @param $thumbUrl string Thumbnail URL
756 * @param $params Array
757 * @param $flags integer
758 * @return MediaTransformOutput
760 protected function transformErrorOutput( $thumbPath, $thumbUrl, $params, $flags ) {
761 global $wgIgnoreImageErrors;
763 if ( $wgIgnoreImageErrors && !( $flags & self
::RENDER_NOW
) ) {
764 return $this->handler
->getTransform( $this, $thumbPath, $thumbUrl, $params );
766 return new MediaTransformError( 'thumbnail_error',
767 $params['width'], 0, wfMsg( 'thumbnail-dest-create' ) );
772 * Transform a media file
774 * @param $params Array: an associative array of handler-specific parameters.
775 * Typical keys are width, height and page.
776 * @param $flags Integer: a bitfield, may contain self::RENDER_NOW to force rendering
777 * @return MediaTransformOutput|bool
779 function transform( $params, $flags = 0 ) {
780 global $wgUseSquid, $wgIgnoreImageErrors, $wgThumbnailEpoch;
782 wfProfileIn( __METHOD__
);
784 if ( !$this->canRender() ) {
785 $thumb = $this->iconThumb();
786 break; // not a bitmap or renderable image, don't try
789 // Get the descriptionUrl to embed it as comment into the thumbnail. Bug 19791.
790 $descriptionUrl = $this->getDescriptionUrl();
791 if ( $descriptionUrl ) {
792 $params['descriptionUrl'] = wfExpandUrl( $descriptionUrl, PROTO_CANONICAL
);
795 $script = $this->getTransformScript();
796 if ( $script && !( $flags & self
::RENDER_NOW
) ) {
797 // Use a script to transform on client request, if possible
798 $thumb = $this->handler
->getScriptedTransform( $this, $script, $params );
804 $normalisedParams = $params;
805 $this->handler
->normaliseParams( $this, $normalisedParams );
807 $thumbName = $this->thumbName( $normalisedParams );
808 $thumbUrl = $this->getThumbUrl( $thumbName );
809 $thumbPath = $this->getThumbPath( $thumbName ); // final thumb path
812 // Defer rendering if a 404 handler is set up...
813 if ( $this->repo
->canTransformVia404() && !( $flags & self
::RENDER_NOW
) ) {
814 wfDebug( __METHOD__
. " transformation deferred." );
815 // XXX: Pass in the storage path even though we are not rendering anything
816 // and the path is supposed to be an FS path. This is due to getScalerType()
817 // getting called on the path and clobbering $thumb->getUrl() if it's false.
818 $thumb = $this->handler
->getTransform( $this, $thumbPath, $thumbUrl, $params );
821 // Clean up broken thumbnails as needed
822 $this->migrateThumbFile( $thumbName );
823 // Check if an up-to-date thumbnail already exists...
824 wfDebug( __METHOD__
.": Doing stat for $thumbPath\n" );
825 if ( $this->repo
->fileExists( $thumbPath ) && !( $flags & self
::RENDER_FORCE
) ) {
826 $timestamp = $this->repo
->getFileTimestamp( $thumbPath );
827 if ( $timestamp !== false && $timestamp >= $wgThumbnailEpoch ) {
828 // XXX: Pass in the storage path even though we are not rendering anything
829 // and the path is supposed to be an FS path. This is due to getScalerType()
830 // getting called on the path and clobbering $thumb->getUrl() if it's false.
831 $thumb = $this->handler
->getTransform( $this, $thumbPath, $thumbUrl, $params );
832 $thumb->setStoragePath( $thumbPath );
835 } elseif ( $flags & self
::RENDER_FORCE
) {
836 wfDebug( __METHOD__
. " forcing rendering per flag File::RENDER_FORCE\n" );
840 // Create a temp FS file with the same extension and the thumbnail
841 $thumbExt = FileBackend
::extensionFromPath( $thumbPath );
842 $tmpFile = TempFSFile
::factory( 'transform_', $thumbExt );
844 $thumb = $this->transformErrorOutput( $thumbPath, $thumbUrl, $params, $flags );
847 $tmpThumbPath = $tmpFile->getPath(); // path of 0-byte temp file
849 // Actually render the thumbnail...
850 $thumb = $this->handler
->doTransform( $this, $tmpThumbPath, $thumbUrl, $params );
851 $tmpFile->bind( $thumb ); // keep alive with $thumb
853 if ( !$thumb ) { // bad params?
855 } elseif ( $thumb->isError() ) { // transform error
856 $this->lastError
= $thumb->toText();
857 // Ignore errors if requested
858 if ( $wgIgnoreImageErrors && !( $flags & self
::RENDER_NOW
) ) {
859 $thumb = $this->handler
->getTransform( $this, $tmpThumbPath, $thumbUrl, $params );
861 } elseif ( $this->repo
&& $thumb->hasFile() && !$thumb->fileIsSource() ) {
862 $backend = $this->repo
->getBackend();
863 // Copy the thumbnail from the file system into storage. This avoids using
864 // FileRepo::store(); getThumbPath() uses a different zone in some subclasses.
865 $backend->prepare( array( 'dir' => dirname( $thumbPath ) ) );
866 $status = $backend->store(
867 array( 'src' => $tmpThumbPath, 'dst' => $thumbPath, 'overwrite' => 1 ),
868 array( 'force' => 1, 'nonLocking' => 1, 'allowStale' => 1 )
870 if ( $status->isOK() ) {
871 $thumb->setStoragePath( $thumbPath );
873 $thumb = $this->transformErrorOutput( $thumbPath, $thumbUrl, $params, $flags );
877 // Purge. Useful in the event of Core -> Squid connection failure or squid
878 // purge collisions from elsewhere during failure. Don't keep triggering for
879 // "thumbs" which have the main image URL though (bug 13776)
881 if ( !$thumb ||
$thumb->isError() ||
$thumb->getUrl() != $this->getURL() ) {
882 SquidUpdate
::purge( array( $thumbUrl ) );
887 wfProfileOut( __METHOD__
);
888 return is_object( $thumb ) ?
$thumb : false;
892 * Hook into transform() to allow migration of thumbnail files
894 * Overridden by LocalFile
896 function migrateThumbFile( $thumbName ) {}
899 * Get a MediaHandler instance for this file
901 * @return MediaHandler
903 function getHandler() {
904 if ( !isset( $this->handler
) ) {
905 $this->handler
= MediaHandler
::getHandler( $this->getMimeType() );
907 return $this->handler
;
911 * Get a ThumbnailImage representing a file type icon
913 * @return ThumbnailImage
915 function iconThumb() {
916 global $wgStylePath, $wgStyleDirectory;
918 $try = array( 'fileicon-' . $this->getExtension() . '.png', 'fileicon.png' );
919 foreach ( $try as $icon ) {
920 $path = '/common/images/icons/' . $icon;
921 $filepath = $wgStyleDirectory . $path;
922 if ( file_exists( $filepath ) ) { // always FS
923 return new ThumbnailImage( $this, $wgStylePath . $path, 120, 120 );
930 * Get last thumbnailing error.
933 function getLastError() {
934 return $this->lastError
;
938 * Get all thumbnail names previously generated for this file
940 * Overridden by LocalFile
942 function getThumbnails() {
947 * Purge shared caches such as thumbnails and DB data caching
949 * Overridden by LocalFile
950 * @param $options Array Options, which include:
951 * 'forThumbRefresh' : The purging is only to refresh thumbnails
953 function purgeCache( $options = array() ) {}
956 * Purge the file description page, but don't go after
957 * pages using the file. Use when modifying file history
958 * but not the current data.
960 function purgeDescription() {
961 $title = $this->getTitle();
963 $title->invalidateCache();
964 $title->purgeSquid();
969 * Purge metadata and all affected pages when the file is created,
970 * deleted, or majorly updated.
972 function purgeEverything() {
973 // Delete thumbnails and refresh file metadata cache
975 $this->purgeDescription();
977 // Purge cache of all pages using this file
978 $title = $this->getTitle();
980 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
986 * Return a fragment of the history of file.
989 * @param $limit integer Limit of rows to return
990 * @param $start timestamp Only revisions older than $start will be returned
991 * @param $end timestamp Only revisions newer than $end will be returned
992 * @param $inc bool Include the endpoints of the time range
996 function getHistory($limit = null, $start = null, $end = null, $inc=true) {
1001 * Return the history of this file, line by line. Starts with current version,
1002 * then old versions. Should return an object similar to an image/oldimage
1006 * Overridden in LocalFile
1008 public function nextHistoryLine() {
1013 * Reset the history pointer to the first element of the history.
1014 * Always call this function after using nextHistoryLine() to free db resources
1016 * Overridden in LocalFile.
1018 public function resetHistory() {}
1021 * Get the filename hash component of the directory including trailing slash,
1023 * If the repository is not hashed, returns an empty string.
1027 function getHashPath() {
1028 if ( !isset( $this->hashPath
) ) {
1029 $this->assertRepoDefined();
1030 $this->hashPath
= $this->repo
->getHashPath( $this->getName() );
1032 return $this->hashPath
;
1036 * Get the path of the file relative to the public zone root.
1037 * This function is overriden in OldLocalFile to be like getArchiveRel().
1042 return $this->getHashPath() . $this->getName();
1046 * Get the path of an archived file relative to the public zone root
1048 * @param $suffix bool|string if not false, the name of an archived thumbnail file
1052 function getArchiveRel( $suffix = false ) {
1053 $path = 'archive/' . $this->getHashPath();
1054 if ( $suffix === false ) {
1055 $path = substr( $path, 0, -1 );
1063 * Get the path, relative to the thumbnail zone root, of the
1064 * thumbnail directory or a particular file if $suffix is specified
1066 * @param $suffix bool|string if not false, the name of a thumbnail file
1070 function getThumbRel( $suffix = false ) {
1071 $path = $this->getRel();
1072 if ( $suffix !== false ) {
1073 $path .= '/' . $suffix;
1079 * Get urlencoded path of the file relative to the public zone root.
1080 * This function is overriden in OldLocalFile to be like getArchiveUrl().
1084 function getUrlRel() {
1085 return $this->getHashPath() . rawurlencode( $this->getName() );
1089 * Get the path, relative to the thumbnail zone root, for an archived file's thumbs directory
1090 * or a specific thumb if the $suffix is given.
1092 * @param $archiveName string the timestamped name of an archived image
1093 * @param $suffix bool|string if not false, the name of a thumbnail file
1097 function getArchiveThumbRel( $archiveName, $suffix = false ) {
1098 $path = 'archive/' . $this->getHashPath() . $archiveName . "/";
1099 if ( $suffix === false ) {
1100 $path = substr( $path, 0, -1 );
1108 * Get the path of the archived file.
1110 * @param $suffix bool|string if not false, the name of an archived file.
1114 function getArchivePath( $suffix = false ) {
1115 $this->assertRepoDefined();
1116 return $this->repo
->getZonePath( 'public' ) . '/' . $this->getArchiveRel( $suffix );
1120 * Get the path of an archived file's thumbs, or a particular thumb if $suffix is specified
1122 * @param $archiveName string the timestamped name of an archived image
1123 * @param $suffix bool|string if not false, the name of a thumbnail file
1127 function getArchiveThumbPath( $archiveName, $suffix = false ) {
1128 $this->assertRepoDefined();
1129 return $this->repo
->getZonePath( 'thumb' ) . '/' .
1130 $this->getArchiveThumbRel( $archiveName, $suffix );
1134 * Get the path of the thumbnail directory, or a particular file if $suffix is specified
1136 * @param $suffix bool|string if not false, the name of a thumbnail file
1140 function getThumbPath( $suffix = false ) {
1141 $this->assertRepoDefined();
1142 return $this->repo
->getZonePath( 'thumb' ) . '/' . $this->getThumbRel( $suffix );
1146 * Get the URL of the archive directory, or a particular file if $suffix is specified
1148 * @param $suffix bool|string if not false, the name of an archived file
1152 function getArchiveUrl( $suffix = false ) {
1153 $this->assertRepoDefined();
1154 $path = $this->repo
->getZoneUrl( 'public' ) . '/archive/' . $this->getHashPath();
1155 if ( $suffix === false ) {
1156 $path = substr( $path, 0, -1 );
1158 $path .= rawurlencode( $suffix );
1164 * Get the URL of the archived file's thumbs, or a particular thumb if $suffix is specified
1166 * @param $archiveName string the timestamped name of an archived image
1167 * @param $suffix bool|string if not false, the name of a thumbnail file
1171 function getArchiveThumbUrl( $archiveName, $suffix = false ) {
1172 $this->assertRepoDefined();
1173 $path = $this->repo
->getZoneUrl( 'thumb' ) . '/archive/' .
1174 $this->getHashPath() . rawurlencode( $archiveName ) . "/";
1175 if ( $suffix === false ) {
1176 $path = substr( $path, 0, -1 );
1178 $path .= rawurlencode( $suffix );
1184 * Get the URL of the thumbnail directory, or a particular file if $suffix is specified
1186 * @param $suffix bool|string if not false, the name of a thumbnail file
1190 function getThumbUrl( $suffix = false ) {
1191 $this->assertRepoDefined();
1192 $path = $this->repo
->getZoneUrl( 'thumb' ) . '/' . $this->getUrlRel();
1193 if ( $suffix !== false ) {
1194 $path .= '/' . rawurlencode( $suffix );
1200 * Get the public zone virtual URL for a current version source file
1202 * @param $suffix bool|string if not false, the name of a thumbnail file
1206 function getVirtualUrl( $suffix = false ) {
1207 $this->assertRepoDefined();
1208 $path = $this->repo
->getVirtualUrl() . '/public/' . $this->getUrlRel();
1209 if ( $suffix !== false ) {
1210 $path .= '/' . rawurlencode( $suffix );
1216 * Get the public zone virtual URL for an archived version source file
1218 * @param $suffix bool|string if not false, the name of a thumbnail file
1222 function getArchiveVirtualUrl( $suffix = false ) {
1223 $this->assertRepoDefined();
1224 $path = $this->repo
->getVirtualUrl() . '/public/archive/' . $this->getHashPath();
1225 if ( $suffix === false ) {
1226 $path = substr( $path, 0, -1 );
1228 $path .= rawurlencode( $suffix );
1234 * Get the virtual URL for a thumbnail file or directory
1236 * @param $suffix bool|string if not false, the name of a thumbnail file
1240 function getThumbVirtualUrl( $suffix = false ) {
1241 $this->assertRepoDefined();
1242 $path = $this->repo
->getVirtualUrl() . '/thumb/' . $this->getUrlRel();
1243 if ( $suffix !== false ) {
1244 $path .= '/' . rawurlencode( $suffix );
1252 function isHashed() {
1253 $this->assertRepoDefined();
1254 return $this->repo
->isHashed();
1258 * @throws MWException
1260 function readOnlyError() {
1261 throw new MWException( get_class($this) . ': write operations are not supported' );
1265 * Record a file upload in the upload log and the image table
1267 * Overridden by LocalFile
1270 * @param $license string
1271 * @param $copyStatus string
1272 * @param $source string
1273 * @param $watch bool
1275 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '', $watch = false ) {
1276 $this->readOnlyError();
1280 * Move or copy a file to its public location. If a file exists at the
1281 * destination, move it to an archive. Returns a FileRepoStatus object with
1282 * the archive name in the "value" member on success.
1284 * The archive name should be passed through to recordUpload for database
1287 * @param $srcPath String: local filesystem path to the source image
1288 * @param $flags Integer: a bitwise combination of:
1289 * File::DELETE_SOURCE Delete the source file, i.e. move
1291 * @return FileRepoStatus object. On success, the value member contains the
1292 * archive name, or an empty string if it was a new file.
1295 * Overridden by LocalFile
1297 function publish( $srcPath, $flags = 0 ) {
1298 $this->readOnlyError();
1304 function formatMetadata() {
1305 if ( !$this->getHandler() ) {
1308 return $this->getHandler()->formatMetadata( $this, $this->getMetadata() );
1312 * Returns true if the file comes from the local file repository.
1316 function isLocal() {
1317 return $this->repo
&& $this->repo
->isLocal();
1321 * Returns the name of the repository.
1325 function getRepoName() {
1326 return $this->repo ?
$this->repo
->getName() : 'unknown';
1330 * Returns the repository
1332 * @return FileRepo|bool
1334 function getRepo() {
1339 * Returns true if the image is an old version
1349 * Is this file a "deleted" file in a private archive?
1356 function isDeleted( $field ) {
1361 * Return the deletion bitfield
1364 function getVisibility() {
1369 * Was this file ever deleted from the wiki?
1373 function wasDeleted() {
1374 $title = $this->getTitle();
1375 return $title && $title->isDeletedQuick();
1379 * Move file to the new title
1381 * Move current, old version and all thumbnails
1382 * to the new filename. Old file is deleted.
1384 * Cache purging is done; checks for validity
1385 * and logging are caller's responsibility
1387 * @param $target Title New file name
1388 * @return FileRepoStatus object.
1390 function move( $target ) {
1391 $this->readOnlyError();
1395 * Delete all versions of the file.
1397 * Moves the files into an archive directory (or deletes them)
1398 * and removes the database rows.
1400 * Cache purging is done; logging is caller's responsibility.
1402 * @param $reason String
1403 * @param $suppress Boolean: hide content from sysops?
1404 * @return bool on success, false on some kind of failure
1406 * Overridden by LocalFile
1408 function delete( $reason, $suppress = false ) {
1409 $this->readOnlyError();
1413 * Restore all or specified deleted revisions to the given file.
1414 * Permissions and logging are left to the caller.
1416 * May throw database exceptions on error.
1418 * @param $versions array set of record ids of deleted items to restore,
1419 * or empty to restore all revisions.
1420 * @param $unsuppress bool remove restrictions on content upon restoration?
1421 * @return int|bool the number of file revisions restored if successful,
1422 * or false on failure
1424 * Overridden by LocalFile
1426 function restore( $versions = array(), $unsuppress = false ) {
1427 $this->readOnlyError();
1431 * Returns 'true' if this file is a type which supports multiple pages,
1432 * e.g. DJVU or PDF. Note that this may be true even if the file in
1433 * question only has a single page.
1437 function isMultipage() {
1438 return $this->getHandler() && $this->handler
->isMultiPage( $this );
1442 * Returns the number of pages of a multipage document, or false for
1443 * documents which aren't multipage documents
1447 function pageCount() {
1448 if ( !isset( $this->pageCount
) ) {
1449 if ( $this->getHandler() && $this->handler
->isMultiPage( $this ) ) {
1450 $this->pageCount
= $this->handler
->pageCount( $this );
1452 $this->pageCount
= false;
1455 return $this->pageCount
;
1459 * Calculate the height of a thumbnail using the source and destination width
1467 static function scaleHeight( $srcWidth, $srcHeight, $dstWidth ) {
1468 // Exact integer multiply followed by division
1469 if ( $srcWidth == 0 ) {
1472 return round( $srcHeight * $dstWidth / $srcWidth );
1477 * Get an image size array like that returned by getImageSize(), or false if it
1478 * can't be determined.
1480 * @param $fileName String: The filename
1483 function getImageSize( $fileName ) {
1484 if ( !$this->getHandler() ) {
1487 return $this->handler
->getImageSize( $this, $fileName );
1491 * Get the URL of the image description page. May return false if it is
1492 * unknown or not applicable.
1496 function getDescriptionUrl() {
1497 if ( $this->repo
) {
1498 return $this->repo
->getDescriptionUrl( $this->getName() );
1505 * Get the HTML text of the description page, if available
1509 function getDescriptionText() {
1510 global $wgMemc, $wgLang;
1511 if ( !$this->repo ||
!$this->repo
->fetchDescription
) {
1514 $renderUrl = $this->repo
->getDescriptionRenderUrl( $this->getName(), $wgLang->getCode() );
1516 if ( $this->repo
->descriptionCacheExpiry
> 0 ) {
1517 wfDebug("Attempting to get the description from cache...");
1518 $key = $this->repo
->getLocalCacheKey( 'RemoteFileDescription', 'url', $wgLang->getCode(),
1520 $obj = $wgMemc->get($key);
1522 wfDebug("success!\n");
1527 wfDebug( "Fetching shared description from $renderUrl\n" );
1528 $res = Http
::get( $renderUrl );
1529 if ( $res && $this->repo
->descriptionCacheExpiry
> 0 ) {
1530 $wgMemc->set( $key, $res, $this->repo
->descriptionCacheExpiry
);
1539 * Get discription of file revision
1544 function getDescription() {
1549 * Get the 14-character timestamp of the file upload
1551 * @return string|bool TS_MW timestamp or false on failure
1553 function getTimestamp() {
1554 $this->assertRepoDefined();
1555 return $this->repo
->getFileTimestamp( $this->getPath() );
1559 * Get the SHA-1 base 36 hash of the file
1563 function getSha1() {
1564 $this->assertRepoDefined();
1565 return $this->repo
->getFileSha1( $this->getPath() );
1569 * Get the deletion archive key, <sha1>.<ext>
1573 function getStorageKey() {
1574 $hash = $this->getSha1();
1578 $ext = $this->getExtension();
1579 $dotExt = $ext === '' ?
'' : ".$ext";
1580 return $hash . $dotExt;
1584 * Determine if the current user is allowed to view a particular
1585 * field of this file, if it's marked as deleted.
1587 * @param $field Integer
1588 * @param $user User object to check, or null to use $wgUser
1591 function userCan( $field, User
$user = null ) {
1596 * Get an associative array containing information about a file in the local filesystem.
1598 * @param $path String: absolute local filesystem path
1599 * @param $ext Mixed: the file extension, or true to extract it from the filename.
1600 * Set it to false to ignore the extension.
1604 static function getPropsFromPath( $path, $ext = true ) {
1605 wfDebug( __METHOD__
.": Getting file info for $path\n" );
1606 wfDeprecated( __METHOD__
, '1.19' );
1608 $fsFile = new FSFile( $path );
1609 return $fsFile->getProps();
1613 * Get a SHA-1 hash of a file in the local filesystem, in base-36 lower case
1614 * encoding, zero padded to 31 digits.
1616 * 160 log 2 / log 36 = 30.95, so the 160-bit hash fills 31 digits in base 36
1619 * @param $path string
1621 * @return bool|string False on failure
1623 static function sha1Base36( $path ) {
1624 wfDeprecated( __METHOD__
, '1.19' );
1626 $fsFile = new FSFile( $path );
1627 return $fsFile->getSha1Base36();
1633 function getLongDesc() {
1634 $handler = $this->getHandler();
1636 return $handler->getLongDesc( $this );
1638 return MediaHandler
::getGeneralLongDesc( $this );
1645 function getShortDesc() {
1646 $handler = $this->getHandler();
1648 return $handler->getShortDesc( $this );
1650 return MediaHandler
::getGeneralShortDesc( $this );
1657 function getDimensionsString() {
1658 $handler = $this->getHandler();
1660 return $handler->getDimensionsString( $this );
1669 function getRedirected() {
1670 return $this->redirected
;
1676 function getRedirectedTitle() {
1677 if ( $this->redirected
) {
1678 if ( !$this->redirectTitle
) {
1679 $this->redirectTitle
= Title
::makeTitle( NS_FILE
, $this->redirected
);
1681 return $this->redirectTitle
;
1689 function redirectedFrom( $from ) {
1690 $this->redirected
= $from;
1696 function isMissing() {
1701 * Assert that $this->repo is set to a valid FileRepo instance
1702 * @throws MWException
1704 protected function assertRepoDefined() {
1705 if ( !( $this->repo
instanceof $this->repoClass
) ) {
1706 throw new MWException( "A {$this->repoClass} object is not set for this File.\n" );
1711 * Assert that $this->title is set to a Title
1712 * @throws MWException
1714 protected function assertTitleDefined() {
1715 if ( !( $this->title
instanceof Title
) ) {
1716 throw new MWException( "A Title object is not set for this File.\n" );