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() );
224 function getViewURL() {
225 if( $this->mustRender()) {
226 if( $this->canRender() ) {
227 return $this->createThumb( $this->getWidth() );
229 wfDebug(__METHOD__
.': supposed to render '.$this->getName().' ('.$this->getMimeType()."), but can't!\n");
230 return $this->getURL(); #hm... return NULL?
233 return $this->getURL();
238 * Return the full filesystem path to the file. Note that this does
239 * not mean that a file actually exists under that location.
241 * This path depends on whether directory hashing is active or not,
242 * i.e. whether the files are all found in the same directory,
243 * or in hashed paths like /images/3/3c.
245 * Most callers don't check the return value, but ForeignAPIFile::getPath
248 * @return string|false
250 public function getPath() {
251 if ( !isset( $this->path
) ) {
252 $this->path
= $this->repo
->getZonePath('public') . '/' . $this->getRel();
258 * Alias for getPath()
260 * @deprecated since 1.18 Use getPath().
264 public function getFullPath() {
265 wfDeprecated( __METHOD__
);
266 return $this->getPath();
270 * Return the width of the image. Returns false if the width is unknown
274 * Overridden by LocalFile, UnregisteredLocalFile
280 public function getWidth( $page = 1 ) {
285 * Return the height of the image. Returns false if the height is unknown
289 * Overridden by LocalFile, UnregisteredLocalFile
291 * @return false|number
293 public function getHeight( $page = 1 ) {
298 * Returns ID or name of user who uploaded the file
301 * @param $type string 'text' or 'id'
305 public function getUser( $type = 'text' ) {
310 * Get the duration of a media file in seconds
314 public function getLength() {
315 $handler = $this->getHandler();
317 return $handler->getLength( $this );
324 * Return true if the file is vectorized
328 public function isVectorized() {
329 $handler = $this->getHandler();
331 return $handler->isVectorized( $this );
338 * Get handler-specific metadata
339 * Overridden by LocalFile, UnregisteredLocalFile
342 public function getMetadata() {
347 * get versioned metadata
349 * @param $metadata Mixed Array or String of (serialized) metadata
350 * @param $version integer version number.
351 * @return Array containing metadata, or what was passed to it on fail (unserializing if not array)
353 public function convertMetadataVersion($metadata, $version) {
354 $handler = $this->getHandler();
355 if ( !is_array( $metadata ) ) {
356 //just to make the return type consistant
357 $metadata = unserialize( $metadata );
360 return $handler->convertMetadataVersion( $metadata, $version );
367 * Return the bit depth of the file
368 * Overridden by LocalFile
371 public function getBitDepth() {
376 * Return the size of the image file, in bytes
377 * Overridden by LocalFile, UnregisteredLocalFile
380 public function getSize() {
385 * Returns the mime type of the file.
386 * Overridden by LocalFile, UnregisteredLocalFile
391 function getMimeType() {
392 return 'unknown/unknown';
396 * Return the type of the media in the file.
397 * Use the value returned by this function with the MEDIATYPE_xxx constants.
398 * Overridden by LocalFile,
401 function getMediaType() { return MEDIATYPE_UNKNOWN
; }
404 * Checks if the output of transform() for this file is likely
405 * to be valid. If this is false, various user elements will
406 * display a placeholder instead.
408 * Currently, this checks if the file is an image format
409 * that can be converted to a format
410 * supported by all browsers (namely GIF, PNG and JPEG),
411 * or if it is an SVG image and SVG conversion is enabled.
415 function canRender() {
416 if ( !isset( $this->canRender
) ) {
417 $this->canRender
= $this->getHandler() && $this->handler
->canRender( $this );
419 return $this->canRender
;
423 * Accessor for __get()
425 protected function getCanRender() {
426 return $this->canRender();
430 * Return true if the file is of a type that can't be directly
431 * rendered by typical browsers and needs to be re-rasterized.
433 * This returns true for everything but the bitmap types
434 * supported by all browsers, i.e. JPEG; GIF and PNG. It will
435 * also return true for any non-image formats.
439 function mustRender() {
440 return $this->getHandler() && $this->handler
->mustRender( $this );
444 * Alias for canRender()
448 function allowInlineDisplay() {
449 return $this->canRender();
453 * Determines if this media file is in a format that is unlikely to
454 * contain viruses or malicious content. It uses the global
455 * $wgTrustedMediaFormats list to determine if the file is safe.
457 * This is used to show a warning on the description page of non-safe files.
458 * It may also be used to disallow direct [[media:...]] links to such files.
460 * Note that this function will always return true if allowInlineDisplay()
461 * or isTrustedFile() is true for this file.
465 function isSafeFile() {
466 if ( !isset( $this->isSafeFile
) ) {
467 $this->isSafeFile
= $this->_getIsSafeFile();
469 return $this->isSafeFile
;
473 * Accessor for __get()
477 protected function getIsSafeFile() {
478 return $this->isSafeFile();
486 protected function _getIsSafeFile() {
487 if ( $this->allowInlineDisplay() ) {
490 if ($this->isTrustedFile()) {
494 global $wgTrustedMediaFormats;
496 $type = $this->getMediaType();
497 $mime = $this->getMimeType();
498 #wfDebug("LocalFile::isSafeFile: type= $type, mime= $mime\n");
500 if ( !$type ||
$type === MEDIATYPE_UNKNOWN
) {
501 return false; #unknown type, not trusted
503 if ( in_array( $type, $wgTrustedMediaFormats ) ) {
507 if ( $mime === "unknown/unknown" ) {
508 return false; #unknown type, not trusted
510 if ( in_array( $mime, $wgTrustedMediaFormats) ) {
518 * Returns true if the file is flagged as trusted. Files flagged that way
519 * can be linked to directly, even if that is not allowed for this type of
522 * This is a dummy function right now and always returns false. It could be
523 * implemented to extract a flag from the database. The trusted flag could be
524 * set on upload, if the user has sufficient privileges, to bypass script-
525 * and html-filters. It may even be coupled with cryptographics signatures
530 function isTrustedFile() {
531 #this could be implemented to check a flag in the databas,
532 #look for signatures, etc
537 * Returns true if file exists in the repository.
539 * Overridden by LocalFile to avoid unnecessary stat calls.
541 * @return boolean Whether file exists in the repository.
543 public function exists() {
544 return $this->getPath() && file_exists( $this->path
);
548 * Returns true if file exists in the repository and can be included in a page.
549 * It would be unsafe to include private images, making public thumbnails inadvertently
551 * @return boolean Whether file exists in the repository and is includable.
553 public function isVisible() {
554 return $this->exists();
560 function getTransformScript() {
561 if ( !isset( $this->transformScript
) ) {
562 $this->transformScript
= false;
564 $script = $this->repo
->getThumbScriptUrl();
566 $this->transformScript
= "$script?f=" . urlencode( $this->getName() );
570 return $this->transformScript
;
574 * Get a ThumbnailImage which is the same size as the source
576 * @param $handlerParams array
580 function getUnscaledThumb( $handlerParams = array() ) {
581 $hp =& $handlerParams;
582 $page = isset( $hp['page'] ) ?
$hp['page'] : false;
583 $width = $this->getWidth( $page );
585 return $this->iconThumb();
587 $hp['width'] = $width;
588 return $this->transform( $hp );
592 * Return the file name of a thumbnail with the specified parameters
594 * @param $params Array: handler-specific parameters
599 function thumbName( $params ) {
600 return $this->generateThumbName( $this->getName(), $params );
604 * Generate a thumbnail file name from a name and specified parameters
606 * @param string $name
607 * @param array $params Parameters which will be passed to MediaHandler::makeParamString
611 function generateThumbName( $name, $params ) {
612 if ( !$this->getHandler() ) {
615 $extension = $this->getExtension();
616 list( $thumbExt, $thumbMime ) = $this->handler
->getThumbType( $extension, $this->getMimeType(), $params );
617 $thumbName = $this->handler
->makeParamString( $params ) . '-' . $name;
618 if ( $thumbExt != $extension ) {
619 $thumbName .= ".$thumbExt";
625 * Create a thumbnail of the image having the specified width/height.
626 * The thumbnail will not be created if the width is larger than the
627 * image's width. Let the browser do the scaling in this case.
628 * The thumbnail is stored on disk and is only computed if the thumbnail
629 * file does not exist OR if it is older than the image.
632 * Keeps aspect ratio of original image. If both width and height are
633 * specified, the generated image will be no bigger than width x height,
634 * and will also have correct aspect ratio.
636 * @param $width Integer: maximum width of the generated thumbnail
637 * @param $height Integer: maximum height of the image (optional)
641 public function createThumb( $width, $height = -1 ) {
642 $params = array( 'width' => $width );
643 if ( $height != -1 ) {
644 $params['height'] = $height;
646 $thumb = $this->transform( $params );
647 if( is_null( $thumb ) ||
$thumb->isError() ) return '';
648 return $thumb->getUrl();
652 * Transform a media file
654 * @param $params Array: an associative array of handler-specific parameters.
655 * Typical keys are width, height and page.
656 * @param $flags Integer: a bitfield, may contain self::RENDER_NOW to force rendering
657 * @return MediaTransformOutput | false
659 function transform( $params, $flags = 0 ) {
660 global $wgUseSquid, $wgIgnoreImageErrors, $wgThumbnailEpoch, $wgServer;
662 wfProfileIn( __METHOD__
);
664 if ( !$this->canRender() ) {
665 // not a bitmap or renderable image, don't try.
666 $thumb = $this->iconThumb();
670 // Get the descriptionUrl to embed it as comment into the thumbnail. Bug 19791.
671 $descriptionUrl = $this->getDescriptionUrl();
672 if ( $descriptionUrl ) {
673 $params['descriptionUrl'] = $wgServer . $descriptionUrl;
676 $script = $this->getTransformScript();
677 if ( $script && !($flags & self
::RENDER_NOW
) ) {
678 // Use a script to transform on client request, if possible
679 $thumb = $this->handler
->getScriptedTransform( $this, $script, $params );
685 $normalisedParams = $params;
686 $this->handler
->normaliseParams( $this, $normalisedParams );
687 $thumbName = $this->thumbName( $normalisedParams );
688 $thumbPath = $this->getThumbPath( $thumbName );
689 $thumbUrl = $this->getThumbUrl( $thumbName );
691 if ( $this->repo
&& $this->repo
->canTransformVia404() && !($flags & self
::RENDER_NOW
) ) {
692 $thumb = $this->handler
->getTransform( $this, $thumbPath, $thumbUrl, $params );
696 wfDebug( __METHOD__
.": Doing stat for $thumbPath\n" );
697 $this->migrateThumbFile( $thumbName );
698 if ( file_exists( $thumbPath )) {
699 $thumbTime = filemtime( $thumbPath );
700 if ( $thumbTime !== FALSE &&
701 gmdate( 'YmdHis', $thumbTime ) >= $wgThumbnailEpoch ) {
703 $thumb = $this->handler
->getTransform( $this, $thumbPath, $thumbUrl, $params );
707 $thumb = $this->handler
->doTransform( $this, $thumbPath, $thumbUrl, $params );
709 // Ignore errors if requested
712 } elseif ( $thumb->isError() ) {
713 $this->lastError
= $thumb->toText();
714 if ( $wgIgnoreImageErrors && !($flags & self
::RENDER_NOW
) ) {
715 $thumb = $this->handler
->getTransform( $this, $thumbPath, $thumbUrl, $params );
719 // Purge. Useful in the event of Core -> Squid connection failure or squid
720 // purge collisions from elsewhere during failure. Don't keep triggering for
721 // "thumbs" which have the main image URL though (bug 13776)
722 if ( $wgUseSquid && ( !$thumb ||
$thumb->isError() ||
$thumb->getUrl() != $this->getURL()) ) {
723 SquidUpdate
::purge( array( $thumbUrl ) );
727 wfProfileOut( __METHOD__
);
728 return is_object( $thumb ) ?
$thumb : false;
732 * Hook into transform() to allow migration of thumbnail files
734 * Overridden by LocalFile
736 function migrateThumbFile( $thumbName ) {}
739 * Get a MediaHandler instance for this file
740 * @return MediaHandler
742 function getHandler() {
743 if ( !isset( $this->handler
) ) {
744 $this->handler
= MediaHandler
::getHandler( $this->getMimeType() );
746 return $this->handler
;
750 * Get a ThumbnailImage representing a file type icon
751 * @return ThumbnailImage
753 function iconThumb() {
754 global $wgStylePath, $wgStyleDirectory;
756 $try = array( 'fileicon-' . $this->getExtension() . '.png', 'fileicon.png' );
757 foreach( $try as $icon ) {
758 $path = '/common/images/icons/' . $icon;
759 $filepath = $wgStyleDirectory . $path;
760 if( file_exists( $filepath ) ) {
761 return new ThumbnailImage( $this, $wgStylePath . $path, 120, 120 );
768 * Get last thumbnailing error.
771 function getLastError() {
772 return $this->lastError
;
776 * Get all thumbnail names previously generated for this file
778 * Overridden by LocalFile
780 function getThumbnails() {
785 * Purge shared caches such as thumbnails and DB data caching
787 * Overridden by LocalFile
789 function purgeCache() {}
792 * Purge the file description page, but don't go after
793 * pages using the file. Use when modifying file history
794 * but not the current data.
796 function purgeDescription() {
797 $title = $this->getTitle();
799 $title->invalidateCache();
800 $title->purgeSquid();
805 * Purge metadata and all affected pages when the file is created,
806 * deleted, or majorly updated.
808 function purgeEverything() {
809 // Delete thumbnails and refresh file metadata cache
811 $this->purgeDescription();
813 // Purge cache of all pages using this file
814 $title = $this->getTitle();
816 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
822 * Return a fragment of the history of file.
825 * @param $limit integer Limit of rows to return
826 * @param $start timestamp Only revisions older than $start will be returned
827 * @param $end timestamp Only revisions newer than $end will be returned
828 * @param $inc bool Include the endpoints of the time range
832 function getHistory($limit = null, $start = null, $end = null, $inc=true) {
837 * Return the history of this file, line by line. Starts with current version,
838 * then old versions. Should return an object similar to an image/oldimage
842 * Overridden in LocalFile
844 public function nextHistoryLine() {
849 * Reset the history pointer to the first element of the history.
850 * Always call this function after using nextHistoryLine() to free db resources
852 * Overridden in LocalFile.
854 public function resetHistory() {}
857 * Get the filename hash component of the directory including trailing slash,
859 * If the repository is not hashed, returns an empty string.
863 function getHashPath() {
864 if ( !isset( $this->hashPath
) ) {
865 $this->hashPath
= $this->repo
->getHashPath( $this->getName() );
867 return $this->hashPath
;
871 * Get the path of the file relative to the public zone root
876 return $this->getHashPath() . $this->getName();
880 * Get urlencoded relative path of the file
884 function getUrlRel() {
885 return $this->getHashPath() . rawurlencode( $this->getName() );
889 * Get the relative path for an archive file
891 * @param $suffix bool
895 function getArchiveRel( $suffix = false ) {
896 $path = 'archive/' . $this->getHashPath();
897 if ( $suffix === false ) {
898 $path = substr( $path, 0, -1 );
906 * Get the path of the archive directory, or a particular file if $suffix is specified
908 * @param $suffix bool
912 function getArchivePath( $suffix = false ) {
913 return $this->repo
->getZonePath( 'public' ) . '/' . $this->getArchiveRel( $suffix );
917 * Get the path of the thumbnail directory, or a particular file if $suffix is specified
919 * @param $suffix bool
923 function getThumbPath( $suffix = false ) {
924 $path = $this->repo
->getZonePath( 'thumb' ) . '/' . $this->getRel();
925 if ( $suffix !== false ) {
926 $path .= '/' . $suffix;
932 * Get the URL of the archive directory, or a particular file if $suffix is specified
934 * @param $suffix bool
938 function getArchiveUrl( $suffix = false ) {
939 $path = $this->repo
->getZoneUrl('public') . '/archive/' . $this->getHashPath();
940 if ( $suffix === false ) {
941 $path = substr( $path, 0, -1 );
943 $path .= rawurlencode( $suffix );
949 * Get the URL of the thumbnail directory, or a particular file if $suffix is specified
951 * @param $suffix bool
955 function getThumbUrl( $suffix = false ) {
956 $path = $this->repo
->getZoneUrl('thumb') . '/' . $this->getUrlRel();
957 if ( $suffix !== false ) {
958 $path .= '/' . rawurlencode( $suffix );
964 * Get the virtual URL for an archive file or directory
966 * @param bool|string $suffix
970 function getArchiveVirtualUrl( $suffix = false ) {
971 $path = $this->repo
->getVirtualUrl() . '/public/archive/' . $this->getHashPath();
972 if ( $suffix === false ) {
973 $path = substr( $path, 0, -1 );
975 $path .= rawurlencode( $suffix );
981 * Get the virtual URL for a thumbnail file or directory
983 * @param $suffix bool
987 function getThumbVirtualUrl( $suffix = false ) {
988 $path = $this->repo
->getVirtualUrl() . '/thumb/' . $this->getUrlRel();
989 if ( $suffix !== false ) {
990 $path .= '/' . rawurlencode( $suffix );
996 * Get the virtual URL for the file itself
998 * @param $suffix bool
1002 function getVirtualUrl( $suffix = false ) {
1003 $path = $this->repo
->getVirtualUrl() . '/public/' . $this->getUrlRel();
1004 if ( $suffix !== false ) {
1005 $path .= '/' . rawurlencode( $suffix );
1013 function isHashed() {
1014 return $this->repo
->isHashed();
1018 * @throws MWException
1020 function readOnlyError() {
1021 throw new MWException( get_class($this) . ': write operations are not supported' );
1025 * Record a file upload in the upload log and the image table
1027 * Overridden by LocalFile
1030 * @param $license string
1031 * @param $copyStatus string
1032 * @param $source string
1033 * @param $watch bool
1035 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '', $watch = false ) {
1036 $this->readOnlyError();
1040 * Move or copy a file to its public location. If a file exists at the
1041 * destination, move it to an archive. Returns a FileRepoStatus object with
1042 * the archive name in the "value" member on success.
1044 * The archive name should be passed through to recordUpload for database
1047 * @param $srcPath String: local filesystem path to the source image
1048 * @param $flags Integer: a bitwise combination of:
1049 * File::DELETE_SOURCE Delete the source file, i.e. move
1051 * @return FileRepoStatus object. On success, the value member contains the
1052 * archive name, or an empty string if it was a new file.
1055 * Overridden by LocalFile
1057 function publish( $srcPath, $flags = 0 ) {
1058 $this->readOnlyError();
1064 function formatMetadata() {
1065 if ( !$this->getHandler() ) {
1068 return $this->getHandler()->formatMetadata( $this, $this->getMetadata() );
1072 * Returns true if the file comes from the local file repository.
1076 function isLocal() {
1077 $repo = $this->getRepo();
1078 return $repo && $repo->isLocal();
1082 * Returns the name of the repository.
1086 function getRepoName() {
1087 return $this->repo ?
$this->repo
->getName() : 'unknown';
1091 * Returns the repository
1095 function getRepo() {
1100 * Returns true if the image is an old version
1110 * Is this file a "deleted" file in a private archive?
1117 function isDeleted( $field ) {
1122 * Return the deletion bitfield
1125 function getVisibility() {
1130 * Was this file ever deleted from the wiki?
1134 function wasDeleted() {
1135 $title = $this->getTitle();
1136 return $title && $title->isDeletedQuick();
1140 * Move file to the new title
1142 * Move current, old version and all thumbnails
1143 * to the new filename. Old file is deleted.
1145 * Cache purging is done; checks for validity
1146 * and logging are caller's responsibility
1148 * @param $target Title New file name
1149 * @return FileRepoStatus object.
1151 function move( $target ) {
1152 $this->readOnlyError();
1156 * Delete all versions of the file.
1158 * Moves the files into an archive directory (or deletes them)
1159 * and removes the database rows.
1161 * Cache purging is done; logging is caller's responsibility.
1163 * @param $reason String
1164 * @param $suppress Boolean: hide content from sysops?
1165 * @return true on success, false on some kind of failure
1167 * Overridden by LocalFile
1169 function delete( $reason, $suppress = false ) {
1170 $this->readOnlyError();
1174 * Restore all or specified deleted revisions to the given file.
1175 * Permissions and logging are left to the caller.
1177 * May throw database exceptions on error.
1179 * @param $versions array set of record ids of deleted items to restore,
1180 * or empty to restore all revisions.
1181 * @param $unsuppress bool remove restrictions on content upon restoration?
1182 * @return int|false the number of file revisions restored if successful,
1183 * or false on failure
1185 * Overridden by LocalFile
1187 function restore( $versions = array(), $unsuppress = false ) {
1188 $this->readOnlyError();
1192 * Returns 'true' if this file is a type which supports multiple pages,
1193 * e.g. DJVU or PDF. Note that this may be true even if the file in
1194 * question only has a single page.
1198 function isMultipage() {
1199 return $this->getHandler() && $this->handler
->isMultiPage( $this );
1203 * Returns the number of pages of a multipage document, or false for
1204 * documents which aren't multipage documents
1208 function pageCount() {
1209 if ( !isset( $this->pageCount
) ) {
1210 if ( $this->getHandler() && $this->handler
->isMultiPage( $this ) ) {
1211 $this->pageCount
= $this->handler
->pageCount( $this );
1213 $this->pageCount
= false;
1216 return $this->pageCount
;
1220 * Calculate the height of a thumbnail using the source and destination width
1228 static function scaleHeight( $srcWidth, $srcHeight, $dstWidth ) {
1229 // Exact integer multiply followed by division
1230 if ( $srcWidth == 0 ) {
1233 return round( $srcHeight * $dstWidth / $srcWidth );
1238 * Get an image size array like that returned by getImageSize(), or false if it
1239 * can't be determined.
1241 * @param $fileName String: The filename
1244 function getImageSize( $fileName ) {
1245 if ( !$this->getHandler() ) {
1248 return $this->handler
->getImageSize( $this, $fileName );
1252 * Get the URL of the image description page. May return false if it is
1253 * unknown or not applicable.
1257 function getDescriptionUrl() {
1258 return $this->repo
->getDescriptionUrl( $this->getName() );
1262 * Get the HTML text of the description page, if available
1266 function getDescriptionText() {
1267 global $wgMemc, $wgLang;
1268 if ( !$this->repo
->fetchDescription
) {
1271 $renderUrl = $this->repo
->getDescriptionRenderUrl( $this->getName(), $wgLang->getCode() );
1273 if ( $this->repo
->descriptionCacheExpiry
> 0 ) {
1274 wfDebug("Attempting to get the description from cache...");
1275 $key = $this->repo
->getLocalCacheKey( 'RemoteFileDescription', 'url', $wgLang->getCode(),
1277 $obj = $wgMemc->get($key);
1279 wfDebug("success!\n");
1284 wfDebug( "Fetching shared description from $renderUrl\n" );
1285 $res = Http
::get( $renderUrl );
1286 if ( $res && $this->repo
->descriptionCacheExpiry
> 0 ) {
1287 $wgMemc->set( $key, $res, $this->repo
->descriptionCacheExpiry
);
1296 * Get discription of file revision
1301 function getDescription() {
1306 * Get the 14-character timestamp of the file upload, or false if
1311 function getTimestamp() {
1312 $path = $this->getPath();
1313 if ( !file_exists( $path ) ) {
1316 return wfTimestamp( TS_MW
, filemtime( $path ) );
1320 * Get the SHA-1 base 36 hash of the file
1324 function getSha1() {
1325 return self
::sha1Base36( $this->getPath() );
1329 * Get the deletion archive key, <sha1>.<ext>
1333 function getStorageKey() {
1334 $hash = $this->getSha1();
1338 $ext = $this->getExtension();
1339 $dotExt = $ext === '' ?
'' : ".$ext";
1340 return $hash . $dotExt;
1344 * Determine if the current user is allowed to view a particular
1345 * field of this file, if it's marked as deleted.
1347 * @param $field Integer
1350 function userCan( $field ) {
1355 * Get an associative array containing information about a file in the local filesystem.
1357 * @param $path String: absolute local filesystem path
1358 * @param $ext Mixed: the file extension, or true to extract it from the filename.
1359 * Set it to false to ignore the extension.
1363 static function getPropsFromPath( $path, $ext = true ) {
1364 wfProfileIn( __METHOD__
);
1365 wfDebug( __METHOD__
.": Getting file info for $path\n" );
1367 'fileExists' => file_exists( $path ) && !is_dir( $path )
1370 if ( $info['fileExists'] ) {
1371 $magic = MimeMagic
::singleton();
1373 if ( $ext === true ) {
1374 $i = strrpos( $path, '.' );
1375 $ext = strtolower( $i ?
substr( $path, $i +
1 ) : '' );
1378 # mime type according to file contents
1379 $info['file-mime'] = $magic->guessMimeType( $path, false );
1381 $info['mime'] = $magic->improveTypeFromExtension( $info['file-mime'], $ext );
1383 list( $info['major_mime'], $info['minor_mime'] ) = self
::splitMime( $info['mime'] );
1384 $info['media_type'] = $magic->getMediaType( $path, $info['mime'] );
1387 $info['size'] = filesize( $path );
1389 # Height, width and metadata
1390 $handler = MediaHandler
::getHandler( $info['mime'] );
1392 $tempImage = (object)array();
1393 $info['metadata'] = $handler->getMetadata( $tempImage, $path );
1394 $gis = $handler->getImageSize( $tempImage, $path, $info['metadata'] );
1397 $info['metadata'] = '';
1399 $info['sha1'] = self
::sha1Base36( $path );
1401 wfDebug(__METHOD__
.": $path loaded, {$info['size']} bytes, {$info['mime']}.\n");
1403 $info['mime'] = null;
1404 $info['media_type'] = MEDIATYPE_UNKNOWN
;
1405 $info['metadata'] = '';
1407 wfDebug(__METHOD__
.": $path NOT FOUND!\n");
1410 # NOTE: $gis[2] contains a code for the image type. This is no longer used.
1411 $info['width'] = $gis[0];
1412 $info['height'] = $gis[1];
1413 if ( isset( $gis['bits'] ) ) {
1414 $info['bits'] = $gis['bits'];
1420 $info['height'] = 0;
1423 wfProfileOut( __METHOD__
);
1428 * Get a SHA-1 hash of a file in the local filesystem, in base-36 lower case
1429 * encoding, zero padded to 31 digits.
1431 * 160 log 2 / log 36 = 30.95, so the 160-bit hash fills 31 digits in base 36
1434 * @param $path string
1436 * @return false|string False on failure
1438 static function sha1Base36( $path ) {
1439 wfSuppressWarnings();
1440 $hash = sha1_file( $path );
1441 wfRestoreWarnings();
1442 if ( $hash === false ) {
1445 return wfBaseConvert( $hash, 16, 36, 31 );
1452 function getLongDesc() {
1453 $handler = $this->getHandler();
1455 return $handler->getLongDesc( $this );
1457 return MediaHandler
::getGeneralLongDesc( $this );
1464 function getShortDesc() {
1465 $handler = $this->getHandler();
1467 return $handler->getShortDesc( $this );
1469 return MediaHandler
::getGeneralShortDesc( $this );
1476 function getDimensionsString() {
1477 $handler = $this->getHandler();
1479 return $handler->getDimensionsString( $this );
1488 function getRedirected() {
1489 return $this->redirected
;
1495 function getRedirectedTitle() {
1496 if ( $this->redirected
) {
1497 if ( !$this->redirectTitle
) {
1498 $this->redirectTitle
= Title
::makeTitle( NS_FILE
, $this->redirected
);
1500 return $this->redirectTitle
;
1508 function redirectedFrom( $from ) {
1509 $this->redirected
= $from;
1515 function isMissing() {
1520 * Aliases for backwards compatibility with 1.6
1522 define( 'MW_IMG_DELETED_FILE', File
::DELETED_FILE
);
1523 define( 'MW_IMG_DELETED_COMMENT', File
::DELETED_COMMENT
);
1524 define( 'MW_IMG_DELETED_USER', File
::DELETED_USER
);
1525 define( 'MW_IMG_DELETED_RESTRICTED', File
::DELETED_RESTRICTED
);