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;
80 protected $url, $extension, $name, $path, $hashPath, $pageCount, $transformScript;
85 protected $canRender, $isSafeFile;
88 * @var string Required Repository class type
90 protected $repoClass = 'FileRepo';
93 * Call this constructor from child classes.
95 * Both $title and $repo are optional, though some functions
96 * may return false or throw exceptions if they are not set.
97 * Most subclasses will want to call assertRepoDefined() here.
99 * @param $title Title|string|false
100 * @param $repo FileRepo|false
102 function __construct( $title, $repo ) {
103 if ( $title !== false ) { // subclasses may not use MW titles
104 $title = self
::normalizeTitle( $title, 'exception' );
106 $this->title
= $title;
111 * Given a string or Title object return either a
112 * valid Title object with namespace NS_FILE or null
113 * @param $title Title|string
114 * @param $exception string|false Use 'exception' to throw an error on bad titles
117 static function normalizeTitle( $title, $exception = false ) {
119 if ( $ret instanceof Title
) {
120 # Normalize NS_MEDIA -> NS_FILE
121 if ( $ret->getNamespace() == NS_MEDIA
) {
122 $ret = Title
::makeTitleSafe( NS_FILE
, $ret->getDBkey() );
123 # Sanity check the title namespace
124 } elseif ( $ret->getNamespace() !== NS_FILE
) {
128 # Convert strings to Title objects
129 $ret = Title
::makeTitleSafe( NS_FILE
, (string)$ret );
131 if ( !$ret && $exception !== false ) {
132 throw new MWException( "`$title` is not a valid file title." );
137 function __get( $name ) {
138 $function = array( $this, 'get' . ucfirst( $name ) );
139 if ( !is_callable( $function ) ) {
142 $this->$name = call_user_func( $function );
148 * Normalize a file extension to the common form, and ensure it's clean.
149 * Extensions with non-alphanumeric characters will be discarded.
151 * @param $ext string (without the .)
154 static function normalizeExtension( $ext ) {
155 $lower = strtolower( $ext );
162 if( isset( $squish[$lower] ) ) {
163 return $squish[$lower];
164 } elseif( preg_match( '/^[0-9a-z]+$/', $lower ) ) {
172 * Checks if file extensions are compatible
174 * @param $old File Old file
175 * @param $new string New name
179 static function checkExtensionCompatibility( File
$old, $new ) {
180 $oldMime = $old->getMimeType();
181 $n = strrpos( $new, '.' );
182 $newExt = self
::normalizeExtension(
183 $n ?
substr( $new, $n +
1 ) : '' );
184 $mimeMagic = MimeMagic
::singleton();
185 return $mimeMagic->isMatchingExtension( $newExt, $oldMime );
189 * Upgrade the database row if there is one
190 * Called by ImagePage
193 function upgradeRow() {}
196 * Split an internet media type into its two components; if not
197 * a two-part name, set the minor type to 'unknown'.
199 * @param string $mime "text/html" etc
200 * @return array ("text", "html") etc
202 public static function splitMime( $mime ) {
203 if( strpos( $mime, '/' ) !== false ) {
204 return explode( '/', $mime, 2 );
206 return array( $mime, 'unknown' );
211 * Return the name of this file
215 public function getName() {
216 if ( !isset( $this->name
) ) {
217 $this->assertRepoDefined();
218 $this->name
= $this->repo
->getNameFromTitle( $this->title
);
224 * Get the file extension, e.g. "svg"
228 function getExtension() {
229 if ( !isset( $this->extension
) ) {
230 $n = strrpos( $this->getName(), '.' );
231 $this->extension
= self
::normalizeExtension(
232 $n ?
substr( $this->getName(), $n +
1 ) : '' );
234 return $this->extension
;
238 * Return the associated title object
239 * @return Title|false
241 public function getTitle() { return $this->title
; }
244 * Return the title used to find this file
248 public function getOriginalTitle() {
249 if ( $this->redirected
) {
250 return $this->getRedirectedTitle();
256 * Return the URL of the file
260 public function getUrl() {
261 if ( !isset( $this->url
) ) {
262 $this->assertRepoDefined();
263 $this->url
= $this->repo
->getZoneUrl( 'public' ) . '/' . $this->getUrlRel();
269 * Return a fully-qualified URL to the file.
270 * Upload URL paths _may or may not_ be fully qualified, so
271 * we check. Local paths are assumed to belong on $wgServer.
275 public function getFullUrl() {
276 return wfExpandUrl( $this->getUrl(), PROTO_RELATIVE
);
282 public function getCanonicalUrl() {
283 return wfExpandUrl( $this->getUrl(), PROTO_CANONICAL
);
289 function getViewURL() {
290 if( $this->mustRender()) {
291 if( $this->canRender() ) {
292 return $this->createThumb( $this->getWidth() );
294 wfDebug(__METHOD__
.': supposed to render '.$this->getName().' ('.$this->getMimeType()."), but can't!\n");
295 return $this->getURL(); #hm... return NULL?
298 return $this->getURL();
303 * Return the full filesystem path to the file. Note that this does
304 * not mean that a file actually exists under that location.
306 * This path depends on whether directory hashing is active or not,
307 * i.e. whether the files are all found in the same directory,
308 * or in hashed paths like /images/3/3c.
310 * Most callers don't check the return value, but ForeignAPIFile::getPath
313 * @return string|false
315 public function getPath() {
316 if ( !isset( $this->path
) ) {
317 $this->assertRepoDefined();
318 $this->path
= $this->repo
->getZonePath( 'public' ) . '/' . $this->getRel();
324 * Return the width of the image. Returns false if the width is unknown
328 * Overridden by LocalFile, UnregisteredLocalFile
334 public function getWidth( $page = 1 ) {
339 * Return the height of the image. Returns false if the height is unknown
343 * Overridden by LocalFile, UnregisteredLocalFile
347 * @return false|number
349 public function getHeight( $page = 1 ) {
354 * Returns ID or name of user who uploaded the file
357 * @param $type string 'text' or 'id'
361 public function getUser( $type = 'text' ) {
366 * Get the duration of a media file in seconds
370 public function getLength() {
371 $handler = $this->getHandler();
373 return $handler->getLength( $this );
380 * Return true if the file is vectorized
384 public function isVectorized() {
385 $handler = $this->getHandler();
387 return $handler->isVectorized( $this );
394 * Get handler-specific metadata
395 * Overridden by LocalFile, UnregisteredLocalFile
398 public function getMetadata() {
403 * get versioned metadata
405 * @param $metadata Mixed Array or String of (serialized) metadata
406 * @param $version integer version number.
407 * @return Array containing metadata, or what was passed to it on fail (unserializing if not array)
409 public function convertMetadataVersion($metadata, $version) {
410 $handler = $this->getHandler();
411 if ( !is_array( $metadata ) ) {
412 //just to make the return type consistant
413 $metadata = unserialize( $metadata );
416 return $handler->convertMetadataVersion( $metadata, $version );
423 * Return the bit depth of the file
424 * Overridden by LocalFile
427 public function getBitDepth() {
432 * Return the size of the image file, in bytes
433 * Overridden by LocalFile, UnregisteredLocalFile
436 public function getSize() {
441 * Returns the mime type of the file.
442 * Overridden by LocalFile, UnregisteredLocalFile
447 function getMimeType() {
448 return 'unknown/unknown';
452 * Return the type of the media in the file.
453 * Use the value returned by this function with the MEDIATYPE_xxx constants.
454 * Overridden by LocalFile,
457 function getMediaType() { return MEDIATYPE_UNKNOWN
; }
460 * Checks if the output of transform() for this file is likely
461 * to be valid. If this is false, various user elements will
462 * display a placeholder instead.
464 * Currently, this checks if the file is an image format
465 * that can be converted to a format
466 * supported by all browsers (namely GIF, PNG and JPEG),
467 * or if it is an SVG image and SVG conversion is enabled.
471 function canRender() {
472 if ( !isset( $this->canRender
) ) {
473 $this->canRender
= $this->getHandler() && $this->handler
->canRender( $this );
475 return $this->canRender
;
479 * Accessor for __get()
481 protected function getCanRender() {
482 return $this->canRender();
486 * Return true if the file is of a type that can't be directly
487 * rendered by typical browsers and needs to be re-rasterized.
489 * This returns true for everything but the bitmap types
490 * supported by all browsers, i.e. JPEG; GIF and PNG. It will
491 * also return true for any non-image formats.
495 function mustRender() {
496 return $this->getHandler() && $this->handler
->mustRender( $this );
500 * Alias for canRender()
504 function allowInlineDisplay() {
505 return $this->canRender();
509 * Determines if this media file is in a format that is unlikely to
510 * contain viruses or malicious content. It uses the global
511 * $wgTrustedMediaFormats list to determine if the file is safe.
513 * This is used to show a warning on the description page of non-safe files.
514 * It may also be used to disallow direct [[media:...]] links to such files.
516 * Note that this function will always return true if allowInlineDisplay()
517 * or isTrustedFile() is true for this file.
521 function isSafeFile() {
522 if ( !isset( $this->isSafeFile
) ) {
523 $this->isSafeFile
= $this->_getIsSafeFile();
525 return $this->isSafeFile
;
529 * Accessor for __get()
533 protected function getIsSafeFile() {
534 return $this->isSafeFile();
542 protected function _getIsSafeFile() {
543 if ( $this->allowInlineDisplay() ) {
546 if ($this->isTrustedFile()) {
550 global $wgTrustedMediaFormats;
552 $type = $this->getMediaType();
553 $mime = $this->getMimeType();
554 #wfDebug("LocalFile::isSafeFile: type= $type, mime= $mime\n");
556 if ( !$type ||
$type === MEDIATYPE_UNKNOWN
) {
557 return false; #unknown type, not trusted
559 if ( in_array( $type, $wgTrustedMediaFormats ) ) {
563 if ( $mime === "unknown/unknown" ) {
564 return false; #unknown type, not trusted
566 if ( in_array( $mime, $wgTrustedMediaFormats) ) {
574 * Returns true if the file is flagged as trusted. Files flagged that way
575 * can be linked to directly, even if that is not allowed for this type of
578 * This is a dummy function right now and always returns false. It could be
579 * implemented to extract a flag from the database. The trusted flag could be
580 * set on upload, if the user has sufficient privileges, to bypass script-
581 * and html-filters. It may even be coupled with cryptographics signatures
586 function isTrustedFile() {
587 #this could be implemented to check a flag in the databas,
588 #look for signatures, etc
593 * Returns true if file exists in the repository.
595 * Overridden by LocalFile to avoid unnecessary stat calls.
597 * @return boolean Whether file exists in the repository.
599 public function exists() {
600 return $this->getPath() && file_exists( $this->path
);
604 * Returns true if file exists in the repository and can be included in a page.
605 * It would be unsafe to include private images, making public thumbnails inadvertently
607 * @return boolean Whether file exists in the repository and is includable.
609 public function isVisible() {
610 return $this->exists();
616 function getTransformScript() {
617 if ( !isset( $this->transformScript
) ) {
618 $this->transformScript
= false;
620 $script = $this->repo
->getThumbScriptUrl();
622 $this->transformScript
= "$script?f=" . urlencode( $this->getName() );
626 return $this->transformScript
;
630 * Get a ThumbnailImage which is the same size as the source
632 * @param $handlerParams array
636 function getUnscaledThumb( $handlerParams = array() ) {
637 $hp =& $handlerParams;
638 $page = isset( $hp['page'] ) ?
$hp['page'] : false;
639 $width = $this->getWidth( $page );
641 return $this->iconThumb();
643 $hp['width'] = $width;
644 return $this->transform( $hp );
648 * Return the file name of a thumbnail with the specified parameters
650 * @param $params Array: handler-specific parameters
655 function thumbName( $params ) {
656 return $this->generateThumbName( $this->getName(), $params );
660 * Generate a thumbnail file name from a name and specified parameters
662 * @param string $name
663 * @param array $params Parameters which will be passed to MediaHandler::makeParamString
667 function generateThumbName( $name, $params ) {
668 if ( !$this->getHandler() ) {
671 $extension = $this->getExtension();
672 list( $thumbExt, $thumbMime ) = $this->handler
->getThumbType( $extension, $this->getMimeType(), $params );
673 $thumbName = $this->handler
->makeParamString( $params ) . '-' . $name;
674 if ( $thumbExt != $extension ) {
675 $thumbName .= ".$thumbExt";
681 * Create a thumbnail of the image having the specified width/height.
682 * The thumbnail will not be created if the width is larger than the
683 * image's width. Let the browser do the scaling in this case.
684 * The thumbnail is stored on disk and is only computed if the thumbnail
685 * file does not exist OR if it is older than the image.
688 * Keeps aspect ratio of original image. If both width and height are
689 * specified, the generated image will be no bigger than width x height,
690 * and will also have correct aspect ratio.
692 * @param $width Integer: maximum width of the generated thumbnail
693 * @param $height Integer: maximum height of the image (optional)
697 public function createThumb( $width, $height = -1 ) {
698 $params = array( 'width' => $width );
699 if ( $height != -1 ) {
700 $params['height'] = $height;
702 $thumb = $this->transform( $params );
703 if( is_null( $thumb ) ||
$thumb->isError() ) return '';
704 return $thumb->getUrl();
708 * Do the work of a transform (from an original into a thumb).
709 * Contains filesystem-specific functions.
711 * @param $thumbName string: the name of the thumbnail file.
712 * @param $thumbUrl string: the URL of the thumbnail file.
713 * @param $params Array: an associative array of handler-specific parameters.
714 * Typical keys are width, height and page.
715 * @param $flags Integer: a bitfield, may contain self::RENDER_NOW to force rendering
717 * @return MediaTransformOutput | false
719 protected function maybeDoTransform( $thumbName, $thumbUrl, $params, $flags = 0 ) {
720 global $wgIgnoreImageErrors, $wgThumbnailEpoch;
722 $thumbPath = $this->getThumbPath( $thumbName );
723 if ( $this->repo
&& $this->repo
->canTransformVia404() && !($flags & self
::RENDER_NOW
) ) {
724 wfDebug( __METHOD__
. " transformation deferred." );
725 return $this->handler
->getTransform( $this, $thumbPath, $thumbUrl, $params );
728 wfDebug( __METHOD__
.": Doing stat for $thumbPath\n" );
729 $this->migrateThumbFile( $thumbName );
730 if ( file_exists( $thumbPath ) && !($flags & self
::RENDER_FORCE
) ) {
731 $thumbTime = filemtime( $thumbPath );
732 if ( $thumbTime !== FALSE &&
733 gmdate( 'YmdHis', $thumbTime ) >= $wgThumbnailEpoch ) {
735 return $this->handler
->getTransform( $this, $thumbPath, $thumbUrl, $params );
737 } elseif( $flags & self
::RENDER_FORCE
) {
738 wfDebug( __METHOD__
. " forcing rendering per flag File::RENDER_FORCE\n" );
740 $thumb = $this->handler
->doTransform( $this, $thumbPath, $thumbUrl, $params );
742 // Ignore errors if requested
745 } elseif ( $thumb->isError() ) {
746 $this->lastError
= $thumb->toText();
747 if ( $wgIgnoreImageErrors && !($flags & self
::RENDER_NOW
) ) {
748 $thumb = $this->handler
->getTransform( $this, $thumbPath, $thumbUrl, $params );
757 * Transform a media file
759 * @param $params Array: an associative array of handler-specific parameters.
760 * Typical keys are width, height and page.
761 * @param $flags Integer: a bitfield, may contain self::RENDER_NOW to force rendering
762 * @return MediaTransformOutput | false
764 function transform( $params, $flags = 0 ) {
767 wfProfileIn( __METHOD__
);
769 if ( !$this->canRender() ) {
770 // not a bitmap or renderable image, don't try.
771 $thumb = $this->iconThumb();
775 // Get the descriptionUrl to embed it as comment into the thumbnail. Bug 19791.
776 $descriptionUrl = $this->getDescriptionUrl();
777 if ( $descriptionUrl ) {
778 $params['descriptionUrl'] = wfExpandUrl( $descriptionUrl, PROTO_CANONICAL
);
781 $script = $this->getTransformScript();
782 if ( $script && !($flags & self
::RENDER_NOW
) ) {
783 // Use a script to transform on client request, if possible
784 $thumb = $this->handler
->getScriptedTransform( $this, $script, $params );
790 $normalisedParams = $params;
791 $this->handler
->normaliseParams( $this, $normalisedParams );
792 $thumbName = $this->thumbName( $normalisedParams );
793 $thumbUrl = $this->getThumbUrl( $thumbName );
795 $thumb = $this->maybeDoTransform( $thumbName, $thumbUrl, $params, $flags );
797 // Purge. Useful in the event of Core -> Squid connection failure or squid
798 // purge collisions from elsewhere during failure. Don't keep triggering for
799 // "thumbs" which have the main image URL though (bug 13776)
800 if ( $wgUseSquid && ( !$thumb ||
$thumb->isError() ||
$thumb->getUrl() != $this->getURL()) ) {
801 SquidUpdate
::purge( array( $thumbUrl ) );
805 wfProfileOut( __METHOD__
);
806 return is_object( $thumb ) ?
$thumb : false;
810 * Hook into transform() to allow migration of thumbnail files
812 * Overridden by LocalFile
814 function migrateThumbFile( $thumbName ) {}
817 * Get a MediaHandler instance for this file
818 * @return MediaHandler
820 function getHandler() {
821 if ( !isset( $this->handler
) ) {
822 $this->handler
= MediaHandler
::getHandler( $this->getMimeType() );
824 return $this->handler
;
828 * Get a ThumbnailImage representing a file type icon
829 * @return ThumbnailImage
831 function iconThumb() {
832 global $wgStylePath, $wgStyleDirectory;
834 $try = array( 'fileicon-' . $this->getExtension() . '.png', 'fileicon.png' );
835 foreach( $try as $icon ) {
836 $path = '/common/images/icons/' . $icon;
837 $filepath = $wgStyleDirectory . $path;
838 if( file_exists( $filepath ) ) {
839 return new ThumbnailImage( $this, $wgStylePath . $path, 120, 120 );
846 * Get last thumbnailing error.
849 function getLastError() {
850 return $this->lastError
;
854 * Get all thumbnail names previously generated for this file
856 * Overridden by LocalFile
858 function getThumbnails() {
863 * Purge shared caches such as thumbnails and DB data caching
865 * Overridden by LocalFile
866 * @param $options Array Options, which include:
867 * 'forRefresh' : The purging is only to refresh thumbnails
869 function purgeCache( $options = array() ) {}
872 * Purge the file description page, but don't go after
873 * pages using the file. Use when modifying file history
874 * but not the current data.
876 function purgeDescription() {
877 $title = $this->getTitle();
879 $title->invalidateCache();
880 $title->purgeSquid();
885 * Purge metadata and all affected pages when the file is created,
886 * deleted, or majorly updated.
888 function purgeEverything() {
889 // Delete thumbnails and refresh file metadata cache
891 $this->purgeDescription();
893 // Purge cache of all pages using this file
894 $title = $this->getTitle();
896 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
902 * Return a fragment of the history of file.
905 * @param $limit integer Limit of rows to return
906 * @param $start timestamp Only revisions older than $start will be returned
907 * @param $end timestamp Only revisions newer than $end will be returned
908 * @param $inc bool Include the endpoints of the time range
912 function getHistory($limit = null, $start = null, $end = null, $inc=true) {
917 * Return the history of this file, line by line. Starts with current version,
918 * then old versions. Should return an object similar to an image/oldimage
922 * Overridden in LocalFile
924 public function nextHistoryLine() {
929 * Reset the history pointer to the first element of the history.
930 * Always call this function after using nextHistoryLine() to free db resources
932 * Overridden in LocalFile.
934 public function resetHistory() {}
937 * Get the filename hash component of the directory including trailing slash,
939 * If the repository is not hashed, returns an empty string.
943 function getHashPath() {
944 if ( !isset( $this->hashPath
) ) {
945 $this->assertRepoDefined();
946 $this->hashPath
= $this->repo
->getHashPath( $this->getName() );
948 return $this->hashPath
;
952 * Get the path of the file relative to the public zone root
957 return $this->getHashPath() . $this->getName();
961 * Get urlencoded relative path of the file
965 function getUrlRel() {
966 return $this->getHashPath() . rawurlencode( $this->getName() );
970 * Get the relative path for an archived file
972 * @param $suffix bool|string if not false, the name of an archived thumbnail file
976 function getArchiveRel( $suffix = false ) {
977 $path = 'archive/' . $this->getHashPath();
978 if ( $suffix === false ) {
979 $path = substr( $path, 0, -1 );
987 * Get the relative path for an archived file's thumbs directory
988 * or a specific thumb if the $suffix is given.
990 * @param $archiveName string the timestamped name of an archived image
991 * @param $suffix bool|string if not false, the name of a thumbnail file
995 function getArchiveThumbRel( $archiveName, $suffix = false ) {
996 $path = 'archive/' . $this->getHashPath() . $archiveName . "/";
997 if ( $suffix === false ) {
998 $path = substr( $path, 0, -1 );
1006 * Get the path of the archived file.
1008 * @param $suffix bool|string if not false, the name of an archived file.
1012 function getArchivePath( $suffix = false ) {
1013 $this->assertRepoDefined();
1014 return $this->repo
->getZonePath( 'public' ) . '/' . $this->getArchiveRel( $suffix );
1018 * Get the path of the archived file's thumbs, or a particular thumb if $suffix is specified
1020 * @param $archiveName string the timestamped name of an archived image
1021 * @param $suffix bool|string if not false, the name of a thumbnail file
1025 function getArchiveThumbPath( $archiveName, $suffix = false ) {
1026 $this->assertRepoDefined();
1027 return $this->repo
->getZonePath( 'thumb' ) . '/' .
1028 $this->getArchiveThumbRel( $archiveName, $suffix );
1032 * Get the path of the thumbnail directory, or a particular file if $suffix is specified
1034 * @param $suffix bool|string if not false, the name of a thumbnail file
1038 function getThumbPath( $suffix = false ) {
1039 $this->assertRepoDefined();
1040 $path = $this->repo
->getZonePath( 'thumb' ) . '/' . $this->getRel();
1041 if ( $suffix !== false ) {
1042 $path .= '/' . $suffix;
1048 * Get the URL of the archive directory, or a particular file if $suffix is specified
1050 * @param $suffix bool|string if not false, the name of an archived file
1054 function getArchiveUrl( $suffix = false ) {
1055 $this->assertRepoDefined();
1056 $path = $this->repo
->getZoneUrl( 'public' ) . '/archive/' . $this->getHashPath();
1057 if ( $suffix === false ) {
1058 $path = substr( $path, 0, -1 );
1060 $path .= rawurlencode( $suffix );
1066 * Get the URL of the archived file's thumbs, or a particular thumb if $suffix is specified
1068 * @param $archiveName string the timestamped name of an archived image
1069 * @param $suffix bool|string if not false, the name of a thumbnail file
1073 function getArchiveThumbUrl( $archiveName, $suffix = false ) {
1074 $this->assertRepoDefined();
1075 $path = $this->repo
->getZoneUrl( 'thumb' ) . '/archive/' .
1076 $this->getHashPath() . rawurlencode( $archiveName ) . "/";
1077 if ( $suffix === false ) {
1078 $path = substr( $path, 0, -1 );
1080 $path .= rawurlencode( $suffix );
1086 * Get the URL of the thumbnail directory, or a particular file if $suffix is specified
1088 * @param $suffix bool|string if not false, the name of a thumbnail file
1092 function getThumbUrl( $suffix = false ) {
1093 $this->assertRepoDefined();
1094 $path = $this->repo
->getZoneUrl('thumb') . '/' . $this->getUrlRel();
1095 if ( $suffix !== false ) {
1096 $path .= '/' . rawurlencode( $suffix );
1102 * Get the virtual URL for an archived file's thumbs, or a specific thumb.
1104 * @param $suffix bool|string if not false, the name of a thumbnail file
1108 function getArchiveVirtualUrl( $suffix = false ) {
1109 $this->assertRepoDefined();
1110 $path = $this->repo
->getVirtualUrl() . '/public/archive/' . $this->getHashPath();
1111 if ( $suffix === false ) {
1112 $path = substr( $path, 0, -1 );
1114 $path .= rawurlencode( $suffix );
1120 * Get the virtual URL for a thumbnail file or directory
1122 * @param $suffix bool|string if not false, the name of a thumbnail file
1126 function getThumbVirtualUrl( $suffix = false ) {
1127 $this->assertRepoDefined();
1128 $path = $this->repo
->getVirtualUrl() . '/thumb/' . $this->getUrlRel();
1129 if ( $suffix !== false ) {
1130 $path .= '/' . rawurlencode( $suffix );
1136 * Get the virtual URL for the file itself
1138 * @param $suffix bool|string if not false, the name of a thumbnail file
1142 function getVirtualUrl( $suffix = false ) {
1143 $this->assertRepoDefined();
1144 $path = $this->repo
->getVirtualUrl() . '/public/' . $this->getUrlRel();
1145 if ( $suffix !== false ) {
1146 $path .= '/' . rawurlencode( $suffix );
1154 function isHashed() {
1155 $this->assertRepoDefined();
1156 return $this->repo
->isHashed();
1160 * @throws MWException
1162 function readOnlyError() {
1163 throw new MWException( get_class($this) . ': write operations are not supported' );
1167 * Record a file upload in the upload log and the image table
1169 * Overridden by LocalFile
1172 * @param $license string
1173 * @param $copyStatus string
1174 * @param $source string
1175 * @param $watch bool
1177 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '', $watch = false ) {
1178 $this->readOnlyError();
1182 * Move or copy a file to its public location. If a file exists at the
1183 * destination, move it to an archive. Returns a FileRepoStatus object with
1184 * the archive name in the "value" member on success.
1186 * The archive name should be passed through to recordUpload for database
1189 * @param $srcPath String: local filesystem path to the source image
1190 * @param $flags Integer: a bitwise combination of:
1191 * File::DELETE_SOURCE Delete the source file, i.e. move
1193 * @return FileRepoStatus object. On success, the value member contains the
1194 * archive name, or an empty string if it was a new file.
1197 * Overridden by LocalFile
1199 function publish( $srcPath, $flags = 0 ) {
1200 $this->readOnlyError();
1206 function formatMetadata() {
1207 if ( !$this->getHandler() ) {
1210 return $this->getHandler()->formatMetadata( $this, $this->getMetadata() );
1214 * Returns true if the file comes from the local file repository.
1218 function isLocal() {
1219 $repo = $this->getRepo();
1220 return $repo && $repo->isLocal();
1224 * Returns the name of the repository.
1228 function getRepoName() {
1229 return $this->repo ?
$this->repo
->getName() : 'unknown';
1233 * Returns the repository
1235 * @return FileRepo|false
1237 function getRepo() {
1242 * Returns true if the image is an old version
1252 * Is this file a "deleted" file in a private archive?
1259 function isDeleted( $field ) {
1264 * Return the deletion bitfield
1267 function getVisibility() {
1272 * Was this file ever deleted from the wiki?
1276 function wasDeleted() {
1277 $title = $this->getTitle();
1278 return $title && $title->isDeletedQuick();
1282 * Move file to the new title
1284 * Move current, old version and all thumbnails
1285 * to the new filename. Old file is deleted.
1287 * Cache purging is done; checks for validity
1288 * and logging are caller's responsibility
1290 * @param $target Title New file name
1291 * @return FileRepoStatus object.
1293 function move( $target ) {
1294 $this->readOnlyError();
1298 * Delete all versions of the file.
1300 * Moves the files into an archive directory (or deletes them)
1301 * and removes the database rows.
1303 * Cache purging is done; logging is caller's responsibility.
1305 * @param $reason String
1306 * @param $suppress Boolean: hide content from sysops?
1307 * @return true on success, false on some kind of failure
1309 * Overridden by LocalFile
1311 function delete( $reason, $suppress = false ) {
1312 $this->readOnlyError();
1316 * Restore all or specified deleted revisions to the given file.
1317 * Permissions and logging are left to the caller.
1319 * May throw database exceptions on error.
1321 * @param $versions array set of record ids of deleted items to restore,
1322 * or empty to restore all revisions.
1323 * @param $unsuppress bool remove restrictions on content upon restoration?
1324 * @return int|false the number of file revisions restored if successful,
1325 * or false on failure
1327 * Overridden by LocalFile
1329 function restore( $versions = array(), $unsuppress = false ) {
1330 $this->readOnlyError();
1334 * Returns 'true' if this file is a type which supports multiple pages,
1335 * e.g. DJVU or PDF. Note that this may be true even if the file in
1336 * question only has a single page.
1340 function isMultipage() {
1341 return $this->getHandler() && $this->handler
->isMultiPage( $this );
1345 * Returns the number of pages of a multipage document, or false for
1346 * documents which aren't multipage documents
1350 function pageCount() {
1351 if ( !isset( $this->pageCount
) ) {
1352 if ( $this->getHandler() && $this->handler
->isMultiPage( $this ) ) {
1353 $this->pageCount
= $this->handler
->pageCount( $this );
1355 $this->pageCount
= false;
1358 return $this->pageCount
;
1362 * Calculate the height of a thumbnail using the source and destination width
1370 static function scaleHeight( $srcWidth, $srcHeight, $dstWidth ) {
1371 // Exact integer multiply followed by division
1372 if ( $srcWidth == 0 ) {
1375 return round( $srcHeight * $dstWidth / $srcWidth );
1380 * Get an image size array like that returned by getImageSize(), or false if it
1381 * can't be determined.
1383 * @param $fileName String: The filename
1386 function getImageSize( $fileName ) {
1387 if ( !$this->getHandler() ) {
1390 return $this->handler
->getImageSize( $this, $fileName );
1394 * Get the URL of the image description page. May return false if it is
1395 * unknown or not applicable.
1399 function getDescriptionUrl() {
1400 if ( $this->repo
) {
1401 return $this->repo
->getDescriptionUrl( $this->getName() );
1408 * Get the HTML text of the description page, if available
1412 function getDescriptionText() {
1413 global $wgMemc, $wgLang;
1414 if ( !$this->repo ||
!$this->repo
->fetchDescription
) {
1417 $renderUrl = $this->repo
->getDescriptionRenderUrl( $this->getName(), $wgLang->getCode() );
1419 if ( $this->repo
->descriptionCacheExpiry
> 0 ) {
1420 wfDebug("Attempting to get the description from cache...");
1421 $key = $this->repo
->getLocalCacheKey( 'RemoteFileDescription', 'url', $wgLang->getCode(),
1423 $obj = $wgMemc->get($key);
1425 wfDebug("success!\n");
1430 wfDebug( "Fetching shared description from $renderUrl\n" );
1431 $res = Http
::get( $renderUrl );
1432 if ( $res && $this->repo
->descriptionCacheExpiry
> 0 ) {
1433 $wgMemc->set( $key, $res, $this->repo
->descriptionCacheExpiry
);
1442 * Get discription of file revision
1447 function getDescription() {
1452 * Get the 14-character timestamp of the file upload, or false if
1457 function getTimestamp() {
1458 $path = $this->getPath();
1459 if ( !file_exists( $path ) ) {
1462 return wfTimestamp( TS_MW
, filemtime( $path ) );
1466 * Get the SHA-1 base 36 hash of the file
1470 function getSha1() {
1471 return self
::sha1Base36( $this->getPath() );
1475 * Get the deletion archive key, <sha1>.<ext>
1479 function getStorageKey() {
1480 $hash = $this->getSha1();
1484 $ext = $this->getExtension();
1485 $dotExt = $ext === '' ?
'' : ".$ext";
1486 return $hash . $dotExt;
1490 * Determine if the current user is allowed to view a particular
1491 * field of this file, if it's marked as deleted.
1493 * @param $field Integer
1494 * @param $user User object to check, or null to use $wgUser
1497 function userCan( $field, User
$user = null ) {
1502 * Get an associative array containing information about a file in the local filesystem.
1504 * @param $path String: absolute local filesystem path
1505 * @param $ext Mixed: the file extension, or true to extract it from the filename.
1506 * Set it to false to ignore the extension.
1510 static function getPropsFromPath( $path, $ext = true ) {
1511 wfProfileIn( __METHOD__
);
1512 wfDebug( __METHOD__
.": Getting file info for $path\n" );
1514 'fileExists' => file_exists( $path ) && !is_dir( $path )
1517 if ( $info['fileExists'] ) {
1518 $magic = MimeMagic
::singleton();
1520 if ( $ext === true ) {
1521 $i = strrpos( $path, '.' );
1522 $ext = strtolower( $i ?
substr( $path, $i +
1 ) : '' );
1525 # mime type according to file contents
1526 $info['file-mime'] = $magic->guessMimeType( $path, false );
1528 $info['mime'] = $magic->improveTypeFromExtension( $info['file-mime'], $ext );
1530 list( $info['major_mime'], $info['minor_mime'] ) = self
::splitMime( $info['mime'] );
1531 $info['media_type'] = $magic->getMediaType( $path, $info['mime'] );
1534 $info['size'] = filesize( $path );
1536 # Height, width and metadata
1537 $handler = MediaHandler
::getHandler( $info['mime'] );
1539 $tempImage = (object)array();
1540 $info['metadata'] = $handler->getMetadata( $tempImage, $path );
1541 $gis = $handler->getImageSize( $tempImage, $path, $info['metadata'] );
1544 $info['metadata'] = '';
1546 $info['sha1'] = self
::sha1Base36( $path );
1548 wfDebug(__METHOD__
.": $path loaded, {$info['size']} bytes, {$info['mime']}.\n");
1550 $info['mime'] = null;
1551 $info['media_type'] = MEDIATYPE_UNKNOWN
;
1552 $info['metadata'] = '';
1554 wfDebug(__METHOD__
.": $path NOT FOUND!\n");
1557 # NOTE: $gis[2] contains a code for the image type. This is no longer used.
1558 $info['width'] = $gis[0];
1559 $info['height'] = $gis[1];
1560 if ( isset( $gis['bits'] ) ) {
1561 $info['bits'] = $gis['bits'];
1567 $info['height'] = 0;
1570 wfProfileOut( __METHOD__
);
1575 * Get a SHA-1 hash of a file in the local filesystem, in base-36 lower case
1576 * encoding, zero padded to 31 digits.
1578 * 160 log 2 / log 36 = 30.95, so the 160-bit hash fills 31 digits in base 36
1581 * @param $path string
1583 * @return false|string False on failure
1585 static function sha1Base36( $path ) {
1586 wfSuppressWarnings();
1587 $hash = sha1_file( $path );
1588 wfRestoreWarnings();
1589 if ( $hash === false ) {
1592 return wfBaseConvert( $hash, 16, 36, 31 );
1599 function getLongDesc() {
1600 $handler = $this->getHandler();
1602 return $handler->getLongDesc( $this );
1604 return MediaHandler
::getGeneralLongDesc( $this );
1611 function getShortDesc() {
1612 $handler = $this->getHandler();
1614 return $handler->getShortDesc( $this );
1616 return MediaHandler
::getGeneralShortDesc( $this );
1623 function getDimensionsString() {
1624 $handler = $this->getHandler();
1626 return $handler->getDimensionsString( $this );
1635 function getRedirected() {
1636 return $this->redirected
;
1642 function getRedirectedTitle() {
1643 if ( $this->redirected
) {
1644 if ( !$this->redirectTitle
) {
1645 $this->redirectTitle
= Title
::makeTitle( NS_FILE
, $this->redirected
);
1647 return $this->redirectTitle
;
1655 function redirectedFrom( $from ) {
1656 $this->redirected
= $from;
1662 function isMissing() {
1667 * Assert that $this->repo is set to a valid FileRepo instance
1668 * @throws MWException
1670 protected function assertRepoDefined() {
1671 if ( !( $this->repo
instanceof $this->repoClass
) ) {
1672 throw new MWException( "A {$this->repoClass} object is not set for this File.\n" );
1677 * Assert that $this->title is set to a Title
1678 * @throws MWException
1680 protected function assertTitleDefined() {
1681 if ( !( $this->title
instanceof Title
) ) {
1682 throw new MWException( "A Title object is not set for this File.\n" );