10 * Implements some public methods and some protected utility functions which
11 * are required by multiple child classes. Contains stub functionality for
12 * unimplemented public methods.
14 * Stub functions which should be overridden are marked with STUB. Some more
15 * concrete functions are also typically overridden by child classes.
17 * Note that only the repo object knows what its file class is called. You should
18 * never name a file class explictly outside of the repo class. Instead use the
19 * repo's factory functions to generate file objects, for example:
21 * RepoGroup::singleton()->getLocalRepo()->newFile($title);
23 * The convenience functions wfLocalFile() and wfFindFile() should be sufficient
29 const DELETED_FILE
= 1;
30 const DELETED_COMMENT
= 2;
31 const DELETED_USER
= 4;
32 const DELETED_RESTRICTED
= 8;
34 /** Force rendering in the current process */
37 * Force rendering even if thumbnail already exist and using RENDER_NOW
38 * I.e. you have to pass both flags: File::RENDER_NOW | File::RENDER_FORCE
40 const RENDER_FORCE
= 2;
42 const DELETE_SOURCE
= 1;
45 * Some member variables can be lazy-initialised using __get(). The
46 * initialisation function for these variables is always a function named
47 * like getVar(), where Var is the variable name with upper-case first
50 * The following variables are initialised in this way in this base class:
51 * name, extension, handler, path, canRender, isSafeFile,
52 * transformScript, hashPath, pageCount, url
54 * Code within this class should generally use the accessor function
55 * directly, since __get() isn't re-entrant and therefore causes bugs that
56 * depend on initialisation order.
60 * The following member variables are not lazy-initialised
73 var $lastError, $redirected, $redirectedTitle;
88 protected $url, $extension, $name, $path, $hashPath, $pageCount, $transformScript;
93 protected $canRender, $isSafeFile;
96 * @var string Required Repository class type
98 protected $repoClass = 'FileRepo';
101 * Call this constructor from child classes.
103 * Both $title and $repo are optional, though some functions
104 * may return false or throw exceptions if they are not set.
105 * Most subclasses will want to call assertRepoDefined() here.
107 * @param $title Title|string|false
108 * @param $repo FileRepo|false
110 function __construct( $title, $repo ) {
111 if ( $title !== false ) { // subclasses may not use MW titles
112 $title = self
::normalizeTitle( $title, 'exception' );
114 $this->title
= $title;
119 * Given a string or Title object return either a
120 * valid Title object with namespace NS_FILE or null
122 * @param $title Title|string
123 * @param $exception string|false Use 'exception' to throw an error on bad titles
126 static function normalizeTitle( $title, $exception = false ) {
128 if ( $ret instanceof Title
) {
129 # Normalize NS_MEDIA -> NS_FILE
130 if ( $ret->getNamespace() == NS_MEDIA
) {
131 $ret = Title
::makeTitleSafe( NS_FILE
, $ret->getDBkey() );
132 # Sanity check the title namespace
133 } elseif ( $ret->getNamespace() !== NS_FILE
) {
137 # Convert strings to Title objects
138 $ret = Title
::makeTitleSafe( NS_FILE
, (string)$ret );
140 if ( !$ret && $exception !== false ) {
141 throw new MWException( "`$title` is not a valid file title." );
146 function __get( $name ) {
147 $function = array( $this, 'get' . ucfirst( $name ) );
148 if ( !is_callable( $function ) ) {
151 $this->$name = call_user_func( $function );
157 * Normalize a file extension to the common form, and ensure it's clean.
158 * Extensions with non-alphanumeric characters will be discarded.
160 * @param $ext string (without the .)
163 static function normalizeExtension( $ext ) {
164 $lower = strtolower( $ext );
171 if( isset( $squish[$lower] ) ) {
172 return $squish[$lower];
173 } elseif( preg_match( '/^[0-9a-z]+$/', $lower ) ) {
181 * Checks if file extensions are compatible
183 * @param $old File Old file
184 * @param $new string New name
188 static function checkExtensionCompatibility( File
$old, $new ) {
189 $oldMime = $old->getMimeType();
190 $n = strrpos( $new, '.' );
191 $newExt = self
::normalizeExtension( $n ?
substr( $new, $n +
1 ) : '' );
192 $mimeMagic = MimeMagic
::singleton();
193 return $mimeMagic->isMatchingExtension( $newExt, $oldMime );
197 * Upgrade the database row if there is one
198 * Called by ImagePage
201 function upgradeRow() {}
204 * Split an internet media type into its two components; if not
205 * a two-part name, set the minor type to 'unknown'.
207 * @param string $mime "text/html" etc
208 * @return array ("text", "html") etc
210 public static function splitMime( $mime ) {
211 if( strpos( $mime, '/' ) !== false ) {
212 return explode( '/', $mime, 2 );
214 return array( $mime, 'unknown' );
219 * Return the name of this file
223 public function getName() {
224 if ( !isset( $this->name
) ) {
225 $this->assertRepoDefined();
226 $this->name
= $this->repo
->getNameFromTitle( $this->title
);
232 * Get the file extension, e.g. "svg"
236 function getExtension() {
237 if ( !isset( $this->extension
) ) {
238 $n = strrpos( $this->getName(), '.' );
239 $this->extension
= self
::normalizeExtension(
240 $n ?
substr( $this->getName(), $n +
1 ) : '' );
242 return $this->extension
;
246 * Return the associated title object
248 * @return Title|false
250 public function getTitle() {
255 * Return the title used to find this file
259 public function getOriginalTitle() {
260 if ( $this->redirected
) {
261 return $this->getRedirectedTitle();
267 * Return the URL of the file
271 public function getUrl() {
272 if ( !isset( $this->url
) ) {
273 $this->assertRepoDefined();
274 $this->url
= $this->repo
->getZoneUrl( 'public' ) . '/' . $this->getUrlRel();
280 * Return a fully-qualified URL to the file.
281 * Upload URL paths _may or may not_ be fully qualified, so
282 * we check. Local paths are assumed to belong on $wgServer.
286 public function getFullUrl() {
287 return wfExpandUrl( $this->getUrl(), PROTO_RELATIVE
);
293 public function getCanonicalUrl() {
294 return wfExpandUrl( $this->getUrl(), PROTO_CANONICAL
);
300 function getViewURL() {
301 if( $this->mustRender()) {
302 if( $this->canRender() ) {
303 return $this->createThumb( $this->getWidth() );
305 wfDebug(__METHOD__
.': supposed to render '.$this->getName().' ('.$this->getMimeType()."), but can't!\n");
306 return $this->getURL(); #hm... return NULL?
309 return $this->getURL();
314 * Return the storage path to the file. Note that this does
315 * not mean that a file actually exists under that location.
317 * This path depends on whether directory hashing is active or not,
318 * i.e. whether the files are all found in the same directory,
319 * or in hashed paths like /images/3/3c.
321 * Most callers don't check the return value, but ForeignAPIFile::getPath
324 * @return string|false
326 public function getPath() {
327 if ( !isset( $this->path
) ) {
328 $this->assertRepoDefined();
329 $this->path
= $this->repo
->getZonePath( 'public' ) . '/' . $this->getRel();
335 * Get an FS copy or original of this file and return the path.
336 * Returns false on failure. Callers must not alter the file.
337 * Temporary files are cleared automatically.
339 * @return string|false
341 public function getLocalRefPath() {
342 $this->assertRepoDefined();
343 if ( !isset( $this->fsFile
) ) {
344 $this->fsFile
= $this->repo
->getLocalReference( $this->getPath() );
345 if ( !$this->fsFile
) {
346 $this->fsFile
= false; // null => false; cache negative hits
349 return ( $this->fsFile
)
350 ?
$this->fsFile
->getPath()
355 * Return the width of the image. Returns false if the width is unknown
359 * Overridden by LocalFile, UnregisteredLocalFile
365 public function getWidth( $page = 1 ) {
370 * Return the height of the image. Returns false if the height is unknown
374 * Overridden by LocalFile, UnregisteredLocalFile
378 * @return false|number
380 public function getHeight( $page = 1 ) {
385 * Returns ID or name of user who uploaded the file
388 * @param $type string 'text' or 'id'
392 public function getUser( $type = 'text' ) {
397 * Get the duration of a media file in seconds
401 public function getLength() {
402 $handler = $this->getHandler();
404 return $handler->getLength( $this );
411 * Return true if the file is vectorized
415 public function isVectorized() {
416 $handler = $this->getHandler();
418 return $handler->isVectorized( $this );
425 * Get handler-specific metadata
426 * Overridden by LocalFile, UnregisteredLocalFile
429 public function getMetadata() {
434 * get versioned metadata
436 * @param $metadata Mixed Array or String of (serialized) metadata
437 * @param $version integer version number.
438 * @return Array containing metadata, or what was passed to it on fail (unserializing if not array)
440 public function convertMetadataVersion($metadata, $version) {
441 $handler = $this->getHandler();
442 if ( !is_array( $metadata ) ) {
443 // Just to make the return type consistent
444 $metadata = unserialize( $metadata );
447 return $handler->convertMetadataVersion( $metadata, $version );
454 * Return the bit depth of the file
455 * Overridden by LocalFile
458 public function getBitDepth() {
463 * Return the size of the image file, in bytes
464 * Overridden by LocalFile, UnregisteredLocalFile
467 public function getSize() {
472 * Returns the mime type of the file.
473 * Overridden by LocalFile, UnregisteredLocalFile
478 function getMimeType() {
479 return 'unknown/unknown';
483 * Return the type of the media in the file.
484 * Use the value returned by this function with the MEDIATYPE_xxx constants.
485 * Overridden by LocalFile,
488 function getMediaType() {
489 return MEDIATYPE_UNKNOWN
;
493 * Checks if the output of transform() for this file is likely
494 * to be valid. If this is false, various user elements will
495 * display a placeholder instead.
497 * Currently, this checks if the file is an image format
498 * that can be converted to a format
499 * supported by all browsers (namely GIF, PNG and JPEG),
500 * or if it is an SVG image and SVG conversion is enabled.
504 function canRender() {
505 if ( !isset( $this->canRender
) ) {
506 $this->canRender
= $this->getHandler() && $this->handler
->canRender( $this );
508 return $this->canRender
;
512 * Accessor for __get()
514 protected function getCanRender() {
515 return $this->canRender();
519 * Return true if the file is of a type that can't be directly
520 * rendered by typical browsers and needs to be re-rasterized.
522 * This returns true for everything but the bitmap types
523 * supported by all browsers, i.e. JPEG; GIF and PNG. It will
524 * also return true for any non-image formats.
528 function mustRender() {
529 return $this->getHandler() && $this->handler
->mustRender( $this );
533 * Alias for canRender()
537 function allowInlineDisplay() {
538 return $this->canRender();
542 * Determines if this media file is in a format that is unlikely to
543 * contain viruses or malicious content. It uses the global
544 * $wgTrustedMediaFormats list to determine if the file is safe.
546 * This is used to show a warning on the description page of non-safe files.
547 * It may also be used to disallow direct [[media:...]] links to such files.
549 * Note that this function will always return true if allowInlineDisplay()
550 * or isTrustedFile() is true for this file.
554 function isSafeFile() {
555 if ( !isset( $this->isSafeFile
) ) {
556 $this->isSafeFile
= $this->_getIsSafeFile();
558 return $this->isSafeFile
;
562 * Accessor for __get()
566 protected function getIsSafeFile() {
567 return $this->isSafeFile();
575 protected function _getIsSafeFile() {
576 global $wgTrustedMediaFormats;
578 if ( $this->allowInlineDisplay() ) {
581 if ($this->isTrustedFile()) {
585 $type = $this->getMediaType();
586 $mime = $this->getMimeType();
587 #wfDebug("LocalFile::isSafeFile: type= $type, mime= $mime\n");
589 if ( !$type ||
$type === MEDIATYPE_UNKNOWN
) {
590 return false; #unknown type, not trusted
592 if ( in_array( $type, $wgTrustedMediaFormats ) ) {
596 if ( $mime === "unknown/unknown" ) {
597 return false; #unknown type, not trusted
599 if ( in_array( $mime, $wgTrustedMediaFormats) ) {
607 * Returns true if the file is flagged as trusted. Files flagged that way
608 * can be linked to directly, even if that is not allowed for this type of
611 * This is a dummy function right now and always returns false. It could be
612 * implemented to extract a flag from the database. The trusted flag could be
613 * set on upload, if the user has sufficient privileges, to bypass script-
614 * and html-filters. It may even be coupled with cryptographics signatures
619 function isTrustedFile() {
620 #this could be implemented to check a flag in the database,
621 #look for signatures, etc
626 * Returns true if file exists in the repository.
628 * Overridden by LocalFile to avoid unnecessary stat calls.
630 * @return boolean Whether file exists in the repository.
632 public function exists() {
633 return $this->getPath() && $this->repo
->fileExists( $this->path
);
637 * Returns true if file exists in the repository and can be included in a page.
638 * It would be unsafe to include private images, making public thumbnails inadvertently
640 * @return boolean Whether file exists in the repository and is includable.
642 public function isVisible() {
643 return $this->exists();
649 function getTransformScript() {
650 if ( !isset( $this->transformScript
) ) {
651 $this->transformScript
= false;
653 $script = $this->repo
->getThumbScriptUrl();
655 $this->transformScript
= "$script?f=" . urlencode( $this->getName() );
659 return $this->transformScript
;
663 * Get a ThumbnailImage which is the same size as the source
665 * @param $handlerParams array
669 function getUnscaledThumb( $handlerParams = array() ) {
670 $hp =& $handlerParams;
671 $page = isset( $hp['page'] ) ?
$hp['page'] : false;
672 $width = $this->getWidth( $page );
674 return $this->iconThumb();
676 $hp['width'] = $width;
677 return $this->transform( $hp );
681 * Return the file name of a thumbnail with the specified parameters
683 * @param $params Array: handler-specific parameters
688 function thumbName( $params ) {
689 return $this->generateThumbName( $this->getName(), $params );
693 * Generate a thumbnail file name from a name and specified parameters
695 * @param string $name
696 * @param array $params Parameters which will be passed to MediaHandler::makeParamString
700 function generateThumbName( $name, $params ) {
701 if ( !$this->getHandler() ) {
704 $extension = $this->getExtension();
705 list( $thumbExt, $thumbMime ) = $this->handler
->getThumbType(
706 $extension, $this->getMimeType(), $params );
707 $thumbName = $this->handler
->makeParamString( $params ) . '-' . $name;
708 if ( $thumbExt != $extension ) {
709 $thumbName .= ".$thumbExt";
715 * Create a thumbnail of the image having the specified width/height.
716 * The thumbnail will not be created if the width is larger than the
717 * image's width. Let the browser do the scaling in this case.
718 * The thumbnail is stored on disk and is only computed if the thumbnail
719 * file does not exist OR if it is older than the image.
722 * Keeps aspect ratio of original image. If both width and height are
723 * specified, the generated image will be no bigger than width x height,
724 * and will also have correct aspect ratio.
726 * @param $width Integer: maximum width of the generated thumbnail
727 * @param $height Integer: maximum height of the image (optional)
731 public function createThumb( $width, $height = -1 ) {
732 $params = array( 'width' => $width );
733 if ( $height != -1 ) {
734 $params['height'] = $height;
736 $thumb = $this->transform( $params );
737 if ( is_null( $thumb ) ||
$thumb->isError() ) {
740 return $thumb->getUrl();
744 * Do the work of a transform (from an original into a thumb).
745 * Contains filesystem-specific functions.
747 * @param $thumbName string: the name of the thumbnail file.
748 * @param $thumbUrl string: the URL of the thumbnail file.
749 * @param $params Array: an associative array of handler-specific parameters.
750 * Typical keys are width, height and page.
751 * @param $flags Integer: a bitfield, may contain self::RENDER_NOW to force rendering
753 * @return MediaTransformOutput|null
755 protected function maybeDoTransform( $thumbName, $thumbUrl, $params, $flags = 0 ) {
756 global $wgIgnoreImageErrors, $wgThumbnailEpoch;
758 $thumbPath = $this->getThumbPath( $thumbName ); // final thumb path
759 if ( $this->repo
&& $this->repo
->canTransformVia404() && !( $flags & self
::RENDER_NOW
) ) {
760 wfDebug( __METHOD__
. " transformation deferred." );
761 // XXX: Pass in the storage path even though we are not rendering anything
762 // and the path is supposed to be an FS path. This is due to getScalerType()
763 // getting called on the path and clobbering $thumb->getUrl() if it's false.
764 return $this->handler
->getTransform( $this, $thumbPath, $thumbUrl, $params );
767 wfDebug( __METHOD__
.": Doing stat for $thumbPath\n" );
768 $this->migrateThumbFile( $thumbName );
769 if ( $this->repo
->fileExists( $thumbPath ) && !( $flags & self
::RENDER_FORCE
) ) {
770 $timestamp = $this->repo
->getFileTimestamp( $thumbPath );
771 if ( $timestamp !== false && $timestamp >= $wgThumbnailEpoch ) {
772 // XXX: Pass in the storage path even though we are not rendering anything
773 // and the path is supposed to be an FS path. This is due to getScalerType()
774 // getting called on the path and clobbering $thumb->getUrl() if it's false.
775 return $this->handler
->getTransform( $this, $thumbPath, $thumbUrl, $params );
777 } elseif ( $flags & self
::RENDER_FORCE
) {
778 wfDebug( __METHOD__
. " forcing rendering per flag File::RENDER_FORCE\n" );
781 // Create a temp FS file with the same extension and the thumbnail
782 $extension = $this->getExtension();
783 list( $thumbExt, $thumbMime ) = $this->handler
->getThumbType(
784 $extension, $this->getMimeType(), $params );
785 $tmpFile = TempFSFile
::factory( 'transform_', FileBackend
::extensionFromPath( $thumbPath ) );
787 return new MediaTransformError( 'thumbnail_error',
788 $params['width'], 0, wfMsg( 'thumbnail-temp-create' ) );
790 $tmpThumbPath = $tmpFile->getPath(); // path of 0-byte temp file
792 // Actually render the thumbnail
793 $thumb = $this->handler
->doTransform( $this, $tmpThumbPath, $thumbUrl, $params );
794 $tmpFile->bind( $thumb ); // keep alive with $thumb
796 // Ignore errors if requested
799 } elseif ( $thumb->isError() ) {
800 $this->lastError
= $thumb->toText();
801 if ( $wgIgnoreImageErrors && !( $flags & self
::RENDER_NOW
) ) {
802 $thumb = $this->handler
->getTransform( $this, $tmpThumbPath, $thumbUrl, $params );
804 } elseif ( $thumb->hasFile() && !$thumb->fileIsSource() ) {
805 // Copy any thumbnail from the FS into storage at $dstpath
806 $status = $this->repo
->store(
807 $tmpThumbPath, 'thumb', $this->getThumbRel( $thumbName ),
808 FileRepo
::OVERWRITE | FileRepo
::SKIP_LOCKING | FileRepo
::ALLOW_STALE
);
809 if ( !$status->isOK() ) {
810 return new MediaTransformError( 'thumbnail_error',
811 $params['width'], 0, wfMsg( 'thumbnail-dest-create' ) );
819 * Transform a media file
821 * @param $params Array: an associative array of handler-specific parameters.
822 * Typical keys are width, height and page.
823 * @param $flags Integer: a bitfield, may contain self::RENDER_NOW to force rendering
824 * @return MediaTransformOutput | false
826 function transform( $params, $flags = 0 ) {
829 wfProfileIn( __METHOD__
);
831 if ( !$this->canRender() ) {
832 // not a bitmap or renderable image, don't try.
833 $thumb = $this->iconThumb();
837 // Get the descriptionUrl to embed it as comment into the thumbnail. Bug 19791.
838 $descriptionUrl = $this->getDescriptionUrl();
839 if ( $descriptionUrl ) {
840 $params['descriptionUrl'] = wfExpandUrl( $descriptionUrl, PROTO_CANONICAL
);
843 $script = $this->getTransformScript();
844 if ( $script && !($flags & self
::RENDER_NOW
) ) {
845 // Use a script to transform on client request, if possible
846 $thumb = $this->handler
->getScriptedTransform( $this, $script, $params );
852 $normalisedParams = $params;
853 $this->handler
->normaliseParams( $this, $normalisedParams );
854 $thumbName = $this->thumbName( $normalisedParams );
855 $thumbUrl = $this->getThumbUrl( $thumbName );
857 $thumb = $this->maybeDoTransform( $thumbName, $thumbUrl, $params, $flags );
859 // Purge. Useful in the event of Core -> Squid connection failure or squid
860 // purge collisions from elsewhere during failure. Don't keep triggering for
861 // "thumbs" which have the main image URL though (bug 13776)
863 if ( !$thumb ||
$thumb->isError() ||
$thumb->getUrl() != $this->getURL() ) {
864 SquidUpdate
::purge( array( $thumbUrl ) );
869 wfProfileOut( __METHOD__
);
870 return is_object( $thumb ) ?
$thumb : false;
874 * Hook into transform() to allow migration of thumbnail files
876 * Overridden by LocalFile
878 function migrateThumbFile( $thumbName ) {}
881 * Get a MediaHandler instance for this file
883 * @return MediaHandler
885 function getHandler() {
886 if ( !isset( $this->handler
) ) {
887 $this->handler
= MediaHandler
::getHandler( $this->getMimeType() );
889 return $this->handler
;
893 * Get a ThumbnailImage representing a file type icon
895 * @return ThumbnailImage
897 function iconThumb() {
898 global $wgStylePath, $wgStyleDirectory;
900 $try = array( 'fileicon-' . $this->getExtension() . '.png', 'fileicon.png' );
901 foreach ( $try as $icon ) {
902 $path = '/common/images/icons/' . $icon;
903 $filepath = $wgStyleDirectory . $path;
904 if ( file_exists( $filepath ) ) { // always FS
905 return new ThumbnailImage( $this, $wgStylePath . $path, 120, 120 );
912 * Get last thumbnailing error.
915 function getLastError() {
916 return $this->lastError
;
920 * Get all thumbnail names previously generated for this file
922 * Overridden by LocalFile
924 function getThumbnails() {
929 * Purge shared caches such as thumbnails and DB data caching
931 * Overridden by LocalFile
932 * @param $options Array Options, which include:
933 * 'forThumbRefresh' : The purging is only to refresh thumbnails
935 function purgeCache( $options = array() ) {}
938 * Purge the file description page, but don't go after
939 * pages using the file. Use when modifying file history
940 * but not the current data.
942 function purgeDescription() {
943 $title = $this->getTitle();
945 $title->invalidateCache();
946 $title->purgeSquid();
951 * Purge metadata and all affected pages when the file is created,
952 * deleted, or majorly updated.
954 function purgeEverything() {
955 // Delete thumbnails and refresh file metadata cache
957 $this->purgeDescription();
959 // Purge cache of all pages using this file
960 $title = $this->getTitle();
962 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
968 * Return a fragment of the history of file.
971 * @param $limit integer Limit of rows to return
972 * @param $start timestamp Only revisions older than $start will be returned
973 * @param $end timestamp Only revisions newer than $end will be returned
974 * @param $inc bool Include the endpoints of the time range
978 function getHistory($limit = null, $start = null, $end = null, $inc=true) {
983 * Return the history of this file, line by line. Starts with current version,
984 * then old versions. Should return an object similar to an image/oldimage
988 * Overridden in LocalFile
990 public function nextHistoryLine() {
995 * Reset the history pointer to the first element of the history.
996 * Always call this function after using nextHistoryLine() to free db resources
998 * Overridden in LocalFile.
1000 public function resetHistory() {}
1003 * Get the filename hash component of the directory including trailing slash,
1005 * If the repository is not hashed, returns an empty string.
1009 function getHashPath() {
1010 if ( !isset( $this->hashPath
) ) {
1011 $this->assertRepoDefined();
1012 $this->hashPath
= $this->repo
->getHashPath( $this->getName() );
1014 return $this->hashPath
;
1018 * Get the path of the file relative to the public zone root.
1019 * This function is overriden in OldLocalFile to be like getArchiveRel().
1024 return $this->getHashPath() . $this->getName();
1028 * Get the path of an archived file relative to the public zone root
1030 * @param $suffix bool|string if not false, the name of an archived thumbnail file
1034 function getArchiveRel( $suffix = false ) {
1035 $path = 'archive/' . $this->getHashPath();
1036 if ( $suffix === false ) {
1037 $path = substr( $path, 0, -1 );
1045 * Get the path, relative to the thumbnail zone root, of the
1046 * thumbnail directory or a particular file if $suffix is specified
1048 * @param $suffix bool|string if not false, the name of a thumbnail file
1052 function getThumbRel( $suffix = false ) {
1053 $path = $this->getRel();
1054 if ( $suffix !== false ) {
1055 $path .= '/' . $suffix;
1061 * Get urlencoded path of the file relative to the public zone root.
1062 * This function is overriden in OldLocalFile to be like getArchiveUrl().
1066 function getUrlRel() {
1067 return $this->getHashPath() . rawurlencode( $this->getName() );
1071 * Get the path, relative to the thumbnail zone root, for an archived file's thumbs directory
1072 * or a specific thumb if the $suffix is given.
1074 * @param $archiveName string the timestamped name of an archived image
1075 * @param $suffix bool|string if not false, the name of a thumbnail file
1079 function getArchiveThumbRel( $archiveName, $suffix = false ) {
1080 $path = 'archive/' . $this->getHashPath() . $archiveName . "/";
1081 if ( $suffix === false ) {
1082 $path = substr( $path, 0, -1 );
1090 * Get the path of the archived file.
1092 * @param $suffix bool|string if not false, the name of an archived file.
1096 function getArchivePath( $suffix = false ) {
1097 $this->assertRepoDefined();
1098 return $this->repo
->getZonePath( 'public' ) . '/' . $this->getArchiveRel( $suffix );
1102 * Get the path of an archived file's thumbs, or a particular thumb if $suffix is specified
1104 * @param $archiveName string the timestamped name of an archived image
1105 * @param $suffix bool|string if not false, the name of a thumbnail file
1109 function getArchiveThumbPath( $archiveName, $suffix = false ) {
1110 $this->assertRepoDefined();
1111 return $this->repo
->getZonePath( 'thumb' ) . '/' .
1112 $this->getArchiveThumbRel( $archiveName, $suffix );
1116 * Get the path of the thumbnail directory, or a particular file if $suffix is specified
1118 * @param $suffix bool|string if not false, the name of a thumbnail file
1122 function getThumbPath( $suffix = false ) {
1123 $this->assertRepoDefined();
1124 return $this->repo
->getZonePath( 'thumb' ) . '/' . $this->getThumbRel( $suffix );
1128 * Get the URL of the archive directory, or a particular file if $suffix is specified
1130 * @param $suffix bool|string if not false, the name of an archived file
1134 function getArchiveUrl( $suffix = false ) {
1135 $this->assertRepoDefined();
1136 $path = $this->repo
->getZoneUrl( 'public' ) . '/archive/' . $this->getHashPath();
1137 if ( $suffix === false ) {
1138 $path = substr( $path, 0, -1 );
1140 $path .= rawurlencode( $suffix );
1146 * Get the URL of the archived file's thumbs, or a particular thumb if $suffix is specified
1148 * @param $archiveName string the timestamped name of an archived image
1149 * @param $suffix bool|string if not false, the name of a thumbnail file
1153 function getArchiveThumbUrl( $archiveName, $suffix = false ) {
1154 $this->assertRepoDefined();
1155 $path = $this->repo
->getZoneUrl( 'thumb' ) . '/archive/' .
1156 $this->getHashPath() . rawurlencode( $archiveName ) . "/";
1157 if ( $suffix === false ) {
1158 $path = substr( $path, 0, -1 );
1160 $path .= rawurlencode( $suffix );
1166 * Get the URL of the thumbnail directory, or a particular file if $suffix is specified
1168 * @param $suffix bool|string if not false, the name of a thumbnail file
1172 function getThumbUrl( $suffix = false ) {
1173 $this->assertRepoDefined();
1174 $path = $this->repo
->getZoneUrl( 'thumb' ) . '/' . $this->getUrlRel();
1175 if ( $suffix !== false ) {
1176 $path .= '/' . rawurlencode( $suffix );
1182 * Get the public zone virtual URL for a current version source file
1184 * @param $suffix bool|string if not false, the name of a thumbnail file
1188 function getVirtualUrl( $suffix = false ) {
1189 $this->assertRepoDefined();
1190 $path = $this->repo
->getVirtualUrl() . '/public/' . $this->getUrlRel();
1191 if ( $suffix !== false ) {
1192 $path .= '/' . rawurlencode( $suffix );
1198 * Get the public zone virtual URL for an archived version source file
1200 * @param $suffix bool|string if not false, the name of a thumbnail file
1204 function getArchiveVirtualUrl( $suffix = false ) {
1205 $this->assertRepoDefined();
1206 $path = $this->repo
->getVirtualUrl() . '/public/archive/' . $this->getHashPath();
1207 if ( $suffix === false ) {
1208 $path = substr( $path, 0, -1 );
1210 $path .= rawurlencode( $suffix );
1216 * Get the virtual URL for a thumbnail file or directory
1218 * @param $suffix bool|string if not false, the name of a thumbnail file
1222 function getThumbVirtualUrl( $suffix = false ) {
1223 $this->assertRepoDefined();
1224 $path = $this->repo
->getVirtualUrl() . '/thumb/' . $this->getUrlRel();
1225 if ( $suffix !== false ) {
1226 $path .= '/' . rawurlencode( $suffix );
1234 function isHashed() {
1235 $this->assertRepoDefined();
1236 return $this->repo
->isHashed();
1240 * @throws MWException
1242 function readOnlyError() {
1243 throw new MWException( get_class($this) . ': write operations are not supported' );
1247 * Record a file upload in the upload log and the image table
1249 * Overridden by LocalFile
1252 * @param $license string
1253 * @param $copyStatus string
1254 * @param $source string
1255 * @param $watch bool
1257 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '', $watch = false ) {
1258 $this->readOnlyError();
1262 * Move or copy a file to its public location. If a file exists at the
1263 * destination, move it to an archive. Returns a FileRepoStatus object with
1264 * the archive name in the "value" member on success.
1266 * The archive name should be passed through to recordUpload for database
1269 * @param $srcPath String: local filesystem path to the source image
1270 * @param $flags Integer: a bitwise combination of:
1271 * File::DELETE_SOURCE Delete the source file, i.e. move
1273 * @return FileRepoStatus object. On success, the value member contains the
1274 * archive name, or an empty string if it was a new file.
1277 * Overridden by LocalFile
1279 function publish( $srcPath, $flags = 0 ) {
1280 $this->readOnlyError();
1286 function formatMetadata() {
1287 if ( !$this->getHandler() ) {
1290 return $this->getHandler()->formatMetadata( $this, $this->getMetadata() );
1294 * Returns true if the file comes from the local file repository.
1298 function isLocal() {
1299 return $this->repo
&& $this->repo
->isLocal();
1303 * Returns the name of the repository.
1307 function getRepoName() {
1308 return $this->repo ?
$this->repo
->getName() : 'unknown';
1312 * Returns the repository
1314 * @return FileRepo|false
1316 function getRepo() {
1321 * Returns true if the image is an old version
1331 * Is this file a "deleted" file in a private archive?
1338 function isDeleted( $field ) {
1343 * Return the deletion bitfield
1346 function getVisibility() {
1351 * Was this file ever deleted from the wiki?
1355 function wasDeleted() {
1356 $title = $this->getTitle();
1357 return $title && $title->isDeletedQuick();
1361 * Move file to the new title
1363 * Move current, old version and all thumbnails
1364 * to the new filename. Old file is deleted.
1366 * Cache purging is done; checks for validity
1367 * and logging are caller's responsibility
1369 * @param $target Title New file name
1370 * @return FileRepoStatus object.
1372 function move( $target ) {
1373 $this->readOnlyError();
1377 * Delete all versions of the file.
1379 * Moves the files into an archive directory (or deletes them)
1380 * and removes the database rows.
1382 * Cache purging is done; logging is caller's responsibility.
1384 * @param $reason String
1385 * @param $suppress Boolean: hide content from sysops?
1386 * @return true on success, false on some kind of failure
1388 * Overridden by LocalFile
1390 function delete( $reason, $suppress = false ) {
1391 $this->readOnlyError();
1395 * Restore all or specified deleted revisions to the given file.
1396 * Permissions and logging are left to the caller.
1398 * May throw database exceptions on error.
1400 * @param $versions array set of record ids of deleted items to restore,
1401 * or empty to restore all revisions.
1402 * @param $unsuppress bool remove restrictions on content upon restoration?
1403 * @return int|false the number of file revisions restored if successful,
1404 * or false on failure
1406 * Overridden by LocalFile
1408 function restore( $versions = array(), $unsuppress = false ) {
1409 $this->readOnlyError();
1413 * Returns 'true' if this file is a type which supports multiple pages,
1414 * e.g. DJVU or PDF. Note that this may be true even if the file in
1415 * question only has a single page.
1419 function isMultipage() {
1420 return $this->getHandler() && $this->handler
->isMultiPage( $this );
1424 * Returns the number of pages of a multipage document, or false for
1425 * documents which aren't multipage documents
1429 function pageCount() {
1430 if ( !isset( $this->pageCount
) ) {
1431 if ( $this->getHandler() && $this->handler
->isMultiPage( $this ) ) {
1432 $this->pageCount
= $this->handler
->pageCount( $this );
1434 $this->pageCount
= false;
1437 return $this->pageCount
;
1441 * Calculate the height of a thumbnail using the source and destination width
1449 static function scaleHeight( $srcWidth, $srcHeight, $dstWidth ) {
1450 // Exact integer multiply followed by division
1451 if ( $srcWidth == 0 ) {
1454 return round( $srcHeight * $dstWidth / $srcWidth );
1459 * Get an image size array like that returned by getImageSize(), or false if it
1460 * can't be determined.
1462 * @param $fileName String: The filename
1465 function getImageSize( $fileName ) {
1466 if ( !$this->getHandler() ) {
1469 return $this->handler
->getImageSize( $this, $fileName );
1473 * Get the URL of the image description page. May return false if it is
1474 * unknown or not applicable.
1478 function getDescriptionUrl() {
1479 if ( $this->repo
) {
1480 return $this->repo
->getDescriptionUrl( $this->getName() );
1487 * Get the HTML text of the description page, if available
1491 function getDescriptionText() {
1492 global $wgMemc, $wgLang;
1493 if ( !$this->repo ||
!$this->repo
->fetchDescription
) {
1496 $renderUrl = $this->repo
->getDescriptionRenderUrl( $this->getName(), $wgLang->getCode() );
1498 if ( $this->repo
->descriptionCacheExpiry
> 0 ) {
1499 wfDebug("Attempting to get the description from cache...");
1500 $key = $this->repo
->getLocalCacheKey( 'RemoteFileDescription', 'url', $wgLang->getCode(),
1502 $obj = $wgMemc->get($key);
1504 wfDebug("success!\n");
1509 wfDebug( "Fetching shared description from $renderUrl\n" );
1510 $res = Http
::get( $renderUrl );
1511 if ( $res && $this->repo
->descriptionCacheExpiry
> 0 ) {
1512 $wgMemc->set( $key, $res, $this->repo
->descriptionCacheExpiry
);
1521 * Get discription of file revision
1526 function getDescription() {
1531 * Get the 14-character timestamp of the file upload
1533 * @return string|false TS_MW timestamp or false on failure
1535 function getTimestamp() {
1536 $this->assertRepoDefined();
1537 return $this->repo
->getFileTimestamp( $this->getPath() );
1541 * Get the SHA-1 base 36 hash of the file
1545 function getSha1() {
1546 $this->assertRepoDefined();
1547 return $this->repo
->getFileSha1( $this->getPath() );
1551 * Get the deletion archive key, <sha1>.<ext>
1555 function getStorageKey() {
1556 $hash = $this->getSha1();
1560 $ext = $this->getExtension();
1561 $dotExt = $ext === '' ?
'' : ".$ext";
1562 return $hash . $dotExt;
1566 * Determine if the current user is allowed to view a particular
1567 * field of this file, if it's marked as deleted.
1569 * @param $field Integer
1570 * @param $user User object to check, or null to use $wgUser
1573 function userCan( $field, User
$user = null ) {
1578 * Get an associative array containing information about a file in the local filesystem.
1580 * @param $path String: absolute local filesystem path
1581 * @param $ext Mixed: the file extension, or true to extract it from the filename.
1582 * Set it to false to ignore the extension.
1586 static function getPropsFromPath( $path, $ext = true ) {
1587 wfDebug( __METHOD__
.": Getting file info for $path\n" );
1588 wfDeprecated( __METHOD__
, '1.19' );
1590 $fsFile = new FSFile( $path );
1591 return $fsFile->getProps();
1595 * Get a SHA-1 hash of a file in the local filesystem, in base-36 lower case
1596 * encoding, zero padded to 31 digits.
1598 * 160 log 2 / log 36 = 30.95, so the 160-bit hash fills 31 digits in base 36
1601 * @param $path string
1603 * @return false|string False on failure
1605 static function sha1Base36( $path ) {
1606 wfDeprecated( __METHOD__
, '1.19' );
1608 $fsFile = new FSFile( $path );
1609 return $fsFile->getSha1Base36();
1615 function getLongDesc() {
1616 $handler = $this->getHandler();
1618 return $handler->getLongDesc( $this );
1620 return MediaHandler
::getGeneralLongDesc( $this );
1627 function getShortDesc() {
1628 $handler = $this->getHandler();
1630 return $handler->getShortDesc( $this );
1632 return MediaHandler
::getGeneralShortDesc( $this );
1639 function getDimensionsString() {
1640 $handler = $this->getHandler();
1642 return $handler->getDimensionsString( $this );
1651 function getRedirected() {
1652 return $this->redirected
;
1658 function getRedirectedTitle() {
1659 if ( $this->redirected
) {
1660 if ( !$this->redirectTitle
) {
1661 $this->redirectTitle
= Title
::makeTitle( NS_FILE
, $this->redirected
);
1663 return $this->redirectTitle
;
1671 function redirectedFrom( $from ) {
1672 $this->redirected
= $from;
1678 function isMissing() {
1683 * Assert that $this->repo is set to a valid FileRepo instance
1684 * @throws MWException
1686 protected function assertRepoDefined() {
1687 if ( !( $this->repo
instanceof $this->repoClass
) ) {
1688 throw new MWException( "A {$this->repoClass} object is not set for this File.\n" );
1693 * Assert that $this->title is set to a Title
1694 * @throws MWException
1696 protected function assertTitleDefined() {
1697 if ( !( $this->title
instanceof Title
) ) {
1698 throw new MWException( "A Title object is not set for this File.\n" );