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;
35 const DELETE_SOURCE
= 1;
38 * Some member variables can be lazy-initialised using __get(). The
39 * initialisation function for these variables is always a function named
40 * like getVar(), where Var is the variable name with upper-case first
43 * The following variables are initialised in this way in this base class:
44 * name, extension, handler, path, canRender, isSafeFile,
45 * transformScript, hashPath, pageCount, url
47 * Code within this class should generally use the accessor function
48 * directly, since __get() isn't re-entrant and therefore causes bugs that
49 * depend on initialisation order.
53 * The following member variables are not lazy-initialised
66 var $lastError, $redirected, $redirectedTitle;
74 * Call this constructor from child classes
76 function __construct( $title, $repo ) {
77 $this->title
= $title;
81 function __get( $name ) {
82 $function = array( $this, 'get' . ucfirst( $name ) );
83 if ( !is_callable( $function ) ) {
86 $this->$name = call_user_func( $function );
92 * Normalize a file extension to the common form, and ensure it's clean.
93 * Extensions with non-alphanumeric characters will be discarded.
95 * @param $ext string (without the .)
98 static function normalizeExtension( $ext ) {
99 $lower = strtolower( $ext );
106 if( isset( $squish[$lower] ) ) {
107 return $squish[$lower];
108 } elseif( preg_match( '/^[0-9a-z]+$/', $lower ) ) {
116 * Checks if file extensions are compatible
118 * @param $old File Old file
119 * @param $new string New name
123 static function checkExtensionCompatibility( File
$old, $new ) {
124 $oldMime = $old->getMimeType();
125 $n = strrpos( $new, '.' );
126 $newExt = self
::normalizeExtension(
127 $n ?
substr( $new, $n +
1 ) : '' );
128 $mimeMagic = MimeMagic
::singleton();
129 return $mimeMagic->isMatchingExtension( $newExt, $oldMime );
133 * Upgrade the database row if there is one
134 * Called by ImagePage
137 function upgradeRow() {}
140 * Split an internet media type into its two components; if not
141 * a two-part name, set the minor type to 'unknown'.
143 * @param string $mime "text/html" etc
144 * @return array ("text", "html") etc
146 public static function splitMime( $mime ) {
147 if( strpos( $mime, '/' ) !== false ) {
148 return explode( '/', $mime, 2 );
150 return array( $mime, 'unknown' );
155 * Return the name of this file
159 public function getName() {
160 if ( !isset( $this->name
) ) {
161 $this->name
= $this->repo
->getNameFromTitle( $this->title
);
167 * Get the file extension, e.g. "svg"
171 function getExtension() {
172 if ( !isset( $this->extension
) ) {
173 $n = strrpos( $this->getName(), '.' );
174 $this->extension
= self
::normalizeExtension(
175 $n ?
substr( $this->getName(), $n +
1 ) : '' );
177 return $this->extension
;
181 * Return the associated title object
184 public function getTitle() { return $this->title
; }
187 * Return the title used to find this file
191 public function getOriginalTitle() {
192 if ( $this->redirected
) {
193 return $this->getRedirectedTitle();
199 * Return the URL of the file
203 public function getUrl() {
204 if ( !isset( $this->url
) ) {
205 $this->url
= $this->repo
->getZoneUrl( 'public' ) . '/' . $this->getUrlRel();
211 * Return a fully-qualified URL to the file.
212 * Upload URL paths _may or may not_ be fully qualified, so
213 * we check. Local paths are assumed to belong on $wgServer.
217 public function getFullUrl() {
218 return wfExpandUrl( $this->getUrl(), PROTO_RELATIVE
);
221 public function getCanonicalUrl() {
222 return wfExpandUrl( $this->getUrl(), PROTO_CANONICAL
);
228 function getViewURL() {
229 if( $this->mustRender()) {
230 if( $this->canRender() ) {
231 return $this->createThumb( $this->getWidth() );
233 wfDebug(__METHOD__
.': supposed to render '.$this->getName().' ('.$this->getMimeType()."), but can't!\n");
234 return $this->getURL(); #hm... return NULL?
237 return $this->getURL();
242 * Return the full filesystem path to the file. Note that this does
243 * not mean that a file actually exists under that location.
245 * This path depends on whether directory hashing is active or not,
246 * i.e. whether the files are all found in the same directory,
247 * or in hashed paths like /images/3/3c.
249 * Most callers don't check the return value, but ForeignAPIFile::getPath
252 * @return string|false
254 public function getPath() {
255 if ( !isset( $this->path
) ) {
256 $this->path
= $this->repo
->getZonePath('public') . '/' . $this->getRel();
262 * Alias for getPath()
264 * @deprecated since 1.18 Use getPath().
268 public function getFullPath() {
269 wfDeprecated( __METHOD__
);
270 return $this->getPath();
274 * Return the width of the image. Returns false if the width is unknown
278 * Overridden by LocalFile, UnregisteredLocalFile
284 public function getWidth( $page = 1 ) {
289 * Return the height of the image. Returns false if the height is unknown
293 * Overridden by LocalFile, UnregisteredLocalFile
295 * @return false|number
297 public function getHeight( $page = 1 ) {
302 * Returns ID or name of user who uploaded the file
305 * @param $type string 'text' or 'id'
309 public function getUser( $type = 'text' ) {
314 * Get the duration of a media file in seconds
318 public function getLength() {
319 $handler = $this->getHandler();
321 return $handler->getLength( $this );
328 * Return true if the file is vectorized
332 public function isVectorized() {
333 $handler = $this->getHandler();
335 return $handler->isVectorized( $this );
342 * Get handler-specific metadata
343 * Overridden by LocalFile, UnregisteredLocalFile
346 public function getMetadata() {
351 * get versioned metadata
353 * @param $metadata Mixed Array or String of (serialized) metadata
354 * @param $version integer version number.
355 * @return Array containing metadata, or what was passed to it on fail (unserializing if not array)
357 public function convertMetadataVersion($metadata, $version) {
358 $handler = $this->getHandler();
359 if ( !is_array( $metadata ) ) {
360 //just to make the return type consistant
361 $metadata = unserialize( $metadata );
364 return $handler->convertMetadataVersion( $metadata, $version );
371 * Return the bit depth of the file
372 * Overridden by LocalFile
375 public function getBitDepth() {
380 * Return the size of the image file, in bytes
381 * Overridden by LocalFile, UnregisteredLocalFile
384 public function getSize() {
389 * Returns the mime type of the file.
390 * Overridden by LocalFile, UnregisteredLocalFile
395 function getMimeType() {
396 return 'unknown/unknown';
400 * Return the type of the media in the file.
401 * Use the value returned by this function with the MEDIATYPE_xxx constants.
402 * Overridden by LocalFile,
405 function getMediaType() { return MEDIATYPE_UNKNOWN
; }
408 * Checks if the output of transform() for this file is likely
409 * to be valid. If this is false, various user elements will
410 * display a placeholder instead.
412 * Currently, this checks if the file is an image format
413 * that can be converted to a format
414 * supported by all browsers (namely GIF, PNG and JPEG),
415 * or if it is an SVG image and SVG conversion is enabled.
419 function canRender() {
420 if ( !isset( $this->canRender
) ) {
421 $this->canRender
= $this->getHandler() && $this->handler
->canRender( $this );
423 return $this->canRender
;
427 * Accessor for __get()
429 protected function getCanRender() {
430 return $this->canRender();
434 * Return true if the file is of a type that can't be directly
435 * rendered by typical browsers and needs to be re-rasterized.
437 * This returns true for everything but the bitmap types
438 * supported by all browsers, i.e. JPEG; GIF and PNG. It will
439 * also return true for any non-image formats.
443 function mustRender() {
444 return $this->getHandler() && $this->handler
->mustRender( $this );
448 * Alias for canRender()
452 function allowInlineDisplay() {
453 return $this->canRender();
457 * Determines if this media file is in a format that is unlikely to
458 * contain viruses or malicious content. It uses the global
459 * $wgTrustedMediaFormats list to determine if the file is safe.
461 * This is used to show a warning on the description page of non-safe files.
462 * It may also be used to disallow direct [[media:...]] links to such files.
464 * Note that this function will always return true if allowInlineDisplay()
465 * or isTrustedFile() is true for this file.
469 function isSafeFile() {
470 if ( !isset( $this->isSafeFile
) ) {
471 $this->isSafeFile
= $this->_getIsSafeFile();
473 return $this->isSafeFile
;
477 * Accessor for __get()
481 protected function getIsSafeFile() {
482 return $this->isSafeFile();
490 protected function _getIsSafeFile() {
491 if ( $this->allowInlineDisplay() ) {
494 if ($this->isTrustedFile()) {
498 global $wgTrustedMediaFormats;
500 $type = $this->getMediaType();
501 $mime = $this->getMimeType();
502 #wfDebug("LocalFile::isSafeFile: type= $type, mime= $mime\n");
504 if ( !$type ||
$type === MEDIATYPE_UNKNOWN
) {
505 return false; #unknown type, not trusted
507 if ( in_array( $type, $wgTrustedMediaFormats ) ) {
511 if ( $mime === "unknown/unknown" ) {
512 return false; #unknown type, not trusted
514 if ( in_array( $mime, $wgTrustedMediaFormats) ) {
522 * Returns true if the file is flagged as trusted. Files flagged that way
523 * can be linked to directly, even if that is not allowed for this type of
526 * This is a dummy function right now and always returns false. It could be
527 * implemented to extract a flag from the database. The trusted flag could be
528 * set on upload, if the user has sufficient privileges, to bypass script-
529 * and html-filters. It may even be coupled with cryptographics signatures
534 function isTrustedFile() {
535 #this could be implemented to check a flag in the databas,
536 #look for signatures, etc
541 * Returns true if file exists in the repository.
543 * Overridden by LocalFile to avoid unnecessary stat calls.
545 * @return boolean Whether file exists in the repository.
547 public function exists() {
548 return $this->getPath() && file_exists( $this->path
);
552 * Returns true if file exists in the repository and can be included in a page.
553 * It would be unsafe to include private images, making public thumbnails inadvertently
555 * @return boolean Whether file exists in the repository and is includable.
557 public function isVisible() {
558 return $this->exists();
564 function getTransformScript() {
565 if ( !isset( $this->transformScript
) ) {
566 $this->transformScript
= false;
568 $script = $this->repo
->getThumbScriptUrl();
570 $this->transformScript
= "$script?f=" . urlencode( $this->getName() );
574 return $this->transformScript
;
578 * Get a ThumbnailImage which is the same size as the source
580 * @param $handlerParams array
584 function getUnscaledThumb( $handlerParams = array() ) {
585 $hp =& $handlerParams;
586 $page = isset( $hp['page'] ) ?
$hp['page'] : false;
587 $width = $this->getWidth( $page );
589 return $this->iconThumb();
591 $hp['width'] = $width;
592 return $this->transform( $hp );
596 * Return the file name of a thumbnail with the specified parameters
598 * @param $params Array: handler-specific parameters
603 function thumbName( $params ) {
604 return $this->generateThumbName( $this->getName(), $params );
608 * Generate a thumbnail file name from a name and specified parameters
610 * @param string $name
611 * @param array $params Parameters which will be passed to MediaHandler::makeParamString
615 function generateThumbName( $name, $params ) {
616 if ( !$this->getHandler() ) {
619 $extension = $this->getExtension();
620 list( $thumbExt, $thumbMime ) = $this->handler
->getThumbType( $extension, $this->getMimeType(), $params );
621 $thumbName = $this->handler
->makeParamString( $params ) . '-' . $name;
622 if ( $thumbExt != $extension ) {
623 $thumbName .= ".$thumbExt";
629 * Create a thumbnail of the image having the specified width/height.
630 * The thumbnail will not be created if the width is larger than the
631 * image's width. Let the browser do the scaling in this case.
632 * The thumbnail is stored on disk and is only computed if the thumbnail
633 * file does not exist OR if it is older than the image.
636 * Keeps aspect ratio of original image. If both width and height are
637 * specified, the generated image will be no bigger than width x height,
638 * and will also have correct aspect ratio.
640 * @param $width Integer: maximum width of the generated thumbnail
641 * @param $height Integer: maximum height of the image (optional)
645 public function createThumb( $width, $height = -1 ) {
646 $params = array( 'width' => $width );
647 if ( $height != -1 ) {
648 $params['height'] = $height;
650 $thumb = $this->transform( $params );
651 if( is_null( $thumb ) ||
$thumb->isError() ) return '';
652 return $thumb->getUrl();
656 * Transform a media file
658 * @param $params Array: an associative array of handler-specific parameters.
659 * Typical keys are width, height and page.
660 * @param $flags Integer: a bitfield, may contain self::RENDER_NOW to force rendering
661 * @return MediaTransformOutput | false
663 function transform( $params, $flags = 0 ) {
664 global $wgUseSquid, $wgIgnoreImageErrors, $wgThumbnailEpoch, $wgServer;
666 wfProfileIn( __METHOD__
);
668 if ( !$this->canRender() ) {
669 // not a bitmap or renderable image, don't try.
670 $thumb = $this->iconThumb();
674 // Get the descriptionUrl to embed it as comment into the thumbnail. Bug 19791.
675 $descriptionUrl = $this->getDescriptionUrl();
676 if ( $descriptionUrl ) {
677 $params['descriptionUrl'] = $wgServer . $descriptionUrl;
680 $script = $this->getTransformScript();
681 if ( $script && !($flags & self
::RENDER_NOW
) ) {
682 // Use a script to transform on client request, if possible
683 $thumb = $this->handler
->getScriptedTransform( $this, $script, $params );
689 $normalisedParams = $params;
690 $this->handler
->normaliseParams( $this, $normalisedParams );
691 $thumbName = $this->thumbName( $normalisedParams );
692 $thumbPath = $this->getThumbPath( $thumbName );
693 $thumbUrl = $this->getThumbUrl( $thumbName );
695 if ( $this->repo
&& $this->repo
->canTransformVia404() && !($flags & self
::RENDER_NOW
) ) {
696 $thumb = $this->handler
->getTransform( $this, $thumbPath, $thumbUrl, $params );
700 wfDebug( __METHOD__
.": Doing stat for $thumbPath\n" );
701 $this->migrateThumbFile( $thumbName );
702 if ( file_exists( $thumbPath )) {
703 $thumbTime = filemtime( $thumbPath );
704 if ( $thumbTime !== FALSE &&
705 gmdate( 'YmdHis', $thumbTime ) >= $wgThumbnailEpoch ) {
707 $thumb = $this->handler
->getTransform( $this, $thumbPath, $thumbUrl, $params );
711 $thumb = $this->handler
->doTransform( $this, $thumbPath, $thumbUrl, $params );
713 // Ignore errors if requested
716 } elseif ( $thumb->isError() ) {
717 $this->lastError
= $thumb->toText();
718 if ( $wgIgnoreImageErrors && !($flags & self
::RENDER_NOW
) ) {
719 $thumb = $this->handler
->getTransform( $this, $thumbPath, $thumbUrl, $params );
723 // Purge. Useful in the event of Core -> Squid connection failure or squid
724 // purge collisions from elsewhere during failure. Don't keep triggering for
725 // "thumbs" which have the main image URL though (bug 13776)
726 if ( $wgUseSquid && ( !$thumb ||
$thumb->isError() ||
$thumb->getUrl() != $this->getURL()) ) {
727 SquidUpdate
::purge( array( $thumbUrl ) );
731 wfProfileOut( __METHOD__
);
732 return is_object( $thumb ) ?
$thumb : false;
736 * Hook into transform() to allow migration of thumbnail files
738 * Overridden by LocalFile
740 function migrateThumbFile( $thumbName ) {}
743 * Get a MediaHandler instance for this file
744 * @return MediaHandler
746 function getHandler() {
747 if ( !isset( $this->handler
) ) {
748 $this->handler
= MediaHandler
::getHandler( $this->getMimeType() );
750 return $this->handler
;
754 * Get a ThumbnailImage representing a file type icon
755 * @return ThumbnailImage
757 function iconThumb() {
758 global $wgStylePath, $wgStyleDirectory;
760 $try = array( 'fileicon-' . $this->getExtension() . '.png', 'fileicon.png' );
761 foreach( $try as $icon ) {
762 $path = '/common/images/icons/' . $icon;
763 $filepath = $wgStyleDirectory . $path;
764 if( file_exists( $filepath ) ) {
765 return new ThumbnailImage( $this, $wgStylePath . $path, 120, 120 );
772 * Get last thumbnailing error.
775 function getLastError() {
776 return $this->lastError
;
780 * Get all thumbnail names previously generated for this file
782 * Overridden by LocalFile
784 function getThumbnails() {
789 * Purge shared caches such as thumbnails and DB data caching
791 * Overridden by LocalFile
793 function purgeCache() {}
796 * Purge the file description page, but don't go after
797 * pages using the file. Use when modifying file history
798 * but not the current data.
800 function purgeDescription() {
801 $title = $this->getTitle();
803 $title->invalidateCache();
804 $title->purgeSquid();
809 * Purge metadata and all affected pages when the file is created,
810 * deleted, or majorly updated.
812 function purgeEverything() {
813 // Delete thumbnails and refresh file metadata cache
815 $this->purgeDescription();
817 // Purge cache of all pages using this file
818 $title = $this->getTitle();
820 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
826 * Return a fragment of the history of file.
829 * @param $limit integer Limit of rows to return
830 * @param $start timestamp Only revisions older than $start will be returned
831 * @param $end timestamp Only revisions newer than $end will be returned
832 * @param $inc bool Include the endpoints of the time range
836 function getHistory($limit = null, $start = null, $end = null, $inc=true) {
841 * Return the history of this file, line by line. Starts with current version,
842 * then old versions. Should return an object similar to an image/oldimage
846 * Overridden in LocalFile
848 public function nextHistoryLine() {
853 * Reset the history pointer to the first element of the history.
854 * Always call this function after using nextHistoryLine() to free db resources
856 * Overridden in LocalFile.
858 public function resetHistory() {}
861 * Get the filename hash component of the directory including trailing slash,
863 * If the repository is not hashed, returns an empty string.
867 function getHashPath() {
868 if ( !isset( $this->hashPath
) ) {
869 $this->hashPath
= $this->repo
->getHashPath( $this->getName() );
871 return $this->hashPath
;
875 * Get the path of the file relative to the public zone root
880 return $this->getHashPath() . $this->getName();
884 * Get urlencoded relative path of the file
888 function getUrlRel() {
889 return $this->getHashPath() . rawurlencode( $this->getName() );
893 * Get the relative path for an archived file
895 * @param $suffix bool|string if not false, the name of an archived thumbnail file
899 function getArchiveRel( $suffix = false ) {
900 $path = 'archive/' . $this->getHashPath();
901 if ( $suffix === false ) {
902 $path = substr( $path, 0, -1 );
910 * Get the relative path for an archived file's thumbs directory
911 * or a specific thumb if the $suffix is given.
913 * @param $archiveName string the timestamped name of an archived image
914 * @param $suffix bool|string if not false, the name of a thumbnail file
916 function getArchiveThumbRel( $archiveName, $suffix = false ) {
917 $path = 'archive/' . $this->getHashPath() . $archiveName . "/";
918 if ( $suffix === false ) {
919 $path = substr( $path, 0, -1 );
927 * Get the path of the archived file.
929 * @param $suffix bool|string if not false, the name of an archived file.
933 function getArchivePath( $suffix = false ) {
934 return $this->repo
->getZonePath( 'public' ) . '/' . $this->getArchiveRel( $suffix );
938 * Get the path of the archived file's thumbs, or a particular thumb if $suffix is specified
940 * @param $archiveName string the timestamped name of an archived image
941 * @param $suffix bool|string if not false, the name of a thumbnail file
945 function getArchiveThumbPath( $archiveName, $suffix = false ) {
946 return $this->repo
->getZonePath( 'thumb' ) . '/' . $this->getArchiveThumbRel( $archiveName, $suffix );
950 * Get the path of the thumbnail directory, or a particular file if $suffix is specified
952 * @param $suffix bool|string if not false, the name of a thumbnail file
956 function getThumbPath( $suffix = false ) {
957 $path = $this->repo
->getZonePath( 'thumb' ) . '/' . $this->getRel();
958 if ( $suffix !== false ) {
959 $path .= '/' . $suffix;
965 * Get the URL of the archive directory, or a particular file if $suffix is specified
967 * @param $suffix bool|string if not false, the name of an archived file
971 function getArchiveUrl( $suffix = false ) {
972 $path = $this->repo
->getZoneUrl('public') . '/archive/' . $this->getHashPath();
973 if ( $suffix === false ) {
974 $path = substr( $path, 0, -1 );
976 $path .= rawurlencode( $suffix );
982 * Get the URL of the archived file's thumbs, or a particular thumb if $suffix is specified
984 * @param $archiveName string the timestamped name of an archived image
985 * @param $suffix bool|string if not false, the name of a thumbnail file
989 function getArchiveThumbUrl( $archiveName, $suffix = false ) {
990 $path = $this->repo
->getZoneUrl('thumb') . '/archive/' . $this->getHashPath() . rawurlencode( $archiveName ) . "/";
991 if ( $suffix === false ) {
992 $path = substr( $path, 0, -1 );
994 $path .= rawurlencode( $suffix );
1000 * Get the URL of the thumbnail directory, or a particular file if $suffix is specified
1002 * @param $suffix bool|string if not false, the name of a thumbnail file
1006 function getThumbUrl( $suffix = false ) {
1007 $path = $this->repo
->getZoneUrl('thumb') . '/' . $this->getUrlRel();
1008 if ( $suffix !== false ) {
1009 $path .= '/' . rawurlencode( $suffix );
1015 * Get the virtual URL for an archived file's thumbs, or a specific thumb.
1017 * @param $suffix bool|string if not false, the name of a thumbnail file
1021 function getArchiveVirtualUrl( $suffix = false ) {
1022 $path = $this->repo
->getVirtualUrl() . '/public/archive/' . $this->getHashPath();
1023 if ( $suffix === false ) {
1024 $path = substr( $path, 0, -1 );
1026 $path .= rawurlencode( $suffix );
1032 * Get the virtual URL for a thumbnail file or directory
1034 * @param $suffix bool|string if not false, the name of a thumbnail file
1038 function getThumbVirtualUrl( $suffix = false ) {
1039 $path = $this->repo
->getVirtualUrl() . '/thumb/' . $this->getUrlRel();
1040 if ( $suffix !== false ) {
1041 $path .= '/' . rawurlencode( $suffix );
1047 * Get the virtual URL for the file itself
1049 * @param $suffix bool|string if not false, the name of a thumbnail file
1053 function getVirtualUrl( $suffix = false ) {
1054 $path = $this->repo
->getVirtualUrl() . '/public/' . $this->getUrlRel();
1055 if ( $suffix !== false ) {
1056 $path .= '/' . rawurlencode( $suffix );
1064 function isHashed() {
1065 return $this->repo
->isHashed();
1069 * @throws MWException
1071 function readOnlyError() {
1072 throw new MWException( get_class($this) . ': write operations are not supported' );
1076 * Record a file upload in the upload log and the image table
1078 * Overridden by LocalFile
1081 * @param $license string
1082 * @param $copyStatus string
1083 * @param $source string
1084 * @param $watch bool
1086 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '', $watch = false ) {
1087 $this->readOnlyError();
1091 * Move or copy a file to its public location. If a file exists at the
1092 * destination, move it to an archive. Returns a FileRepoStatus object with
1093 * the archive name in the "value" member on success.
1095 * The archive name should be passed through to recordUpload for database
1098 * @param $srcPath String: local filesystem path to the source image
1099 * @param $flags Integer: a bitwise combination of:
1100 * File::DELETE_SOURCE Delete the source file, i.e. move
1102 * @return FileRepoStatus object. On success, the value member contains the
1103 * archive name, or an empty string if it was a new file.
1106 * Overridden by LocalFile
1108 function publish( $srcPath, $flags = 0 ) {
1109 $this->readOnlyError();
1115 function formatMetadata() {
1116 if ( !$this->getHandler() ) {
1119 return $this->getHandler()->formatMetadata( $this, $this->getMetadata() );
1123 * Returns true if the file comes from the local file repository.
1127 function isLocal() {
1128 $repo = $this->getRepo();
1129 return $repo && $repo->isLocal();
1133 * Returns the name of the repository.
1137 function getRepoName() {
1138 return $this->repo ?
$this->repo
->getName() : 'unknown';
1142 * Returns the repository
1146 function getRepo() {
1151 * Returns true if the image is an old version
1161 * Is this file a "deleted" file in a private archive?
1168 function isDeleted( $field ) {
1173 * Return the deletion bitfield
1176 function getVisibility() {
1181 * Was this file ever deleted from the wiki?
1185 function wasDeleted() {
1186 $title = $this->getTitle();
1187 return $title && $title->isDeletedQuick();
1191 * Move file to the new title
1193 * Move current, old version and all thumbnails
1194 * to the new filename. Old file is deleted.
1196 * Cache purging is done; checks for validity
1197 * and logging are caller's responsibility
1199 * @param $target Title New file name
1200 * @return FileRepoStatus object.
1202 function move( $target ) {
1203 $this->readOnlyError();
1207 * Delete all versions of the file.
1209 * Moves the files into an archive directory (or deletes them)
1210 * and removes the database rows.
1212 * Cache purging is done; logging is caller's responsibility.
1214 * @param $reason String
1215 * @param $suppress Boolean: hide content from sysops?
1216 * @return true on success, false on some kind of failure
1218 * Overridden by LocalFile
1220 function delete( $reason, $suppress = false ) {
1221 $this->readOnlyError();
1225 * Restore all or specified deleted revisions to the given file.
1226 * Permissions and logging are left to the caller.
1228 * May throw database exceptions on error.
1230 * @param $versions array set of record ids of deleted items to restore,
1231 * or empty to restore all revisions.
1232 * @param $unsuppress bool remove restrictions on content upon restoration?
1233 * @return int|false the number of file revisions restored if successful,
1234 * or false on failure
1236 * Overridden by LocalFile
1238 function restore( $versions = array(), $unsuppress = false ) {
1239 $this->readOnlyError();
1243 * Returns 'true' if this file is a type which supports multiple pages,
1244 * e.g. DJVU or PDF. Note that this may be true even if the file in
1245 * question only has a single page.
1249 function isMultipage() {
1250 return $this->getHandler() && $this->handler
->isMultiPage( $this );
1254 * Returns the number of pages of a multipage document, or false for
1255 * documents which aren't multipage documents
1259 function pageCount() {
1260 if ( !isset( $this->pageCount
) ) {
1261 if ( $this->getHandler() && $this->handler
->isMultiPage( $this ) ) {
1262 $this->pageCount
= $this->handler
->pageCount( $this );
1264 $this->pageCount
= false;
1267 return $this->pageCount
;
1271 * Calculate the height of a thumbnail using the source and destination width
1279 static function scaleHeight( $srcWidth, $srcHeight, $dstWidth ) {
1280 // Exact integer multiply followed by division
1281 if ( $srcWidth == 0 ) {
1284 return round( $srcHeight * $dstWidth / $srcWidth );
1289 * Get an image size array like that returned by getImageSize(), or false if it
1290 * can't be determined.
1292 * @param $fileName String: The filename
1295 function getImageSize( $fileName ) {
1296 if ( !$this->getHandler() ) {
1299 return $this->handler
->getImageSize( $this, $fileName );
1303 * Get the URL of the image description page. May return false if it is
1304 * unknown or not applicable.
1308 function getDescriptionUrl() {
1309 return $this->repo
->getDescriptionUrl( $this->getName() );
1313 * Get the HTML text of the description page, if available
1317 function getDescriptionText() {
1318 global $wgMemc, $wgLang;
1319 if ( !$this->repo
->fetchDescription
) {
1322 $renderUrl = $this->repo
->getDescriptionRenderUrl( $this->getName(), $wgLang->getCode() );
1324 if ( $this->repo
->descriptionCacheExpiry
> 0 ) {
1325 wfDebug("Attempting to get the description from cache...");
1326 $key = $this->repo
->getLocalCacheKey( 'RemoteFileDescription', 'url', $wgLang->getCode(),
1328 $obj = $wgMemc->get($key);
1330 wfDebug("success!\n");
1335 wfDebug( "Fetching shared description from $renderUrl\n" );
1336 $res = Http
::get( $renderUrl );
1337 if ( $res && $this->repo
->descriptionCacheExpiry
> 0 ) {
1338 $wgMemc->set( $key, $res, $this->repo
->descriptionCacheExpiry
);
1347 * Get discription of file revision
1352 function getDescription() {
1357 * Get the 14-character timestamp of the file upload, or false if
1362 function getTimestamp() {
1363 $path = $this->getPath();
1364 if ( !file_exists( $path ) ) {
1367 return wfTimestamp( TS_MW
, filemtime( $path ) );
1371 * Get the SHA-1 base 36 hash of the file
1375 function getSha1() {
1376 return self
::sha1Base36( $this->getPath() );
1380 * Get the deletion archive key, <sha1>.<ext>
1384 function getStorageKey() {
1385 $hash = $this->getSha1();
1389 $ext = $this->getExtension();
1390 $dotExt = $ext === '' ?
'' : ".$ext";
1391 return $hash . $dotExt;
1395 * Determine if the current user is allowed to view a particular
1396 * field of this file, if it's marked as deleted.
1398 * @param $field Integer
1401 function userCan( $field ) {
1406 * Get an associative array containing information about a file in the local filesystem.
1408 * @param $path String: absolute local filesystem path
1409 * @param $ext Mixed: the file extension, or true to extract it from the filename.
1410 * Set it to false to ignore the extension.
1414 static function getPropsFromPath( $path, $ext = true ) {
1415 wfProfileIn( __METHOD__
);
1416 wfDebug( __METHOD__
.": Getting file info for $path\n" );
1418 'fileExists' => file_exists( $path ) && !is_dir( $path )
1421 if ( $info['fileExists'] ) {
1422 $magic = MimeMagic
::singleton();
1424 if ( $ext === true ) {
1425 $i = strrpos( $path, '.' );
1426 $ext = strtolower( $i ?
substr( $path, $i +
1 ) : '' );
1429 # mime type according to file contents
1430 $info['file-mime'] = $magic->guessMimeType( $path, false );
1432 $info['mime'] = $magic->improveTypeFromExtension( $info['file-mime'], $ext );
1434 list( $info['major_mime'], $info['minor_mime'] ) = self
::splitMime( $info['mime'] );
1435 $info['media_type'] = $magic->getMediaType( $path, $info['mime'] );
1438 $info['size'] = filesize( $path );
1440 # Height, width and metadata
1441 $handler = MediaHandler
::getHandler( $info['mime'] );
1443 $tempImage = (object)array();
1444 $info['metadata'] = $handler->getMetadata( $tempImage, $path );
1445 $gis = $handler->getImageSize( $tempImage, $path, $info['metadata'] );
1448 $info['metadata'] = '';
1450 $info['sha1'] = self
::sha1Base36( $path );
1452 wfDebug(__METHOD__
.": $path loaded, {$info['size']} bytes, {$info['mime']}.\n");
1454 $info['mime'] = null;
1455 $info['media_type'] = MEDIATYPE_UNKNOWN
;
1456 $info['metadata'] = '';
1458 wfDebug(__METHOD__
.": $path NOT FOUND!\n");
1461 # NOTE: $gis[2] contains a code for the image type. This is no longer used.
1462 $info['width'] = $gis[0];
1463 $info['height'] = $gis[1];
1464 if ( isset( $gis['bits'] ) ) {
1465 $info['bits'] = $gis['bits'];
1471 $info['height'] = 0;
1474 wfProfileOut( __METHOD__
);
1479 * Get a SHA-1 hash of a file in the local filesystem, in base-36 lower case
1480 * encoding, zero padded to 31 digits.
1482 * 160 log 2 / log 36 = 30.95, so the 160-bit hash fills 31 digits in base 36
1485 * @param $path string
1487 * @return false|string False on failure
1489 static function sha1Base36( $path ) {
1490 wfSuppressWarnings();
1491 $hash = sha1_file( $path );
1492 wfRestoreWarnings();
1493 if ( $hash === false ) {
1496 return wfBaseConvert( $hash, 16, 36, 31 );
1503 function getLongDesc() {
1504 $handler = $this->getHandler();
1506 return $handler->getLongDesc( $this );
1508 return MediaHandler
::getGeneralLongDesc( $this );
1515 function getShortDesc() {
1516 $handler = $this->getHandler();
1518 return $handler->getShortDesc( $this );
1520 return MediaHandler
::getGeneralShortDesc( $this );
1527 function getDimensionsString() {
1528 $handler = $this->getHandler();
1530 return $handler->getDimensionsString( $this );
1539 function getRedirected() {
1540 return $this->redirected
;
1546 function getRedirectedTitle() {
1547 if ( $this->redirected
) {
1548 if ( !$this->redirectTitle
) {
1549 $this->redirectTitle
= Title
::makeTitle( NS_FILE
, $this->redirected
);
1551 return $this->redirectTitle
;
1559 function redirectedFrom( $from ) {
1560 $this->redirected
= $from;
1566 function isMissing() {
1571 * Aliases for backwards compatibility with 1.6
1573 define( 'MW_IMG_DELETED_FILE', File
::DELETED_FILE
);
1574 define( 'MW_IMG_DELETED_COMMENT', File
::DELETED_COMMENT
);
1575 define( 'MW_IMG_DELETED_USER', File
::DELETED_USER
);
1576 define( 'MW_IMG_DELETED_RESTRICTED', File
::DELETED_RESTRICTED
);