4 * Implements some public methods and some protected utility functions which
5 * are required by multiple child classes. Contains stub functionality for
6 * unimplemented public methods.
8 * Stub functions which should be overridden are marked with STUB. Some more
9 * concrete functions are also typically overridden by child classes.
11 * Note that only the repo object knows what its file class is called. You should
12 * never name a file class explictly outside of the repo class. Instead use the
13 * repo's factory functions to generate file objects, for example:
15 * RepoGroup::singleton()->getLocalRepo()->newFile($title);
17 * The convenience functions wfLocalFile() and wfFindFile() should be sufficient
20 * @addtogroup FileRepo
23 const DELETED_FILE
= 1;
24 const DELETED_COMMENT
= 2;
25 const DELETED_USER
= 4;
26 const DELETED_RESTRICTED
= 8;
29 const DELETE_SOURCE
= 1;
32 * Some member variables can be lazy-initialised using __get(). The
33 * initialisation function for these variables is always a function named
34 * like getVar(), where Var is the variable name with upper-case first
37 * The following variables are initialised in this way in this base class:
38 * name, extension, handler, path, canRender, isSafeFile,
39 * transformScript, hashPath, pageCount, url
41 * Code within this class should generally use the accessor function
42 * directly, since __get() isn't re-entrant and therefore causes bugs that
43 * depend on initialisation order.
47 * The following member variables are not lazy-initialised
49 var $repo, $title, $lastError, $redirected;
52 * Call this constructor from child classes
54 function __construct( $title, $repo ) {
55 $this->title
= $title;
59 function __get( $name ) {
60 $function = array( $this, 'get' . ucfirst( $name ) );
61 if ( !is_callable( $function ) ) {
64 $this->$name = call_user_func( $function );
70 * Normalize a file extension to the common form, and ensure it's clean.
71 * Extensions with non-alphanumeric characters will be discarded.
73 * @param $ext string (without the .)
76 static function normalizeExtension( $ext ) {
77 $lower = strtolower( $ext );
83 if( isset( $squish[$lower] ) ) {
84 return $squish[$lower];
85 } elseif( preg_match( '/^[0-9a-z]+$/', $lower ) ) {
93 * Upgrade the database row if there is one
97 function upgradeRow() {}
100 * Split an internet media type into its two components; if not
101 * a two-part name, set the minor type to 'unknown'.
103 * @param $mime "text/html" etc
104 * @return array ("text", "html") etc
106 static function splitMime( $mime ) {
107 if( strpos( $mime, '/' ) !== false ) {
108 return explode( '/', $mime, 2 );
110 return array( $mime, 'unknown' );
115 * Return the name of this file
117 public function getName() {
118 if ( !isset( $this->name
) ) {
119 $this->name
= $this->repo
->getNameFromTitle( $this->title
);
125 * Get the file extension, e.g. "svg"
127 function getExtension() {
128 if ( !isset( $this->extension
) ) {
129 $n = strrpos( $this->getName(), '.' );
130 $this->extension
= self
::normalizeExtension(
131 $n ?
substr( $this->getName(), $n +
1 ) : '' );
133 return $this->extension
;
137 * Return the associated title object
139 public function getTitle() { return $this->title
; }
142 * Return the URL of the file
144 public function getUrl() {
145 if ( !isset( $this->url
) ) {
146 $this->url
= $this->repo
->getZoneUrl( 'public' ) . '/' . $this->getUrlRel();
152 * Return a fully-qualified URL to the file.
153 * Upload URL paths _may or may not_ be fully qualified, so
154 * we check. Local paths are assumed to belong on $wgServer.
157 public function getFullUrl() {
158 $url = $this->getUrl();
159 if( substr( $url, 0, 1 ) == '/' ) {
161 return $wgServer . $url;
166 function getViewURL() {
167 if( $this->mustRender()) {
168 if( $this->canRender() ) {
169 return $this->createThumb( $this->getWidth() );
172 wfDebug(__METHOD__
.': supposed to render '.$this->getName().' ('.$this->getMimeType()."), but can't!\n");
173 return $this->getURL(); #hm... return NULL?
176 return $this->getURL();
181 * Return the full filesystem path to the file. Note that this does
182 * not mean that a file actually exists under that location.
184 * This path depends on whether directory hashing is active or not,
185 * i.e. whether the files are all found in the same directory,
186 * or in hashed paths like /images/3/3c.
188 * May return false if the file is not locally accessible.
190 public function getPath() {
191 if ( !isset( $this->path
) ) {
192 $this->path
= $this->repo
->getZonePath('public') . '/' . $this->getRel();
198 * Alias for getPath()
200 public function getFullPath() {
201 return $this->getPath();
205 * Return the width of the image. Returns false if the width is unknown
209 * Overridden by LocalFile, UnregisteredLocalFile
211 public function getWidth( $page = 1 ) { return false; }
214 * Return the height of the image. Returns false if the height is unknown
218 * Overridden by LocalFile, UnregisteredLocalFile
220 public function getHeight( $page = 1 ) { return false; }
223 * Returns ID or name of user who uploaded the file
226 * @param $type string 'text' or 'id'
228 public function getUser( $type='text' ) { return null; }
231 * Get the duration of a media file in seconds
233 public function getLength() {
234 $handler = $this->getHandler();
236 return $handler->getLength( $this );
243 * Get handler-specific metadata
244 * Overridden by LocalFile, UnregisteredLocalFile
247 function getMetadata() { return false; }
250 * Return the size of the image file, in bytes
251 * Overridden by LocalFile, UnregisteredLocalFile
254 public function getSize() { return false; }
257 * Returns the mime type of the file.
258 * Overridden by LocalFile, UnregisteredLocalFile
261 function getMimeType() { return 'unknown/unknown'; }
264 * Return the type of the media in the file.
265 * Use the value returned by this function with the MEDIATYPE_xxx constants.
266 * Overridden by LocalFile,
269 function getMediaType() { return MEDIATYPE_UNKNOWN
; }
272 * Checks if the output of transform() for this file is likely
273 * to be valid. If this is false, various user elements will
274 * display a placeholder instead.
276 * Currently, this checks if the file is an image format
277 * that can be converted to a format
278 * supported by all browsers (namely GIF, PNG and JPEG),
279 * or if it is an SVG image and SVG conversion is enabled.
281 function canRender() {
282 if ( !isset( $this->canRender
) ) {
283 $this->canRender
= $this->getHandler() && $this->handler
->canRender( $this );
285 return $this->canRender
;
289 * Accessor for __get()
291 protected function getCanRender() {
292 return $this->canRender();
296 * Return true if the file is of a type that can't be directly
297 * rendered by typical browsers and needs to be re-rasterized.
299 * This returns true for everything but the bitmap types
300 * supported by all browsers, i.e. JPEG; GIF and PNG. It will
301 * also return true for any non-image formats.
305 function mustRender() {
306 return $this->getHandler() && $this->handler
->mustRender( $this );
310 * Alias for canRender()
312 function allowInlineDisplay() {
313 return $this->canRender();
317 * Determines if this media file is in a format that is unlikely to
318 * contain viruses or malicious content. It uses the global
319 * $wgTrustedMediaFormats list to determine if the file is safe.
321 * This is used to show a warning on the description page of non-safe files.
322 * It may also be used to disallow direct [[media:...]] links to such files.
324 * Note that this function will always return true if allowInlineDisplay()
325 * or isTrustedFile() is true for this file.
327 function isSafeFile() {
328 if ( !isset( $this->isSafeFile
) ) {
329 $this->isSafeFile
= $this->_getIsSafeFile();
331 return $this->isSafeFile
;
334 /** Accessor for __get() */
335 protected function getIsSafeFile() {
336 return $this->isSafeFile();
339 /** Uncached accessor */
340 protected function _getIsSafeFile() {
341 if ($this->allowInlineDisplay()) return true;
342 if ($this->isTrustedFile()) return true;
344 global $wgTrustedMediaFormats;
346 $type= $this->getMediaType();
347 $mime= $this->getMimeType();
348 #wfDebug("LocalFile::isSafeFile: type= $type, mime= $mime\n");
350 if (!$type ||
$type===MEDIATYPE_UNKNOWN
) return false; #unknown type, not trusted
351 if ( in_array( $type, $wgTrustedMediaFormats) ) return true;
353 if ($mime==="unknown/unknown") return false; #unknown type, not trusted
354 if ( in_array( $mime, $wgTrustedMediaFormats) ) return true;
359 /** Returns true if the file is flagged as trusted. Files flagged that way
360 * can be linked to directly, even if that is not allowed for this type of
363 * This is a dummy function right now and always returns false. It could be
364 * implemented to extract a flag from the database. The trusted flag could be
365 * set on upload, if the user has sufficient privileges, to bypass script-
366 * and html-filters. It may even be coupled with cryptographics signatures
369 function isTrustedFile() {
370 #this could be implemented to check a flag in the databas,
371 #look for signatures, etc
376 * Returns true if file exists in the repository.
378 * Overridden by LocalFile to avoid unnecessary stat calls.
380 * @return boolean Whether file exists in the repository.
382 public function exists() {
383 return $this->getPath() && file_exists( $this->path
);
386 function getTransformScript() {
387 if ( !isset( $this->transformScript
) ) {
388 $this->transformScript
= false;
390 $script = $this->repo
->getThumbScriptUrl();
392 $this->transformScript
= "$script?f=" . urlencode( $this->getName() );
396 return $this->transformScript
;
400 * Get a ThumbnailImage which is the same size as the source
402 function getUnscaledThumb( $page = false ) {
403 $width = $this->getWidth( $page );
405 return $this->iconThumb();
410 'width' => $this->getWidth( $page )
413 $params = array( 'width' => $this->getWidth() );
415 return $this->transform( $params );
419 * Return the file name of a thumbnail with the specified parameters
421 * @param array $params Handler-specific parameters
424 function thumbName( $params ) {
425 if ( !$this->getHandler() ) {
428 $extension = $this->getExtension();
429 list( $thumbExt, $thumbMime ) = $this->handler
->getThumbType( $extension, $this->getMimeType() );
430 $thumbName = $this->handler
->makeParamString( $params ) . '-' . $this->getName();
431 if ( $thumbExt != $extension ) {
432 $thumbName .= ".$thumbExt";
438 * Create a thumbnail of the image having the specified width/height.
439 * The thumbnail will not be created if the width is larger than the
440 * image's width. Let the browser do the scaling in this case.
441 * The thumbnail is stored on disk and is only computed if the thumbnail
442 * file does not exist OR if it is older than the image.
445 * Keeps aspect ratio of original image. If both width and height are
446 * specified, the generated image will be no bigger than width x height,
447 * and will also have correct aspect ratio.
449 * @param integer $width maximum width of the generated thumbnail
450 * @param integer $height maximum height of the image (optional)
452 public function createThumb( $width, $height = -1 ) {
453 $params = array( 'width' => $width );
454 if ( $height != -1 ) {
455 $params['height'] = $height;
457 $thumb = $this->transform( $params );
458 if( is_null( $thumb ) ||
$thumb->isError() ) return '';
459 return $thumb->getUrl();
463 * As createThumb, but returns a ThumbnailImage object. This can
464 * provide access to the actual file, the real size of the thumb,
465 * and can produce a convenient <img> tag for you.
467 * For non-image formats, this may return a filetype-specific icon.
469 * @param integer $width maximum width of the generated thumbnail
470 * @param integer $height maximum height of the image (optional)
471 * @param boolean $render True to render the thumbnail if it doesn't exist,
472 * false to just return the URL
474 * @return ThumbnailImage or null on failure
476 * @deprecated use transform()
478 public function getThumbnail( $width, $height=-1, $render = true ) {
479 $params = array( 'width' => $width );
480 if ( $height != -1 ) {
481 $params['height'] = $height;
483 $flags = $render ? self
::RENDER_NOW
: 0;
484 return $this->transform( $params, $flags );
488 * Transform a media file
490 * @param array $params An associative array of handler-specific parameters. Typical
491 * keys are width, height and page.
492 * @param integer $flags A bitfield, may contain self::RENDER_NOW to force rendering
493 * @return MediaTransformOutput
495 function transform( $params, $flags = 0 ) {
496 global $wgUseSquid, $wgIgnoreImageErrors;
498 wfProfileIn( __METHOD__
);
500 if ( !$this->canRender() ) {
501 // not a bitmap or renderable image, don't try.
502 $thumb = $this->iconThumb();
506 $script = $this->getTransformScript();
507 if ( $script && !($flags & self
::RENDER_NOW
) ) {
508 // Use a script to transform on client request, if possible
509 $thumb = $this->handler
->getScriptedTransform( $this, $script, $params );
515 $normalisedParams = $params;
516 $this->handler
->normaliseParams( $this, $normalisedParams );
517 $thumbName = $this->thumbName( $normalisedParams );
518 $thumbPath = $this->getThumbPath( $thumbName );
519 $thumbUrl = $this->getThumbUrl( $thumbName );
521 if ( $this->repo
->canTransformVia404() && !($flags & self
::RENDER_NOW
) ) {
522 $thumb = $this->handler
->getTransform( $this, $thumbPath, $thumbUrl, $params );
526 wfDebug( __METHOD__
.": Doing stat for $thumbPath\n" );
527 $this->migrateThumbFile( $thumbName );
528 if ( file_exists( $thumbPath ) ) {
529 $thumb = $this->handler
->getTransform( $this, $thumbPath, $thumbUrl, $params );
532 $thumb = $this->handler
->doTransform( $this, $thumbPath, $thumbUrl, $params );
534 // Ignore errors if requested
537 } elseif ( $thumb->isError() ) {
538 $this->lastError
= $thumb->toText();
539 if ( $wgIgnoreImageErrors && !($flags & self
::RENDER_NOW
) ) {
540 $thumb = $this->handler
->getTransform( $this, $thumbPath, $thumbUrl, $params );
545 wfPurgeSquidServers( array( $thumbUrl ) );
549 wfProfileOut( __METHOD__
);
554 * Hook into transform() to allow migration of thumbnail files
556 * Overridden by LocalFile
558 function migrateThumbFile( $thumbName ) {}
561 * Get a MediaHandler instance for this file
563 function getHandler() {
564 if ( !isset( $this->handler
) ) {
565 $this->handler
= MediaHandler
::getHandler( $this->getMimeType() );
567 return $this->handler
;
571 * Get a ThumbnailImage representing a file type icon
572 * @return ThumbnailImage
574 function iconThumb() {
575 global $wgStylePath, $wgStyleDirectory;
577 $try = array( 'fileicon-' . $this->getExtension() . '.png', 'fileicon.png' );
578 foreach( $try as $icon ) {
579 $path = '/common/images/icons/' . $icon;
580 $filepath = $wgStyleDirectory . $path;
581 if( file_exists( $filepath ) ) {
582 return new ThumbnailImage( $this, $wgStylePath . $path, 120, 120 );
589 * Get last thumbnailing error.
592 function getLastError() {
593 return $this->lastError
;
597 * Get all thumbnail names previously generated for this file
599 * Overridden by LocalFile
601 function getThumbnails() { return array(); }
604 * Purge shared caches such as thumbnails and DB data caching
606 * Overridden by LocalFile
608 function purgeCache() {}
611 * Purge the file description page, but don't go after
612 * pages using the file. Use when modifying file history
613 * but not the current data.
615 function purgeDescription() {
616 $title = $this->getTitle();
618 $title->invalidateCache();
619 $title->purgeSquid();
624 * Purge metadata and all affected pages when the file is created,
625 * deleted, or majorly updated.
627 function purgeEverything() {
628 // Delete thumbnails and refresh file metadata cache
630 $this->purgeDescription();
632 // Purge cache of all pages using this file
633 $title = $this->getTitle();
635 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
641 * Return a fragment of the history of file.
644 * @param $limit integer Limit of rows to return
645 * @param $start timestamp Only revisions older than $start will be returned
646 * @param $end timestamp Only revisions newer than $end will be returned
648 function getHistory($limit = null, $start = null, $end = null) {
653 * Return the history of this file, line by line. Starts with current version,
654 * then old versions. Should return an object similar to an image/oldimage
658 * Overridden in LocalFile
660 public function nextHistoryLine() {
665 * Reset the history pointer to the first element of the history.
666 * Always call this function after using nextHistoryLine() to free db resources
668 * Overridden in LocalFile.
670 public function resetHistory() {}
673 * Get the filename hash component of the directory including trailing slash,
675 * If the repository is not hashed, returns an empty string.
677 function getHashPath() {
678 if ( !isset( $this->hashPath
) ) {
679 $this->hashPath
= $this->repo
->getHashPath( $this->getName() );
681 return $this->hashPath
;
685 * Get the path of the file relative to the public zone root
688 return $this->getHashPath() . $this->getName();
692 * Get urlencoded relative path of the file
694 function getUrlRel() {
695 return $this->getHashPath() . rawurlencode( $this->getName() );
698 /** Get the relative path for an archive file */
699 function getArchiveRel( $suffix = false ) {
700 $path = 'archive/' . $this->getHashPath();
701 if ( $suffix === false ) {
702 $path = substr( $path, 0, -1 );
709 /** Get relative path for a thumbnail file */
710 function getThumbRel( $suffix = false ) {
711 $path = 'thumb/' . $this->getRel();
712 if ( $suffix !== false ) {
713 $path .= '/' . $suffix;
718 /** Get the path of the archive directory, or a particular file if $suffix is specified */
719 function getArchivePath( $suffix = false ) {
720 return $this->repo
->getZonePath('public') . '/' . $this->getArchiveRel();
723 /** Get the path of the thumbnail directory, or a particular file if $suffix is specified */
724 function getThumbPath( $suffix = false ) {
725 return $this->repo
->getZonePath('public') . '/' . $this->getThumbRel( $suffix );
728 /** Get the URL of the archive directory, or a particular file if $suffix is specified */
729 function getArchiveUrl( $suffix = false ) {
730 $path = $this->repo
->getZoneUrl('public') . '/archive/' . $this->getHashPath();
731 if ( $suffix === false ) {
732 $path = substr( $path, 0, -1 );
734 $path .= rawurlencode( $suffix );
739 /** Get the URL of the thumbnail directory, or a particular file if $suffix is specified */
740 function getThumbUrl( $suffix = false ) {
741 $path = $this->repo
->getZoneUrl('public') . '/thumb/' . $this->getUrlRel();
742 if ( $suffix !== false ) {
743 $path .= '/' . rawurlencode( $suffix );
748 /** Get the virtual URL for an archive file or directory */
749 function getArchiveVirtualUrl( $suffix = false ) {
750 $path = $this->repo
->getVirtualUrl() . '/public/archive/' . $this->getHashPath();
751 if ( $suffix === false ) {
752 $path = substr( $path, 0, -1 );
754 $path .= rawurlencode( $suffix );
759 /** Get the virtual URL for a thumbnail file or directory */
760 function getThumbVirtualUrl( $suffix = false ) {
761 $path = $this->repo
->getVirtualUrl() . '/public/thumb/' . $this->getUrlRel();
762 if ( $suffix !== false ) {
763 $path .= '/' . rawurlencode( $suffix );
768 /** Get the virtual URL for the file itself */
769 function getVirtualUrl( $suffix = false ) {
770 $path = $this->repo
->getVirtualUrl() . '/public/' . $this->getUrlRel();
771 if ( $suffix !== false ) {
772 $path .= '/' . rawurlencode( $suffix );
780 function isHashed() {
781 return $this->repo
->isHashed();
784 function readOnlyError() {
785 throw new MWException( get_class($this) . ': write operations are not supported' );
789 * Record a file upload in the upload log and the image table
791 * Overridden by LocalFile
793 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '', $watch = false ) {
794 $this->readOnlyError();
798 * Move or copy a file to its public location. If a file exists at the
799 * destination, move it to an archive. Returns the archive name on success
800 * or an empty string if it was a new file, and a wikitext-formatted
801 * WikiError object on failure.
803 * The archive name should be passed through to recordUpload for database
806 * @param string $sourcePath Local filesystem path to the source image
807 * @param integer $flags A bitwise combination of:
808 * File::DELETE_SOURCE Delete the source file, i.e. move
810 * @return The archive name on success or an empty string if it was a new
811 * file, and a wikitext-formatted WikiError object on failure.
814 * Overridden by LocalFile
816 function publish( $srcPath, $flags = 0 ) {
817 $this->readOnlyError();
821 * Get an array of Title objects which are articles which use this file
822 * Also adds their IDs to the link cache
824 * This is mostly copied from Title::getLinksTo()
826 * @deprecated Use HTMLCacheUpdate, this function uses too much memory
828 function getLinksTo( $options = '' ) {
829 wfProfileIn( __METHOD__
);
831 // Note: use local DB not repo DB, we want to know local links
833 $db = wfGetDB( DB_MASTER
);
835 $db = wfGetDB( DB_SLAVE
);
837 $linkCache =& LinkCache
::singleton();
839 list( $page, $imagelinks ) = $db->tableNamesN( 'page', 'imagelinks' );
840 $encName = $db->addQuotes( $this->getName() );
841 $sql = "SELECT page_namespace,page_title,page_id FROM $page,$imagelinks WHERE page_id=il_from AND il_to=$encName $options";
842 $res = $db->query( $sql, __METHOD__
);
845 if ( $db->numRows( $res ) ) {
846 while ( $row = $db->fetchObject( $res ) ) {
847 if ( $titleObj = Title
::makeTitle( $row->page_namespace
, $row->page_title
) ) {
848 $linkCache->addGoodLinkObj( $row->page_id
, $titleObj );
849 $retVal[] = $titleObj;
853 $db->freeResult( $res );
854 wfProfileOut( __METHOD__
);
858 function formatMetadata() {
859 if ( !$this->getHandler() ) {
862 return $this->getHandler()->formatMetadata( $this, $this->getMetadata() );
866 * Returns true if the file comes from the local file repository.
871 return $this->getRepoName() == 'local';
875 * Returns the name of the repository.
879 function getRepoName() {
880 return $this->repo ?
$this->repo
->getName() : 'unknown';
884 * Returns true if the image is an old version
892 * Is this file a "deleted" file in a private archive?
895 function isDeleted( $field ) {
900 * Was this file ever deleted from the wiki?
904 function wasDeleted() {
905 $title = $this->getTitle();
906 return $title && $title->isDeleted() > 0;
910 * Delete all versions of the file.
912 * Moves the files into an archive directory (or deletes them)
913 * and removes the database rows.
915 * Cache purging is done; logging is caller's responsibility.
918 * @return true on success, false on some kind of failure
920 * Overridden by LocalFile
922 function delete( $reason ) {
923 $this->readOnlyError();
927 * Restore all or specified deleted revisions to the given file.
928 * Permissions and logging are left to the caller.
930 * May throw database exceptions on error.
932 * @param $versions set of record ids of deleted items to restore,
933 * or empty to restore all revisions.
934 * @return the number of file revisions restored if successful,
935 * or false on failure
937 * Overridden by LocalFile
939 function restore( $versions=array(), $Unsuppress=false ) {
940 $this->readOnlyError();
944 * Returns 'true' if this image is a multipage document, e.g. a DJVU
949 function isMultipage() {
950 return $this->getHandler() && $this->handler
->isMultiPage( $this );
954 * Returns the number of pages of a multipage document, or NULL for
955 * documents which aren't multipage documents
957 function pageCount() {
958 if ( !isset( $this->pageCount
) ) {
959 if ( $this->getHandler() && $this->handler
->isMultiPage( $this ) ) {
960 $this->pageCount
= $this->handler
->pageCount( $this );
962 $this->pageCount
= false;
965 return $this->pageCount
;
969 * Calculate the height of a thumbnail using the source and destination width
971 static function scaleHeight( $srcWidth, $srcHeight, $dstWidth ) {
972 // Exact integer multiply followed by division
973 if ( $srcWidth == 0 ) {
976 return round( $srcHeight * $dstWidth / $srcWidth );
981 * Get an image size array like that returned by getimagesize(), or false if it
982 * can't be determined.
984 * @param string $fileName The filename
987 function getImageSize( $fileName ) {
988 if ( !$this->getHandler() ) {
991 return $this->handler
->getImageSize( $this, $fileName );
995 * Get the URL of the image description page. May return false if it is
996 * unknown or not applicable.
998 function getDescriptionUrl() {
999 return $this->repo
->getDescriptionUrl( $this->getName() );
1003 * Get the HTML text of the description page, if available
1005 function getDescriptionText() {
1006 if ( !$this->repo
->fetchDescription
) {
1009 $renderUrl = $this->repo
->getDescriptionRenderUrl( $this->getName() );
1011 wfDebug( "Fetching shared description from $renderUrl\n" );
1012 return Http
::get( $renderUrl );
1019 * Get discription of file revision
1022 function getDescription() {
1027 * Get the 14-character timestamp of the file upload, or false if
1030 function getTimestamp() {
1031 $path = $this->getPath();
1032 if ( !file_exists( $path ) ) {
1035 return wfTimestamp( filemtime( $path ) );
1039 * Get the SHA-1 base 36 hash of the file
1041 function getSha1() {
1042 return self
::sha1Base36( $this->getPath() );
1046 * Determine if the current user is allowed to view a particular
1047 * field of this file, if it's marked as deleted.
1052 function userCan( $field ) {
1057 * Get an associative array containing information about a file in the local filesystem.
1059 * @param string $path Absolute local filesystem path
1060 * @param mixed $ext The file extension, or true to extract it from the filename.
1061 * Set it to false to ignore the extension.
1063 static function getPropsFromPath( $path, $ext = true ) {
1064 wfProfileIn( __METHOD__
);
1065 wfDebug( __METHOD__
.": Getting file info for $path\n" );
1067 'fileExists' => file_exists( $path ) && !is_dir( $path )
1070 if ( $info['fileExists'] ) {
1071 $magic = MimeMagic
::singleton();
1073 $info['mime'] = $magic->guessMimeType( $path, $ext );
1074 list( $info['major_mime'], $info['minor_mime'] ) = self
::splitMime( $info['mime'] );
1075 $info['media_type'] = $magic->getMediaType( $path, $info['mime'] );
1078 $info['size'] = filesize( $path );
1080 # Height, width and metadata
1081 $handler = MediaHandler
::getHandler( $info['mime'] );
1083 $tempImage = (object)array();
1084 $info['metadata'] = $handler->getMetadata( $tempImage, $path );
1085 $gis = $handler->getImageSize( $tempImage, $path, $info['metadata'] );
1088 $info['metadata'] = '';
1090 $info['sha1'] = self
::sha1Base36( $path );
1092 wfDebug(__METHOD__
.": $path loaded, {$info['size']} bytes, {$info['mime']}.\n");
1094 $info['mime'] = NULL;
1095 $info['media_type'] = MEDIATYPE_UNKNOWN
;
1096 $info['metadata'] = '';
1098 wfDebug(__METHOD__
.": $path NOT FOUND!\n");
1101 # NOTE: $gis[2] contains a code for the image type. This is no longer used.
1102 $info['width'] = $gis[0];
1103 $info['height'] = $gis[1];
1104 if ( isset( $gis['bits'] ) ) {
1105 $info['bits'] = $gis['bits'];
1111 $info['height'] = 0;
1114 wfProfileOut( __METHOD__
);
1119 * Get a SHA-1 hash of a file in the local filesystem, in base-36 lower case
1120 * encoding, zero padded to 31 digits.
1122 * 160 log 2 / log 36 = 30.95, so the 160-bit hash fills 31 digits in base 36
1125 * Returns false on failure
1127 static function sha1Base36( $path ) {
1128 wfSuppressWarnings();
1129 $hash = sha1_file( $path );
1130 wfRestoreWarnings();
1131 if ( $hash === false ) {
1134 return wfBaseConvert( $hash, 16, 36, 31 );
1138 function getLongDesc() {
1139 $handler = $this->getHandler();
1141 return $handler->getLongDesc( $this );
1143 return MediaHandler
::getLongDesc( $this );
1147 function getShortDesc() {
1148 $handler = $this->getHandler();
1150 return $handler->getShortDesc( $this );
1152 return MediaHandler
::getShortDesc( $this );
1156 function getDimensionsString() {
1157 $handler = $this->getHandler();
1159 return $handler->getDimensionsString( $this );
1165 function getRedirected() {
1166 return $this->redirected
;
1169 function redirectedFrom( $from ) {
1170 $this->redirected
= $from;
1174 * Aliases for backwards compatibility with 1.6
1176 define( 'MW_IMG_DELETED_FILE', File
::DELETED_FILE
);
1177 define( 'MW_IMG_DELETED_COMMENT', File
::DELETED_COMMENT
);
1178 define( 'MW_IMG_DELETED_USER', File
::DELETED_USER
);
1179 define( 'MW_IMG_DELETED_RESTRICTED', File
::DELETED_RESTRICTED
);