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 archive file
895 * @param $suffix bool
899 function getArchiveRel( $suffix = false ) {
900 $path = 'archive/' . $this->getHashPath();
901 if ( $suffix === false ) {
902 $path = substr( $path, 0, -1 );
910 * Get the path of the archive directory, or a particular file if $suffix is specified
912 * @param $suffix bool
916 function getArchivePath( $suffix = false ) {
917 return $this->repo
->getZonePath( 'public' ) . '/' . $this->getArchiveRel( $suffix );
921 * Get the path of the thumbnail directory, or a particular file if $suffix is specified
923 * @param $suffix bool
927 function getThumbPath( $suffix = false ) {
928 $path = $this->repo
->getZonePath( 'thumb' ) . '/' . $this->getRel();
929 if ( $suffix !== false ) {
930 $path .= '/' . $suffix;
936 * Get the URL of the archive directory, or a particular file if $suffix is specified
938 * @param $suffix bool
942 function getArchiveUrl( $suffix = false ) {
943 $path = $this->repo
->getZoneUrl('public') . '/archive/' . $this->getHashPath();
944 if ( $suffix === false ) {
945 $path = substr( $path, 0, -1 );
947 $path .= rawurlencode( $suffix );
953 * Get the URL of the thumbnail directory, or a particular file if $suffix is specified
955 * @param $suffix bool
959 function getThumbUrl( $suffix = false ) {
960 $path = $this->repo
->getZoneUrl('thumb') . '/' . $this->getUrlRel();
961 if ( $suffix !== false ) {
962 $path .= '/' . rawurlencode( $suffix );
968 * Get the virtual URL for an archive file or directory
970 * @param bool|string $suffix
974 function getArchiveVirtualUrl( $suffix = false ) {
975 $path = $this->repo
->getVirtualUrl() . '/public/archive/' . $this->getHashPath();
976 if ( $suffix === false ) {
977 $path = substr( $path, 0, -1 );
979 $path .= rawurlencode( $suffix );
985 * Get the virtual URL for a thumbnail file or directory
987 * @param $suffix bool
991 function getThumbVirtualUrl( $suffix = false ) {
992 $path = $this->repo
->getVirtualUrl() . '/thumb/' . $this->getUrlRel();
993 if ( $suffix !== false ) {
994 $path .= '/' . rawurlencode( $suffix );
1000 * Get the virtual URL for the file itself
1002 * @param $suffix bool
1006 function getVirtualUrl( $suffix = false ) {
1007 $path = $this->repo
->getVirtualUrl() . '/public/' . $this->getUrlRel();
1008 if ( $suffix !== false ) {
1009 $path .= '/' . rawurlencode( $suffix );
1017 function isHashed() {
1018 return $this->repo
->isHashed();
1022 * @throws MWException
1024 function readOnlyError() {
1025 throw new MWException( get_class($this) . ': write operations are not supported' );
1029 * Record a file upload in the upload log and the image table
1031 * Overridden by LocalFile
1034 * @param $license string
1035 * @param $copyStatus string
1036 * @param $source string
1037 * @param $watch bool
1039 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '', $watch = false ) {
1040 $this->readOnlyError();
1044 * Move or copy a file to its public location. If a file exists at the
1045 * destination, move it to an archive. Returns a FileRepoStatus object with
1046 * the archive name in the "value" member on success.
1048 * The archive name should be passed through to recordUpload for database
1051 * @param $srcPath String: local filesystem path to the source image
1052 * @param $flags Integer: a bitwise combination of:
1053 * File::DELETE_SOURCE Delete the source file, i.e. move
1055 * @return FileRepoStatus object. On success, the value member contains the
1056 * archive name, or an empty string if it was a new file.
1059 * Overridden by LocalFile
1061 function publish( $srcPath, $flags = 0 ) {
1062 $this->readOnlyError();
1068 function formatMetadata() {
1069 if ( !$this->getHandler() ) {
1072 return $this->getHandler()->formatMetadata( $this, $this->getMetadata() );
1076 * Returns true if the file comes from the local file repository.
1080 function isLocal() {
1081 $repo = $this->getRepo();
1082 return $repo && $repo->isLocal();
1086 * Returns the name of the repository.
1090 function getRepoName() {
1091 return $this->repo ?
$this->repo
->getName() : 'unknown';
1095 * Returns the repository
1099 function getRepo() {
1104 * Returns true if the image is an old version
1114 * Is this file a "deleted" file in a private archive?
1121 function isDeleted( $field ) {
1126 * Return the deletion bitfield
1129 function getVisibility() {
1134 * Was this file ever deleted from the wiki?
1138 function wasDeleted() {
1139 $title = $this->getTitle();
1140 return $title && $title->isDeletedQuick();
1144 * Move file to the new title
1146 * Move current, old version and all thumbnails
1147 * to the new filename. Old file is deleted.
1149 * Cache purging is done; checks for validity
1150 * and logging are caller's responsibility
1152 * @param $target Title New file name
1153 * @return FileRepoStatus object.
1155 function move( $target ) {
1156 $this->readOnlyError();
1160 * Delete all versions of the file.
1162 * Moves the files into an archive directory (or deletes them)
1163 * and removes the database rows.
1165 * Cache purging is done; logging is caller's responsibility.
1167 * @param $reason String
1168 * @param $suppress Boolean: hide content from sysops?
1169 * @return true on success, false on some kind of failure
1171 * Overridden by LocalFile
1173 function delete( $reason, $suppress = false ) {
1174 $this->readOnlyError();
1178 * Restore all or specified deleted revisions to the given file.
1179 * Permissions and logging are left to the caller.
1181 * May throw database exceptions on error.
1183 * @param $versions array set of record ids of deleted items to restore,
1184 * or empty to restore all revisions.
1185 * @param $unsuppress bool remove restrictions on content upon restoration?
1186 * @return int|false the number of file revisions restored if successful,
1187 * or false on failure
1189 * Overridden by LocalFile
1191 function restore( $versions = array(), $unsuppress = false ) {
1192 $this->readOnlyError();
1196 * Returns 'true' if this file is a type which supports multiple pages,
1197 * e.g. DJVU or PDF. Note that this may be true even if the file in
1198 * question only has a single page.
1202 function isMultipage() {
1203 return $this->getHandler() && $this->handler
->isMultiPage( $this );
1207 * Returns the number of pages of a multipage document, or false for
1208 * documents which aren't multipage documents
1212 function pageCount() {
1213 if ( !isset( $this->pageCount
) ) {
1214 if ( $this->getHandler() && $this->handler
->isMultiPage( $this ) ) {
1215 $this->pageCount
= $this->handler
->pageCount( $this );
1217 $this->pageCount
= false;
1220 return $this->pageCount
;
1224 * Calculate the height of a thumbnail using the source and destination width
1232 static function scaleHeight( $srcWidth, $srcHeight, $dstWidth ) {
1233 // Exact integer multiply followed by division
1234 if ( $srcWidth == 0 ) {
1237 return round( $srcHeight * $dstWidth / $srcWidth );
1242 * Get an image size array like that returned by getImageSize(), or false if it
1243 * can't be determined.
1245 * @param $fileName String: The filename
1248 function getImageSize( $fileName ) {
1249 if ( !$this->getHandler() ) {
1252 return $this->handler
->getImageSize( $this, $fileName );
1256 * Get the URL of the image description page. May return false if it is
1257 * unknown or not applicable.
1261 function getDescriptionUrl() {
1262 return $this->repo
->getDescriptionUrl( $this->getName() );
1266 * Get the HTML text of the description page, if available
1270 function getDescriptionText() {
1271 global $wgMemc, $wgLang;
1272 if ( !$this->repo
->fetchDescription
) {
1275 $renderUrl = $this->repo
->getDescriptionRenderUrl( $this->getName(), $wgLang->getCode() );
1277 if ( $this->repo
->descriptionCacheExpiry
> 0 ) {
1278 wfDebug("Attempting to get the description from cache...");
1279 $key = $this->repo
->getLocalCacheKey( 'RemoteFileDescription', 'url', $wgLang->getCode(),
1281 $obj = $wgMemc->get($key);
1283 wfDebug("success!\n");
1288 wfDebug( "Fetching shared description from $renderUrl\n" );
1289 $res = Http
::get( $renderUrl );
1290 if ( $res && $this->repo
->descriptionCacheExpiry
> 0 ) {
1291 $wgMemc->set( $key, $res, $this->repo
->descriptionCacheExpiry
);
1300 * Get discription of file revision
1305 function getDescription() {
1310 * Get the 14-character timestamp of the file upload, or false if
1315 function getTimestamp() {
1316 $path = $this->getPath();
1317 if ( !file_exists( $path ) ) {
1320 return wfTimestamp( TS_MW
, filemtime( $path ) );
1324 * Get the SHA-1 base 36 hash of the file
1328 function getSha1() {
1329 return self
::sha1Base36( $this->getPath() );
1333 * Get the deletion archive key, <sha1>.<ext>
1337 function getStorageKey() {
1338 $hash = $this->getSha1();
1342 $ext = $this->getExtension();
1343 $dotExt = $ext === '' ?
'' : ".$ext";
1344 return $hash . $dotExt;
1348 * Determine if the current user is allowed to view a particular
1349 * field of this file, if it's marked as deleted.
1351 * @param $field Integer
1354 function userCan( $field ) {
1359 * Get an associative array containing information about a file in the local filesystem.
1361 * @param $path String: absolute local filesystem path
1362 * @param $ext Mixed: the file extension, or true to extract it from the filename.
1363 * Set it to false to ignore the extension.
1367 static function getPropsFromPath( $path, $ext = true ) {
1368 wfProfileIn( __METHOD__
);
1369 wfDebug( __METHOD__
.": Getting file info for $path\n" );
1371 'fileExists' => file_exists( $path ) && !is_dir( $path )
1374 if ( $info['fileExists'] ) {
1375 $magic = MimeMagic
::singleton();
1377 if ( $ext === true ) {
1378 $i = strrpos( $path, '.' );
1379 $ext = strtolower( $i ?
substr( $path, $i +
1 ) : '' );
1382 # mime type according to file contents
1383 $info['file-mime'] = $magic->guessMimeType( $path, false );
1385 $info['mime'] = $magic->improveTypeFromExtension( $info['file-mime'], $ext );
1387 list( $info['major_mime'], $info['minor_mime'] ) = self
::splitMime( $info['mime'] );
1388 $info['media_type'] = $magic->getMediaType( $path, $info['mime'] );
1391 $info['size'] = filesize( $path );
1393 # Height, width and metadata
1394 $handler = MediaHandler
::getHandler( $info['mime'] );
1396 $tempImage = (object)array();
1397 $info['metadata'] = $handler->getMetadata( $tempImage, $path );
1398 $gis = $handler->getImageSize( $tempImage, $path, $info['metadata'] );
1401 $info['metadata'] = '';
1403 $info['sha1'] = self
::sha1Base36( $path );
1405 wfDebug(__METHOD__
.": $path loaded, {$info['size']} bytes, {$info['mime']}.\n");
1407 $info['mime'] = null;
1408 $info['media_type'] = MEDIATYPE_UNKNOWN
;
1409 $info['metadata'] = '';
1411 wfDebug(__METHOD__
.": $path NOT FOUND!\n");
1414 # NOTE: $gis[2] contains a code for the image type. This is no longer used.
1415 $info['width'] = $gis[0];
1416 $info['height'] = $gis[1];
1417 if ( isset( $gis['bits'] ) ) {
1418 $info['bits'] = $gis['bits'];
1424 $info['height'] = 0;
1427 wfProfileOut( __METHOD__
);
1432 * Get a SHA-1 hash of a file in the local filesystem, in base-36 lower case
1433 * encoding, zero padded to 31 digits.
1435 * 160 log 2 / log 36 = 30.95, so the 160-bit hash fills 31 digits in base 36
1438 * @param $path string
1440 * @return false|string False on failure
1442 static function sha1Base36( $path ) {
1443 wfSuppressWarnings();
1444 $hash = sha1_file( $path );
1445 wfRestoreWarnings();
1446 if ( $hash === false ) {
1449 return wfBaseConvert( $hash, 16, 36, 31 );
1456 function getLongDesc() {
1457 $handler = $this->getHandler();
1459 return $handler->getLongDesc( $this );
1461 return MediaHandler
::getGeneralLongDesc( $this );
1468 function getShortDesc() {
1469 $handler = $this->getHandler();
1471 return $handler->getShortDesc( $this );
1473 return MediaHandler
::getGeneralShortDesc( $this );
1480 function getDimensionsString() {
1481 $handler = $this->getHandler();
1483 return $handler->getDimensionsString( $this );
1492 function getRedirected() {
1493 return $this->redirected
;
1499 function getRedirectedTitle() {
1500 if ( $this->redirected
) {
1501 if ( !$this->redirectTitle
) {
1502 $this->redirectTitle
= Title
::makeTitle( NS_FILE
, $this->redirected
);
1504 return $this->redirectTitle
;
1512 function redirectedFrom( $from ) {
1513 $this->redirected
= $from;
1519 function isMissing() {
1524 * Aliases for backwards compatibility with 1.6
1526 define( 'MW_IMG_DELETED_FILE', File
::DELETED_FILE
);
1527 define( 'MW_IMG_DELETED_COMMENT', File
::DELETED_COMMENT
);
1528 define( 'MW_IMG_DELETED_USER', File
::DELETED_USER
);
1529 define( 'MW_IMG_DELETED_RESTRICTED', File
::DELETED_RESTRICTED
);