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;
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
140 function getTitle() { return $this->title
; }
143 * Return the URL of the file
147 if ( !isset( $this->url
) ) {
148 $this->url
= $this->repo
->getZoneUrl( 'public' ) . '/' . $this->getUrlRel();
154 * Return a fully-qualified URL to the file.
155 * Upload URL paths _may or may not_ be fully qualified, so
156 * we check. Local paths are assumed to belong on $wgServer.
159 public function getFullUrl() {
160 $url = $this->getUrl();
161 if( substr( $url, 0, 1 ) == '/' ) {
163 return $wgServer . $url;
168 function getViewURL() {
169 if( $this->mustRender()) {
170 if( $this->canRender() ) {
171 return $this->createThumb( $this->getWidth() );
174 wfDebug(__METHOD__
.': supposed to render '.$this->getName().' ('.$this->getMimeType()."), but can't!\n");
175 return $this->getURL(); #hm... return NULL?
178 return $this->getURL();
183 * Return the full filesystem path to the file. Note that this does
184 * not mean that a file actually exists under that location.
186 * This path depends on whether directory hashing is active or not,
187 * i.e. whether the files are all found in the same directory,
188 * or in hashed paths like /images/3/3c.
190 * May return false if the file is not locally accessible.
195 if ( !isset( $this->path
) ) {
196 $this->path
= $this->repo
->getZonePath('public') . '/' . $this->getRel();
202 * Alias for getPath()
205 function getFullPath() {
206 return $this->getPath();
210 * Return the width of the image. Returns false if the width is unknown
214 * Overridden by LocalFile, UnregisteredLocalFile
216 public function getWidth( $page = 1 ) { return false; }
219 * Return the height of the image. Returns false if the height is unknown
223 * Overridden by LocalFile, UnregisteredLocalFile
225 public function getHeight( $page = 1 ) { return false; }
228 * Get the duration of a media file in seconds
230 public function getLength() {
231 $handler = $this->getHandler();
233 return $handler->getLength( $this );
240 * Get handler-specific metadata
241 * Overridden by LocalFile, UnregisteredLocalFile
244 function getMetadata() { return false; }
247 * Return the size of the image file, in bytes
248 * Overridden by LocalFile, UnregisteredLocalFile
251 public function getSize() { return false; }
254 * Returns the mime type of the file.
255 * Overridden by LocalFile, UnregisteredLocalFile
258 function getMimeType() { return 'unknown/unknown'; }
261 * Return the type of the media in the file.
262 * Use the value returned by this function with the MEDIATYPE_xxx constants.
263 * Overridden by LocalFile,
266 function getMediaType() { return MEDIATYPE_UNKNOWN
; }
269 * Checks if the output of transform() for this file is likely
270 * to be valid. If this is false, various user elements will
271 * display a placeholder instead.
273 * Currently, this checks if the file is an image format
274 * that can be converted to a format
275 * supported by all browsers (namely GIF, PNG and JPEG),
276 * or if it is an SVG image and SVG conversion is enabled.
278 function canRender() {
279 if ( !isset( $this->canRender
) ) {
280 $this->canRender
= $this->getHandler() && $this->handler
->canRender( $this );
282 return $this->canRender
;
286 * Accessor for __get()
288 protected function getCanRender() {
289 return $this->canRender();
293 * Return true if the file is of a type that can't be directly
294 * rendered by typical browsers and needs to be re-rasterized.
296 * This returns true for everything but the bitmap types
297 * supported by all browsers, i.e. JPEG; GIF and PNG. It will
298 * also return true for any non-image formats.
302 function mustRender() {
303 return $this->getHandler() && $this->handler
->mustRender( $this );
307 * Alias for canRender()
309 function allowInlineDisplay() {
310 return $this->canRender();
314 * Determines if this media file is in a format that is unlikely to
315 * contain viruses or malicious content. It uses the global
316 * $wgTrustedMediaFormats list to determine if the file is safe.
318 * This is used to show a warning on the description page of non-safe files.
319 * It may also be used to disallow direct [[media:...]] links to such files.
321 * Note that this function will always return true if allowInlineDisplay()
322 * or isTrustedFile() is true for this file.
324 function isSafeFile() {
325 if ( !isset( $this->isSafeFile
) ) {
326 $this->isSafeFile
= $this->_getIsSafeFile();
328 return $this->isSafeFile
;
331 /** Accessor for __get() */
332 protected function getIsSafeFile() {
333 return $this->isSafeFile();
336 /** Uncached accessor */
337 protected function _getIsSafeFile() {
338 if ($this->allowInlineDisplay()) return true;
339 if ($this->isTrustedFile()) return true;
341 global $wgTrustedMediaFormats;
343 $type= $this->getMediaType();
344 $mime= $this->getMimeType();
345 #wfDebug("LocalFile::isSafeFile: type= $type, mime= $mime\n");
347 if (!$type ||
$type===MEDIATYPE_UNKNOWN
) return false; #unknown type, not trusted
348 if ( in_array( $type, $wgTrustedMediaFormats) ) return true;
350 if ($mime==="unknown/unknown") return false; #unknown type, not trusted
351 if ( in_array( $mime, $wgTrustedMediaFormats) ) return true;
356 /** Returns true if the file is flagged as trusted. Files flagged that way
357 * can be linked to directly, even if that is not allowed for this type of
360 * This is a dummy function right now and always returns false. It could be
361 * implemented to extract a flag from the database. The trusted flag could be
362 * set on upload, if the user has sufficient privileges, to bypass script-
363 * and html-filters. It may even be coupled with cryptographics signatures
366 function isTrustedFile() {
367 #this could be implemented to check a flag in the databas,
368 #look for signatures, etc
373 * Returns true if file exists in the repository.
375 * Overridden by LocalFile to avoid unnecessary stat calls.
377 * @return boolean Whether file exists in the repository.
379 public function exists() {
380 return $this->getPath() && file_exists( $this->path
);
383 function getTransformScript() {
384 if ( !isset( $this->transformScript
) ) {
385 $this->transformScript
= false;
387 $script = $this->repo
->getThumbScriptUrl();
389 $this->transformScript
= "$script?f=" . urlencode( $this->getName() );
393 return $this->transformScript
;
397 * Get a ThumbnailImage which is the same size as the source
399 function getUnscaledThumb( $page = false ) {
400 $width = $this->getWidth( $page );
402 return $this->iconThumb();
407 'width' => $this->getWidth( $page )
410 $params = array( 'width' => $this->getWidth() );
412 return $this->transform( $params );
416 * Return the file name of a thumbnail with the specified parameters
418 * @param array $params Handler-specific parameters
421 function thumbName( $params ) {
422 if ( !$this->getHandler() ) {
425 $extension = $this->getExtension();
426 list( $thumbExt, $thumbMime ) = $this->handler
->getThumbType( $extension, $this->getMimeType() );
427 $thumbName = $this->handler
->makeParamString( $params ) . '-' . $this->getName();
428 if ( $thumbExt != $extension ) {
429 $thumbName .= ".$thumbExt";
435 * Create a thumbnail of the image having the specified width/height.
436 * The thumbnail will not be created if the width is larger than the
437 * image's width. Let the browser do the scaling in this case.
438 * The thumbnail is stored on disk and is only computed if the thumbnail
439 * file does not exist OR if it is older than the image.
442 * Keeps aspect ratio of original image. If both width and height are
443 * specified, the generated image will be no bigger than width x height,
444 * and will also have correct aspect ratio.
446 * @param integer $width maximum width of the generated thumbnail
447 * @param integer $height maximum height of the image (optional)
449 public function createThumb( $width, $height = -1 ) {
450 $params = array( 'width' => $width );
451 if ( $height != -1 ) {
452 $params['height'] = $height;
454 $thumb = $this->transform( $params );
455 if( is_null( $thumb ) ||
$thumb->isError() ) return '';
456 return $thumb->getUrl();
460 * As createThumb, but returns a ThumbnailImage object. This can
461 * provide access to the actual file, the real size of the thumb,
462 * and can produce a convenient <img> tag for you.
464 * For non-image formats, this may return a filetype-specific icon.
466 * @param integer $width maximum width of the generated thumbnail
467 * @param integer $height maximum height of the image (optional)
468 * @param boolean $render True to render the thumbnail if it doesn't exist,
469 * false to just return the URL
471 * @return ThumbnailImage or null on failure
473 * @deprecated use transform()
475 public function getThumbnail( $width, $height=-1, $render = true ) {
476 $params = array( 'width' => $width );
477 if ( $height != -1 ) {
478 $params['height'] = $height;
480 $flags = $render ? self
::RENDER_NOW
: 0;
481 return $this->transform( $params, $flags );
485 * Transform a media file
487 * @param array $params An associative array of handler-specific parameters. Typical
488 * keys are width, height and page.
489 * @param integer $flags A bitfield, may contain self::RENDER_NOW to force rendering
490 * @return MediaTransformOutput
492 function transform( $params, $flags = 0 ) {
493 global $wgUseSquid, $wgIgnoreImageErrors;
495 wfProfileIn( __METHOD__
);
497 if ( !$this->canRender() ) {
498 // not a bitmap or renderable image, don't try.
499 $thumb = $this->iconThumb();
503 $script = $this->getTransformScript();
504 if ( $script && !($flags & self
::RENDER_NOW
) ) {
505 // Use a script to transform on client request
506 $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( $archiveFiles = array() ) {}
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 the history of this file, line by line. Starts with current version,
637 * then old versions. Should return an object similar to an image/oldimage
641 * Overridden in LocalFile
643 public function nextHistoryLine() {
648 * Reset the history pointer to the first element of the history.
649 * Always call this function after using nextHistoryLine() to free db resources
651 * Overridden in LocalFile.
653 public function resetHistory() {}
656 * Get the filename hash component of the directory including trailing slash,
658 * If the repository is not hashed, returns an empty string.
660 function getHashPath() {
661 if ( !isset( $this->hashPath
) ) {
662 $this->hashPath
= $this->repo
->getHashPath( $this->getName() );
664 return $this->hashPath
;
668 * Get the path of the file relative to the public zone root
671 return $this->getHashPath() . $this->getName();
675 * Get urlencoded relative path of the file
677 function getUrlRel() {
678 return $this->getHashPath() . rawurlencode( $this->getName() );
681 /** Get the relative path for an archive file */
682 function getArchiveRel( $suffix = false ) {
683 $path = 'archive/' . $this->getHashPath();
684 if ( $suffix === false ) {
685 $path = substr( $path, 0, -1 );
692 /** Get relative path for a thumbnail file */
693 function getThumbRel( $suffix = false ) {
694 $path = 'thumb/' . $this->getRel();
695 if ( $suffix !== false ) {
696 $path .= '/' . $suffix;
701 /** Get the path of the archive directory, or a particular file if $suffix is specified */
702 function getArchivePath( $suffix = false ) {
703 return $this->repo
->getZonePath('public') . '/' . $this->getArchiveRel();
706 /** Get the path of the thumbnail directory, or a particular file if $suffix is specified */
707 function getThumbPath( $suffix = false ) {
708 return $this->repo
->getZonePath('public') . '/' . $this->getThumbRel( $suffix );
711 /** Get the URL of the archive directory, or a particular file if $suffix is specified */
712 function getArchiveUrl( $suffix = false ) {
713 $path = $this->repo
->getZoneUrl('public') . '/archive/' . $this->getHashPath();
714 if ( $suffix === false ) {
715 $path = substr( $path, 0, -1 );
717 $path .= rawurlencode( $suffix );
722 /** Get the URL of the thumbnail directory, or a particular file if $suffix is specified */
723 function getThumbUrl( $suffix = false ) {
724 $path = $this->repo
->getZoneUrl('public') . '/thumb/' . $this->getUrlRel();
725 if ( $suffix !== false ) {
726 $path .= '/' . rawurlencode( $suffix );
731 /** Get the virtual URL for an archive file or directory */
732 function getArchiveVirtualUrl( $suffix = false ) {
733 $path = $this->repo
->getVirtualUrl() . '/public/archive/' . $this->getHashPath();
734 if ( $suffix === false ) {
735 $path = substr( $path, 0, -1 );
737 $path .= rawurlencode( $suffix );
742 /** Get the virtual URL for a thumbnail file or directory */
743 function getThumbVirtualUrl( $suffix = false ) {
744 $path = $this->repo
->getVirtualUrl() . '/public/thumb/' . $this->getUrlRel();
745 if ( $suffix !== false ) {
746 $path .= '/' . rawurlencode( $suffix );
751 /** Get the virtual URL for the file itself */
752 function getVirtualUrl( $suffix = false ) {
753 $path = $this->repo
->getVirtualUrl() . '/public/' . $this->getUrlRel();
754 if ( $suffix !== false ) {
755 $path .= '/' . rawurlencode( $suffix );
763 function isHashed() {
764 return $this->repo
->isHashed();
767 function readOnlyError() {
768 throw new MWException( get_class($this) . ': write operations are not supported' );
772 * Record a file upload in the upload log and the image table
774 * Overridden by LocalFile
776 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '', $watch = false ) {
777 $this->readOnlyError();
781 * Move or copy a file to its public location. If a file exists at the
782 * destination, move it to an archive. Returns the archive name on success
783 * or an empty string if it was a new file, and a wikitext-formatted
784 * WikiError object on failure.
786 * The archive name should be passed through to recordUpload for database
789 * @param string $sourcePath Local filesystem path to the source image
790 * @param integer $flags A bitwise combination of:
791 * File::DELETE_SOURCE Delete the source file, i.e. move
793 * @return The archive name on success or an empty string if it was a new
794 * file, and a wikitext-formatted WikiError object on failure.
797 * Overridden by LocalFile
799 function publish( $srcPath, $flags = 0 ) {
800 $this->readOnlyError();
804 * Get an array of Title objects which are articles which use this file
805 * Also adds their IDs to the link cache
807 * This is mostly copied from Title::getLinksTo()
809 * @deprecated Use HTMLCacheUpdate, this function uses too much memory
811 function getLinksTo( $options = '' ) {
812 wfProfileIn( __METHOD__
);
814 // Note: use local DB not repo DB, we want to know local links
816 $db = wfGetDB( DB_MASTER
);
818 $db = wfGetDB( DB_SLAVE
);
820 $linkCache =& LinkCache
::singleton();
822 list( $page, $imagelinks ) = $db->tableNamesN( 'page', 'imagelinks' );
823 $encName = $db->addQuotes( $this->getName() );
824 $sql = "SELECT page_namespace,page_title,page_id FROM $page,$imagelinks WHERE page_id=il_from AND il_to=$encName $options";
825 $res = $db->query( $sql, __METHOD__
);
828 if ( $db->numRows( $res ) ) {
829 while ( $row = $db->fetchObject( $res ) ) {
830 if ( $titleObj = Title
::makeTitle( $row->page_namespace
, $row->page_title
) ) {
831 $linkCache->addGoodLinkObj( $row->page_id
, $titleObj );
832 $retVal[] = $titleObj;
836 $db->freeResult( $res );
837 wfProfileOut( __METHOD__
);
841 function formatMetadata() {
842 if ( !$this->getHandler() ) {
845 return $this->getHandler()->formatMetadata( $this, $this->getMetadata() );
849 * Returns true if the file comes from the local file repository.
854 return $this->getRepoName() == 'local';
858 * Returns the name of the repository.
862 function getRepoName() {
863 return $this->repo ?
$this->repo
->getName() : 'unknown';
867 * Returns true if the image is an old version
875 * Is this file a "deleted" file in a private archive?
878 function isDeleted( $field ) {
883 * Was this file ever deleted from the wiki?
887 function wasDeleted() {
888 $title = $this->getTitle();
889 return $title && $title->isDeleted() > 0;
893 * Delete all versions of the file.
895 * Moves the files into an archive directory (or deletes them)
896 * and removes the database rows.
898 * Cache purging is done; logging is caller's responsibility.
901 * @return true on success, false on some kind of failure
903 * Overridden by LocalFile
905 function delete( $reason, $suppress=false ) {
906 $this->readOnlyError();
910 * Restore all or specified deleted revisions to the given file.
911 * Permissions and logging are left to the caller.
913 * May throw database exceptions on error.
915 * @param $versions set of record ids of deleted items to restore,
916 * or empty to restore all revisions.
917 * @return the number of file revisions restored if successful,
918 * or false on failure
920 * Overridden by LocalFile
922 function restore( $versions=array(), $Unsuppress=false ) {
923 $this->readOnlyError();
927 * Returns 'true' if this image is a multipage document, e.g. a DJVU
932 function isMultipage() {
933 return $this->getHandler() && $this->handler
->isMultiPage( $this );
937 * Returns the number of pages of a multipage document, or NULL for
938 * documents which aren't multipage documents
940 function pageCount() {
941 if ( !isset( $this->pageCount
) ) {
942 if ( $this->getHandler() && $this->handler
->isMultiPage( $this ) ) {
943 $this->pageCount
= $this->handler
->pageCount( $this );
945 $this->pageCount
= false;
948 return $this->pageCount
;
952 * Calculate the height of a thumbnail using the source and destination width
954 static function scaleHeight( $srcWidth, $srcHeight, $dstWidth ) {
955 // Exact integer multiply followed by division
956 if ( $srcWidth == 0 ) {
959 return round( $srcHeight * $dstWidth / $srcWidth );
964 * Get an image size array like that returned by getimagesize(), or false if it
965 * can't be determined.
967 * @param string $fileName The filename
970 function getImageSize( $fileName ) {
971 if ( !$this->getHandler() ) {
974 return $this->handler
->getImageSize( $this, $fileName );
978 * Get the URL of the image description page. May return false if it is
979 * unknown or not applicable.
981 function getDescriptionUrl() {
982 return $this->repo
->getDescriptionUrl( $this->getName() );
986 * Get the HTML text of the description page, if available
988 function getDescriptionText() {
989 if ( !$this->repo
->fetchDescription
) {
992 $renderUrl = $this->repo
->getDescriptionRenderUrl( $this->getName() );
994 wfDebug( "Fetching shared description from $renderUrl\n" );
995 return Http
::get( $renderUrl );
1002 * Get the 14-character timestamp of the file upload, or false if
1005 function getTimestamp() {
1006 $path = $this->getPath();
1007 if ( !file_exists( $path ) ) {
1010 return wfTimestamp( filemtime( $path ) );
1014 * Get the SHA-1 base 36 hash of the file
1016 function getSha1() {
1017 return self
::sha1Base36( $this->getPath() );
1021 * Determine if the current user is allowed to view a particular
1022 * field of this file, if it's marked as deleted.
1027 function userCan( $field ) {
1032 * Get an associative array containing information about a file in the local filesystem.
1034 * @param string $path Absolute local filesystem path
1035 * @param mixed $ext The file extension, or true to extract it from the filename.
1036 * Set it to false to ignore the extension.
1038 static function getPropsFromPath( $path, $ext = true ) {
1039 wfProfileIn( __METHOD__
);
1040 wfDebug( __METHOD__
.": Getting file info for $path\n" );
1042 'fileExists' => file_exists( $path ) && !is_dir( $path )
1045 if ( $info['fileExists'] ) {
1046 $magic = MimeMagic
::singleton();
1048 $info['mime'] = $magic->guessMimeType( $path, $ext );
1049 list( $info['major_mime'], $info['minor_mime'] ) = self
::splitMime( $info['mime'] );
1050 $info['media_type'] = $magic->getMediaType( $path, $info['mime'] );
1053 $info['size'] = filesize( $path );
1055 # Height, width and metadata
1056 $handler = MediaHandler
::getHandler( $info['mime'] );
1058 $tempImage = (object)array();
1059 $info['metadata'] = $handler->getMetadata( $tempImage, $path );
1060 $gis = $handler->getImageSize( $tempImage, $path, $info['metadata'] );
1063 $info['metadata'] = '';
1065 $info['sha1'] = self
::sha1Base36( $path );
1067 wfDebug(__METHOD__
.": $path loaded, {$info['size']} bytes, {$info['mime']}.\n");
1069 $info['mime'] = NULL;
1070 $info['media_type'] = MEDIATYPE_UNKNOWN
;
1071 $info['metadata'] = '';
1073 wfDebug(__METHOD__
.": $path NOT FOUND!\n");
1076 # NOTE: $gis[2] contains a code for the image type. This is no longer used.
1077 $info['width'] = $gis[0];
1078 $info['height'] = $gis[1];
1079 if ( isset( $gis['bits'] ) ) {
1080 $info['bits'] = $gis['bits'];
1086 $info['height'] = 0;
1089 wfProfileOut( __METHOD__
);
1094 * Get a SHA-1 hash of a file in the local filesystem, in base-36 lower case
1095 * encoding, zero padded to 31 digits.
1097 * 160 log 2 / log 36 = 30.95, so the 160-bit hash fills 31 digits in base 36
1100 * Returns false on failure
1102 static function sha1Base36( $path ) {
1103 wfSuppressWarnings();
1104 $hash = sha1_file( $path );
1105 wfRestoreWarnings();
1106 if ( $hash === false ) {
1109 return wfBaseConvert( $hash, 16, 36, 31 );
1113 function getLongDesc() {
1114 $handler = $this->getHandler();
1116 return $handler->getLongDesc( $this );
1118 return MediaHandler
::getLongDesc( $this );
1122 function getShortDesc() {
1123 $handler = $this->getHandler();
1125 return $handler->getShortDesc( $this );
1127 return MediaHandler
::getShortDesc( $this );
1131 function getDimensionsString() {
1132 $handler = $this->getHandler();
1134 return $handler->getDimensionsString( $this );
1141 * Aliases for backwards compatibility with 1.6
1143 define( 'MW_IMG_DELETED_FILE', File
::DELETED_FILE
);
1144 define( 'MW_IMG_DELETED_COMMENT', File
::DELETED_COMMENT
);
1145 define( 'MW_IMG_DELETED_USER', File
::DELETED_USER
);
1146 define( 'MW_IMG_DELETED_RESTRICTED', File
::DELETED_RESTRICTED
);