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
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, $redirectedTitle;
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 );
84 if( isset( $squish[$lower] ) ) {
85 return $squish[$lower];
86 } elseif( preg_match( '/^[0-9a-z]+$/', $lower ) ) {
94 * Checks if file extensions are compatible
96 * @param $old File Old file
97 * @param $new string New name
99 static function checkExtensionCompatibility( File
$old, $new ) {
100 $oldMime = $old->getMimeType();
101 $n = strrpos( $new, '.' );
102 $newExt = self
::normalizeExtension(
103 $n ?
substr( $new, $n +
1 ) : '' );
104 $mimeMagic = MimeMagic
::singleton();
105 return $mimeMagic->isMatchingExtension( $newExt, $oldMime );
109 * Upgrade the database row if there is one
110 * Called by ImagePage
113 function upgradeRow() {}
116 * Split an internet media type into its two components; if not
117 * a two-part name, set the minor type to 'unknown'.
119 * @param $mime "text/html" etc
120 * @return array ("text", "html") etc
122 static function splitMime( $mime ) {
123 if( strpos( $mime, '/' ) !== false ) {
124 return explode( '/', $mime, 2 );
126 return array( $mime, 'unknown' );
131 * Return the name of this file
133 public function getName() {
134 if ( !isset( $this->name
) ) {
135 $this->name
= $this->repo
->getNameFromTitle( $this->title
);
141 * Get the file extension, e.g. "svg"
143 function getExtension() {
144 if ( !isset( $this->extension
) ) {
145 $n = strrpos( $this->getName(), '.' );
146 $this->extension
= self
::normalizeExtension(
147 $n ?
substr( $this->getName(), $n +
1 ) : '' );
149 return $this->extension
;
153 * Return the associated title object
155 public function getTitle() { return $this->title
; }
158 * Return the title used to find this file
160 public function getOriginalTitle() {
161 if ( $this->redirected
)
162 return $this->getRedirectedTitle();
167 * Return the URL of the file
169 public function getUrl() {
170 if ( !isset( $this->url
) ) {
171 $this->url
= $this->repo
->getZoneUrl( 'public' ) . '/' . $this->getUrlRel();
177 * Return a fully-qualified URL to the file.
178 * Upload URL paths _may or may not_ be fully qualified, so
179 * we check. Local paths are assumed to belong on $wgServer.
182 public function getFullUrl() {
183 return wfExpandUrl( $this->getUrl() );
186 function getViewURL() {
187 if( $this->mustRender()) {
188 if( $this->canRender() ) {
189 return $this->createThumb( $this->getWidth() );
192 wfDebug(__METHOD__
.': supposed to render '.$this->getName().' ('.$this->getMimeType()."), but can't!\n");
193 return $this->getURL(); #hm... return NULL?
196 return $this->getURL();
201 * Return the full filesystem path to the file. Note that this does
202 * not mean that a file actually exists under that location.
204 * This path depends on whether directory hashing is active or not,
205 * i.e. whether the files are all found in the same directory,
206 * or in hashed paths like /images/3/3c.
208 * May return false if the file is not locally accessible.
210 public function getPath() {
211 if ( !isset( $this->path
) ) {
212 $this->path
= $this->repo
->getZonePath('public') . '/' . $this->getRel();
218 * Alias for getPath()
220 public function getFullPath() {
221 return $this->getPath();
225 * Return the width of the image. Returns false if the width is unknown
229 * Overridden by LocalFile, UnregisteredLocalFile
231 public function getWidth( $page = 1 ) { return false; }
234 * Return the height of the image. Returns false if the height is unknown
238 * Overridden by LocalFile, UnregisteredLocalFile
240 public function getHeight( $page = 1 ) { return false; }
243 * Returns ID or name of user who uploaded the file
246 * @param $type string 'text' or 'id'
248 public function getUser( $type='text' ) { return null; }
251 * Get the duration of a media file in seconds
253 public function getLength() {
254 $handler = $this->getHandler();
256 return $handler->getLength( $this );
263 * Get handler-specific metadata
264 * Overridden by LocalFile, UnregisteredLocalFile
267 function getMetadata() { return false; }
270 * Return the size of the image file, in bytes
271 * Overridden by LocalFile, UnregisteredLocalFile
274 public function getSize() { return false; }
277 * Returns the mime type of the file.
278 * Overridden by LocalFile, UnregisteredLocalFile
281 function getMimeType() { return 'unknown/unknown'; }
284 * Return the type of the media in the file.
285 * Use the value returned by this function with the MEDIATYPE_xxx constants.
286 * Overridden by LocalFile,
289 function getMediaType() { return MEDIATYPE_UNKNOWN
; }
292 * Checks if the output of transform() for this file is likely
293 * to be valid. If this is false, various user elements will
294 * display a placeholder instead.
296 * Currently, this checks if the file is an image format
297 * that can be converted to a format
298 * supported by all browsers (namely GIF, PNG and JPEG),
299 * or if it is an SVG image and SVG conversion is enabled.
301 function canRender() {
302 if ( !isset( $this->canRender
) ) {
303 $this->canRender
= $this->getHandler() && $this->handler
->canRender( $this );
305 return $this->canRender
;
309 * Accessor for __get()
311 protected function getCanRender() {
312 return $this->canRender();
316 * Return true if the file is of a type that can't be directly
317 * rendered by typical browsers and needs to be re-rasterized.
319 * This returns true for everything but the bitmap types
320 * supported by all browsers, i.e. JPEG; GIF and PNG. It will
321 * also return true for any non-image formats.
325 function mustRender() {
326 return $this->getHandler() && $this->handler
->mustRender( $this );
330 * Alias for canRender()
332 function allowInlineDisplay() {
333 return $this->canRender();
337 * Determines if this media file is in a format that is unlikely to
338 * contain viruses or malicious content. It uses the global
339 * $wgTrustedMediaFormats list to determine if the file is safe.
341 * This is used to show a warning on the description page of non-safe files.
342 * It may also be used to disallow direct [[media:...]] links to such files.
344 * Note that this function will always return true if allowInlineDisplay()
345 * or isTrustedFile() is true for this file.
347 function isSafeFile() {
348 if ( !isset( $this->isSafeFile
) ) {
349 $this->isSafeFile
= $this->_getIsSafeFile();
351 return $this->isSafeFile
;
354 /** Accessor for __get() */
355 protected function getIsSafeFile() {
356 return $this->isSafeFile();
359 /** Uncached accessor */
360 protected function _getIsSafeFile() {
361 if ($this->allowInlineDisplay()) return true;
362 if ($this->isTrustedFile()) return true;
364 global $wgTrustedMediaFormats;
366 $type= $this->getMediaType();
367 $mime= $this->getMimeType();
368 #wfDebug("LocalFile::isSafeFile: type= $type, mime= $mime\n");
370 if (!$type ||
$type===MEDIATYPE_UNKNOWN
) return false; #unknown type, not trusted
371 if ( in_array( $type, $wgTrustedMediaFormats) ) return true;
373 if ($mime==="unknown/unknown") return false; #unknown type, not trusted
374 if ( in_array( $mime, $wgTrustedMediaFormats) ) return true;
379 /** Returns true if the file is flagged as trusted. Files flagged that way
380 * can be linked to directly, even if that is not allowed for this type of
383 * This is a dummy function right now and always returns false. It could be
384 * implemented to extract a flag from the database. The trusted flag could be
385 * set on upload, if the user has sufficient privileges, to bypass script-
386 * and html-filters. It may even be coupled with cryptographics signatures
389 function isTrustedFile() {
390 #this could be implemented to check a flag in the databas,
391 #look for signatures, etc
396 * Returns true if file exists in the repository.
398 * Overridden by LocalFile to avoid unnecessary stat calls.
400 * @return boolean Whether file exists in the repository.
402 public function exists() {
403 return $this->getPath() && file_exists( $this->path
);
407 * Returns true if file exists in the repository and can be included in a page.
408 * It would be unsafe to include private images, making public thumbnails inadvertently
410 * @return boolean Whether file exists in the repository and is includable.
413 function isVisible() {
414 return $this->exists();
417 function getTransformScript() {
418 if ( !isset( $this->transformScript
) ) {
419 $this->transformScript
= false;
421 $script = $this->repo
->getThumbScriptUrl();
423 $this->transformScript
= "$script?f=" . urlencode( $this->getName() );
427 return $this->transformScript
;
431 * Get a ThumbnailImage which is the same size as the source
433 function getUnscaledThumb( $page = false ) {
434 $width = $this->getWidth( $page );
436 return $this->iconThumb();
441 'width' => $this->getWidth( $page )
444 $params = array( 'width' => $this->getWidth() );
446 return $this->transform( $params );
450 * Return the file name of a thumbnail with the specified parameters
452 * @param array $params Handler-specific parameters
455 function thumbName( $params ) {
456 if ( !$this->getHandler() ) {
459 $extension = $this->getExtension();
460 list( $thumbExt, $thumbMime ) = $this->handler
->getThumbType( $extension, $this->getMimeType() );
461 $thumbName = $this->handler
->makeParamString( $params ) . '-' . $this->getName();
462 if ( $thumbExt != $extension ) {
463 $thumbName .= ".$thumbExt";
469 * Create a thumbnail of the image having the specified width/height.
470 * The thumbnail will not be created if the width is larger than the
471 * image's width. Let the browser do the scaling in this case.
472 * The thumbnail is stored on disk and is only computed if the thumbnail
473 * file does not exist OR if it is older than the image.
476 * Keeps aspect ratio of original image. If both width and height are
477 * specified, the generated image will be no bigger than width x height,
478 * and will also have correct aspect ratio.
480 * @param integer $width maximum width of the generated thumbnail
481 * @param integer $height maximum height of the image (optional)
483 public function createThumb( $width, $height = -1 ) {
484 $params = array( 'width' => $width );
485 if ( $height != -1 ) {
486 $params['height'] = $height;
488 $thumb = $this->transform( $params );
489 if( is_null( $thumb ) ||
$thumb->isError() ) return '';
490 return $thumb->getUrl();
494 * As createThumb, but returns a ThumbnailImage object. This can
495 * provide access to the actual file, the real size of the thumb,
496 * and can produce a convenient <img> tag for you.
498 * For non-image formats, this may return a filetype-specific icon.
500 * @param integer $width maximum width of the generated thumbnail
501 * @param integer $height maximum height of the image (optional)
502 * @param boolean $render True to render the thumbnail if it doesn't exist,
503 * false to just return the URL
505 * @return ThumbnailImage or null on failure
507 * @deprecated use transform()
509 public function getThumbnail( $width, $height=-1, $render = true ) {
510 $params = array( 'width' => $width );
511 if ( $height != -1 ) {
512 $params['height'] = $height;
514 $flags = $render ? self
::RENDER_NOW
: 0;
515 return $this->transform( $params, $flags );
519 * Transform a media file
521 * @param array $params An associative array of handler-specific parameters. Typical
522 * keys are width, height and page.
523 * @param integer $flags A bitfield, may contain self::RENDER_NOW to force rendering
524 * @return MediaTransformOutput
526 function transform( $params, $flags = 0 ) {
527 global $wgUseSquid, $wgIgnoreImageErrors;
529 wfProfileIn( __METHOD__
);
531 if ( !$this->canRender() ) {
532 // not a bitmap or renderable image, don't try.
533 $thumb = $this->iconThumb();
537 $script = $this->getTransformScript();
538 if ( $script && !($flags & self
::RENDER_NOW
) ) {
539 // Use a script to transform on client request, if possible
540 $thumb = $this->handler
->getScriptedTransform( $this, $script, $params );
546 $normalisedParams = $params;
547 $this->handler
->normaliseParams( $this, $normalisedParams );
548 $thumbName = $this->thumbName( $normalisedParams );
549 $thumbPath = $this->getThumbPath( $thumbName );
550 $thumbUrl = $this->getThumbUrl( $thumbName );
552 if ( $this->repo
->canTransformVia404() && !($flags & self
::RENDER_NOW
) ) {
553 $thumb = $this->handler
->getTransform( $this, $thumbPath, $thumbUrl, $params );
557 wfDebug( __METHOD__
.": Doing stat for $thumbPath\n" );
558 $this->migrateThumbFile( $thumbName );
559 if ( file_exists( $thumbPath ) ) {
560 $thumb = $this->handler
->getTransform( $this, $thumbPath, $thumbUrl, $params );
563 $thumb = $this->handler
->doTransform( $this, $thumbPath, $thumbUrl, $params );
565 // Ignore errors if requested
568 } elseif ( $thumb->isError() ) {
569 $this->lastError
= $thumb->toText();
570 if ( $wgIgnoreImageErrors && !($flags & self
::RENDER_NOW
) ) {
571 $thumb = $this->handler
->getTransform( $this, $thumbPath, $thumbUrl, $params );
575 // Purge. Useful in the event of Core -> Squid connection failure or squid
576 // purge collisions from elsewhere during failure. Don't keep triggering for
577 // "thumbs" which have the main image URL though (bug 13776)
578 if ( $wgUseSquid && ($thumb->isError() ||
$thumb->getUrl() != $this->getURL()) ) {
579 SquidUpdate
::purge( array( $thumbUrl ) );
583 wfProfileOut( __METHOD__
);
588 * Hook into transform() to allow migration of thumbnail files
590 * Overridden by LocalFile
592 function migrateThumbFile( $thumbName ) {}
595 * Get a MediaHandler instance for this file
597 function getHandler() {
598 if ( !isset( $this->handler
) ) {
599 $this->handler
= MediaHandler
::getHandler( $this->getMimeType() );
601 return $this->handler
;
605 * Get a ThumbnailImage representing a file type icon
606 * @return ThumbnailImage
608 function iconThumb() {
609 global $wgStylePath, $wgStyleDirectory;
611 $try = array( 'fileicon-' . $this->getExtension() . '.png', 'fileicon.png' );
612 foreach( $try as $icon ) {
613 $path = '/common/images/icons/' . $icon;
614 $filepath = $wgStyleDirectory . $path;
615 if( file_exists( $filepath ) ) {
616 return new ThumbnailImage( $this, $wgStylePath . $path, 120, 120 );
623 * Get last thumbnailing error.
626 function getLastError() {
627 return $this->lastError
;
631 * Get all thumbnail names previously generated for this file
633 * Overridden by LocalFile
635 function getThumbnails() { return array(); }
638 * Purge shared caches such as thumbnails and DB data caching
640 * Overridden by LocalFile
642 function purgeCache() {}
645 * Purge the file description page, but don't go after
646 * pages using the file. Use when modifying file history
647 * but not the current data.
649 function purgeDescription() {
650 $title = $this->getTitle();
652 $title->invalidateCache();
653 $title->purgeSquid();
658 * Purge metadata and all affected pages when the file is created,
659 * deleted, or majorly updated.
661 function purgeEverything() {
662 // Delete thumbnails and refresh file metadata cache
664 $this->purgeDescription();
666 // Purge cache of all pages using this file
667 $title = $this->getTitle();
669 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
675 * Return a fragment of the history of file.
678 * @param $limit integer Limit of rows to return
679 * @param $start timestamp Only revisions older than $start will be returned
680 * @param $end timestamp Only revisions newer than $end will be returned
682 function getHistory($limit = null, $start = null, $end = null) {
687 * Return the history of this file, line by line. Starts with current version,
688 * then old versions. Should return an object similar to an image/oldimage
692 * Overridden in LocalFile
694 public function nextHistoryLine() {
699 * Reset the history pointer to the first element of the history.
700 * Always call this function after using nextHistoryLine() to free db resources
702 * Overridden in LocalFile.
704 public function resetHistory() {}
707 * Get the filename hash component of the directory including trailing slash,
709 * If the repository is not hashed, returns an empty string.
711 function getHashPath() {
712 if ( !isset( $this->hashPath
) ) {
713 $this->hashPath
= $this->repo
->getHashPath( $this->getName() );
715 return $this->hashPath
;
719 * Get the path of the file relative to the public zone root
722 return $this->getHashPath() . $this->getName();
726 * Get urlencoded relative path of the file
728 function getUrlRel() {
729 return $this->getHashPath() . rawurlencode( $this->getName() );
732 /** Get the relative path for an archive file */
733 function getArchiveRel( $suffix = false ) {
734 $path = 'archive/' . $this->getHashPath();
735 if ( $suffix === false ) {
736 $path = substr( $path, 0, -1 );
743 /** Get relative path for a thumbnail file */
744 function getThumbRel( $suffix = false ) {
745 $path = 'thumb/' . $this->getRel();
746 if ( $suffix !== false ) {
747 $path .= '/' . $suffix;
752 /** Get the path of the archive directory, or a particular file if $suffix is specified */
753 function getArchivePath( $suffix = false ) {
754 return $this->repo
->getZonePath('public') . '/' . $this->getArchiveRel( $suffix );
757 /** Get the path of the thumbnail directory, or a particular file if $suffix is specified */
758 function getThumbPath( $suffix = false ) {
759 return $this->repo
->getZonePath('public') . '/' . $this->getThumbRel( $suffix );
762 /** Get the URL of the archive directory, or a particular file if $suffix is specified */
763 function getArchiveUrl( $suffix = false ) {
764 $path = $this->repo
->getZoneUrl('public') . '/archive/' . $this->getHashPath();
765 if ( $suffix === false ) {
766 $path = substr( $path, 0, -1 );
768 $path .= rawurlencode( $suffix );
773 /** Get the URL of the thumbnail directory, or a particular file if $suffix is specified */
774 function getThumbUrl( $suffix = false ) {
775 $path = $this->repo
->getZoneUrl('public') . '/thumb/' . $this->getUrlRel();
776 if ( $suffix !== false ) {
777 $path .= '/' . rawurlencode( $suffix );
782 /** Get the virtual URL for an archive file or directory */
783 function getArchiveVirtualUrl( $suffix = false ) {
784 $path = $this->repo
->getVirtualUrl() . '/public/archive/' . $this->getHashPath();
785 if ( $suffix === false ) {
786 $path = substr( $path, 0, -1 );
788 $path .= rawurlencode( $suffix );
793 /** Get the virtual URL for a thumbnail file or directory */
794 function getThumbVirtualUrl( $suffix = false ) {
795 $path = $this->repo
->getVirtualUrl() . '/public/thumb/' . $this->getUrlRel();
796 if ( $suffix !== false ) {
797 $path .= '/' . rawurlencode( $suffix );
802 /** Get the virtual URL for the file itself */
803 function getVirtualUrl( $suffix = false ) {
804 $path = $this->repo
->getVirtualUrl() . '/public/' . $this->getUrlRel();
805 if ( $suffix !== false ) {
806 $path .= '/' . rawurlencode( $suffix );
814 function isHashed() {
815 return $this->repo
->isHashed();
818 function readOnlyError() {
819 throw new MWException( get_class($this) . ': write operations are not supported' );
823 * Record a file upload in the upload log and the image table
825 * Overridden by LocalFile
827 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '', $watch = false ) {
828 $this->readOnlyError();
832 * Move or copy a file to its public location. If a file exists at the
833 * destination, move it to an archive. Returns the archive name on success
834 * or an empty string if it was a new file, and a wikitext-formatted
835 * WikiError object on failure.
837 * The archive name should be passed through to recordUpload for database
840 * @param string $sourcePath Local filesystem path to the source image
841 * @param integer $flags A bitwise combination of:
842 * File::DELETE_SOURCE Delete the source file, i.e. move
844 * @return The archive name on success or an empty string if it was a new
845 * file, and a wikitext-formatted WikiError object on failure.
848 * Overridden by LocalFile
850 function publish( $srcPath, $flags = 0 ) {
851 $this->readOnlyError();
855 * Get an array of Title objects which are articles which use this file
856 * Also adds their IDs to the link cache
858 * This is mostly copied from Title::getLinksTo()
860 * @deprecated Use HTMLCacheUpdate, this function uses too much memory
862 function getLinksTo( $options = '' ) {
863 wfProfileIn( __METHOD__
);
865 // Note: use local DB not repo DB, we want to know local links
867 $db = wfGetDB( DB_MASTER
);
869 $db = wfGetDB( DB_SLAVE
);
871 $linkCache = LinkCache
::singleton();
873 list( $page, $imagelinks ) = $db->tableNamesN( 'page', 'imagelinks' );
874 $encName = $db->addQuotes( $this->getName() );
875 $sql = "SELECT page_namespace,page_title,page_id,page_len,page_is_redirect,
876 FROM $page,$imagelinks WHERE page_id=il_from AND il_to=$encName $options";
877 $res = $db->query( $sql, __METHOD__
);
880 if ( $db->numRows( $res ) ) {
881 while ( $row = $db->fetchObject( $res ) ) {
882 if ( $titleObj = Title
::newFromRow( $row ) ) {
883 $linkCache->addGoodLinkObj( $row->page_id
, $titleObj, $row->page_len
, $row->page_is_redirect
);
884 $retVal[] = $titleObj;
888 $db->freeResult( $res );
889 wfProfileOut( __METHOD__
);
893 function formatMetadata() {
894 if ( !$this->getHandler() ) {
897 return $this->getHandler()->formatMetadata( $this, $this->getMetadata() );
901 * Returns true if the file comes from the local file repository.
906 return $this->getRepoName() == 'local';
910 * Returns the name of the repository.
914 function getRepoName() {
915 return $this->repo ?
$this->repo
->getName() : 'unknown';
918 * Returns the repository
925 * Returns true if the image is an old version
933 * Is this file a "deleted" file in a private archive?
936 function isDeleted( $field ) {
941 * Was this file ever deleted from the wiki?
945 function wasDeleted() {
946 $title = $this->getTitle();
947 return $title && $title->isDeleted() > 0;
951 * Move file to the new title
953 * Move current, old version and all thumbnails
954 * to the new filename. Old file is deleted.
956 * Cache purging is done; checks for validity
957 * and logging are caller's responsibility
959 * @param $target Title New file name
960 * @return FileRepoStatus object.
962 function move( $target ) {
963 $this->readOnlyError();
967 * Delete all versions of the file.
969 * Moves the files into an archive directory (or deletes them)
970 * and removes the database rows.
972 * Cache purging is done; logging is caller's responsibility.
975 * @param $suppress, hide content from sysops?
976 * @return true on success, false on some kind of failure
978 * Overridden by LocalFile
980 function delete( $reason, $suppress = false ) {
981 $this->readOnlyError();
985 * Restore all or specified deleted revisions to the given file.
986 * Permissions and logging are left to the caller.
988 * May throw database exceptions on error.
990 * @param $versions set of record ids of deleted items to restore,
991 * or empty to restore all revisions.
992 * @param $unsuppress, remove restrictions on content upon restoration?
993 * @return the number of file revisions restored if successful,
994 * or false on failure
996 * Overridden by LocalFile
998 function restore( $versions=array(), $unsuppress=false ) {
999 $this->readOnlyError();
1003 * Returns 'true' if this image is a multipage document, e.g. a DJVU
1008 function isMultipage() {
1009 return $this->getHandler() && $this->handler
->isMultiPage( $this );
1013 * Returns the number of pages of a multipage document, or NULL for
1014 * documents which aren't multipage documents
1016 function pageCount() {
1017 if ( !isset( $this->pageCount
) ) {
1018 if ( $this->getHandler() && $this->handler
->isMultiPage( $this ) ) {
1019 $this->pageCount
= $this->handler
->pageCount( $this );
1021 $this->pageCount
= false;
1024 return $this->pageCount
;
1028 * Calculate the height of a thumbnail using the source and destination width
1030 static function scaleHeight( $srcWidth, $srcHeight, $dstWidth ) {
1031 // Exact integer multiply followed by division
1032 if ( $srcWidth == 0 ) {
1035 return round( $srcHeight * $dstWidth / $srcWidth );
1040 * Get an image size array like that returned by getimagesize(), or false if it
1041 * can't be determined.
1043 * @param string $fileName The filename
1046 function getImageSize( $fileName ) {
1047 if ( !$this->getHandler() ) {
1050 return $this->handler
->getImageSize( $this, $fileName );
1054 * Get the URL of the image description page. May return false if it is
1055 * unknown or not applicable.
1057 function getDescriptionUrl() {
1058 return $this->repo
->getDescriptionUrl( $this->getName() );
1062 * Get the HTML text of the description page, if available
1064 function getDescriptionText() {
1066 if ( !$this->repo
->fetchDescription
) {
1069 $renderUrl = $this->repo
->getDescriptionRenderUrl( $this->getName() );
1071 if ( $this->repo
->descriptionCacheExpiry
> 0 ) {
1072 wfDebug("Attempting to get the description from cache...");
1073 $key = wfMemcKey( 'RemoteFileDescription', 'url', md5($renderUrl) );
1074 $obj = $wgMemc->get($key);
1076 wfDebug("success!\n");
1081 wfDebug( "Fetching shared description from $renderUrl\n" );
1082 $res = Http
::get( $renderUrl );
1083 if ( $res && $this->repo
->descriptionCacheExpiry
> 0 ) $wgMemc->set( $key, $res, $this->repo
->descriptionCacheExpiry
);
1091 * Get discription of file revision
1094 function getDescription() {
1099 * Get the 14-character timestamp of the file upload, or false if
1102 function getTimestamp() {
1103 $path = $this->getPath();
1104 if ( !file_exists( $path ) ) {
1107 return wfTimestamp( TS_MW
, filemtime( $path ) );
1111 * Get the SHA-1 base 36 hash of the file
1113 function getSha1() {
1114 return self
::sha1Base36( $this->getPath() );
1118 * Determine if the current user is allowed to view a particular
1119 * field of this file, if it's marked as deleted.
1124 function userCan( $field ) {
1129 * Get an associative array containing information about a file in the local filesystem.
1131 * @param string $path Absolute local filesystem path
1132 * @param mixed $ext The file extension, or true to extract it from the filename.
1133 * Set it to false to ignore the extension.
1135 static function getPropsFromPath( $path, $ext = true ) {
1136 wfProfileIn( __METHOD__
);
1137 wfDebug( __METHOD__
.": Getting file info for $path\n" );
1139 'fileExists' => file_exists( $path ) && !is_dir( $path )
1142 if ( $info['fileExists'] ) {
1143 $magic = MimeMagic
::singleton();
1145 $info['mime'] = $magic->guessMimeType( $path, $ext );
1146 list( $info['major_mime'], $info['minor_mime'] ) = self
::splitMime( $info['mime'] );
1147 $info['media_type'] = $magic->getMediaType( $path, $info['mime'] );
1150 $info['size'] = filesize( $path );
1152 # Height, width and metadata
1153 $handler = MediaHandler
::getHandler( $info['mime'] );
1155 $tempImage = (object)array();
1156 $info['metadata'] = $handler->getMetadata( $tempImage, $path );
1157 $gis = $handler->getImageSize( $tempImage, $path, $info['metadata'] );
1160 $info['metadata'] = '';
1162 $info['sha1'] = self
::sha1Base36( $path );
1164 wfDebug(__METHOD__
.": $path loaded, {$info['size']} bytes, {$info['mime']}.\n");
1166 $info['mime'] = NULL;
1167 $info['media_type'] = MEDIATYPE_UNKNOWN
;
1168 $info['metadata'] = '';
1170 wfDebug(__METHOD__
.": $path NOT FOUND!\n");
1173 # NOTE: $gis[2] contains a code for the image type. This is no longer used.
1174 $info['width'] = $gis[0];
1175 $info['height'] = $gis[1];
1176 if ( isset( $gis['bits'] ) ) {
1177 $info['bits'] = $gis['bits'];
1183 $info['height'] = 0;
1186 wfProfileOut( __METHOD__
);
1191 * Get a SHA-1 hash of a file in the local filesystem, in base-36 lower case
1192 * encoding, zero padded to 31 digits.
1194 * 160 log 2 / log 36 = 30.95, so the 160-bit hash fills 31 digits in base 36
1197 * Returns false on failure
1199 static function sha1Base36( $path ) {
1200 wfSuppressWarnings();
1201 $hash = sha1_file( $path );
1202 wfRestoreWarnings();
1203 if ( $hash === false ) {
1206 return wfBaseConvert( $hash, 16, 36, 31 );
1210 function getLongDesc() {
1211 $handler = $this->getHandler();
1213 return $handler->getLongDesc( $this );
1215 return MediaHandler
::getLongDesc( $this );
1219 function getShortDesc() {
1220 $handler = $this->getHandler();
1222 return $handler->getShortDesc( $this );
1224 return MediaHandler
::getShortDesc( $this );
1228 function getDimensionsString() {
1229 $handler = $this->getHandler();
1231 return $handler->getDimensionsString( $this );
1237 function getRedirected() {
1238 return $this->redirected
;
1241 function getRedirectedTitle() {
1242 if ( $this->redirected
) {
1243 if ( !$this->redirectTitle
)
1244 $this->redirectTitle
= Title
::makeTitle( NS_IMAGE
, $this->redirected
);
1245 return $this->redirectTitle
;
1249 function redirectedFrom( $from ) {
1250 $this->redirected
= $from;
1254 * Aliases for backwards compatibility with 1.6
1256 define( 'MW_IMG_DELETED_FILE', File
::DELETED_FILE
);
1257 define( 'MW_IMG_DELETED_COMMENT', File
::DELETED_COMMENT
);
1258 define( 'MW_IMG_DELETED_USER', File
::DELETED_USER
);
1259 define( 'MW_IMG_DELETED_RESTRICTED', File
::DELETED_RESTRICTED
);