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 public function getMetadata() { return false; }
270 * Return the bit depth of the file
271 * Overridden by LocalFile
274 public function getBitDepth() { return 0; }
277 * Return the size of the image file, in bytes
278 * Overridden by LocalFile, UnregisteredLocalFile
281 public function getSize() { return false; }
284 * Returns the mime type of the file.
285 * Overridden by LocalFile, UnregisteredLocalFile
288 function getMimeType() { return 'unknown/unknown'; }
291 * Return the type of the media in the file.
292 * Use the value returned by this function with the MEDIATYPE_xxx constants.
293 * Overridden by LocalFile,
296 function getMediaType() { return MEDIATYPE_UNKNOWN
; }
299 * Checks if the output of transform() for this file is likely
300 * to be valid. If this is false, various user elements will
301 * display a placeholder instead.
303 * Currently, this checks if the file is an image format
304 * that can be converted to a format
305 * supported by all browsers (namely GIF, PNG and JPEG),
306 * or if it is an SVG image and SVG conversion is enabled.
308 function canRender() {
309 if ( !isset( $this->canRender
) ) {
310 $this->canRender
= $this->getHandler() && $this->handler
->canRender( $this );
312 return $this->canRender
;
316 * Accessor for __get()
318 protected function getCanRender() {
319 return $this->canRender();
323 * Return true if the file is of a type that can't be directly
324 * rendered by typical browsers and needs to be re-rasterized.
326 * This returns true for everything but the bitmap types
327 * supported by all browsers, i.e. JPEG; GIF and PNG. It will
328 * also return true for any non-image formats.
332 function mustRender() {
333 return $this->getHandler() && $this->handler
->mustRender( $this );
337 * Alias for canRender()
339 function allowInlineDisplay() {
340 return $this->canRender();
344 * Determines if this media file is in a format that is unlikely to
345 * contain viruses or malicious content. It uses the global
346 * $wgTrustedMediaFormats list to determine if the file is safe.
348 * This is used to show a warning on the description page of non-safe files.
349 * It may also be used to disallow direct [[media:...]] links to such files.
351 * Note that this function will always return true if allowInlineDisplay()
352 * or isTrustedFile() is true for this file.
354 function isSafeFile() {
355 if ( !isset( $this->isSafeFile
) ) {
356 $this->isSafeFile
= $this->_getIsSafeFile();
358 return $this->isSafeFile
;
361 /** Accessor for __get() */
362 protected function getIsSafeFile() {
363 return $this->isSafeFile();
366 /** Uncached accessor */
367 protected function _getIsSafeFile() {
368 if ($this->allowInlineDisplay()) return true;
369 if ($this->isTrustedFile()) return true;
371 global $wgTrustedMediaFormats;
373 $type= $this->getMediaType();
374 $mime= $this->getMimeType();
375 #wfDebug("LocalFile::isSafeFile: type= $type, mime= $mime\n");
377 if (!$type ||
$type===MEDIATYPE_UNKNOWN
) return false; #unknown type, not trusted
378 if ( in_array( $type, $wgTrustedMediaFormats) ) return true;
380 if ($mime==="unknown/unknown") return false; #unknown type, not trusted
381 if ( in_array( $mime, $wgTrustedMediaFormats) ) return true;
386 /** Returns true if the file is flagged as trusted. Files flagged that way
387 * can be linked to directly, even if that is not allowed for this type of
390 * This is a dummy function right now and always returns false. It could be
391 * implemented to extract a flag from the database. The trusted flag could be
392 * set on upload, if the user has sufficient privileges, to bypass script-
393 * and html-filters. It may even be coupled with cryptographics signatures
396 function isTrustedFile() {
397 #this could be implemented to check a flag in the databas,
398 #look for signatures, etc
403 * Returns true if file exists in the repository.
405 * Overridden by LocalFile to avoid unnecessary stat calls.
407 * @return boolean Whether file exists in the repository.
409 public function exists() {
410 return $this->getPath() && file_exists( $this->path
);
414 * Returns true if file exists in the repository and can be included in a page.
415 * It would be unsafe to include private images, making public thumbnails inadvertently
417 * @return boolean Whether file exists in the repository and is includable.
420 function isVisible() {
421 return $this->exists();
424 function getTransformScript() {
425 if ( !isset( $this->transformScript
) ) {
426 $this->transformScript
= false;
428 $script = $this->repo
->getThumbScriptUrl();
430 $this->transformScript
= "$script?f=" . urlencode( $this->getName() );
434 return $this->transformScript
;
438 * Get a ThumbnailImage which is the same size as the source
440 function getUnscaledThumb( $page = false ) {
441 $width = $this->getWidth( $page );
443 return $this->iconThumb();
448 'width' => $this->getWidth( $page )
451 $params = array( 'width' => $this->getWidth() );
453 return $this->transform( $params );
457 * Return the file name of a thumbnail with the specified parameters
459 * @param array $params Handler-specific parameters
462 function thumbName( $params ) {
463 if ( !$this->getHandler() ) {
466 $extension = $this->getExtension();
467 list( $thumbExt, $thumbMime ) = $this->handler
->getThumbType( $extension, $this->getMimeType() );
468 $thumbName = $this->handler
->makeParamString( $params ) . '-' . $this->getName();
469 if ( $thumbExt != $extension ) {
470 $thumbName .= ".$thumbExt";
476 * Create a thumbnail of the image having the specified width/height.
477 * The thumbnail will not be created if the width is larger than the
478 * image's width. Let the browser do the scaling in this case.
479 * The thumbnail is stored on disk and is only computed if the thumbnail
480 * file does not exist OR if it is older than the image.
483 * Keeps aspect ratio of original image. If both width and height are
484 * specified, the generated image will be no bigger than width x height,
485 * and will also have correct aspect ratio.
487 * @param integer $width maximum width of the generated thumbnail
488 * @param integer $height maximum height of the image (optional)
490 public function createThumb( $width, $height = -1 ) {
491 $params = array( 'width' => $width );
492 if ( $height != -1 ) {
493 $params['height'] = $height;
495 $thumb = $this->transform( $params );
496 if( is_null( $thumb ) ||
$thumb->isError() ) return '';
497 return $thumb->getUrl();
501 * As createThumb, but returns a ThumbnailImage object. This can
502 * provide access to the actual file, the real size of the thumb,
503 * and can produce a convenient <img> tag for you.
505 * For non-image formats, this may return a filetype-specific icon.
507 * @param integer $width maximum width of the generated thumbnail
508 * @param integer $height maximum height of the image (optional)
509 * @param boolean $render Deprecated
511 * @return ThumbnailImage or null on failure
513 * @deprecated use transform()
515 public function getThumbnail( $width, $height=-1, $render = true ) {
516 $params = array( 'width' => $width );
517 if ( $height != -1 ) {
518 $params['height'] = $height;
520 return $this->transform( $params, 0 );
524 * Transform a media file
526 * @param array $params An associative array of handler-specific parameters. Typical
527 * keys are width, height and page.
528 * @param integer $flags A bitfield, may contain self::RENDER_NOW to force rendering
529 * @return MediaTransformOutput
531 function transform( $params, $flags = 0 ) {
532 global $wgUseSquid, $wgIgnoreImageErrors;
534 wfProfileIn( __METHOD__
);
536 if ( !$this->canRender() ) {
537 // not a bitmap or renderable image, don't try.
538 $thumb = $this->iconThumb();
542 $script = $this->getTransformScript();
543 if ( $script && !($flags & self
::RENDER_NOW
) ) {
544 // Use a script to transform on client request, if possible
545 $thumb = $this->handler
->getScriptedTransform( $this, $script, $params );
551 $normalisedParams = $params;
552 $this->handler
->normaliseParams( $this, $normalisedParams );
553 $thumbName = $this->thumbName( $normalisedParams );
554 $thumbPath = $this->getThumbPath( $thumbName );
555 $thumbUrl = $this->getThumbUrl( $thumbName );
557 if ( $this->repo
->canTransformVia404() && !($flags & self
::RENDER_NOW
) ) {
558 $thumb = $this->handler
->getTransform( $this, $thumbPath, $thumbUrl, $params );
562 wfDebug( __METHOD__
.": Doing stat for $thumbPath\n" );
563 $this->migrateThumbFile( $thumbName );
564 if ( file_exists( $thumbPath ) ) {
565 $thumb = $this->handler
->getTransform( $this, $thumbPath, $thumbUrl, $params );
568 $thumb = $this->handler
->doTransform( $this, $thumbPath, $thumbUrl, $params );
570 // Ignore errors if requested
573 } elseif ( $thumb->isError() ) {
574 $this->lastError
= $thumb->toText();
575 if ( $wgIgnoreImageErrors && !($flags & self
::RENDER_NOW
) ) {
576 $thumb = $this->handler
->getTransform( $this, $thumbPath, $thumbUrl, $params );
580 // Purge. Useful in the event of Core -> Squid connection failure or squid
581 // purge collisions from elsewhere during failure. Don't keep triggering for
582 // "thumbs" which have the main image URL though (bug 13776)
583 if ( $wgUseSquid && ( !$thumb ||
$thumb->isError() ||
$thumb->getUrl() != $this->getURL()) ) {
584 SquidUpdate
::purge( array( $thumbUrl ) );
588 wfProfileOut( __METHOD__
);
589 return is_object( $thumb ) ?
$thumb : false;
593 * Hook into transform() to allow migration of thumbnail files
595 * Overridden by LocalFile
597 function migrateThumbFile( $thumbName ) {}
600 * Get a MediaHandler instance for this file
602 function getHandler() {
603 if ( !isset( $this->handler
) ) {
604 $this->handler
= MediaHandler
::getHandler( $this->getMimeType() );
606 return $this->handler
;
610 * Get a ThumbnailImage representing a file type icon
611 * @return ThumbnailImage
613 function iconThumb() {
614 global $wgStylePath, $wgStyleDirectory;
616 $try = array( 'fileicon-' . $this->getExtension() . '.png', 'fileicon.png' );
617 foreach( $try as $icon ) {
618 $path = '/common/images/icons/' . $icon;
619 $filepath = $wgStyleDirectory . $path;
620 if( file_exists( $filepath ) ) {
621 return new ThumbnailImage( $this, $wgStylePath . $path, 120, 120 );
628 * Get last thumbnailing error.
631 function getLastError() {
632 return $this->lastError
;
636 * Get all thumbnail names previously generated for this file
638 * Overridden by LocalFile
640 function getThumbnails() { return array(); }
643 * Purge shared caches such as thumbnails and DB data caching
645 * Overridden by LocalFile
647 function purgeCache() {}
650 * Purge the file description page, but don't go after
651 * pages using the file. Use when modifying file history
652 * but not the current data.
654 function purgeDescription() {
655 $title = $this->getTitle();
657 $title->invalidateCache();
658 $title->purgeSquid();
663 * Purge metadata and all affected pages when the file is created,
664 * deleted, or majorly updated.
666 function purgeEverything() {
667 // Delete thumbnails and refresh file metadata cache
669 $this->purgeDescription();
671 // Purge cache of all pages using this file
672 $title = $this->getTitle();
674 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
680 * Return a fragment of the history of file.
683 * @param $limit integer Limit of rows to return
684 * @param $start timestamp Only revisions older than $start will be returned
685 * @param $end timestamp Only revisions newer than $end will be returned
686 * @param $inc bool Include the endpoints of the time range
688 function getHistory($limit = null, $start = null, $end = null, $inc=true) {
693 * Return the history of this file, line by line. Starts with current version,
694 * then old versions. Should return an object similar to an image/oldimage
698 * Overridden in LocalFile
700 public function nextHistoryLine() {
705 * Reset the history pointer to the first element of the history.
706 * Always call this function after using nextHistoryLine() to free db resources
708 * Overridden in LocalFile.
710 public function resetHistory() {}
713 * Get the filename hash component of the directory including trailing slash,
715 * If the repository is not hashed, returns an empty string.
717 function getHashPath() {
718 if ( !isset( $this->hashPath
) ) {
719 $this->hashPath
= $this->repo
->getHashPath( $this->getName() );
721 return $this->hashPath
;
725 * Get the path of the file relative to the public zone root
728 return $this->getHashPath() . $this->getName();
732 * Get urlencoded relative path of the file
734 function getUrlRel() {
735 return $this->getHashPath() . rawurlencode( $this->getName() );
738 /** Get the relative path for an archive file */
739 function getArchiveRel( $suffix = false ) {
740 $path = 'archive/' . $this->getHashPath();
741 if ( $suffix === false ) {
742 $path = substr( $path, 0, -1 );
749 /** Get relative path for a thumbnail file */
750 function getThumbRel( $suffix = false ) {
751 $path = 'thumb/' . $this->getRel();
752 if ( $suffix !== false ) {
753 $path .= '/' . $suffix;
758 /** Get the path of the archive directory, or a particular file if $suffix is specified */
759 function getArchivePath( $suffix = false ) {
760 return $this->repo
->getZonePath('public') . '/' . $this->getArchiveRel( $suffix );
763 /** Get the path of the thumbnail directory, or a particular file if $suffix is specified */
764 function getThumbPath( $suffix = false ) {
765 return $this->repo
->getZonePath('public') . '/' . $this->getThumbRel( $suffix );
768 /** Get the URL of the archive directory, or a particular file if $suffix is specified */
769 function getArchiveUrl( $suffix = false ) {
770 $path = $this->repo
->getZoneUrl('public') . '/archive/' . $this->getHashPath();
771 if ( $suffix === false ) {
772 $path = substr( $path, 0, -1 );
774 $path .= rawurlencode( $suffix );
779 /** Get the URL of the thumbnail directory, or a particular file if $suffix is specified */
780 function getThumbUrl( $suffix = false ) {
781 $path = $this->repo
->getZoneUrl('public') . '/thumb/' . $this->getUrlRel();
782 if ( $suffix !== false ) {
783 $path .= '/' . rawurlencode( $suffix );
788 /** Get the virtual URL for an archive file or directory */
789 function getArchiveVirtualUrl( $suffix = false ) {
790 $path = $this->repo
->getVirtualUrl() . '/public/archive/' . $this->getHashPath();
791 if ( $suffix === false ) {
792 $path = substr( $path, 0, -1 );
794 $path .= rawurlencode( $suffix );
799 /** Get the virtual URL for a thumbnail file or directory */
800 function getThumbVirtualUrl( $suffix = false ) {
801 $path = $this->repo
->getVirtualUrl() . '/public/thumb/' . $this->getUrlRel();
802 if ( $suffix !== false ) {
803 $path .= '/' . rawurlencode( $suffix );
808 /** Get the virtual URL for the file itself */
809 function getVirtualUrl( $suffix = false ) {
810 $path = $this->repo
->getVirtualUrl() . '/public/' . $this->getUrlRel();
811 if ( $suffix !== false ) {
812 $path .= '/' . rawurlencode( $suffix );
820 function isHashed() {
821 return $this->repo
->isHashed();
824 function readOnlyError() {
825 throw new MWException( get_class($this) . ': write operations are not supported' );
829 * Record a file upload in the upload log and the image table
831 * Overridden by LocalFile
833 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '', $watch = false ) {
834 $this->readOnlyError();
838 * Move or copy a file to its public location. If a file exists at the
839 * destination, move it to an archive. Returns the archive name on success
840 * or an empty string if it was a new file, and a wikitext-formatted
841 * WikiError object on failure.
843 * The archive name should be passed through to recordUpload for database
846 * @param string $sourcePath Local filesystem path to the source image
847 * @param integer $flags A bitwise combination of:
848 * File::DELETE_SOURCE Delete the source file, i.e. move
850 * @return The archive name on success or an empty string if it was a new
851 * file, and a wikitext-formatted WikiError object on failure.
854 * Overridden by LocalFile
856 function publish( $srcPath, $flags = 0 ) {
857 $this->readOnlyError();
861 * Get an array of Title objects which are articles which use this file
862 * Also adds their IDs to the link cache
864 * This is mostly copied from Title::getLinksTo()
866 * @deprecated Use HTMLCacheUpdate, this function uses too much memory
868 function getLinksTo( $options = array() ) {
869 wfProfileIn( __METHOD__
);
871 // Note: use local DB not repo DB, we want to know local links
872 if ( count( $options ) > 0 ) {
873 $db = wfGetDB( DB_MASTER
);
875 $db = wfGetDB( DB_SLAVE
);
877 $linkCache = LinkCache
::singleton();
879 $encName = $db->addQuotes( $this->getName() );
880 $res = $db->select( array( 'page', 'imagelinks'),
881 array( 'page_namespace', 'page_title', 'page_id', 'page_len', 'page_is_redirect' ),
882 array( 'page_id' => 'il_from', 'il_to' => $encName ),
887 if ( $db->numRows( $res ) ) {
888 while ( $row = $db->fetchObject( $res ) ) {
889 if ( $titleObj = Title
::newFromRow( $row ) ) {
890 $linkCache->addGoodLinkObj( $row->page_id
, $titleObj, $row->page_len
, $row->page_is_redirect
);
891 $retVal[] = $titleObj;
895 $db->freeResult( $res );
896 wfProfileOut( __METHOD__
);
900 function formatMetadata() {
901 if ( !$this->getHandler() ) {
904 return $this->getHandler()->formatMetadata( $this, $this->getMetadata() );
908 * Returns true if the file comes from the local file repository.
913 return $this->getRepoName() == 'local';
917 * Returns the name of the repository.
921 function getRepoName() {
922 return $this->repo ?
$this->repo
->getName() : 'unknown';
925 * Returns the repository
932 * Returns true if the image is an old version
940 * Is this file a "deleted" file in a private archive?
943 function isDeleted( $field ) {
948 * Was this file ever deleted from the wiki?
952 function wasDeleted() {
953 $title = $this->getTitle();
954 return $title && $title->isDeletedQuick();
958 * Move file to the new title
960 * Move current, old version and all thumbnails
961 * to the new filename. Old file is deleted.
963 * Cache purging is done; checks for validity
964 * and logging are caller's responsibility
966 * @param $target Title New file name
967 * @return FileRepoStatus object.
969 function move( $target ) {
970 $this->readOnlyError();
974 * Delete all versions of the file.
976 * Moves the files into an archive directory (or deletes them)
977 * and removes the database rows.
979 * Cache purging is done; logging is caller's responsibility.
982 * @param $suppress, hide content from sysops?
983 * @return true on success, false on some kind of failure
985 * Overridden by LocalFile
987 function delete( $reason, $suppress = false ) {
988 $this->readOnlyError();
992 * Restore all or specified deleted revisions to the given file.
993 * Permissions and logging are left to the caller.
995 * May throw database exceptions on error.
997 * @param $versions set of record ids of deleted items to restore,
998 * or empty to restore all revisions.
999 * @param $unsuppress, remove restrictions on content upon restoration?
1000 * @return the number of file revisions restored if successful,
1001 * or false on failure
1003 * Overridden by LocalFile
1005 function restore( $versions=array(), $unsuppress=false ) {
1006 $this->readOnlyError();
1010 * Returns 'true' if this image is a multipage document, e.g. a DJVU
1015 function isMultipage() {
1016 return $this->getHandler() && $this->handler
->isMultiPage( $this );
1020 * Returns the number of pages of a multipage document, or NULL for
1021 * documents which aren't multipage documents
1023 function pageCount() {
1024 if ( !isset( $this->pageCount
) ) {
1025 if ( $this->getHandler() && $this->handler
->isMultiPage( $this ) ) {
1026 $this->pageCount
= $this->handler
->pageCount( $this );
1028 $this->pageCount
= false;
1031 return $this->pageCount
;
1035 * Calculate the height of a thumbnail using the source and destination width
1037 static function scaleHeight( $srcWidth, $srcHeight, $dstWidth ) {
1038 // Exact integer multiply followed by division
1039 if ( $srcWidth == 0 ) {
1042 return round( $srcHeight * $dstWidth / $srcWidth );
1047 * Get an image size array like that returned by getimagesize(), or false if it
1048 * can't be determined.
1050 * @param string $fileName The filename
1053 function getImageSize( $fileName ) {
1054 if ( !$this->getHandler() ) {
1057 return $this->handler
->getImageSize( $this, $fileName );
1061 * Get the URL of the image description page. May return false if it is
1062 * unknown or not applicable.
1064 function getDescriptionUrl() {
1065 return $this->repo
->getDescriptionUrl( $this->getName() );
1069 * Get the HTML text of the description page, if available
1071 function getDescriptionText() {
1072 global $wgMemc, $wgContLang;
1073 if ( !$this->repo
->fetchDescription
) {
1076 $renderUrl = $this->repo
->getDescriptionRenderUrl( $this->getName(), $wgContLang->getCode() );
1078 if ( $this->repo
->descriptionCacheExpiry
> 0 ) {
1079 wfDebug("Attempting to get the description from cache...");
1080 $key = wfMemcKey( 'RemoteFileDescription', 'url', $wgContLang->getCode(),
1082 $obj = $wgMemc->get($key);
1084 wfDebug("success!\n");
1089 wfDebug( "Fetching shared description from $renderUrl\n" );
1090 $res = Http
::get( $renderUrl );
1091 if ( $res && $this->repo
->descriptionCacheExpiry
> 0 ) {
1092 $wgMemc->set( $key, $res, $this->repo
->descriptionCacheExpiry
);
1101 * Get discription of file revision
1104 function getDescription() {
1109 * Get the 14-character timestamp of the file upload, or false if
1112 function getTimestamp() {
1113 $path = $this->getPath();
1114 if ( !file_exists( $path ) ) {
1117 return wfTimestamp( TS_MW
, filemtime( $path ) );
1121 * Get the SHA-1 base 36 hash of the file
1123 function getSha1() {
1124 return self
::sha1Base36( $this->getPath() );
1128 * Determine if the current user is allowed to view a particular
1129 * field of this file, if it's marked as deleted.
1134 function userCan( $field ) {
1139 * Get an associative array containing information about a file in the local filesystem.
1141 * @param string $path Absolute local filesystem path
1142 * @param mixed $ext The file extension, or true to extract it from the filename.
1143 * Set it to false to ignore the extension.
1145 static function getPropsFromPath( $path, $ext = true ) {
1146 wfProfileIn( __METHOD__
);
1147 wfDebug( __METHOD__
.": Getting file info for $path\n" );
1149 'fileExists' => file_exists( $path ) && !is_dir( $path )
1152 if ( $info['fileExists'] ) {
1153 $magic = MimeMagic
::singleton();
1155 $info['mime'] = $magic->guessMimeType( $path, $ext );
1156 list( $info['major_mime'], $info['minor_mime'] ) = self
::splitMime( $info['mime'] );
1157 $info['media_type'] = $magic->getMediaType( $path, $info['mime'] );
1160 $info['size'] = filesize( $path );
1162 # Height, width and metadata
1163 $handler = MediaHandler
::getHandler( $info['mime'] );
1165 $tempImage = (object)array();
1166 $info['metadata'] = $handler->getMetadata( $tempImage, $path );
1167 $gis = $handler->getImageSize( $tempImage, $path, $info['metadata'] );
1170 $info['metadata'] = '';
1172 $info['sha1'] = self
::sha1Base36( $path );
1174 wfDebug(__METHOD__
.": $path loaded, {$info['size']} bytes, {$info['mime']}.\n");
1176 $info['mime'] = NULL;
1177 $info['media_type'] = MEDIATYPE_UNKNOWN
;
1178 $info['metadata'] = '';
1180 wfDebug(__METHOD__
.": $path NOT FOUND!\n");
1183 # NOTE: $gis[2] contains a code for the image type. This is no longer used.
1184 $info['width'] = $gis[0];
1185 $info['height'] = $gis[1];
1186 if ( isset( $gis['bits'] ) ) {
1187 $info['bits'] = $gis['bits'];
1193 $info['height'] = 0;
1196 wfProfileOut( __METHOD__
);
1201 * Get a SHA-1 hash of a file in the local filesystem, in base-36 lower case
1202 * encoding, zero padded to 31 digits.
1204 * 160 log 2 / log 36 = 30.95, so the 160-bit hash fills 31 digits in base 36
1207 * Returns false on failure
1209 static function sha1Base36( $path ) {
1210 wfSuppressWarnings();
1211 $hash = sha1_file( $path );
1212 wfRestoreWarnings();
1213 if ( $hash === false ) {
1216 return wfBaseConvert( $hash, 16, 36, 31 );
1220 function getLongDesc() {
1221 $handler = $this->getHandler();
1223 return $handler->getLongDesc( $this );
1225 return MediaHandler
::getGeneralLongDesc( $this );
1229 function getShortDesc() {
1230 $handler = $this->getHandler();
1232 return $handler->getShortDesc( $this );
1234 return MediaHandler
::getGeneralShortDesc( $this );
1238 function getDimensionsString() {
1239 $handler = $this->getHandler();
1241 return $handler->getDimensionsString( $this );
1247 function getRedirected() {
1248 return $this->redirected
;
1251 function getRedirectedTitle() {
1252 if ( $this->redirected
) {
1253 if ( !$this->redirectTitle
)
1254 $this->redirectTitle
= Title
::makeTitle( NS_FILE
, $this->redirected
);
1255 return $this->redirectTitle
;
1259 function redirectedFrom( $from ) {
1260 $this->redirected
= $from;
1264 * Aliases for backwards compatibility with 1.6
1266 define( 'MW_IMG_DELETED_FILE', File
::DELETED_FILE
);
1267 define( 'MW_IMG_DELETED_COMMENT', File
::DELETED_COMMENT
);
1268 define( 'MW_IMG_DELETED_USER', File
::DELETED_USER
);
1269 define( 'MW_IMG_DELETED_RESTRICTED', File
::DELETED_RESTRICTED
);