630f1f8d180f3936ef4294011da417e2fcaa47a7
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 * Do the work of a transform (from an original into a thumb).
672 * Contains filesystem-specific functions.
674 * @param $thumbName string: the name of the thumbnail file.
675 * @param $thumbUrl string: the URL of the thumbnail file.
676 * @param $params Array: an associative array of handler-specific parameters.
677 * Typical keys are width, height and page.
678 * @param $flags Integer: a bitfield, may contain self::RENDER_NOW to force rendering
680 * @return MediaTransformOutput | false
682 protected function maybeDoTransform( $thumbName, $thumbUrl, $params, $flags = 0 ) {
683 global $wgIgnoreImageErrors, $wgThumbnailEpoch;
685 $thumbPath = $this->getThumbPath( $thumbName );
686 if ( $this->repo
&& $this->repo
->canTransformVia404() && !($flags & self
::RENDER_NOW
) ) {
687 return $this->handler
->getTransform( $this, $thumbPath, $thumbUrl, $params );
690 wfDebug( __METHOD__
.": Doing stat for $thumbPath\n" );
691 $this->migrateThumbFile( $thumbName );
692 if ( file_exists( $thumbPath )) {
693 $thumbTime = filemtime( $thumbPath );
694 if ( $thumbTime !== FALSE &&
695 gmdate( 'YmdHis', $thumbTime ) >= $wgThumbnailEpoch ) {
697 return $this->handler
->getTransform( $this, $thumbPath, $thumbUrl, $params );
700 $thumb = $this->handler
->doTransform( $this, $thumbPath, $thumbUrl, $params );
702 // Ignore errors if requested
705 } elseif ( $thumb->isError() ) {
706 $this->lastError
= $thumb->toText();
707 if ( $wgIgnoreImageErrors && !($flags & self
::RENDER_NOW
) ) {
708 $thumb = $this->handler
->getTransform( $this, $thumbPath, $thumbUrl, $params );
717 * Transform a media file
719 * @param $params Array: an associative array of handler-specific parameters.
720 * Typical keys are width, height and page.
721 * @param $flags Integer: a bitfield, may contain self::RENDER_NOW to force rendering
722 * @return MediaTransformOutput | false
724 function transform( $params, $flags = 0 ) {
725 global $wgUseSquid, $wgServer;
727 wfProfileIn( __METHOD__
);
729 if ( !$this->canRender() ) {
730 // not a bitmap or renderable image, don't try.
731 $thumb = $this->iconThumb();
735 // Get the descriptionUrl to embed it as comment into the thumbnail. Bug 19791.
736 $descriptionUrl = $this->getDescriptionUrl();
737 if ( $descriptionUrl ) {
738 $params['descriptionUrl'] = wfExpandUrl( $descriptionUrl, PROTO_CANONICAL
);
741 $script = $this->getTransformScript();
742 if ( $script && !($flags & self
::RENDER_NOW
) ) {
743 // Use a script to transform on client request, if possible
744 $thumb = $this->handler
->getScriptedTransform( $this, $script, $params );
750 $normalisedParams = $params;
751 $this->handler
->normaliseParams( $this, $normalisedParams );
752 $thumbName = $this->thumbName( $normalisedParams );
753 $thumbUrl = $this->getThumbUrl( $thumbName );
755 $thumb = $this->maybeDoTransform( $thumbName, $thumbUrl, $params, $flags );
757 // Purge. Useful in the event of Core -> Squid connection failure or squid
758 // purge collisions from elsewhere during failure. Don't keep triggering for
759 // "thumbs" which have the main image URL though (bug 13776)
760 if ( $wgUseSquid && ( !$thumb ||
$thumb->isError() ||
$thumb->getUrl() != $this->getURL()) ) {
761 SquidUpdate
::purge( array( $thumbUrl ) );
765 wfProfileOut( __METHOD__
);
766 return is_object( $thumb ) ?
$thumb : false;
770 * Hook into transform() to allow migration of thumbnail files
772 * Overridden by LocalFile
774 function migrateThumbFile( $thumbName ) {}
777 * Get a MediaHandler instance for this file
778 * @return MediaHandler
780 function getHandler() {
781 if ( !isset( $this->handler
) ) {
782 $this->handler
= MediaHandler
::getHandler( $this->getMimeType() );
784 return $this->handler
;
788 * Get a ThumbnailImage representing a file type icon
789 * @return ThumbnailImage
791 function iconThumb() {
792 global $wgStylePath, $wgStyleDirectory;
794 $try = array( 'fileicon-' . $this->getExtension() . '.png', 'fileicon.png' );
795 foreach( $try as $icon ) {
796 $path = '/common/images/icons/' . $icon;
797 $filepath = $wgStyleDirectory . $path;
798 if( file_exists( $filepath ) ) {
799 return new ThumbnailImage( $this, $wgStylePath . $path, 120, 120 );
806 * Get last thumbnailing error.
809 function getLastError() {
810 return $this->lastError
;
814 * Get all thumbnail names previously generated for this file
816 * Overridden by LocalFile
818 function getThumbnails() {
823 * Purge shared caches such as thumbnails and DB data caching
825 * Overridden by LocalFile
826 * @param array $options Array with options, currently undefined
828 function purgeCache( $options = array() ) {}
831 * Purge the file description page, but don't go after
832 * pages using the file. Use when modifying file history
833 * but not the current data.
835 function purgeDescription() {
836 $title = $this->getTitle();
838 $title->invalidateCache();
839 $title->purgeSquid();
844 * Purge metadata and all affected pages when the file is created,
845 * deleted, or majorly updated.
847 function purgeEverything() {
848 // Delete thumbnails and refresh file metadata cache
850 $this->purgeDescription();
852 // Purge cache of all pages using this file
853 $title = $this->getTitle();
855 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
861 * Return a fragment of the history of file.
864 * @param $limit integer Limit of rows to return
865 * @param $start timestamp Only revisions older than $start will be returned
866 * @param $end timestamp Only revisions newer than $end will be returned
867 * @param $inc bool Include the endpoints of the time range
871 function getHistory($limit = null, $start = null, $end = null, $inc=true) {
876 * Return the history of this file, line by line. Starts with current version,
877 * then old versions. Should return an object similar to an image/oldimage
881 * Overridden in LocalFile
883 public function nextHistoryLine() {
888 * Reset the history pointer to the first element of the history.
889 * Always call this function after using nextHistoryLine() to free db resources
891 * Overridden in LocalFile.
893 public function resetHistory() {}
896 * Get the filename hash component of the directory including trailing slash,
898 * If the repository is not hashed, returns an empty string.
902 function getHashPath() {
903 if ( !isset( $this->hashPath
) ) {
904 $this->hashPath
= $this->repo
->getHashPath( $this->getName() );
906 return $this->hashPath
;
910 * Get the path of the file relative to the public zone root
915 return $this->getHashPath() . $this->getName();
919 * Get urlencoded relative path of the file
923 function getUrlRel() {
924 return $this->getHashPath() . rawurlencode( $this->getName() );
928 * Get the relative path for an archived file
930 * @param $suffix bool|string if not false, the name of an archived thumbnail file
934 function getArchiveRel( $suffix = false ) {
935 $path = 'archive/' . $this->getHashPath();
936 if ( $suffix === false ) {
937 $path = substr( $path, 0, -1 );
945 * Get the relative path for an archived file's thumbs directory
946 * or a specific thumb if the $suffix is given.
948 * @param $archiveName string the timestamped name of an archived image
949 * @param $suffix bool|string if not false, the name of a thumbnail file
953 function getArchiveThumbRel( $archiveName, $suffix = false ) {
954 $path = 'archive/' . $this->getHashPath() . $archiveName . "/";
955 if ( $suffix === false ) {
956 $path = substr( $path, 0, -1 );
964 * Get the path of the archived file.
966 * @param $suffix bool|string if not false, the name of an archived file.
970 function getArchivePath( $suffix = false ) {
971 return $this->repo
->getZonePath( 'public' ) . '/' . $this->getArchiveRel( $suffix );
975 * Get the path of the archived file's thumbs, or a particular thumb if $suffix is specified
977 * @param $archiveName string the timestamped name of an archived image
978 * @param $suffix bool|string if not false, the name of a thumbnail file
982 function getArchiveThumbPath( $archiveName, $suffix = false ) {
983 return $this->repo
->getZonePath( 'thumb' ) . '/' . $this->getArchiveThumbRel( $archiveName, $suffix );
987 * Get the path of the thumbnail directory, or a particular file if $suffix is specified
989 * @param $suffix bool|string if not false, the name of a thumbnail file
993 function getThumbPath( $suffix = false ) {
994 $path = $this->repo
->getZonePath( 'thumb' ) . '/' . $this->getRel();
995 if ( $suffix !== false ) {
996 $path .= '/' . $suffix;
1002 * Get the URL of the archive directory, or a particular file if $suffix is specified
1004 * @param $suffix bool|string if not false, the name of an archived file
1008 function getArchiveUrl( $suffix = false ) {
1009 $path = $this->repo
->getZoneUrl('public') . '/archive/' . $this->getHashPath();
1010 if ( $suffix === false ) {
1011 $path = substr( $path, 0, -1 );
1013 $path .= rawurlencode( $suffix );
1019 * Get the URL of the archived file's thumbs, or a particular thumb if $suffix is specified
1021 * @param $archiveName string the timestamped name of an archived image
1022 * @param $suffix bool|string if not false, the name of a thumbnail file
1026 function getArchiveThumbUrl( $archiveName, $suffix = false ) {
1027 $path = $this->repo
->getZoneUrl('thumb') . '/archive/' . $this->getHashPath() . rawurlencode( $archiveName ) . "/";
1028 if ( $suffix === false ) {
1029 $path = substr( $path, 0, -1 );
1031 $path .= rawurlencode( $suffix );
1037 * Get the URL of the thumbnail directory, or a particular file if $suffix is specified
1039 * @param $suffix bool|string if not false, the name of a thumbnail file
1043 function getThumbUrl( $suffix = false ) {
1044 $path = $this->repo
->getZoneUrl('thumb') . '/' . $this->getUrlRel();
1045 if ( $suffix !== false ) {
1046 $path .= '/' . rawurlencode( $suffix );
1052 * Get the virtual URL for an archived file's thumbs, or a specific thumb.
1054 * @param $suffix bool|string if not false, the name of a thumbnail file
1058 function getArchiveVirtualUrl( $suffix = false ) {
1059 $path = $this->repo
->getVirtualUrl() . '/public/archive/' . $this->getHashPath();
1060 if ( $suffix === false ) {
1061 $path = substr( $path, 0, -1 );
1063 $path .= rawurlencode( $suffix );
1069 * Get the virtual URL for a thumbnail file or directory
1071 * @param $suffix bool|string if not false, the name of a thumbnail file
1075 function getThumbVirtualUrl( $suffix = false ) {
1076 $path = $this->repo
->getVirtualUrl() . '/thumb/' . $this->getUrlRel();
1077 if ( $suffix !== false ) {
1078 $path .= '/' . rawurlencode( $suffix );
1084 * Get the virtual URL for the file itself
1086 * @param $suffix bool|string if not false, the name of a thumbnail file
1090 function getVirtualUrl( $suffix = false ) {
1091 $path = $this->repo
->getVirtualUrl() . '/public/' . $this->getUrlRel();
1092 if ( $suffix !== false ) {
1093 $path .= '/' . rawurlencode( $suffix );
1101 function isHashed() {
1102 return $this->repo
->isHashed();
1106 * @throws MWException
1108 function readOnlyError() {
1109 throw new MWException( get_class($this) . ': write operations are not supported' );
1113 * Record a file upload in the upload log and the image table
1115 * Overridden by LocalFile
1118 * @param $license string
1119 * @param $copyStatus string
1120 * @param $source string
1121 * @param $watch bool
1123 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '', $watch = false ) {
1124 $this->readOnlyError();
1128 * Move or copy a file to its public location. If a file exists at the
1129 * destination, move it to an archive. Returns a FileRepoStatus object with
1130 * the archive name in the "value" member on success.
1132 * The archive name should be passed through to recordUpload for database
1135 * @param $srcPath String: local filesystem path to the source image
1136 * @param $flags Integer: a bitwise combination of:
1137 * File::DELETE_SOURCE Delete the source file, i.e. move
1139 * @return FileRepoStatus object. On success, the value member contains the
1140 * archive name, or an empty string if it was a new file.
1143 * Overridden by LocalFile
1145 function publish( $srcPath, $flags = 0 ) {
1146 $this->readOnlyError();
1152 function formatMetadata() {
1153 if ( !$this->getHandler() ) {
1156 return $this->getHandler()->formatMetadata( $this, $this->getMetadata() );
1160 * Returns true if the file comes from the local file repository.
1164 function isLocal() {
1165 $repo = $this->getRepo();
1166 return $repo && $repo->isLocal();
1170 * Returns the name of the repository.
1174 function getRepoName() {
1175 return $this->repo ?
$this->repo
->getName() : 'unknown';
1179 * Returns the repository
1183 function getRepo() {
1188 * Returns true if the image is an old version
1198 * Is this file a "deleted" file in a private archive?
1205 function isDeleted( $field ) {
1210 * Return the deletion bitfield
1213 function getVisibility() {
1218 * Was this file ever deleted from the wiki?
1222 function wasDeleted() {
1223 $title = $this->getTitle();
1224 return $title && $title->isDeletedQuick();
1228 * Move file to the new title
1230 * Move current, old version and all thumbnails
1231 * to the new filename. Old file is deleted.
1233 * Cache purging is done; checks for validity
1234 * and logging are caller's responsibility
1236 * @param $target Title New file name
1237 * @return FileRepoStatus object.
1239 function move( $target ) {
1240 $this->readOnlyError();
1244 * Delete all versions of the file.
1246 * Moves the files into an archive directory (or deletes them)
1247 * and removes the database rows.
1249 * Cache purging is done; logging is caller's responsibility.
1251 * @param $reason String
1252 * @param $suppress Boolean: hide content from sysops?
1253 * @return true on success, false on some kind of failure
1255 * Overridden by LocalFile
1257 function delete( $reason, $suppress = false ) {
1258 $this->readOnlyError();
1262 * Restore all or specified deleted revisions to the given file.
1263 * Permissions and logging are left to the caller.
1265 * May throw database exceptions on error.
1267 * @param $versions array set of record ids of deleted items to restore,
1268 * or empty to restore all revisions.
1269 * @param $unsuppress bool remove restrictions on content upon restoration?
1270 * @return int|false the number of file revisions restored if successful,
1271 * or false on failure
1273 * Overridden by LocalFile
1275 function restore( $versions = array(), $unsuppress = false ) {
1276 $this->readOnlyError();
1280 * Returns 'true' if this file is a type which supports multiple pages,
1281 * e.g. DJVU or PDF. Note that this may be true even if the file in
1282 * question only has a single page.
1286 function isMultipage() {
1287 return $this->getHandler() && $this->handler
->isMultiPage( $this );
1291 * Returns the number of pages of a multipage document, or false for
1292 * documents which aren't multipage documents
1296 function pageCount() {
1297 if ( !isset( $this->pageCount
) ) {
1298 if ( $this->getHandler() && $this->handler
->isMultiPage( $this ) ) {
1299 $this->pageCount
= $this->handler
->pageCount( $this );
1301 $this->pageCount
= false;
1304 return $this->pageCount
;
1308 * Calculate the height of a thumbnail using the source and destination width
1316 static function scaleHeight( $srcWidth, $srcHeight, $dstWidth ) {
1317 // Exact integer multiply followed by division
1318 if ( $srcWidth == 0 ) {
1321 return round( $srcHeight * $dstWidth / $srcWidth );
1326 * Get an image size array like that returned by getImageSize(), or false if it
1327 * can't be determined.
1329 * @param $fileName String: The filename
1332 function getImageSize( $fileName ) {
1333 if ( !$this->getHandler() ) {
1336 return $this->handler
->getImageSize( $this, $fileName );
1340 * Get the URL of the image description page. May return false if it is
1341 * unknown or not applicable.
1345 function getDescriptionUrl() {
1346 if ( $this->repo
) {
1347 return $this->repo
->getDescriptionUrl( $this->getName() );
1354 * Get the HTML text of the description page, if available
1358 function getDescriptionText() {
1359 global $wgMemc, $wgLang;
1360 if ( !$this->repo
->fetchDescription
) {
1363 $renderUrl = $this->repo
->getDescriptionRenderUrl( $this->getName(), $wgLang->getCode() );
1365 if ( $this->repo
->descriptionCacheExpiry
> 0 ) {
1366 wfDebug("Attempting to get the description from cache...");
1367 $key = $this->repo
->getLocalCacheKey( 'RemoteFileDescription', 'url', $wgLang->getCode(),
1369 $obj = $wgMemc->get($key);
1371 wfDebug("success!\n");
1376 wfDebug( "Fetching shared description from $renderUrl\n" );
1377 $res = Http
::get( $renderUrl );
1378 if ( $res && $this->repo
->descriptionCacheExpiry
> 0 ) {
1379 $wgMemc->set( $key, $res, $this->repo
->descriptionCacheExpiry
);
1388 * Get discription of file revision
1393 function getDescription() {
1398 * Get the 14-character timestamp of the file upload, or false if
1403 function getTimestamp() {
1404 $path = $this->getPath();
1405 if ( !file_exists( $path ) ) {
1408 return wfTimestamp( TS_MW
, filemtime( $path ) );
1412 * Get the SHA-1 base 36 hash of the file
1416 function getSha1() {
1417 return self
::sha1Base36( $this->getPath() );
1421 * Get the deletion archive key, <sha1>.<ext>
1425 function getStorageKey() {
1426 $hash = $this->getSha1();
1430 $ext = $this->getExtension();
1431 $dotExt = $ext === '' ?
'' : ".$ext";
1432 return $hash . $dotExt;
1436 * Determine if the current user is allowed to view a particular
1437 * field of this file, if it's marked as deleted.
1439 * @param $field Integer
1442 function userCan( $field ) {
1447 * Get an associative array containing information about a file in the local filesystem.
1449 * @param $path String: absolute local filesystem path
1450 * @param $ext Mixed: the file extension, or true to extract it from the filename.
1451 * Set it to false to ignore the extension.
1455 static function getPropsFromPath( $path, $ext = true ) {
1456 wfProfileIn( __METHOD__
);
1457 wfDebug( __METHOD__
.": Getting file info for $path\n" );
1459 'fileExists' => file_exists( $path ) && !is_dir( $path )
1462 if ( $info['fileExists'] ) {
1463 $magic = MimeMagic
::singleton();
1465 if ( $ext === true ) {
1466 $i = strrpos( $path, '.' );
1467 $ext = strtolower( $i ?
substr( $path, $i +
1 ) : '' );
1470 # mime type according to file contents
1471 $info['file-mime'] = $magic->guessMimeType( $path, false );
1473 $info['mime'] = $magic->improveTypeFromExtension( $info['file-mime'], $ext );
1475 list( $info['major_mime'], $info['minor_mime'] ) = self
::splitMime( $info['mime'] );
1476 $info['media_type'] = $magic->getMediaType( $path, $info['mime'] );
1479 $info['size'] = filesize( $path );
1481 # Height, width and metadata
1482 $handler = MediaHandler
::getHandler( $info['mime'] );
1484 $tempImage = (object)array();
1485 $info['metadata'] = $handler->getMetadata( $tempImage, $path );
1486 $gis = $handler->getImageSize( $tempImage, $path, $info['metadata'] );
1489 $info['metadata'] = '';
1491 $info['sha1'] = self
::sha1Base36( $path );
1493 wfDebug(__METHOD__
.": $path loaded, {$info['size']} bytes, {$info['mime']}.\n");
1495 $info['mime'] = null;
1496 $info['media_type'] = MEDIATYPE_UNKNOWN
;
1497 $info['metadata'] = '';
1499 wfDebug(__METHOD__
.": $path NOT FOUND!\n");
1502 # NOTE: $gis[2] contains a code for the image type. This is no longer used.
1503 $info['width'] = $gis[0];
1504 $info['height'] = $gis[1];
1505 if ( isset( $gis['bits'] ) ) {
1506 $info['bits'] = $gis['bits'];
1512 $info['height'] = 0;
1515 wfProfileOut( __METHOD__
);
1520 * Get a SHA-1 hash of a file in the local filesystem, in base-36 lower case
1521 * encoding, zero padded to 31 digits.
1523 * 160 log 2 / log 36 = 30.95, so the 160-bit hash fills 31 digits in base 36
1526 * @param $path string
1528 * @return false|string False on failure
1530 static function sha1Base36( $path ) {
1531 wfSuppressWarnings();
1532 $hash = sha1_file( $path );
1533 wfRestoreWarnings();
1534 if ( $hash === false ) {
1537 return wfBaseConvert( $hash, 16, 36, 31 );
1544 function getLongDesc() {
1545 $handler = $this->getHandler();
1547 return $handler->getLongDesc( $this );
1549 return MediaHandler
::getGeneralLongDesc( $this );
1556 function getShortDesc() {
1557 $handler = $this->getHandler();
1559 return $handler->getShortDesc( $this );
1561 return MediaHandler
::getGeneralShortDesc( $this );
1568 function getDimensionsString() {
1569 $handler = $this->getHandler();
1571 return $handler->getDimensionsString( $this );
1580 function getRedirected() {
1581 return $this->redirected
;
1587 function getRedirectedTitle() {
1588 if ( $this->redirected
) {
1589 if ( !$this->redirectTitle
) {
1590 $this->redirectTitle
= Title
::makeTitle( NS_FILE
, $this->redirected
);
1592 return $this->redirectTitle
;
1600 function redirectedFrom( $from ) {
1601 $this->redirected
= $from;
1607 function isMissing() {
1612 * Aliases for backwards compatibility with 1.6
1614 define( 'MW_IMG_DELETED_FILE', File
::DELETED_FILE
);
1615 define( 'MW_IMG_DELETED_COMMENT', File
::DELETED_COMMENT
);
1616 define( 'MW_IMG_DELETED_USER', File
::DELETED_USER
);
1617 define( 'MW_IMG_DELETED_RESTRICTED', File
::DELETED_RESTRICTED
);