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 return wfExpandUrl( $this->getUrl() );
161 function getViewURL() {
162 if( $this->mustRender()) {
163 if( $this->canRender() ) {
164 return $this->createThumb( $this->getWidth() );
167 wfDebug(__METHOD__
.': supposed to render '.$this->getName().' ('.$this->getMimeType()."), but can't!\n");
168 return $this->getURL(); #hm... return NULL?
171 return $this->getURL();
176 * Return the full filesystem path to the file. Note that this does
177 * not mean that a file actually exists under that location.
179 * This path depends on whether directory hashing is active or not,
180 * i.e. whether the files are all found in the same directory,
181 * or in hashed paths like /images/3/3c.
183 * May return false if the file is not locally accessible.
185 public function getPath() {
186 if ( !isset( $this->path
) ) {
187 $this->path
= $this->repo
->getZonePath('public') . '/' . $this->getRel();
193 * Alias for getPath()
195 public function getFullPath() {
196 return $this->getPath();
200 * Return the width of the image. Returns false if the width is unknown
204 * Overridden by LocalFile, UnregisteredLocalFile
206 public function getWidth( $page = 1 ) { return false; }
209 * Return the height of the image. Returns false if the height is unknown
213 * Overridden by LocalFile, UnregisteredLocalFile
215 public function getHeight( $page = 1 ) { return false; }
218 * Returns ID or name of user who uploaded the file
221 * @param $type string 'text' or 'id'
223 public function getUser( $type='text' ) { return null; }
226 * Get the duration of a media file in seconds
228 public function getLength() {
229 $handler = $this->getHandler();
231 return $handler->getLength( $this );
238 * Get handler-specific metadata
239 * Overridden by LocalFile, UnregisteredLocalFile
242 function getMetadata() { return false; }
245 * Return the size of the image file, in bytes
246 * Overridden by LocalFile, UnregisteredLocalFile
249 public function getSize() { return false; }
252 * Returns the mime type of the file.
253 * Overridden by LocalFile, UnregisteredLocalFile
256 function getMimeType() { return 'unknown/unknown'; }
259 * Return the type of the media in the file.
260 * Use the value returned by this function with the MEDIATYPE_xxx constants.
261 * Overridden by LocalFile,
264 function getMediaType() { return MEDIATYPE_UNKNOWN
; }
267 * Checks if the output of transform() for this file is likely
268 * to be valid. If this is false, various user elements will
269 * display a placeholder instead.
271 * Currently, this checks if the file is an image format
272 * that can be converted to a format
273 * supported by all browsers (namely GIF, PNG and JPEG),
274 * or if it is an SVG image and SVG conversion is enabled.
276 function canRender() {
277 if ( !isset( $this->canRender
) ) {
278 $this->canRender
= $this->getHandler() && $this->handler
->canRender( $this );
280 return $this->canRender
;
284 * Accessor for __get()
286 protected function getCanRender() {
287 return $this->canRender();
291 * Return true if the file is of a type that can't be directly
292 * rendered by typical browsers and needs to be re-rasterized.
294 * This returns true for everything but the bitmap types
295 * supported by all browsers, i.e. JPEG; GIF and PNG. It will
296 * also return true for any non-image formats.
300 function mustRender() {
301 return $this->getHandler() && $this->handler
->mustRender( $this );
305 * Alias for canRender()
307 function allowInlineDisplay() {
308 return $this->canRender();
312 * Determines if this media file is in a format that is unlikely to
313 * contain viruses or malicious content. It uses the global
314 * $wgTrustedMediaFormats list to determine if the file is safe.
316 * This is used to show a warning on the description page of non-safe files.
317 * It may also be used to disallow direct [[media:...]] links to such files.
319 * Note that this function will always return true if allowInlineDisplay()
320 * or isTrustedFile() is true for this file.
322 function isSafeFile() {
323 if ( !isset( $this->isSafeFile
) ) {
324 $this->isSafeFile
= $this->_getIsSafeFile();
326 return $this->isSafeFile
;
329 /** Accessor for __get() */
330 protected function getIsSafeFile() {
331 return $this->isSafeFile();
334 /** Uncached accessor */
335 protected function _getIsSafeFile() {
336 if ($this->allowInlineDisplay()) return true;
337 if ($this->isTrustedFile()) return true;
339 global $wgTrustedMediaFormats;
341 $type= $this->getMediaType();
342 $mime= $this->getMimeType();
343 #wfDebug("LocalFile::isSafeFile: type= $type, mime= $mime\n");
345 if (!$type ||
$type===MEDIATYPE_UNKNOWN
) return false; #unknown type, not trusted
346 if ( in_array( $type, $wgTrustedMediaFormats) ) return true;
348 if ($mime==="unknown/unknown") return false; #unknown type, not trusted
349 if ( in_array( $mime, $wgTrustedMediaFormats) ) return true;
354 /** Returns true if the file is flagged as trusted. Files flagged that way
355 * can be linked to directly, even if that is not allowed for this type of
358 * This is a dummy function right now and always returns false. It could be
359 * implemented to extract a flag from the database. The trusted flag could be
360 * set on upload, if the user has sufficient privileges, to bypass script-
361 * and html-filters. It may even be coupled with cryptographics signatures
364 function isTrustedFile() {
365 #this could be implemented to check a flag in the databas,
366 #look for signatures, etc
371 * Returns true if file exists in the repository.
373 * Overridden by LocalFile to avoid unnecessary stat calls.
375 * @return boolean Whether file exists in the repository.
377 public function exists() {
378 return $this->getPath() && file_exists( $this->path
);
381 function getTransformScript() {
382 if ( !isset( $this->transformScript
) ) {
383 $this->transformScript
= false;
385 $script = $this->repo
->getThumbScriptUrl();
387 $this->transformScript
= "$script?f=" . urlencode( $this->getName() );
391 return $this->transformScript
;
395 * Get a ThumbnailImage which is the same size as the source
397 function getUnscaledThumb( $page = false ) {
398 $width = $this->getWidth( $page );
400 return $this->iconThumb();
405 'width' => $this->getWidth( $page )
408 $params = array( 'width' => $this->getWidth() );
410 return $this->transform( $params );
414 * Return the file name of a thumbnail with the specified parameters
416 * @param array $params Handler-specific parameters
419 function thumbName( $params ) {
420 if ( !$this->getHandler() ) {
423 $extension = $this->getExtension();
424 list( $thumbExt, $thumbMime ) = $this->handler
->getThumbType( $extension, $this->getMimeType() );
425 $thumbName = $this->handler
->makeParamString( $params ) . '-' . $this->getName();
426 if ( $thumbExt != $extension ) {
427 $thumbName .= ".$thumbExt";
433 * Create a thumbnail of the image having the specified width/height.
434 * The thumbnail will not be created if the width is larger than the
435 * image's width. Let the browser do the scaling in this case.
436 * The thumbnail is stored on disk and is only computed if the thumbnail
437 * file does not exist OR if it is older than the image.
440 * Keeps aspect ratio of original image. If both width and height are
441 * specified, the generated image will be no bigger than width x height,
442 * and will also have correct aspect ratio.
444 * @param integer $width maximum width of the generated thumbnail
445 * @param integer $height maximum height of the image (optional)
447 public function createThumb( $width, $height = -1 ) {
448 $params = array( 'width' => $width );
449 if ( $height != -1 ) {
450 $params['height'] = $height;
452 $thumb = $this->transform( $params );
453 if( is_null( $thumb ) ||
$thumb->isError() ) return '';
454 return $thumb->getUrl();
458 * As createThumb, but returns a ThumbnailImage object. This can
459 * provide access to the actual file, the real size of the thumb,
460 * and can produce a convenient <img> tag for you.
462 * For non-image formats, this may return a filetype-specific icon.
464 * @param integer $width maximum width of the generated thumbnail
465 * @param integer $height maximum height of the image (optional)
466 * @param boolean $render True to render the thumbnail if it doesn't exist,
467 * false to just return the URL
469 * @return ThumbnailImage or null on failure
471 * @deprecated use transform()
473 public function getThumbnail( $width, $height=-1, $render = true ) {
474 $params = array( 'width' => $width );
475 if ( $height != -1 ) {
476 $params['height'] = $height;
478 $flags = $render ? self
::RENDER_NOW
: 0;
479 return $this->transform( $params, $flags );
483 * Transform a media file
485 * @param array $params An associative array of handler-specific parameters. Typical
486 * keys are width, height and page.
487 * @param integer $flags A bitfield, may contain self::RENDER_NOW to force rendering
488 * @return MediaTransformOutput
490 function transform( $params, $flags = 0 ) {
491 global $wgUseSquid, $wgIgnoreImageErrors;
493 wfProfileIn( __METHOD__
);
495 if ( !$this->canRender() ) {
496 // not a bitmap or renderable image, don't try.
497 $thumb = $this->iconThumb();
501 $script = $this->getTransformScript();
502 if ( $script && !($flags & self
::RENDER_NOW
) ) {
503 // Use a script to transform on client request, if possible
504 $thumb = $this->handler
->getScriptedTransform( $this, $script, $params );
510 $normalisedParams = $params;
511 $this->handler
->normaliseParams( $this, $normalisedParams );
512 $thumbName = $this->thumbName( $normalisedParams );
513 $thumbPath = $this->getThumbPath( $thumbName );
514 $thumbUrl = $this->getThumbUrl( $thumbName );
516 if ( $this->repo
->canTransformVia404() && !($flags & self
::RENDER_NOW
) ) {
517 $thumb = $this->handler
->getTransform( $this, $thumbPath, $thumbUrl, $params );
521 wfDebug( __METHOD__
.": Doing stat for $thumbPath\n" );
522 $this->migrateThumbFile( $thumbName );
523 if ( file_exists( $thumbPath ) ) {
524 $thumb = $this->handler
->getTransform( $this, $thumbPath, $thumbUrl, $params );
527 $thumb = $this->handler
->doTransform( $this, $thumbPath, $thumbUrl, $params );
529 // Ignore errors if requested
532 } elseif ( $thumb->isError() ) {
533 $this->lastError
= $thumb->toText();
534 if ( $wgIgnoreImageErrors && !($flags & self
::RENDER_NOW
) ) {
535 $thumb = $this->handler
->getTransform( $this, $thumbPath, $thumbUrl, $params );
540 wfPurgeSquidServers( array( $thumbUrl ) );
544 wfProfileOut( __METHOD__
);
549 * Hook into transform() to allow migration of thumbnail files
551 * Overridden by LocalFile
553 function migrateThumbFile( $thumbName ) {}
556 * Get a MediaHandler instance for this file
558 function getHandler() {
559 if ( !isset( $this->handler
) ) {
560 $this->handler
= MediaHandler
::getHandler( $this->getMimeType() );
562 return $this->handler
;
566 * Get a ThumbnailImage representing a file type icon
567 * @return ThumbnailImage
569 function iconThumb() {
570 global $wgStylePath, $wgStyleDirectory;
572 $try = array( 'fileicon-' . $this->getExtension() . '.png', 'fileicon.png' );
573 foreach( $try as $icon ) {
574 $path = '/common/images/icons/' . $icon;
575 $filepath = $wgStyleDirectory . $path;
576 if( file_exists( $filepath ) ) {
577 return new ThumbnailImage( $this, $wgStylePath . $path, 120, 120 );
584 * Get last thumbnailing error.
587 function getLastError() {
588 return $this->lastError
;
592 * Get all thumbnail names previously generated for this file
594 * Overridden by LocalFile
596 function getThumbnails() { return array(); }
599 * Purge shared caches such as thumbnails and DB data caching
601 * Overridden by LocalFile
603 function purgeCache() {}
606 * Purge the file description page, but don't go after
607 * pages using the file. Use when modifying file history
608 * but not the current data.
610 function purgeDescription() {
611 $title = $this->getTitle();
613 $title->invalidateCache();
614 $title->purgeSquid();
619 * Purge metadata and all affected pages when the file is created,
620 * deleted, or majorly updated.
622 function purgeEverything() {
623 // Delete thumbnails and refresh file metadata cache
625 $this->purgeDescription();
627 // Purge cache of all pages using this file
628 $title = $this->getTitle();
630 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
636 * Return a fragment of the history of file.
639 * @param $limit integer Limit of rows to return
640 * @param $start timestamp Only revisions older than $start will be returned
641 * @param $end timestamp Only revisions newer than $end will be returned
643 function getHistory($limit = null, $start = null, $end = null) {
648 * Return the history of this file, line by line. Starts with current version,
649 * then old versions. Should return an object similar to an image/oldimage
653 * Overridden in LocalFile
655 public function nextHistoryLine() {
660 * Reset the history pointer to the first element of the history.
661 * Always call this function after using nextHistoryLine() to free db resources
663 * Overridden in LocalFile.
665 public function resetHistory() {}
668 * Get the filename hash component of the directory including trailing slash,
670 * If the repository is not hashed, returns an empty string.
672 function getHashPath() {
673 if ( !isset( $this->hashPath
) ) {
674 $this->hashPath
= $this->repo
->getHashPath( $this->getName() );
676 return $this->hashPath
;
680 * Get the path of the file relative to the public zone root
683 return $this->getHashPath() . $this->getName();
687 * Get urlencoded relative path of the file
689 function getUrlRel() {
690 return $this->getHashPath() . rawurlencode( $this->getName() );
693 /** Get the relative path for an archive file */
694 function getArchiveRel( $suffix = false ) {
695 $path = 'archive/' . $this->getHashPath();
696 if ( $suffix === false ) {
697 $path = substr( $path, 0, -1 );
704 /** Get relative path for a thumbnail file */
705 function getThumbRel( $suffix = false ) {
706 $path = 'thumb/' . $this->getRel();
707 if ( $suffix !== false ) {
708 $path .= '/' . $suffix;
713 /** Get the path of the archive directory, or a particular file if $suffix is specified */
714 function getArchivePath( $suffix = false ) {
715 return $this->repo
->getZonePath('public') . '/' . $this->getArchiveRel();
718 /** Get the path of the thumbnail directory, or a particular file if $suffix is specified */
719 function getThumbPath( $suffix = false ) {
720 return $this->repo
->getZonePath('public') . '/' . $this->getThumbRel( $suffix );
723 /** Get the URL of the archive directory, or a particular file if $suffix is specified */
724 function getArchiveUrl( $suffix = false ) {
725 $path = $this->repo
->getZoneUrl('public') . '/archive/' . $this->getHashPath();
726 if ( $suffix === false ) {
727 $path = substr( $path, 0, -1 );
729 $path .= rawurlencode( $suffix );
734 /** Get the URL of the thumbnail directory, or a particular file if $suffix is specified */
735 function getThumbUrl( $suffix = false ) {
736 $path = $this->repo
->getZoneUrl('public') . '/thumb/' . $this->getUrlRel();
737 if ( $suffix !== false ) {
738 $path .= '/' . rawurlencode( $suffix );
743 /** Get the virtual URL for an archive file or directory */
744 function getArchiveVirtualUrl( $suffix = false ) {
745 $path = $this->repo
->getVirtualUrl() . '/public/archive/' . $this->getHashPath();
746 if ( $suffix === false ) {
747 $path = substr( $path, 0, -1 );
749 $path .= rawurlencode( $suffix );
754 /** Get the virtual URL for a thumbnail file or directory */
755 function getThumbVirtualUrl( $suffix = false ) {
756 $path = $this->repo
->getVirtualUrl() . '/public/thumb/' . $this->getUrlRel();
757 if ( $suffix !== false ) {
758 $path .= '/' . rawurlencode( $suffix );
763 /** Get the virtual URL for the file itself */
764 function getVirtualUrl( $suffix = false ) {
765 $path = $this->repo
->getVirtualUrl() . '/public/' . $this->getUrlRel();
766 if ( $suffix !== false ) {
767 $path .= '/' . rawurlencode( $suffix );
775 function isHashed() {
776 return $this->repo
->isHashed();
779 function readOnlyError() {
780 throw new MWException( get_class($this) . ': write operations are not supported' );
784 * Record a file upload in the upload log and the image table
786 * Overridden by LocalFile
788 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '', $watch = false ) {
789 $this->readOnlyError();
793 * Move or copy a file to its public location. If a file exists at the
794 * destination, move it to an archive. Returns the archive name on success
795 * or an empty string if it was a new file, and a wikitext-formatted
796 * WikiError object on failure.
798 * The archive name should be passed through to recordUpload for database
801 * @param string $sourcePath Local filesystem path to the source image
802 * @param integer $flags A bitwise combination of:
803 * File::DELETE_SOURCE Delete the source file, i.e. move
805 * @return The archive name on success or an empty string if it was a new
806 * file, and a wikitext-formatted WikiError object on failure.
809 * Overridden by LocalFile
811 function publish( $srcPath, $flags = 0 ) {
812 $this->readOnlyError();
816 * Get an array of Title objects which are articles which use this file
817 * Also adds their IDs to the link cache
819 * This is mostly copied from Title::getLinksTo()
821 * @deprecated Use HTMLCacheUpdate, this function uses too much memory
823 function getLinksTo( $options = '' ) {
824 wfProfileIn( __METHOD__
);
826 // Note: use local DB not repo DB, we want to know local links
828 $db = wfGetDB( DB_MASTER
);
830 $db = wfGetDB( DB_SLAVE
);
832 $linkCache =& LinkCache
::singleton();
834 list( $page, $imagelinks ) = $db->tableNamesN( 'page', 'imagelinks' );
835 $encName = $db->addQuotes( $this->getName() );
836 $sql = "SELECT page_namespace,page_title,page_id FROM $page,$imagelinks WHERE page_id=il_from AND il_to=$encName $options";
837 $res = $db->query( $sql, __METHOD__
);
840 if ( $db->numRows( $res ) ) {
841 while ( $row = $db->fetchObject( $res ) ) {
842 if ( $titleObj = Title
::makeTitle( $row->page_namespace
, $row->page_title
) ) {
843 $linkCache->addGoodLinkObj( $row->page_id
, $titleObj );
844 $retVal[] = $titleObj;
848 $db->freeResult( $res );
849 wfProfileOut( __METHOD__
);
853 function formatMetadata() {
854 if ( !$this->getHandler() ) {
857 return $this->getHandler()->formatMetadata( $this, $this->getMetadata() );
861 * Returns true if the file comes from the local file repository.
866 return $this->getRepoName() == 'local';
870 * Returns the name of the repository.
874 function getRepoName() {
875 return $this->repo ?
$this->repo
->getName() : 'unknown';
879 * Returns true if the image is an old version
887 * Is this file a "deleted" file in a private archive?
890 function isDeleted( $field ) {
895 * Was this file ever deleted from the wiki?
899 function wasDeleted() {
900 $title = $this->getTitle();
901 return $title && $title->isDeleted() > 0;
905 * Delete all versions of the file.
907 * Moves the files into an archive directory (or deletes them)
908 * and removes the database rows.
910 * Cache purging is done; logging is caller's responsibility.
913 * @return true on success, false on some kind of failure
915 * Overridden by LocalFile
917 function delete( $reason ) {
918 $this->readOnlyError();
922 * Restore all or specified deleted revisions to the given file.
923 * Permissions and logging are left to the caller.
925 * May throw database exceptions on error.
927 * @param $versions set of record ids of deleted items to restore,
928 * or empty to restore all revisions.
929 * @return the number of file revisions restored if successful,
930 * or false on failure
932 * Overridden by LocalFile
934 function restore( $versions=array(), $Unsuppress=false ) {
935 $this->readOnlyError();
939 * Returns 'true' if this image is a multipage document, e.g. a DJVU
944 function isMultipage() {
945 return $this->getHandler() && $this->handler
->isMultiPage( $this );
949 * Returns the number of pages of a multipage document, or NULL for
950 * documents which aren't multipage documents
952 function pageCount() {
953 if ( !isset( $this->pageCount
) ) {
954 if ( $this->getHandler() && $this->handler
->isMultiPage( $this ) ) {
955 $this->pageCount
= $this->handler
->pageCount( $this );
957 $this->pageCount
= false;
960 return $this->pageCount
;
964 * Calculate the height of a thumbnail using the source and destination width
966 static function scaleHeight( $srcWidth, $srcHeight, $dstWidth ) {
967 // Exact integer multiply followed by division
968 if ( $srcWidth == 0 ) {
971 return round( $srcHeight * $dstWidth / $srcWidth );
976 * Get an image size array like that returned by getimagesize(), or false if it
977 * can't be determined.
979 * @param string $fileName The filename
982 function getImageSize( $fileName ) {
983 if ( !$this->getHandler() ) {
986 return $this->handler
->getImageSize( $this, $fileName );
990 * Get the URL of the image description page. May return false if it is
991 * unknown or not applicable.
993 function getDescriptionUrl() {
994 return $this->repo
->getDescriptionUrl( $this->getName() );
998 * Get the HTML text of the description page, if available
1000 function getDescriptionText() {
1001 if ( !$this->repo
->fetchDescription
) {
1004 $renderUrl = $this->repo
->getDescriptionRenderUrl( $this->getName() );
1006 wfDebug( "Fetching shared description from $renderUrl\n" );
1007 return Http
::get( $renderUrl );
1014 * Get discription of file revision
1017 function getDescription() {
1022 * Get the 14-character timestamp of the file upload, or false if
1025 function getTimestamp() {
1026 $path = $this->getPath();
1027 if ( !file_exists( $path ) ) {
1030 return wfTimestamp( filemtime( $path ) );
1034 * Get the SHA-1 base 36 hash of the file
1036 function getSha1() {
1037 return self
::sha1Base36( $this->getPath() );
1041 * Determine if the current user is allowed to view a particular
1042 * field of this file, if it's marked as deleted.
1047 function userCan( $field ) {
1052 * Get an associative array containing information about a file in the local filesystem.
1054 * @param string $path Absolute local filesystem path
1055 * @param mixed $ext The file extension, or true to extract it from the filename.
1056 * Set it to false to ignore the extension.
1058 static function getPropsFromPath( $path, $ext = true ) {
1059 wfProfileIn( __METHOD__
);
1060 wfDebug( __METHOD__
.": Getting file info for $path\n" );
1062 'fileExists' => file_exists( $path ) && !is_dir( $path )
1065 if ( $info['fileExists'] ) {
1066 $magic = MimeMagic
::singleton();
1068 $info['mime'] = $magic->guessMimeType( $path, $ext );
1069 list( $info['major_mime'], $info['minor_mime'] ) = self
::splitMime( $info['mime'] );
1070 $info['media_type'] = $magic->getMediaType( $path, $info['mime'] );
1073 $info['size'] = filesize( $path );
1075 # Height, width and metadata
1076 $handler = MediaHandler
::getHandler( $info['mime'] );
1078 $tempImage = (object)array();
1079 $info['metadata'] = $handler->getMetadata( $tempImage, $path );
1080 $gis = $handler->getImageSize( $tempImage, $path, $info['metadata'] );
1083 $info['metadata'] = '';
1085 $info['sha1'] = self
::sha1Base36( $path );
1087 wfDebug(__METHOD__
.": $path loaded, {$info['size']} bytes, {$info['mime']}.\n");
1089 $info['mime'] = NULL;
1090 $info['media_type'] = MEDIATYPE_UNKNOWN
;
1091 $info['metadata'] = '';
1093 wfDebug(__METHOD__
.": $path NOT FOUND!\n");
1096 # NOTE: $gis[2] contains a code for the image type. This is no longer used.
1097 $info['width'] = $gis[0];
1098 $info['height'] = $gis[1];
1099 if ( isset( $gis['bits'] ) ) {
1100 $info['bits'] = $gis['bits'];
1106 $info['height'] = 0;
1109 wfProfileOut( __METHOD__
);
1114 * Get a SHA-1 hash of a file in the local filesystem, in base-36 lower case
1115 * encoding, zero padded to 31 digits.
1117 * 160 log 2 / log 36 = 30.95, so the 160-bit hash fills 31 digits in base 36
1120 * Returns false on failure
1122 static function sha1Base36( $path ) {
1123 wfSuppressWarnings();
1124 $hash = sha1_file( $path );
1125 wfRestoreWarnings();
1126 if ( $hash === false ) {
1129 return wfBaseConvert( $hash, 16, 36, 31 );
1133 function getLongDesc() {
1134 $handler = $this->getHandler();
1136 return $handler->getLongDesc( $this );
1138 return MediaHandler
::getLongDesc( $this );
1142 function getShortDesc() {
1143 $handler = $this->getHandler();
1145 return $handler->getShortDesc( $this );
1147 return MediaHandler
::getShortDesc( $this );
1151 function getDimensionsString() {
1152 $handler = $this->getHandler();
1154 return $handler->getDimensionsString( $this );
1160 function getRedirected() {
1161 return $this->redirected
;
1164 function redirectedFrom( $from ) {
1165 $this->redirected
= $from;
1169 * Aliases for backwards compatibility with 1.6
1171 define( 'MW_IMG_DELETED_FILE', File
::DELETED_FILE
);
1172 define( 'MW_IMG_DELETED_COMMENT', File
::DELETED_COMMENT
);
1173 define( 'MW_IMG_DELETED_USER', File
::DELETED_USER
);
1174 define( 'MW_IMG_DELETED_RESTRICTED', File
::DELETED_RESTRICTED
);