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 * Return the width of the image. Returns false if the width is unknown
279 * Overridden by LocalFile, UnregisteredLocalFile
285 public function getWidth( $page = 1 ) {
290 * Return the height of the image. Returns false if the height is unknown
294 * Overridden by LocalFile, UnregisteredLocalFile
298 * @return false|number
300 public function getHeight( $page = 1 ) {
305 * Returns ID or name of user who uploaded the file
308 * @param $type string 'text' or 'id'
312 public function getUser( $type = 'text' ) {
317 * Get the duration of a media file in seconds
321 public function getLength() {
322 $handler = $this->getHandler();
324 return $handler->getLength( $this );
331 * Return true if the file is vectorized
335 public function isVectorized() {
336 $handler = $this->getHandler();
338 return $handler->isVectorized( $this );
345 * Get handler-specific metadata
346 * Overridden by LocalFile, UnregisteredLocalFile
349 public function getMetadata() {
354 * get versioned metadata
356 * @param $metadata Mixed Array or String of (serialized) metadata
357 * @param $version integer version number.
358 * @return Array containing metadata, or what was passed to it on fail (unserializing if not array)
360 public function convertMetadataVersion($metadata, $version) {
361 $handler = $this->getHandler();
362 if ( !is_array( $metadata ) ) {
363 //just to make the return type consistant
364 $metadata = unserialize( $metadata );
367 return $handler->convertMetadataVersion( $metadata, $version );
374 * Return the bit depth of the file
375 * Overridden by LocalFile
378 public function getBitDepth() {
383 * Return the size of the image file, in bytes
384 * Overridden by LocalFile, UnregisteredLocalFile
387 public function getSize() {
392 * Returns the mime type of the file.
393 * Overridden by LocalFile, UnregisteredLocalFile
398 function getMimeType() {
399 return 'unknown/unknown';
403 * Return the type of the media in the file.
404 * Use the value returned by this function with the MEDIATYPE_xxx constants.
405 * Overridden by LocalFile,
408 function getMediaType() { return MEDIATYPE_UNKNOWN
; }
411 * Checks if the output of transform() for this file is likely
412 * to be valid. If this is false, various user elements will
413 * display a placeholder instead.
415 * Currently, this checks if the file is an image format
416 * that can be converted to a format
417 * supported by all browsers (namely GIF, PNG and JPEG),
418 * or if it is an SVG image and SVG conversion is enabled.
422 function canRender() {
423 if ( !isset( $this->canRender
) ) {
424 $this->canRender
= $this->getHandler() && $this->handler
->canRender( $this );
426 return $this->canRender
;
430 * Accessor for __get()
432 protected function getCanRender() {
433 return $this->canRender();
437 * Return true if the file is of a type that can't be directly
438 * rendered by typical browsers and needs to be re-rasterized.
440 * This returns true for everything but the bitmap types
441 * supported by all browsers, i.e. JPEG; GIF and PNG. It will
442 * also return true for any non-image formats.
446 function mustRender() {
447 return $this->getHandler() && $this->handler
->mustRender( $this );
451 * Alias for canRender()
455 function allowInlineDisplay() {
456 return $this->canRender();
460 * Determines if this media file is in a format that is unlikely to
461 * contain viruses or malicious content. It uses the global
462 * $wgTrustedMediaFormats list to determine if the file is safe.
464 * This is used to show a warning on the description page of non-safe files.
465 * It may also be used to disallow direct [[media:...]] links to such files.
467 * Note that this function will always return true if allowInlineDisplay()
468 * or isTrustedFile() is true for this file.
472 function isSafeFile() {
473 if ( !isset( $this->isSafeFile
) ) {
474 $this->isSafeFile
= $this->_getIsSafeFile();
476 return $this->isSafeFile
;
480 * Accessor for __get()
484 protected function getIsSafeFile() {
485 return $this->isSafeFile();
493 protected function _getIsSafeFile() {
494 if ( $this->allowInlineDisplay() ) {
497 if ($this->isTrustedFile()) {
501 global $wgTrustedMediaFormats;
503 $type = $this->getMediaType();
504 $mime = $this->getMimeType();
505 #wfDebug("LocalFile::isSafeFile: type= $type, mime= $mime\n");
507 if ( !$type ||
$type === MEDIATYPE_UNKNOWN
) {
508 return false; #unknown type, not trusted
510 if ( in_array( $type, $wgTrustedMediaFormats ) ) {
514 if ( $mime === "unknown/unknown" ) {
515 return false; #unknown type, not trusted
517 if ( in_array( $mime, $wgTrustedMediaFormats) ) {
525 * Returns true if the file is flagged as trusted. Files flagged that way
526 * can be linked to directly, even if that is not allowed for this type of
529 * This is a dummy function right now and always returns false. It could be
530 * implemented to extract a flag from the database. The trusted flag could be
531 * set on upload, if the user has sufficient privileges, to bypass script-
532 * and html-filters. It may even be coupled with cryptographics signatures
537 function isTrustedFile() {
538 #this could be implemented to check a flag in the databas,
539 #look for signatures, etc
544 * Returns true if file exists in the repository.
546 * Overridden by LocalFile to avoid unnecessary stat calls.
548 * @return boolean Whether file exists in the repository.
550 public function exists() {
551 return $this->getPath() && file_exists( $this->path
);
555 * Returns true if file exists in the repository and can be included in a page.
556 * It would be unsafe to include private images, making public thumbnails inadvertently
558 * @return boolean Whether file exists in the repository and is includable.
560 public function isVisible() {
561 return $this->exists();
567 function getTransformScript() {
568 if ( !isset( $this->transformScript
) ) {
569 $this->transformScript
= false;
571 $script = $this->repo
->getThumbScriptUrl();
573 $this->transformScript
= "$script?f=" . urlencode( $this->getName() );
577 return $this->transformScript
;
581 * Get a ThumbnailImage which is the same size as the source
583 * @param $handlerParams array
587 function getUnscaledThumb( $handlerParams = array() ) {
588 $hp =& $handlerParams;
589 $page = isset( $hp['page'] ) ?
$hp['page'] : false;
590 $width = $this->getWidth( $page );
592 return $this->iconThumb();
594 $hp['width'] = $width;
595 return $this->transform( $hp );
599 * Return the file name of a thumbnail with the specified parameters
601 * @param $params Array: handler-specific parameters
606 function thumbName( $params ) {
607 return $this->generateThumbName( $this->getName(), $params );
611 * Generate a thumbnail file name from a name and specified parameters
613 * @param string $name
614 * @param array $params Parameters which will be passed to MediaHandler::makeParamString
618 function generateThumbName( $name, $params ) {
619 if ( !$this->getHandler() ) {
622 $extension = $this->getExtension();
623 list( $thumbExt, $thumbMime ) = $this->handler
->getThumbType( $extension, $this->getMimeType(), $params );
624 $thumbName = $this->handler
->makeParamString( $params ) . '-' . $name;
625 if ( $thumbExt != $extension ) {
626 $thumbName .= ".$thumbExt";
632 * Create a thumbnail of the image having the specified width/height.
633 * The thumbnail will not be created if the width is larger than the
634 * image's width. Let the browser do the scaling in this case.
635 * The thumbnail is stored on disk and is only computed if the thumbnail
636 * file does not exist OR if it is older than the image.
639 * Keeps aspect ratio of original image. If both width and height are
640 * specified, the generated image will be no bigger than width x height,
641 * and will also have correct aspect ratio.
643 * @param $width Integer: maximum width of the generated thumbnail
644 * @param $height Integer: maximum height of the image (optional)
648 public function createThumb( $width, $height = -1 ) {
649 $params = array( 'width' => $width );
650 if ( $height != -1 ) {
651 $params['height'] = $height;
653 $thumb = $this->transform( $params );
654 if( is_null( $thumb ) ||
$thumb->isError() ) return '';
655 return $thumb->getUrl();
659 * Do the work of a transform (from an original into a thumb).
660 * Contains filesystem-specific functions.
662 * @param $thumbName string: the name of the thumbnail file.
663 * @param $thumbUrl string: the URL of the thumbnail file.
664 * @param $params Array: an associative array of handler-specific parameters.
665 * Typical keys are width, height and page.
666 * @param $flags Integer: a bitfield, may contain self::RENDER_NOW to force rendering
668 * @return MediaTransformOutput | false
670 protected function maybeDoTransform( $thumbName, $thumbUrl, $params, $flags = 0 ) {
671 global $wgIgnoreImageErrors, $wgThumbnailEpoch;
673 $thumbPath = $this->getThumbPath( $thumbName );
674 if ( $this->repo
&& $this->repo
->canTransformVia404() && !($flags & self
::RENDER_NOW
) ) {
675 return $this->handler
->getTransform( $this, $thumbPath, $thumbUrl, $params );
678 wfDebug( __METHOD__
.": Doing stat for $thumbPath\n" );
679 $this->migrateThumbFile( $thumbName );
680 if ( file_exists( $thumbPath )) {
681 $thumbTime = filemtime( $thumbPath );
682 if ( $thumbTime !== FALSE &&
683 gmdate( 'YmdHis', $thumbTime ) >= $wgThumbnailEpoch ) {
685 return $this->handler
->getTransform( $this, $thumbPath, $thumbUrl, $params );
688 $thumb = $this->handler
->doTransform( $this, $thumbPath, $thumbUrl, $params );
690 // Ignore errors if requested
693 } elseif ( $thumb->isError() ) {
694 $this->lastError
= $thumb->toText();
695 if ( $wgIgnoreImageErrors && !($flags & self
::RENDER_NOW
) ) {
696 $thumb = $this->handler
->getTransform( $this, $thumbPath, $thumbUrl, $params );
705 * Transform a media file
707 * @param $params Array: an associative array of handler-specific parameters.
708 * Typical keys are width, height and page.
709 * @param $flags Integer: a bitfield, may contain self::RENDER_NOW to force rendering
710 * @return MediaTransformOutput | false
712 function transform( $params, $flags = 0 ) {
713 global $wgUseSquid, $wgServer;
715 wfProfileIn( __METHOD__
);
717 if ( !$this->canRender() ) {
718 // not a bitmap or renderable image, don't try.
719 $thumb = $this->iconThumb();
723 // Get the descriptionUrl to embed it as comment into the thumbnail. Bug 19791.
724 $descriptionUrl = $this->getDescriptionUrl();
725 if ( $descriptionUrl ) {
726 $params['descriptionUrl'] = wfExpandUrl( $descriptionUrl, PROTO_CANONICAL
);
729 $script = $this->getTransformScript();
730 if ( $script && !($flags & self
::RENDER_NOW
) ) {
731 // Use a script to transform on client request, if possible
732 $thumb = $this->handler
->getScriptedTransform( $this, $script, $params );
738 $normalisedParams = $params;
739 $this->handler
->normaliseParams( $this, $normalisedParams );
740 $thumbName = $this->thumbName( $normalisedParams );
741 $thumbUrl = $this->getThumbUrl( $thumbName );
743 $thumb = $this->maybeDoTransform( $thumbName, $thumbUrl, $params, $flags );
745 // Purge. Useful in the event of Core -> Squid connection failure or squid
746 // purge collisions from elsewhere during failure. Don't keep triggering for
747 // "thumbs" which have the main image URL though (bug 13776)
748 if ( $wgUseSquid && ( !$thumb ||
$thumb->isError() ||
$thumb->getUrl() != $this->getURL()) ) {
749 SquidUpdate
::purge( array( $thumbUrl ) );
753 wfProfileOut( __METHOD__
);
754 return is_object( $thumb ) ?
$thumb : false;
758 * Hook into transform() to allow migration of thumbnail files
760 * Overridden by LocalFile
762 function migrateThumbFile( $thumbName ) {}
765 * Get a MediaHandler instance for this file
766 * @return MediaHandler
768 function getHandler() {
769 if ( !isset( $this->handler
) ) {
770 $this->handler
= MediaHandler
::getHandler( $this->getMimeType() );
772 return $this->handler
;
776 * Get a ThumbnailImage representing a file type icon
777 * @return ThumbnailImage
779 function iconThumb() {
780 global $wgStylePath, $wgStyleDirectory;
782 $try = array( 'fileicon-' . $this->getExtension() . '.png', 'fileicon.png' );
783 foreach( $try as $icon ) {
784 $path = '/common/images/icons/' . $icon;
785 $filepath = $wgStyleDirectory . $path;
786 if( file_exists( $filepath ) ) {
787 return new ThumbnailImage( $this, $wgStylePath . $path, 120, 120 );
794 * Get last thumbnailing error.
797 function getLastError() {
798 return $this->lastError
;
802 * Get all thumbnail names previously generated for this file
804 * Overridden by LocalFile
806 function getThumbnails() {
811 * Purge shared caches such as thumbnails and DB data caching
813 * Overridden by LocalFile
814 * @param array $options Array with options, currently undefined
816 function purgeCache( $options = array() ) {}
819 * Purge the file description page, but don't go after
820 * pages using the file. Use when modifying file history
821 * but not the current data.
823 function purgeDescription() {
824 $title = $this->getTitle();
826 $title->invalidateCache();
827 $title->purgeSquid();
832 * Purge metadata and all affected pages when the file is created,
833 * deleted, or majorly updated.
835 function purgeEverything() {
836 // Delete thumbnails and refresh file metadata cache
838 $this->purgeDescription();
840 // Purge cache of all pages using this file
841 $title = $this->getTitle();
843 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
849 * Return a fragment of the history of file.
852 * @param $limit integer Limit of rows to return
853 * @param $start timestamp Only revisions older than $start will be returned
854 * @param $end timestamp Only revisions newer than $end will be returned
855 * @param $inc bool Include the endpoints of the time range
859 function getHistory($limit = null, $start = null, $end = null, $inc=true) {
864 * Return the history of this file, line by line. Starts with current version,
865 * then old versions. Should return an object similar to an image/oldimage
869 * Overridden in LocalFile
871 public function nextHistoryLine() {
876 * Reset the history pointer to the first element of the history.
877 * Always call this function after using nextHistoryLine() to free db resources
879 * Overridden in LocalFile.
881 public function resetHistory() {}
884 * Get the filename hash component of the directory including trailing slash,
886 * If the repository is not hashed, returns an empty string.
890 function getHashPath() {
891 if ( !isset( $this->hashPath
) ) {
892 $this->hashPath
= $this->repo
->getHashPath( $this->getName() );
894 return $this->hashPath
;
898 * Get the path of the file relative to the public zone root
903 return $this->getHashPath() . $this->getName();
907 * Get urlencoded relative path of the file
911 function getUrlRel() {
912 return $this->getHashPath() . rawurlencode( $this->getName() );
916 * Get the relative path for an archived file
918 * @param $suffix bool|string if not false, the name of an archived thumbnail file
922 function getArchiveRel( $suffix = false ) {
923 $path = 'archive/' . $this->getHashPath();
924 if ( $suffix === false ) {
925 $path = substr( $path, 0, -1 );
933 * Get the relative path for an archived file's thumbs directory
934 * or a specific thumb if the $suffix is given.
936 * @param $archiveName string the timestamped name of an archived image
937 * @param $suffix bool|string if not false, the name of a thumbnail file
941 function getArchiveThumbRel( $archiveName, $suffix = false ) {
942 $path = 'archive/' . $this->getHashPath() . $archiveName . "/";
943 if ( $suffix === false ) {
944 $path = substr( $path, 0, -1 );
952 * Get the path of the archived file.
954 * @param $suffix bool|string if not false, the name of an archived file.
958 function getArchivePath( $suffix = false ) {
959 return $this->repo
->getZonePath( 'public' ) . '/' . $this->getArchiveRel( $suffix );
963 * Get the path of the archived file's thumbs, or a particular thumb if $suffix is specified
965 * @param $archiveName string the timestamped name of an archived image
966 * @param $suffix bool|string if not false, the name of a thumbnail file
970 function getArchiveThumbPath( $archiveName, $suffix = false ) {
971 return $this->repo
->getZonePath( 'thumb' ) . '/' . $this->getArchiveThumbRel( $archiveName, $suffix );
975 * Get the path of the thumbnail directory, or a particular file if $suffix is specified
977 * @param $suffix bool|string if not false, the name of a thumbnail file
981 function getThumbPath( $suffix = false ) {
982 $path = $this->repo
->getZonePath( 'thumb' ) . '/' . $this->getRel();
983 if ( $suffix !== false ) {
984 $path .= '/' . $suffix;
990 * Get the URL of the archive directory, or a particular file if $suffix is specified
992 * @param $suffix bool|string if not false, the name of an archived file
996 function getArchiveUrl( $suffix = false ) {
997 $path = $this->repo
->getZoneUrl('public') . '/archive/' . $this->getHashPath();
998 if ( $suffix === false ) {
999 $path = substr( $path, 0, -1 );
1001 $path .= rawurlencode( $suffix );
1007 * Get the URL of the archived file's thumbs, or a particular thumb if $suffix is specified
1009 * @param $archiveName string the timestamped name of an archived image
1010 * @param $suffix bool|string if not false, the name of a thumbnail file
1014 function getArchiveThumbUrl( $archiveName, $suffix = false ) {
1015 $path = $this->repo
->getZoneUrl('thumb') . '/archive/' . $this->getHashPath() . rawurlencode( $archiveName ) . "/";
1016 if ( $suffix === false ) {
1017 $path = substr( $path, 0, -1 );
1019 $path .= rawurlencode( $suffix );
1025 * Get the URL of the thumbnail directory, or a particular file if $suffix is specified
1027 * @param $suffix bool|string if not false, the name of a thumbnail file
1031 function getThumbUrl( $suffix = false ) {
1032 $path = $this->repo
->getZoneUrl('thumb') . '/' . $this->getUrlRel();
1033 if ( $suffix !== false ) {
1034 $path .= '/' . rawurlencode( $suffix );
1040 * Get the virtual URL for an archived file's thumbs, or a specific thumb.
1042 * @param $suffix bool|string if not false, the name of a thumbnail file
1046 function getArchiveVirtualUrl( $suffix = false ) {
1047 $path = $this->repo
->getVirtualUrl() . '/public/archive/' . $this->getHashPath();
1048 if ( $suffix === false ) {
1049 $path = substr( $path, 0, -1 );
1051 $path .= rawurlencode( $suffix );
1057 * Get the virtual URL for a thumbnail file or directory
1059 * @param $suffix bool|string if not false, the name of a thumbnail file
1063 function getThumbVirtualUrl( $suffix = false ) {
1064 $path = $this->repo
->getVirtualUrl() . '/thumb/' . $this->getUrlRel();
1065 if ( $suffix !== false ) {
1066 $path .= '/' . rawurlencode( $suffix );
1072 * Get the virtual URL for the file itself
1074 * @param $suffix bool|string if not false, the name of a thumbnail file
1078 function getVirtualUrl( $suffix = false ) {
1079 $path = $this->repo
->getVirtualUrl() . '/public/' . $this->getUrlRel();
1080 if ( $suffix !== false ) {
1081 $path .= '/' . rawurlencode( $suffix );
1089 function isHashed() {
1090 return $this->repo
->isHashed();
1094 * @throws MWException
1096 function readOnlyError() {
1097 throw new MWException( get_class($this) . ': write operations are not supported' );
1101 * Record a file upload in the upload log and the image table
1103 * Overridden by LocalFile
1106 * @param $license string
1107 * @param $copyStatus string
1108 * @param $source string
1109 * @param $watch bool
1111 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '', $watch = false ) {
1112 $this->readOnlyError();
1116 * Move or copy a file to its public location. If a file exists at the
1117 * destination, move it to an archive. Returns a FileRepoStatus object with
1118 * the archive name in the "value" member on success.
1120 * The archive name should be passed through to recordUpload for database
1123 * @param $srcPath String: local filesystem path to the source image
1124 * @param $flags Integer: a bitwise combination of:
1125 * File::DELETE_SOURCE Delete the source file, i.e. move
1127 * @return FileRepoStatus object. On success, the value member contains the
1128 * archive name, or an empty string if it was a new file.
1131 * Overridden by LocalFile
1133 function publish( $srcPath, $flags = 0 ) {
1134 $this->readOnlyError();
1140 function formatMetadata() {
1141 if ( !$this->getHandler() ) {
1144 return $this->getHandler()->formatMetadata( $this, $this->getMetadata() );
1148 * Returns true if the file comes from the local file repository.
1152 function isLocal() {
1153 $repo = $this->getRepo();
1154 return $repo && $repo->isLocal();
1158 * Returns the name of the repository.
1162 function getRepoName() {
1163 return $this->repo ?
$this->repo
->getName() : 'unknown';
1167 * Returns the repository
1171 function getRepo() {
1176 * Returns true if the image is an old version
1186 * Is this file a "deleted" file in a private archive?
1193 function isDeleted( $field ) {
1198 * Return the deletion bitfield
1201 function getVisibility() {
1206 * Was this file ever deleted from the wiki?
1210 function wasDeleted() {
1211 $title = $this->getTitle();
1212 return $title && $title->isDeletedQuick();
1216 * Move file to the new title
1218 * Move current, old version and all thumbnails
1219 * to the new filename. Old file is deleted.
1221 * Cache purging is done; checks for validity
1222 * and logging are caller's responsibility
1224 * @param $target Title New file name
1225 * @return FileRepoStatus object.
1227 function move( $target ) {
1228 $this->readOnlyError();
1232 * Delete all versions of the file.
1234 * Moves the files into an archive directory (or deletes them)
1235 * and removes the database rows.
1237 * Cache purging is done; logging is caller's responsibility.
1239 * @param $reason String
1240 * @param $suppress Boolean: hide content from sysops?
1241 * @return true on success, false on some kind of failure
1243 * Overridden by LocalFile
1245 function delete( $reason, $suppress = false ) {
1246 $this->readOnlyError();
1250 * Restore all or specified deleted revisions to the given file.
1251 * Permissions and logging are left to the caller.
1253 * May throw database exceptions on error.
1255 * @param $versions array set of record ids of deleted items to restore,
1256 * or empty to restore all revisions.
1257 * @param $unsuppress bool remove restrictions on content upon restoration?
1258 * @return int|false the number of file revisions restored if successful,
1259 * or false on failure
1261 * Overridden by LocalFile
1263 function restore( $versions = array(), $unsuppress = false ) {
1264 $this->readOnlyError();
1268 * Returns 'true' if this file is a type which supports multiple pages,
1269 * e.g. DJVU or PDF. Note that this may be true even if the file in
1270 * question only has a single page.
1274 function isMultipage() {
1275 return $this->getHandler() && $this->handler
->isMultiPage( $this );
1279 * Returns the number of pages of a multipage document, or false for
1280 * documents which aren't multipage documents
1284 function pageCount() {
1285 if ( !isset( $this->pageCount
) ) {
1286 if ( $this->getHandler() && $this->handler
->isMultiPage( $this ) ) {
1287 $this->pageCount
= $this->handler
->pageCount( $this );
1289 $this->pageCount
= false;
1292 return $this->pageCount
;
1296 * Calculate the height of a thumbnail using the source and destination width
1304 static function scaleHeight( $srcWidth, $srcHeight, $dstWidth ) {
1305 // Exact integer multiply followed by division
1306 if ( $srcWidth == 0 ) {
1309 return round( $srcHeight * $dstWidth / $srcWidth );
1314 * Get an image size array like that returned by getImageSize(), or false if it
1315 * can't be determined.
1317 * @param $fileName String: The filename
1320 function getImageSize( $fileName ) {
1321 if ( !$this->getHandler() ) {
1324 return $this->handler
->getImageSize( $this, $fileName );
1328 * Get the URL of the image description page. May return false if it is
1329 * unknown or not applicable.
1333 function getDescriptionUrl() {
1334 if ( $this->repo
) {
1335 return $this->repo
->getDescriptionUrl( $this->getName() );
1342 * Get the HTML text of the description page, if available
1346 function getDescriptionText() {
1347 global $wgMemc, $wgLang;
1348 if ( !$this->repo
->fetchDescription
) {
1351 $renderUrl = $this->repo
->getDescriptionRenderUrl( $this->getName(), $wgLang->getCode() );
1353 if ( $this->repo
->descriptionCacheExpiry
> 0 ) {
1354 wfDebug("Attempting to get the description from cache...");
1355 $key = $this->repo
->getLocalCacheKey( 'RemoteFileDescription', 'url', $wgLang->getCode(),
1357 $obj = $wgMemc->get($key);
1359 wfDebug("success!\n");
1364 wfDebug( "Fetching shared description from $renderUrl\n" );
1365 $res = Http
::get( $renderUrl );
1366 if ( $res && $this->repo
->descriptionCacheExpiry
> 0 ) {
1367 $wgMemc->set( $key, $res, $this->repo
->descriptionCacheExpiry
);
1376 * Get discription of file revision
1381 function getDescription() {
1386 * Get the 14-character timestamp of the file upload, or false if
1391 function getTimestamp() {
1392 $path = $this->getPath();
1393 if ( !file_exists( $path ) ) {
1396 return wfTimestamp( TS_MW
, filemtime( $path ) );
1400 * Get the SHA-1 base 36 hash of the file
1404 function getSha1() {
1405 return self
::sha1Base36( $this->getPath() );
1409 * Get the deletion archive key, <sha1>.<ext>
1413 function getStorageKey() {
1414 $hash = $this->getSha1();
1418 $ext = $this->getExtension();
1419 $dotExt = $ext === '' ?
'' : ".$ext";
1420 return $hash . $dotExt;
1424 * Determine if the current user is allowed to view a particular
1425 * field of this file, if it's marked as deleted.
1427 * @param $field Integer
1428 * @param $user User object to check, or null to use $wgUser
1431 function userCan( $field, User
$user = null ) {
1436 * Get an associative array containing information about a file in the local filesystem.
1438 * @param $path String: absolute local filesystem path
1439 * @param $ext Mixed: the file extension, or true to extract it from the filename.
1440 * Set it to false to ignore the extension.
1444 static function getPropsFromPath( $path, $ext = true ) {
1445 wfProfileIn( __METHOD__
);
1446 wfDebug( __METHOD__
.": Getting file info for $path\n" );
1448 'fileExists' => file_exists( $path ) && !is_dir( $path )
1451 if ( $info['fileExists'] ) {
1452 $magic = MimeMagic
::singleton();
1454 if ( $ext === true ) {
1455 $i = strrpos( $path, '.' );
1456 $ext = strtolower( $i ?
substr( $path, $i +
1 ) : '' );
1459 # mime type according to file contents
1460 $info['file-mime'] = $magic->guessMimeType( $path, false );
1462 $info['mime'] = $magic->improveTypeFromExtension( $info['file-mime'], $ext );
1464 list( $info['major_mime'], $info['minor_mime'] ) = self
::splitMime( $info['mime'] );
1465 $info['media_type'] = $magic->getMediaType( $path, $info['mime'] );
1468 $info['size'] = filesize( $path );
1470 # Height, width and metadata
1471 $handler = MediaHandler
::getHandler( $info['mime'] );
1473 $tempImage = (object)array();
1474 $info['metadata'] = $handler->getMetadata( $tempImage, $path );
1475 $gis = $handler->getImageSize( $tempImage, $path, $info['metadata'] );
1478 $info['metadata'] = '';
1480 $info['sha1'] = self
::sha1Base36( $path );
1482 wfDebug(__METHOD__
.": $path loaded, {$info['size']} bytes, {$info['mime']}.\n");
1484 $info['mime'] = null;
1485 $info['media_type'] = MEDIATYPE_UNKNOWN
;
1486 $info['metadata'] = '';
1488 wfDebug(__METHOD__
.": $path NOT FOUND!\n");
1491 # NOTE: $gis[2] contains a code for the image type. This is no longer used.
1492 $info['width'] = $gis[0];
1493 $info['height'] = $gis[1];
1494 if ( isset( $gis['bits'] ) ) {
1495 $info['bits'] = $gis['bits'];
1501 $info['height'] = 0;
1504 wfProfileOut( __METHOD__
);
1509 * Get a SHA-1 hash of a file in the local filesystem, in base-36 lower case
1510 * encoding, zero padded to 31 digits.
1512 * 160 log 2 / log 36 = 30.95, so the 160-bit hash fills 31 digits in base 36
1515 * @param $path string
1517 * @return false|string False on failure
1519 static function sha1Base36( $path ) {
1520 wfSuppressWarnings();
1521 $hash = sha1_file( $path );
1522 wfRestoreWarnings();
1523 if ( $hash === false ) {
1526 return wfBaseConvert( $hash, 16, 36, 31 );
1533 function getLongDesc() {
1534 $handler = $this->getHandler();
1536 return $handler->getLongDesc( $this );
1538 return MediaHandler
::getGeneralLongDesc( $this );
1545 function getShortDesc() {
1546 $handler = $this->getHandler();
1548 return $handler->getShortDesc( $this );
1550 return MediaHandler
::getGeneralShortDesc( $this );
1557 function getDimensionsString() {
1558 $handler = $this->getHandler();
1560 return $handler->getDimensionsString( $this );
1569 function getRedirected() {
1570 return $this->redirected
;
1576 function getRedirectedTitle() {
1577 if ( $this->redirected
) {
1578 if ( !$this->redirectTitle
) {
1579 $this->redirectTitle
= Title
::makeTitle( NS_FILE
, $this->redirected
);
1581 return $this->redirectTitle
;
1589 function redirectedFrom( $from ) {
1590 $this->redirected
= $from;
1596 function isMissing() {
1601 * Aliases for backwards compatibility with 1.6
1603 define( 'MW_IMG_DELETED_FILE', File
::DELETED_FILE
);
1604 define( 'MW_IMG_DELETED_COMMENT', File
::DELETED_COMMENT
);
1605 define( 'MW_IMG_DELETED_USER', File
::DELETED_USER
);
1606 define( 'MW_IMG_DELETED_RESTRICTED', File
::DELETED_RESTRICTED
);