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 * Checks if file extensions are compatible
95 * @param $old File Old file
96 * @param $new string New name
98 static function checkExtensionCompatibility( File
$old, $new ) {
99 $oldMime = $old->getMimeType();
100 $n = strrpos( $new, '.' );
101 $newExt = self
::normalizeExtension(
102 $n ?
substr( $new, $n +
1 ) : '' );
103 $mimeMagic = MimeMagic
::singleton();
104 return $mimeMagic->isMatchingExtension( $newExt, $oldMime );
108 * Upgrade the database row if there is one
109 * Called by ImagePage
112 function upgradeRow() {}
115 * Split an internet media type into its two components; if not
116 * a two-part name, set the minor type to 'unknown'.
118 * @param $mime "text/html" etc
119 * @return array ("text", "html") etc
121 static function splitMime( $mime ) {
122 if( strpos( $mime, '/' ) !== false ) {
123 return explode( '/', $mime, 2 );
125 return array( $mime, 'unknown' );
130 * Return the name of this file
132 public function getName() {
133 if ( !isset( $this->name
) ) {
134 $this->name
= $this->repo
->getNameFromTitle( $this->title
);
140 * Get the file extension, e.g. "svg"
142 function getExtension() {
143 if ( !isset( $this->extension
) ) {
144 $n = strrpos( $this->getName(), '.' );
145 $this->extension
= self
::normalizeExtension(
146 $n ?
substr( $this->getName(), $n +
1 ) : '' );
148 return $this->extension
;
152 * Return the associated title object
154 public function getTitle() { return $this->title
; }
157 * Return the URL of the file
159 public function getUrl() {
160 if ( !isset( $this->url
) ) {
161 $this->url
= $this->repo
->getZoneUrl( 'public' ) . '/' . $this->getUrlRel();
167 * Return a fully-qualified URL to the file.
168 * Upload URL paths _may or may not_ be fully qualified, so
169 * we check. Local paths are assumed to belong on $wgServer.
172 public function getFullUrl() {
173 return wfExpandUrl( $this->getUrl() );
176 function getViewURL() {
177 if( $this->mustRender()) {
178 if( $this->canRender() ) {
179 return $this->createThumb( $this->getWidth() );
182 wfDebug(__METHOD__
.': supposed to render '.$this->getName().' ('.$this->getMimeType()."), but can't!\n");
183 return $this->getURL(); #hm... return NULL?
186 return $this->getURL();
191 * Return the full filesystem path to the file. Note that this does
192 * not mean that a file actually exists under that location.
194 * This path depends on whether directory hashing is active or not,
195 * i.e. whether the files are all found in the same directory,
196 * or in hashed paths like /images/3/3c.
198 * May return false if the file is not locally accessible.
200 public function getPath() {
201 if ( !isset( $this->path
) ) {
202 $this->path
= $this->repo
->getZonePath('public') . '/' . $this->getRel();
208 * Alias for getPath()
210 public function getFullPath() {
211 return $this->getPath();
215 * Return the width of the image. Returns false if the width is unknown
219 * Overridden by LocalFile, UnregisteredLocalFile
221 public function getWidth( $page = 1 ) { return false; }
224 * Return the height of the image. Returns false if the height is unknown
228 * Overridden by LocalFile, UnregisteredLocalFile
230 public function getHeight( $page = 1 ) { return false; }
233 * Returns ID or name of user who uploaded the file
236 * @param $type string 'text' or 'id'
238 public function getUser( $type='text' ) { return null; }
241 * Get the duration of a media file in seconds
243 public function getLength() {
244 $handler = $this->getHandler();
246 return $handler->getLength( $this );
253 * Get handler-specific metadata
254 * Overridden by LocalFile, UnregisteredLocalFile
257 function getMetadata() { return false; }
260 * Return the size of the image file, in bytes
261 * Overridden by LocalFile, UnregisteredLocalFile
264 public function getSize() { return false; }
267 * Returns the mime type of the file.
268 * Overridden by LocalFile, UnregisteredLocalFile
271 function getMimeType() { return 'unknown/unknown'; }
274 * Return the type of the media in the file.
275 * Use the value returned by this function with the MEDIATYPE_xxx constants.
276 * Overridden by LocalFile,
279 function getMediaType() { return MEDIATYPE_UNKNOWN
; }
282 * Checks if the output of transform() for this file is likely
283 * to be valid. If this is false, various user elements will
284 * display a placeholder instead.
286 * Currently, this checks if the file is an image format
287 * that can be converted to a format
288 * supported by all browsers (namely GIF, PNG and JPEG),
289 * or if it is an SVG image and SVG conversion is enabled.
291 function canRender() {
292 if ( !isset( $this->canRender
) ) {
293 $this->canRender
= $this->getHandler() && $this->handler
->canRender( $this );
295 return $this->canRender
;
299 * Accessor for __get()
301 protected function getCanRender() {
302 return $this->canRender();
306 * Return true if the file is of a type that can't be directly
307 * rendered by typical browsers and needs to be re-rasterized.
309 * This returns true for everything but the bitmap types
310 * supported by all browsers, i.e. JPEG; GIF and PNG. It will
311 * also return true for any non-image formats.
315 function mustRender() {
316 return $this->getHandler() && $this->handler
->mustRender( $this );
320 * Alias for canRender()
322 function allowInlineDisplay() {
323 return $this->canRender();
327 * Determines if this media file is in a format that is unlikely to
328 * contain viruses or malicious content. It uses the global
329 * $wgTrustedMediaFormats list to determine if the file is safe.
331 * This is used to show a warning on the description page of non-safe files.
332 * It may also be used to disallow direct [[media:...]] links to such files.
334 * Note that this function will always return true if allowInlineDisplay()
335 * or isTrustedFile() is true for this file.
337 function isSafeFile() {
338 if ( !isset( $this->isSafeFile
) ) {
339 $this->isSafeFile
= $this->_getIsSafeFile();
341 return $this->isSafeFile
;
344 /** Accessor for __get() */
345 protected function getIsSafeFile() {
346 return $this->isSafeFile();
349 /** Uncached accessor */
350 protected function _getIsSafeFile() {
351 if ($this->allowInlineDisplay()) return true;
352 if ($this->isTrustedFile()) return true;
354 global $wgTrustedMediaFormats;
356 $type= $this->getMediaType();
357 $mime= $this->getMimeType();
358 #wfDebug("LocalFile::isSafeFile: type= $type, mime= $mime\n");
360 if (!$type ||
$type===MEDIATYPE_UNKNOWN
) return false; #unknown type, not trusted
361 if ( in_array( $type, $wgTrustedMediaFormats) ) return true;
363 if ($mime==="unknown/unknown") return false; #unknown type, not trusted
364 if ( in_array( $mime, $wgTrustedMediaFormats) ) return true;
369 /** Returns true if the file is flagged as trusted. Files flagged that way
370 * can be linked to directly, even if that is not allowed for this type of
373 * This is a dummy function right now and always returns false. It could be
374 * implemented to extract a flag from the database. The trusted flag could be
375 * set on upload, if the user has sufficient privileges, to bypass script-
376 * and html-filters. It may even be coupled with cryptographics signatures
379 function isTrustedFile() {
380 #this could be implemented to check a flag in the databas,
381 #look for signatures, etc
386 * Returns true if file exists in the repository.
388 * Overridden by LocalFile to avoid unnecessary stat calls.
390 * @return boolean Whether file exists in the repository.
392 public function exists() {
393 return $this->getPath() && file_exists( $this->path
);
397 * Returns true if file exists in the repository and can be included in a page.
398 * It would be unsafe to include private images, making public thumbnails inadvertently
400 * @return boolean Whether file exists in the repository and is includable.
403 function isVisible() {
404 return $this->exists();
407 function getTransformScript() {
408 if ( !isset( $this->transformScript
) ) {
409 $this->transformScript
= false;
411 $script = $this->repo
->getThumbScriptUrl();
413 $this->transformScript
= "$script?f=" . urlencode( $this->getName() );
417 return $this->transformScript
;
421 * Get a ThumbnailImage which is the same size as the source
423 function getUnscaledThumb( $page = false ) {
424 $width = $this->getWidth( $page );
426 return $this->iconThumb();
431 'width' => $this->getWidth( $page )
434 $params = array( 'width' => $this->getWidth() );
436 return $this->transform( $params );
440 * Return the file name of a thumbnail with the specified parameters
442 * @param array $params Handler-specific parameters
445 function thumbName( $params ) {
446 if ( !$this->getHandler() ) {
449 $extension = $this->getExtension();
450 list( $thumbExt, $thumbMime ) = $this->handler
->getThumbType( $extension, $this->getMimeType() );
451 $thumbName = $this->handler
->makeParamString( $params ) . '-' . $this->getName();
452 if ( $thumbExt != $extension ) {
453 $thumbName .= ".$thumbExt";
459 * Create a thumbnail of the image having the specified width/height.
460 * The thumbnail will not be created if the width is larger than the
461 * image's width. Let the browser do the scaling in this case.
462 * The thumbnail is stored on disk and is only computed if the thumbnail
463 * file does not exist OR if it is older than the image.
466 * Keeps aspect ratio of original image. If both width and height are
467 * specified, the generated image will be no bigger than width x height,
468 * and will also have correct aspect ratio.
470 * @param integer $width maximum width of the generated thumbnail
471 * @param integer $height maximum height of the image (optional)
473 public function createThumb( $width, $height = -1 ) {
474 $params = array( 'width' => $width );
475 if ( $height != -1 ) {
476 $params['height'] = $height;
478 $thumb = $this->transform( $params );
479 if( is_null( $thumb ) ||
$thumb->isError() ) return '';
480 return $thumb->getUrl();
484 * As createThumb, but returns a ThumbnailImage object. This can
485 * provide access to the actual file, the real size of the thumb,
486 * and can produce a convenient <img> tag for you.
488 * For non-image formats, this may return a filetype-specific icon.
490 * @param integer $width maximum width of the generated thumbnail
491 * @param integer $height maximum height of the image (optional)
492 * @param boolean $render True to render the thumbnail if it doesn't exist,
493 * false to just return the URL
495 * @return ThumbnailImage or null on failure
497 * @deprecated use transform()
499 public function getThumbnail( $width, $height=-1, $render = true ) {
500 $params = array( 'width' => $width );
501 if ( $height != -1 ) {
502 $params['height'] = $height;
504 $flags = $render ? self
::RENDER_NOW
: 0;
505 return $this->transform( $params, $flags );
509 * Transform a media file
511 * @param array $params An associative array of handler-specific parameters. Typical
512 * keys are width, height and page.
513 * @param integer $flags A bitfield, may contain self::RENDER_NOW to force rendering
514 * @return MediaTransformOutput
516 function transform( $params, $flags = 0 ) {
517 global $wgUseSquid, $wgIgnoreImageErrors;
519 wfProfileIn( __METHOD__
);
521 if ( !$this->canRender() ) {
522 // not a bitmap or renderable image, don't try.
523 $thumb = $this->iconThumb();
527 $script = $this->getTransformScript();
528 if ( $script && !($flags & self
::RENDER_NOW
) ) {
529 // Use a script to transform on client request, if possible
530 $thumb = $this->handler
->getScriptedTransform( $this, $script, $params );
536 $normalisedParams = $params;
537 $this->handler
->normaliseParams( $this, $normalisedParams );
538 $thumbName = $this->thumbName( $normalisedParams );
539 $thumbPath = $this->getThumbPath( $thumbName );
540 $thumbUrl = $this->getThumbUrl( $thumbName );
542 if ( $this->repo
->canTransformVia404() && !($flags & self
::RENDER_NOW
) ) {
543 $thumb = $this->handler
->getTransform( $this, $thumbPath, $thumbUrl, $params );
547 wfDebug( __METHOD__
.": Doing stat for $thumbPath\n" );
548 $this->migrateThumbFile( $thumbName );
549 if ( file_exists( $thumbPath ) ) {
550 $thumb = $this->handler
->getTransform( $this, $thumbPath, $thumbUrl, $params );
553 $thumb = $this->handler
->doTransform( $this, $thumbPath, $thumbUrl, $params );
555 // Ignore errors if requested
558 } elseif ( $thumb->isError() ) {
559 $this->lastError
= $thumb->toText();
560 if ( $wgIgnoreImageErrors && !($flags & self
::RENDER_NOW
) ) {
561 $thumb = $this->handler
->getTransform( $this, $thumbPath, $thumbUrl, $params );
565 // Purge. Useful in the event of Core -> Squid connection failure or squid
566 // purge collisions from elsewhere during failure. Don't keep triggering for
567 // "thumbs" which have the main image URL though (bug 13776)
568 if ( $wgUseSquid && ($thumb->isError() ||
$thumb->getUrl() != $this->getURL()) ) {
569 SquidUpdate
::purge( array( $thumbUrl ) );
573 wfProfileOut( __METHOD__
);
578 * Hook into transform() to allow migration of thumbnail files
580 * Overridden by LocalFile
582 function migrateThumbFile( $thumbName ) {}
585 * Get a MediaHandler instance for this file
587 function getHandler() {
588 if ( !isset( $this->handler
) ) {
589 $this->handler
= MediaHandler
::getHandler( $this->getMimeType() );
591 return $this->handler
;
595 * Get a ThumbnailImage representing a file type icon
596 * @return ThumbnailImage
598 function iconThumb() {
599 global $wgStylePath, $wgStyleDirectory;
601 $try = array( 'fileicon-' . $this->getExtension() . '.png', 'fileicon.png' );
602 foreach( $try as $icon ) {
603 $path = '/common/images/icons/' . $icon;
604 $filepath = $wgStyleDirectory . $path;
605 if( file_exists( $filepath ) ) {
606 return new ThumbnailImage( $this, $wgStylePath . $path, 120, 120 );
613 * Get last thumbnailing error.
616 function getLastError() {
617 return $this->lastError
;
621 * Get all thumbnail names previously generated for this file
623 * Overridden by LocalFile
625 function getThumbnails() { return array(); }
628 * Purge shared caches such as thumbnails and DB data caching
630 * Overridden by LocalFile
632 function purgeCache() {}
635 * Purge the file description page, but don't go after
636 * pages using the file. Use when modifying file history
637 * but not the current data.
639 function purgeDescription() {
640 $title = $this->getTitle();
642 $title->invalidateCache();
643 $title->purgeSquid();
648 * Purge metadata and all affected pages when the file is created,
649 * deleted, or majorly updated.
651 function purgeEverything() {
652 // Delete thumbnails and refresh file metadata cache
654 $this->purgeDescription();
656 // Purge cache of all pages using this file
657 $title = $this->getTitle();
659 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
665 * Return a fragment of the history of file.
668 * @param $limit integer Limit of rows to return
669 * @param $start timestamp Only revisions older than $start will be returned
670 * @param $end timestamp Only revisions newer than $end will be returned
672 function getHistory($limit = null, $start = null, $end = null) {
677 * Return the history of this file, line by line. Starts with current version,
678 * then old versions. Should return an object similar to an image/oldimage
682 * Overridden in LocalFile
684 public function nextHistoryLine() {
689 * Reset the history pointer to the first element of the history.
690 * Always call this function after using nextHistoryLine() to free db resources
692 * Overridden in LocalFile.
694 public function resetHistory() {}
697 * Get the filename hash component of the directory including trailing slash,
699 * If the repository is not hashed, returns an empty string.
701 function getHashPath() {
702 if ( !isset( $this->hashPath
) ) {
703 $this->hashPath
= $this->repo
->getHashPath( $this->getName() );
705 return $this->hashPath
;
709 * Get the path of the file relative to the public zone root
712 return $this->getHashPath() . $this->getName();
716 * Get urlencoded relative path of the file
718 function getUrlRel() {
719 return $this->getHashPath() . rawurlencode( $this->getName() );
722 /** Get the relative path for an archive file */
723 function getArchiveRel( $suffix = false ) {
724 $path = 'archive/' . $this->getHashPath();
725 if ( $suffix === false ) {
726 $path = substr( $path, 0, -1 );
733 /** Get relative path for a thumbnail file */
734 function getThumbRel( $suffix = false ) {
735 $path = 'thumb/' . $this->getRel();
736 if ( $suffix !== false ) {
737 $path .= '/' . $suffix;
742 /** Get the path of the archive directory, or a particular file if $suffix is specified */
743 function getArchivePath( $suffix = false ) {
744 return $this->repo
->getZonePath('public') . '/' . $this->getArchiveRel( $suffix );
747 /** Get the path of the thumbnail directory, or a particular file if $suffix is specified */
748 function getThumbPath( $suffix = false ) {
749 return $this->repo
->getZonePath('public') . '/' . $this->getThumbRel( $suffix );
752 /** Get the URL of the archive directory, or a particular file if $suffix is specified */
753 function getArchiveUrl( $suffix = false ) {
754 $path = $this->repo
->getZoneUrl('public') . '/archive/' . $this->getHashPath();
755 if ( $suffix === false ) {
756 $path = substr( $path, 0, -1 );
758 $path .= rawurlencode( $suffix );
763 /** Get the URL of the thumbnail directory, or a particular file if $suffix is specified */
764 function getThumbUrl( $suffix = false ) {
765 $path = $this->repo
->getZoneUrl('public') . '/thumb/' . $this->getUrlRel();
766 if ( $suffix !== false ) {
767 $path .= '/' . rawurlencode( $suffix );
772 /** Get the virtual URL for an archive file or directory */
773 function getArchiveVirtualUrl( $suffix = false ) {
774 $path = $this->repo
->getVirtualUrl() . '/public/archive/' . $this->getHashPath();
775 if ( $suffix === false ) {
776 $path = substr( $path, 0, -1 );
778 $path .= rawurlencode( $suffix );
783 /** Get the virtual URL for a thumbnail file or directory */
784 function getThumbVirtualUrl( $suffix = false ) {
785 $path = $this->repo
->getVirtualUrl() . '/public/thumb/' . $this->getUrlRel();
786 if ( $suffix !== false ) {
787 $path .= '/' . rawurlencode( $suffix );
792 /** Get the virtual URL for the file itself */
793 function getVirtualUrl( $suffix = false ) {
794 $path = $this->repo
->getVirtualUrl() . '/public/' . $this->getUrlRel();
795 if ( $suffix !== false ) {
796 $path .= '/' . rawurlencode( $suffix );
804 function isHashed() {
805 return $this->repo
->isHashed();
808 function readOnlyError() {
809 throw new MWException( get_class($this) . ': write operations are not supported' );
813 * Record a file upload in the upload log and the image table
815 * Overridden by LocalFile
817 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '', $watch = false ) {
818 $this->readOnlyError();
822 * Move or copy a file to its public location. If a file exists at the
823 * destination, move it to an archive. Returns the archive name on success
824 * or an empty string if it was a new file, and a wikitext-formatted
825 * WikiError object on failure.
827 * The archive name should be passed through to recordUpload for database
830 * @param string $sourcePath Local filesystem path to the source image
831 * @param integer $flags A bitwise combination of:
832 * File::DELETE_SOURCE Delete the source file, i.e. move
834 * @return The archive name on success or an empty string if it was a new
835 * file, and a wikitext-formatted WikiError object on failure.
838 * Overridden by LocalFile
840 function publish( $srcPath, $flags = 0 ) {
841 $this->readOnlyError();
845 * Get an array of Title objects which are articles which use this file
846 * Also adds their IDs to the link cache
848 * This is mostly copied from Title::getLinksTo()
850 * @deprecated Use HTMLCacheUpdate, this function uses too much memory
852 function getLinksTo( $options = '' ) {
853 wfProfileIn( __METHOD__
);
855 // Note: use local DB not repo DB, we want to know local links
857 $db = wfGetDB( DB_MASTER
);
859 $db = wfGetDB( DB_SLAVE
);
861 $linkCache = LinkCache
::singleton();
863 list( $page, $imagelinks ) = $db->tableNamesN( 'page', 'imagelinks' );
864 $encName = $db->addQuotes( $this->getName() );
865 $sql = "SELECT page_namespace,page_title,page_id,page_len,page_is_redirect,
866 FROM $page,$imagelinks WHERE page_id=il_from AND il_to=$encName $options";
867 $res = $db->query( $sql, __METHOD__
);
870 if ( $db->numRows( $res ) ) {
871 while ( $row = $db->fetchObject( $res ) ) {
872 if ( $titleObj = Title
::newFromRow( $row ) ) {
873 $linkCache->addGoodLinkObj( $row->page_id
, $titleObj, $row->page_len
, $row->page_is_redirect
);
874 $retVal[] = $titleObj;
878 $db->freeResult( $res );
879 wfProfileOut( __METHOD__
);
883 function formatMetadata() {
884 if ( !$this->getHandler() ) {
887 return $this->getHandler()->formatMetadata( $this, $this->getMetadata() );
891 * Returns true if the file comes from the local file repository.
896 return $this->getRepoName() == 'local';
900 * Returns the name of the repository.
904 function getRepoName() {
905 return $this->repo ?
$this->repo
->getName() : 'unknown';
909 * Returns true if the image is an old version
917 * Is this file a "deleted" file in a private archive?
920 function isDeleted( $field ) {
925 * Was this file ever deleted from the wiki?
929 function wasDeleted() {
930 $title = $this->getTitle();
931 return $title && $title->isDeleted() > 0;
935 * Move file to the new title
937 * Move current, old version and all thumbnails
938 * to the new filename. Old file is deleted.
940 * Cache purging is done; checks for validity
941 * and logging are caller's responsibility
943 * @param $target Title New file name
944 * @return FileRepoStatus object.
946 function move( $target ) {
947 $this->readOnlyError();
951 * Delete all versions of the file.
953 * Moves the files into an archive directory (or deletes them)
954 * and removes the database rows.
956 * Cache purging is done; logging is caller's responsibility.
959 * @param $suppress, hide content from sysops?
960 * @return true on success, false on some kind of failure
962 * Overridden by LocalFile
964 function delete( $reason, $suppress = false ) {
965 $this->readOnlyError();
969 * Restore all or specified deleted revisions to the given file.
970 * Permissions and logging are left to the caller.
972 * May throw database exceptions on error.
974 * @param $versions set of record ids of deleted items to restore,
975 * or empty to restore all revisions.
976 * @param $unsuppress, remove restrictions on content upon restoration?
977 * @return the number of file revisions restored if successful,
978 * or false on failure
980 * Overridden by LocalFile
982 function restore( $versions=array(), $unsuppress=false ) {
983 $this->readOnlyError();
987 * Returns 'true' if this image is a multipage document, e.g. a DJVU
992 function isMultipage() {
993 return $this->getHandler() && $this->handler
->isMultiPage( $this );
997 * Returns the number of pages of a multipage document, or NULL for
998 * documents which aren't multipage documents
1000 function pageCount() {
1001 if ( !isset( $this->pageCount
) ) {
1002 if ( $this->getHandler() && $this->handler
->isMultiPage( $this ) ) {
1003 $this->pageCount
= $this->handler
->pageCount( $this );
1005 $this->pageCount
= false;
1008 return $this->pageCount
;
1012 * Calculate the height of a thumbnail using the source and destination width
1014 static function scaleHeight( $srcWidth, $srcHeight, $dstWidth ) {
1015 // Exact integer multiply followed by division
1016 if ( $srcWidth == 0 ) {
1019 return round( $srcHeight * $dstWidth / $srcWidth );
1024 * Get an image size array like that returned by getimagesize(), or false if it
1025 * can't be determined.
1027 * @param string $fileName The filename
1030 function getImageSize( $fileName ) {
1031 if ( !$this->getHandler() ) {
1034 return $this->handler
->getImageSize( $this, $fileName );
1038 * Get the URL of the image description page. May return false if it is
1039 * unknown or not applicable.
1041 function getDescriptionUrl() {
1042 return $this->repo
->getDescriptionUrl( $this->getName() );
1046 * Get the HTML text of the description page, if available
1048 function getDescriptionText() {
1049 if ( !$this->repo
->fetchDescription
) {
1052 $renderUrl = $this->repo
->getDescriptionRenderUrl( $this->getName() );
1054 wfDebug( "Fetching shared description from $renderUrl\n" );
1055 return Http
::get( $renderUrl );
1062 * Get discription of file revision
1065 function getDescription() {
1070 * Get the 14-character timestamp of the file upload, or false if
1073 function getTimestamp() {
1074 $path = $this->getPath();
1075 if ( !file_exists( $path ) ) {
1078 return wfTimestamp( TS_MW
, filemtime( $path ) );
1082 * Get the SHA-1 base 36 hash of the file
1084 function getSha1() {
1085 return self
::sha1Base36( $this->getPath() );
1089 * Determine if the current user is allowed to view a particular
1090 * field of this file, if it's marked as deleted.
1095 function userCan( $field ) {
1100 * Get an associative array containing information about a file in the local filesystem.
1102 * @param string $path Absolute local filesystem path
1103 * @param mixed $ext The file extension, or true to extract it from the filename.
1104 * Set it to false to ignore the extension.
1106 static function getPropsFromPath( $path, $ext = true ) {
1107 wfProfileIn( __METHOD__
);
1108 wfDebug( __METHOD__
.": Getting file info for $path\n" );
1110 'fileExists' => file_exists( $path ) && !is_dir( $path )
1113 if ( $info['fileExists'] ) {
1114 $magic = MimeMagic
::singleton();
1116 $info['mime'] = $magic->guessMimeType( $path, $ext );
1117 list( $info['major_mime'], $info['minor_mime'] ) = self
::splitMime( $info['mime'] );
1118 $info['media_type'] = $magic->getMediaType( $path, $info['mime'] );
1121 $info['size'] = filesize( $path );
1123 # Height, width and metadata
1124 $handler = MediaHandler
::getHandler( $info['mime'] );
1126 $tempImage = (object)array();
1127 $info['metadata'] = $handler->getMetadata( $tempImage, $path );
1128 $gis = $handler->getImageSize( $tempImage, $path, $info['metadata'] );
1131 $info['metadata'] = '';
1133 $info['sha1'] = self
::sha1Base36( $path );
1135 wfDebug(__METHOD__
.": $path loaded, {$info['size']} bytes, {$info['mime']}.\n");
1137 $info['mime'] = NULL;
1138 $info['media_type'] = MEDIATYPE_UNKNOWN
;
1139 $info['metadata'] = '';
1141 wfDebug(__METHOD__
.": $path NOT FOUND!\n");
1144 # NOTE: $gis[2] contains a code for the image type. This is no longer used.
1145 $info['width'] = $gis[0];
1146 $info['height'] = $gis[1];
1147 if ( isset( $gis['bits'] ) ) {
1148 $info['bits'] = $gis['bits'];
1154 $info['height'] = 0;
1157 wfProfileOut( __METHOD__
);
1162 * Get a SHA-1 hash of a file in the local filesystem, in base-36 lower case
1163 * encoding, zero padded to 31 digits.
1165 * 160 log 2 / log 36 = 30.95, so the 160-bit hash fills 31 digits in base 36
1168 * Returns false on failure
1170 static function sha1Base36( $path ) {
1171 wfSuppressWarnings();
1172 $hash = sha1_file( $path );
1173 wfRestoreWarnings();
1174 if ( $hash === false ) {
1177 return wfBaseConvert( $hash, 16, 36, 31 );
1181 function getLongDesc() {
1182 $handler = $this->getHandler();
1184 return $handler->getLongDesc( $this );
1186 return MediaHandler
::getLongDesc( $this );
1190 function getShortDesc() {
1191 $handler = $this->getHandler();
1193 return $handler->getShortDesc( $this );
1195 return MediaHandler
::getShortDesc( $this );
1199 function getDimensionsString() {
1200 $handler = $this->getHandler();
1202 return $handler->getDimensionsString( $this );
1208 function getRedirected() {
1209 return $this->redirected
;
1212 function redirectedFrom( $from ) {
1213 $this->redirected
= $from;
1217 * Aliases for backwards compatibility with 1.6
1219 define( 'MW_IMG_DELETED_FILE', File
::DELETED_FILE
);
1220 define( 'MW_IMG_DELETED_COMMENT', File
::DELETED_COMMENT
);
1221 define( 'MW_IMG_DELETED_USER', File
::DELETED_USER
);
1222 define( 'MW_IMG_DELETED_RESTRICTED', File
::DELETED_RESTRICTED
);