891a1e4e7fd1dc2977cfc2140f81cfbf68e039c3
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;
73 protected $url, $extension, $name, $path, $hashPath, $pageCount, $transformScript;
78 protected $canRender, $isSafeFile;
81 * Call this constructor from child classes
86 function __construct( $title, $repo ) {
87 $this->title
= $title;
91 function __get( $name ) {
92 $function = array( $this, 'get' . ucfirst( $name ) );
93 if ( !is_callable( $function ) ) {
96 $this->$name = call_user_func( $function );
102 * Normalize a file extension to the common form, and ensure it's clean.
103 * Extensions with non-alphanumeric characters will be discarded.
105 * @param $ext string (without the .)
108 static function normalizeExtension( $ext ) {
109 $lower = strtolower( $ext );
116 if( isset( $squish[$lower] ) ) {
117 return $squish[$lower];
118 } elseif( preg_match( '/^[0-9a-z]+$/', $lower ) ) {
126 * Checks if file extensions are compatible
128 * @param $old File Old file
129 * @param $new string New name
133 static function checkExtensionCompatibility( File
$old, $new ) {
134 $oldMime = $old->getMimeType();
135 $n = strrpos( $new, '.' );
136 $newExt = self
::normalizeExtension(
137 $n ?
substr( $new, $n +
1 ) : '' );
138 $mimeMagic = MimeMagic
::singleton();
139 return $mimeMagic->isMatchingExtension( $newExt, $oldMime );
143 * Upgrade the database row if there is one
144 * Called by ImagePage
147 function upgradeRow() {}
150 * Split an internet media type into its two components; if not
151 * a two-part name, set the minor type to 'unknown'.
153 * @param string $mime "text/html" etc
154 * @return array ("text", "html") etc
156 public static function splitMime( $mime ) {
157 if( strpos( $mime, '/' ) !== false ) {
158 return explode( '/', $mime, 2 );
160 return array( $mime, 'unknown' );
165 * Return the name of this file
169 public function getName() {
170 if ( !isset( $this->name
) ) {
171 $this->name
= $this->repo
->getNameFromTitle( $this->title
);
177 * Get the file extension, e.g. "svg"
181 function getExtension() {
182 if ( !isset( $this->extension
) ) {
183 $n = strrpos( $this->getName(), '.' );
184 $this->extension
= self
::normalizeExtension(
185 $n ?
substr( $this->getName(), $n +
1 ) : '' );
187 return $this->extension
;
191 * Return the associated title object
194 public function getTitle() { return $this->title
; }
197 * Return the title used to find this file
201 public function getOriginalTitle() {
202 if ( $this->redirected
) {
203 return $this->getRedirectedTitle();
209 * Return the URL of the file
213 public function getUrl() {
214 if ( !isset( $this->url
) ) {
215 $this->url
= $this->repo
->getZoneUrl( 'public' ) . '/' . $this->getUrlRel();
221 * Return a fully-qualified URL to the file.
222 * Upload URL paths _may or may not_ be fully qualified, so
223 * we check. Local paths are assumed to belong on $wgServer.
227 public function getFullUrl() {
228 return wfExpandUrl( $this->getUrl(), PROTO_RELATIVE
);
234 public function getCanonicalUrl() {
235 return wfExpandUrl( $this->getUrl(), PROTO_CANONICAL
);
241 function getViewURL() {
242 if( $this->mustRender()) {
243 if( $this->canRender() ) {
244 return $this->createThumb( $this->getWidth() );
246 wfDebug(__METHOD__
.': supposed to render '.$this->getName().' ('.$this->getMimeType()."), but can't!\n");
247 return $this->getURL(); #hm... return NULL?
250 return $this->getURL();
255 * Return the full filesystem path to the file. Note that this does
256 * not mean that a file actually exists under that location.
258 * This path depends on whether directory hashing is active or not,
259 * i.e. whether the files are all found in the same directory,
260 * or in hashed paths like /images/3/3c.
262 * Most callers don't check the return value, but ForeignAPIFile::getPath
265 * @return string|false
267 public function getPath() {
268 if ( !isset( $this->path
) ) {
269 $this->path
= $this->repo
->getZonePath('public') . '/' . $this->getRel();
275 * Alias for getPath()
277 * @deprecated since 1.18 Use getPath().
281 public function getFullPath() {
282 wfDeprecated( __METHOD__
);
283 return $this->getPath();
287 * Return the width of the image. Returns false if the width is unknown
291 * Overridden by LocalFile, UnregisteredLocalFile
297 public function getWidth( $page = 1 ) {
302 * Return the height of the image. Returns false if the height is unknown
306 * Overridden by LocalFile, UnregisteredLocalFile
310 * @return false|number
312 public function getHeight( $page = 1 ) {
317 * Returns ID or name of user who uploaded the file
320 * @param $type string 'text' or 'id'
324 public function getUser( $type = 'text' ) {
329 * Get the duration of a media file in seconds
333 public function getLength() {
334 $handler = $this->getHandler();
336 return $handler->getLength( $this );
343 * Return true if the file is vectorized
347 public function isVectorized() {
348 $handler = $this->getHandler();
350 return $handler->isVectorized( $this );
357 * Get handler-specific metadata
358 * Overridden by LocalFile, UnregisteredLocalFile
361 public function getMetadata() {
366 * get versioned metadata
368 * @param $metadata Mixed Array or String of (serialized) metadata
369 * @param $version integer version number.
370 * @return Array containing metadata, or what was passed to it on fail (unserializing if not array)
372 public function convertMetadataVersion($metadata, $version) {
373 $handler = $this->getHandler();
374 if ( !is_array( $metadata ) ) {
375 //just to make the return type consistant
376 $metadata = unserialize( $metadata );
379 return $handler->convertMetadataVersion( $metadata, $version );
386 * Return the bit depth of the file
387 * Overridden by LocalFile
390 public function getBitDepth() {
395 * Return the size of the image file, in bytes
396 * Overridden by LocalFile, UnregisteredLocalFile
399 public function getSize() {
404 * Returns the mime type of the file.
405 * Overridden by LocalFile, UnregisteredLocalFile
410 function getMimeType() {
411 return 'unknown/unknown';
415 * Return the type of the media in the file.
416 * Use the value returned by this function with the MEDIATYPE_xxx constants.
417 * Overridden by LocalFile,
420 function getMediaType() { return MEDIATYPE_UNKNOWN
; }
423 * Checks if the output of transform() for this file is likely
424 * to be valid. If this is false, various user elements will
425 * display a placeholder instead.
427 * Currently, this checks if the file is an image format
428 * that can be converted to a format
429 * supported by all browsers (namely GIF, PNG and JPEG),
430 * or if it is an SVG image and SVG conversion is enabled.
434 function canRender() {
435 if ( !isset( $this->canRender
) ) {
436 $this->canRender
= $this->getHandler() && $this->handler
->canRender( $this );
438 return $this->canRender
;
442 * Accessor for __get()
444 protected function getCanRender() {
445 return $this->canRender();
449 * Return true if the file is of a type that can't be directly
450 * rendered by typical browsers and needs to be re-rasterized.
452 * This returns true for everything but the bitmap types
453 * supported by all browsers, i.e. JPEG; GIF and PNG. It will
454 * also return true for any non-image formats.
458 function mustRender() {
459 return $this->getHandler() && $this->handler
->mustRender( $this );
463 * Alias for canRender()
467 function allowInlineDisplay() {
468 return $this->canRender();
472 * Determines if this media file is in a format that is unlikely to
473 * contain viruses or malicious content. It uses the global
474 * $wgTrustedMediaFormats list to determine if the file is safe.
476 * This is used to show a warning on the description page of non-safe files.
477 * It may also be used to disallow direct [[media:...]] links to such files.
479 * Note that this function will always return true if allowInlineDisplay()
480 * or isTrustedFile() is true for this file.
484 function isSafeFile() {
485 if ( !isset( $this->isSafeFile
) ) {
486 $this->isSafeFile
= $this->_getIsSafeFile();
488 return $this->isSafeFile
;
492 * Accessor for __get()
496 protected function getIsSafeFile() {
497 return $this->isSafeFile();
505 protected function _getIsSafeFile() {
506 if ( $this->allowInlineDisplay() ) {
509 if ($this->isTrustedFile()) {
513 global $wgTrustedMediaFormats;
515 $type = $this->getMediaType();
516 $mime = $this->getMimeType();
517 #wfDebug("LocalFile::isSafeFile: type= $type, mime= $mime\n");
519 if ( !$type ||
$type === MEDIATYPE_UNKNOWN
) {
520 return false; #unknown type, not trusted
522 if ( in_array( $type, $wgTrustedMediaFormats ) ) {
526 if ( $mime === "unknown/unknown" ) {
527 return false; #unknown type, not trusted
529 if ( in_array( $mime, $wgTrustedMediaFormats) ) {
537 * Returns true if the file is flagged as trusted. Files flagged that way
538 * can be linked to directly, even if that is not allowed for this type of
541 * This is a dummy function right now and always returns false. It could be
542 * implemented to extract a flag from the database. The trusted flag could be
543 * set on upload, if the user has sufficient privileges, to bypass script-
544 * and html-filters. It may even be coupled with cryptographics signatures
549 function isTrustedFile() {
550 #this could be implemented to check a flag in the databas,
551 #look for signatures, etc
556 * Returns true if file exists in the repository.
558 * Overridden by LocalFile to avoid unnecessary stat calls.
560 * @return boolean Whether file exists in the repository.
562 public function exists() {
563 return $this->getPath() && file_exists( $this->path
);
567 * Returns true if file exists in the repository and can be included in a page.
568 * It would be unsafe to include private images, making public thumbnails inadvertently
570 * @return boolean Whether file exists in the repository and is includable.
572 public function isVisible() {
573 return $this->exists();
579 function getTransformScript() {
580 if ( !isset( $this->transformScript
) ) {
581 $this->transformScript
= false;
583 $script = $this->repo
->getThumbScriptUrl();
585 $this->transformScript
= "$script?f=" . urlencode( $this->getName() );
589 return $this->transformScript
;
593 * Get a ThumbnailImage which is the same size as the source
595 * @param $handlerParams array
599 function getUnscaledThumb( $handlerParams = array() ) {
600 $hp =& $handlerParams;
601 $page = isset( $hp['page'] ) ?
$hp['page'] : false;
602 $width = $this->getWidth( $page );
604 return $this->iconThumb();
606 $hp['width'] = $width;
607 return $this->transform( $hp );
611 * Return the file name of a thumbnail with the specified parameters
613 * @param $params Array: handler-specific parameters
618 function thumbName( $params ) {
619 return $this->generateThumbName( $this->getName(), $params );
623 * Generate a thumbnail file name from a name and specified parameters
625 * @param string $name
626 * @param array $params Parameters which will be passed to MediaHandler::makeParamString
630 function generateThumbName( $name, $params ) {
631 if ( !$this->getHandler() ) {
634 $extension = $this->getExtension();
635 list( $thumbExt, $thumbMime ) = $this->handler
->getThumbType( $extension, $this->getMimeType(), $params );
636 $thumbName = $this->handler
->makeParamString( $params ) . '-' . $name;
637 if ( $thumbExt != $extension ) {
638 $thumbName .= ".$thumbExt";
644 * Create a thumbnail of the image having the specified width/height.
645 * The thumbnail will not be created if the width is larger than the
646 * image's width. Let the browser do the scaling in this case.
647 * The thumbnail is stored on disk and is only computed if the thumbnail
648 * file does not exist OR if it is older than the image.
651 * Keeps aspect ratio of original image. If both width and height are
652 * specified, the generated image will be no bigger than width x height,
653 * and will also have correct aspect ratio.
655 * @param $width Integer: maximum width of the generated thumbnail
656 * @param $height Integer: maximum height of the image (optional)
660 public function createThumb( $width, $height = -1 ) {
661 $params = array( 'width' => $width );
662 if ( $height != -1 ) {
663 $params['height'] = $height;
665 $thumb = $this->transform( $params );
666 if( is_null( $thumb ) ||
$thumb->isError() ) return '';
667 return $thumb->getUrl();
671 * Transform a media file
673 * @param $params Array: an associative array of handler-specific parameters.
674 * Typical keys are width, height and page.
675 * @param $flags Integer: a bitfield, may contain self::RENDER_NOW to force rendering
676 * @return MediaTransformOutput | false
678 function transform( $params, $flags = 0 ) {
679 global $wgUseSquid, $wgIgnoreImageErrors, $wgThumbnailEpoch, $wgServer;
681 wfProfileIn( __METHOD__
);
683 if ( !$this->canRender() ) {
684 // not a bitmap or renderable image, don't try.
685 $thumb = $this->iconThumb();
689 // Get the descriptionUrl to embed it as comment into the thumbnail. Bug 19791.
690 $descriptionUrl = $this->getDescriptionUrl();
691 if ( $descriptionUrl ) {
692 $params['descriptionUrl'] = $wgServer . $descriptionUrl;
695 $script = $this->getTransformScript();
696 if ( $script && !($flags & self
::RENDER_NOW
) ) {
697 // Use a script to transform on client request, if possible
698 $thumb = $this->handler
->getScriptedTransform( $this, $script, $params );
704 $normalisedParams = $params;
705 $this->handler
->normaliseParams( $this, $normalisedParams );
706 $thumbName = $this->thumbName( $normalisedParams );
707 $thumbPath = $this->getThumbPath( $thumbName );
708 $thumbUrl = $this->getThumbUrl( $thumbName );
710 if ( $this->repo
&& $this->repo
->canTransformVia404() && !($flags & self
::RENDER_NOW
) ) {
711 $thumb = $this->handler
->getTransform( $this, $thumbPath, $thumbUrl, $params );
715 wfDebug( __METHOD__
.": Doing stat for $thumbPath\n" );
716 $this->migrateThumbFile( $thumbName );
717 if ( file_exists( $thumbPath )) {
718 $thumbTime = filemtime( $thumbPath );
719 if ( $thumbTime !== FALSE &&
720 gmdate( 'YmdHis', $thumbTime ) >= $wgThumbnailEpoch ) {
722 $thumb = $this->handler
->getTransform( $this, $thumbPath, $thumbUrl, $params );
726 $thumb = $this->handler
->doTransform( $this, $thumbPath, $thumbUrl, $params );
728 // Ignore errors if requested
731 } elseif ( $thumb->isError() ) {
732 $this->lastError
= $thumb->toText();
733 if ( $wgIgnoreImageErrors && !($flags & self
::RENDER_NOW
) ) {
734 $thumb = $this->handler
->getTransform( $this, $thumbPath, $thumbUrl, $params );
738 // Purge. Useful in the event of Core -> Squid connection failure or squid
739 // purge collisions from elsewhere during failure. Don't keep triggering for
740 // "thumbs" which have the main image URL though (bug 13776)
741 if ( $wgUseSquid && ( !$thumb ||
$thumb->isError() ||
$thumb->getUrl() != $this->getURL()) ) {
742 SquidUpdate
::purge( array( $thumbUrl ) );
746 wfProfileOut( __METHOD__
);
747 return is_object( $thumb ) ?
$thumb : false;
751 * Hook into transform() to allow migration of thumbnail files
753 * Overridden by LocalFile
755 function migrateThumbFile( $thumbName ) {}
758 * Get a MediaHandler instance for this file
759 * @return MediaHandler
761 function getHandler() {
762 if ( !isset( $this->handler
) ) {
763 $this->handler
= MediaHandler
::getHandler( $this->getMimeType() );
765 return $this->handler
;
769 * Get a ThumbnailImage representing a file type icon
770 * @return ThumbnailImage
772 function iconThumb() {
773 global $wgStylePath, $wgStyleDirectory;
775 $try = array( 'fileicon-' . $this->getExtension() . '.png', 'fileicon.png' );
776 foreach( $try as $icon ) {
777 $path = '/common/images/icons/' . $icon;
778 $filepath = $wgStyleDirectory . $path;
779 if( file_exists( $filepath ) ) {
780 return new ThumbnailImage( $this, $wgStylePath . $path, 120, 120 );
787 * Get last thumbnailing error.
790 function getLastError() {
791 return $this->lastError
;
795 * Get all thumbnail names previously generated for this file
797 * Overridden by LocalFile
799 function getThumbnails() {
804 * Purge shared caches such as thumbnails and DB data caching
806 * Overridden by LocalFile
808 function purgeCache() {}
811 * Purge the file description page, but don't go after
812 * pages using the file. Use when modifying file history
813 * but not the current data.
815 function purgeDescription() {
816 $title = $this->getTitle();
818 $title->invalidateCache();
819 $title->purgeSquid();
824 * Purge metadata and all affected pages when the file is created,
825 * deleted, or majorly updated.
827 function purgeEverything() {
828 // Delete thumbnails and refresh file metadata cache
830 $this->purgeDescription();
832 // Purge cache of all pages using this file
833 $title = $this->getTitle();
835 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
841 * Return a fragment of the history of file.
844 * @param $limit integer Limit of rows to return
845 * @param $start timestamp Only revisions older than $start will be returned
846 * @param $end timestamp Only revisions newer than $end will be returned
847 * @param $inc bool Include the endpoints of the time range
851 function getHistory($limit = null, $start = null, $end = null, $inc=true) {
856 * Return the history of this file, line by line. Starts with current version,
857 * then old versions. Should return an object similar to an image/oldimage
861 * Overridden in LocalFile
863 public function nextHistoryLine() {
868 * Reset the history pointer to the first element of the history.
869 * Always call this function after using nextHistoryLine() to free db resources
871 * Overridden in LocalFile.
873 public function resetHistory() {}
876 * Get the filename hash component of the directory including trailing slash,
878 * If the repository is not hashed, returns an empty string.
882 function getHashPath() {
883 if ( !isset( $this->hashPath
) ) {
884 $this->hashPath
= $this->repo
->getHashPath( $this->getName() );
886 return $this->hashPath
;
890 * Get the path of the file relative to the public zone root
895 return $this->getHashPath() . $this->getName();
899 * Get urlencoded relative path of the file
903 function getUrlRel() {
904 return $this->getHashPath() . rawurlencode( $this->getName() );
908 * Get the relative path for an archived file
910 * @param $suffix bool|string if not false, the name of an archived thumbnail file
914 function getArchiveRel( $suffix = false ) {
915 $path = 'archive/' . $this->getHashPath();
916 if ( $suffix === false ) {
917 $path = substr( $path, 0, -1 );
925 * Get the relative path for an archived file's thumbs directory
926 * or a specific thumb if the $suffix is given.
928 * @param $archiveName string the timestamped name of an archived image
929 * @param $suffix bool|string if not false, the name of a thumbnail file
933 function getArchiveThumbRel( $archiveName, $suffix = false ) {
934 $path = 'archive/' . $this->getHashPath() . $archiveName . "/";
935 if ( $suffix === false ) {
936 $path = substr( $path, 0, -1 );
944 * Get the path of the archived file.
946 * @param $suffix bool|string if not false, the name of an archived file.
950 function getArchivePath( $suffix = false ) {
951 return $this->repo
->getZonePath( 'public' ) . '/' . $this->getArchiveRel( $suffix );
955 * Get the path of the archived file's thumbs, or a particular thumb if $suffix is specified
957 * @param $archiveName string the timestamped name of an archived image
958 * @param $suffix bool|string if not false, the name of a thumbnail file
962 function getArchiveThumbPath( $archiveName, $suffix = false ) {
963 return $this->repo
->getZonePath( 'thumb' ) . '/' . $this->getArchiveThumbRel( $archiveName, $suffix );
967 * Get the path of the thumbnail directory, or a particular file if $suffix is specified
969 * @param $suffix bool|string if not false, the name of a thumbnail file
973 function getThumbPath( $suffix = false ) {
974 $path = $this->repo
->getZonePath( 'thumb' ) . '/' . $this->getRel();
975 if ( $suffix !== false ) {
976 $path .= '/' . $suffix;
982 * Get the URL of the archive directory, or a particular file if $suffix is specified
984 * @param $suffix bool|string if not false, the name of an archived file
988 function getArchiveUrl( $suffix = false ) {
989 $path = $this->repo
->getZoneUrl('public') . '/archive/' . $this->getHashPath();
990 if ( $suffix === false ) {
991 $path = substr( $path, 0, -1 );
993 $path .= rawurlencode( $suffix );
999 * Get the URL of the archived file's thumbs, or a particular thumb if $suffix is specified
1001 * @param $archiveName string the timestamped name of an archived image
1002 * @param $suffix bool|string if not false, the name of a thumbnail file
1006 function getArchiveThumbUrl( $archiveName, $suffix = false ) {
1007 $path = $this->repo
->getZoneUrl('thumb') . '/archive/' . $this->getHashPath() . rawurlencode( $archiveName ) . "/";
1008 if ( $suffix === false ) {
1009 $path = substr( $path, 0, -1 );
1011 $path .= rawurlencode( $suffix );
1017 * Get the URL of the thumbnail directory, or a particular file if $suffix is specified
1019 * @param $suffix bool|string if not false, the name of a thumbnail file
1023 function getThumbUrl( $suffix = false ) {
1024 $path = $this->repo
->getZoneUrl('thumb') . '/' . $this->getUrlRel();
1025 if ( $suffix !== false ) {
1026 $path .= '/' . rawurlencode( $suffix );
1032 * Get the virtual URL for an archived file's thumbs, or a specific thumb.
1034 * @param $suffix bool|string if not false, the name of a thumbnail file
1038 function getArchiveVirtualUrl( $suffix = false ) {
1039 $path = $this->repo
->getVirtualUrl() . '/public/archive/' . $this->getHashPath();
1040 if ( $suffix === false ) {
1041 $path = substr( $path, 0, -1 );
1043 $path .= rawurlencode( $suffix );
1049 * Get the virtual URL for a thumbnail file or directory
1051 * @param $suffix bool|string if not false, the name of a thumbnail file
1055 function getThumbVirtualUrl( $suffix = false ) {
1056 $path = $this->repo
->getVirtualUrl() . '/thumb/' . $this->getUrlRel();
1057 if ( $suffix !== false ) {
1058 $path .= '/' . rawurlencode( $suffix );
1064 * Get the virtual URL for the file itself
1066 * @param $suffix bool|string if not false, the name of a thumbnail file
1070 function getVirtualUrl( $suffix = false ) {
1071 $path = $this->repo
->getVirtualUrl() . '/public/' . $this->getUrlRel();
1072 if ( $suffix !== false ) {
1073 $path .= '/' . rawurlencode( $suffix );
1081 function isHashed() {
1082 return $this->repo
->isHashed();
1086 * @throws MWException
1088 function readOnlyError() {
1089 throw new MWException( get_class($this) . ': write operations are not supported' );
1093 * Record a file upload in the upload log and the image table
1095 * Overridden by LocalFile
1098 * @param $license string
1099 * @param $copyStatus string
1100 * @param $source string
1101 * @param $watch bool
1103 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '', $watch = false ) {
1104 $this->readOnlyError();
1108 * Move or copy a file to its public location. If a file exists at the
1109 * destination, move it to an archive. Returns a FileRepoStatus object with
1110 * the archive name in the "value" member on success.
1112 * The archive name should be passed through to recordUpload for database
1115 * @param $srcPath String: local filesystem path to the source image
1116 * @param $flags Integer: a bitwise combination of:
1117 * File::DELETE_SOURCE Delete the source file, i.e. move
1119 * @return FileRepoStatus object. On success, the value member contains the
1120 * archive name, or an empty string if it was a new file.
1123 * Overridden by LocalFile
1125 function publish( $srcPath, $flags = 0 ) {
1126 $this->readOnlyError();
1132 function formatMetadata() {
1133 if ( !$this->getHandler() ) {
1136 return $this->getHandler()->formatMetadata( $this, $this->getMetadata() );
1140 * Returns true if the file comes from the local file repository.
1144 function isLocal() {
1145 $repo = $this->getRepo();
1146 return $repo && $repo->isLocal();
1150 * Returns the name of the repository.
1154 function getRepoName() {
1155 return $this->repo ?
$this->repo
->getName() : 'unknown';
1159 * Returns the repository
1163 function getRepo() {
1168 * Returns true if the image is an old version
1178 * Is this file a "deleted" file in a private archive?
1185 function isDeleted( $field ) {
1190 * Return the deletion bitfield
1193 function getVisibility() {
1198 * Was this file ever deleted from the wiki?
1202 function wasDeleted() {
1203 $title = $this->getTitle();
1204 return $title && $title->isDeletedQuick();
1208 * Move file to the new title
1210 * Move current, old version and all thumbnails
1211 * to the new filename. Old file is deleted.
1213 * Cache purging is done; checks for validity
1214 * and logging are caller's responsibility
1216 * @param $target Title New file name
1217 * @return FileRepoStatus object.
1219 function move( $target ) {
1220 $this->readOnlyError();
1224 * Delete all versions of the file.
1226 * Moves the files into an archive directory (or deletes them)
1227 * and removes the database rows.
1229 * Cache purging is done; logging is caller's responsibility.
1231 * @param $reason String
1232 * @param $suppress Boolean: hide content from sysops?
1233 * @return true on success, false on some kind of failure
1235 * Overridden by LocalFile
1237 function delete( $reason, $suppress = false ) {
1238 $this->readOnlyError();
1242 * Restore all or specified deleted revisions to the given file.
1243 * Permissions and logging are left to the caller.
1245 * May throw database exceptions on error.
1247 * @param $versions array set of record ids of deleted items to restore,
1248 * or empty to restore all revisions.
1249 * @param $unsuppress bool remove restrictions on content upon restoration?
1250 * @return int|false the number of file revisions restored if successful,
1251 * or false on failure
1253 * Overridden by LocalFile
1255 function restore( $versions = array(), $unsuppress = false ) {
1256 $this->readOnlyError();
1260 * Returns 'true' if this file is a type which supports multiple pages,
1261 * e.g. DJVU or PDF. Note that this may be true even if the file in
1262 * question only has a single page.
1266 function isMultipage() {
1267 return $this->getHandler() && $this->handler
->isMultiPage( $this );
1271 * Returns the number of pages of a multipage document, or false for
1272 * documents which aren't multipage documents
1276 function pageCount() {
1277 if ( !isset( $this->pageCount
) ) {
1278 if ( $this->getHandler() && $this->handler
->isMultiPage( $this ) ) {
1279 $this->pageCount
= $this->handler
->pageCount( $this );
1281 $this->pageCount
= false;
1284 return $this->pageCount
;
1288 * Calculate the height of a thumbnail using the source and destination width
1296 static function scaleHeight( $srcWidth, $srcHeight, $dstWidth ) {
1297 // Exact integer multiply followed by division
1298 if ( $srcWidth == 0 ) {
1301 return round( $srcHeight * $dstWidth / $srcWidth );
1306 * Get an image size array like that returned by getImageSize(), or false if it
1307 * can't be determined.
1309 * @param $fileName String: The filename
1312 function getImageSize( $fileName ) {
1313 if ( !$this->getHandler() ) {
1316 return $this->handler
->getImageSize( $this, $fileName );
1320 * Get the URL of the image description page. May return false if it is
1321 * unknown or not applicable.
1325 function getDescriptionUrl() {
1326 return $this->repo
->getDescriptionUrl( $this->getName() );
1330 * Get the HTML text of the description page, if available
1334 function getDescriptionText() {
1335 global $wgMemc, $wgLang;
1336 if ( !$this->repo
->fetchDescription
) {
1339 $renderUrl = $this->repo
->getDescriptionRenderUrl( $this->getName(), $wgLang->getCode() );
1341 if ( $this->repo
->descriptionCacheExpiry
> 0 ) {
1342 wfDebug("Attempting to get the description from cache...");
1343 $key = $this->repo
->getLocalCacheKey( 'RemoteFileDescription', 'url', $wgLang->getCode(),
1345 $obj = $wgMemc->get($key);
1347 wfDebug("success!\n");
1352 wfDebug( "Fetching shared description from $renderUrl\n" );
1353 $res = Http
::get( $renderUrl );
1354 if ( $res && $this->repo
->descriptionCacheExpiry
> 0 ) {
1355 $wgMemc->set( $key, $res, $this->repo
->descriptionCacheExpiry
);
1364 * Get discription of file revision
1369 function getDescription() {
1374 * Get the 14-character timestamp of the file upload, or false if
1379 function getTimestamp() {
1380 $path = $this->getPath();
1381 if ( !file_exists( $path ) ) {
1384 return wfTimestamp( TS_MW
, filemtime( $path ) );
1388 * Get the SHA-1 base 36 hash of the file
1392 function getSha1() {
1393 return self
::sha1Base36( $this->getPath() );
1397 * Get the deletion archive key, <sha1>.<ext>
1401 function getStorageKey() {
1402 $hash = $this->getSha1();
1406 $ext = $this->getExtension();
1407 $dotExt = $ext === '' ?
'' : ".$ext";
1408 return $hash . $dotExt;
1412 * Determine if the current user is allowed to view a particular
1413 * field of this file, if it's marked as deleted.
1415 * @param $field Integer
1418 function userCan( $field ) {
1423 * Get an associative array containing information about a file in the local filesystem.
1425 * @param $path String: absolute local filesystem path
1426 * @param $ext Mixed: the file extension, or true to extract it from the filename.
1427 * Set it to false to ignore the extension.
1431 static function getPropsFromPath( $path, $ext = true ) {
1432 wfProfileIn( __METHOD__
);
1433 wfDebug( __METHOD__
.": Getting file info for $path\n" );
1435 'fileExists' => file_exists( $path ) && !is_dir( $path )
1438 if ( $info['fileExists'] ) {
1439 $magic = MimeMagic
::singleton();
1441 if ( $ext === true ) {
1442 $i = strrpos( $path, '.' );
1443 $ext = strtolower( $i ?
substr( $path, $i +
1 ) : '' );
1446 # mime type according to file contents
1447 $info['file-mime'] = $magic->guessMimeType( $path, false );
1449 $info['mime'] = $magic->improveTypeFromExtension( $info['file-mime'], $ext );
1451 list( $info['major_mime'], $info['minor_mime'] ) = self
::splitMime( $info['mime'] );
1452 $info['media_type'] = $magic->getMediaType( $path, $info['mime'] );
1455 $info['size'] = filesize( $path );
1457 # Height, width and metadata
1458 $handler = MediaHandler
::getHandler( $info['mime'] );
1460 $tempImage = (object)array();
1461 $info['metadata'] = $handler->getMetadata( $tempImage, $path );
1462 $gis = $handler->getImageSize( $tempImage, $path, $info['metadata'] );
1465 $info['metadata'] = '';
1467 $info['sha1'] = self
::sha1Base36( $path );
1469 wfDebug(__METHOD__
.": $path loaded, {$info['size']} bytes, {$info['mime']}.\n");
1471 $info['mime'] = null;
1472 $info['media_type'] = MEDIATYPE_UNKNOWN
;
1473 $info['metadata'] = '';
1475 wfDebug(__METHOD__
.": $path NOT FOUND!\n");
1478 # NOTE: $gis[2] contains a code for the image type. This is no longer used.
1479 $info['width'] = $gis[0];
1480 $info['height'] = $gis[1];
1481 if ( isset( $gis['bits'] ) ) {
1482 $info['bits'] = $gis['bits'];
1488 $info['height'] = 0;
1491 wfProfileOut( __METHOD__
);
1496 * Get a SHA-1 hash of a file in the local filesystem, in base-36 lower case
1497 * encoding, zero padded to 31 digits.
1499 * 160 log 2 / log 36 = 30.95, so the 160-bit hash fills 31 digits in base 36
1502 * @param $path string
1504 * @return false|string False on failure
1506 static function sha1Base36( $path ) {
1507 wfSuppressWarnings();
1508 $hash = sha1_file( $path );
1509 wfRestoreWarnings();
1510 if ( $hash === false ) {
1513 return wfBaseConvert( $hash, 16, 36, 31 );
1520 function getLongDesc() {
1521 $handler = $this->getHandler();
1523 return $handler->getLongDesc( $this );
1525 return MediaHandler
::getGeneralLongDesc( $this );
1532 function getShortDesc() {
1533 $handler = $this->getHandler();
1535 return $handler->getShortDesc( $this );
1537 return MediaHandler
::getGeneralShortDesc( $this );
1544 function getDimensionsString() {
1545 $handler = $this->getHandler();
1547 return $handler->getDimensionsString( $this );
1556 function getRedirected() {
1557 return $this->redirected
;
1563 function getRedirectedTitle() {
1564 if ( $this->redirected
) {
1565 if ( !$this->redirectTitle
) {
1566 $this->redirectTitle
= Title
::makeTitle( NS_FILE
, $this->redirected
);
1568 return $this->redirectTitle
;
1576 function redirectedFrom( $from ) {
1577 $this->redirected
= $from;
1583 function isMissing() {
1588 * Aliases for backwards compatibility with 1.6
1590 define( 'MW_IMG_DELETED_FILE', File
::DELETED_FILE
);
1591 define( 'MW_IMG_DELETED_COMMENT', File
::DELETED_COMMENT
);
1592 define( 'MW_IMG_DELETED_USER', File
::DELETED_USER
);
1593 define( 'MW_IMG_DELETED_RESTRICTED', File
::DELETED_RESTRICTED
);