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 );
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 title used to find this file
159 public function getOriginalTitle() {
160 if ( $this->redirected
)
161 return $this->getRedirectedTitle();
166 * Return the URL of the file
168 public function getUrl() {
169 if ( !isset( $this->url
) ) {
170 $this->url
= $this->repo
->getZoneUrl( 'public' ) . '/' . $this->getUrlRel();
176 * Return a fully-qualified URL to the file.
177 * Upload URL paths _may or may not_ be fully qualified, so
178 * we check. Local paths are assumed to belong on $wgServer.
181 public function getFullUrl() {
182 return wfExpandUrl( $this->getUrl() );
185 function getViewURL() {
186 if( $this->mustRender()) {
187 if( $this->canRender() ) {
188 return $this->createThumb( $this->getWidth() );
191 wfDebug(__METHOD__
.': supposed to render '.$this->getName().' ('.$this->getMimeType()."), but can't!\n");
192 return $this->getURL(); #hm... return NULL?
195 return $this->getURL();
200 * Return the full filesystem path to the file. Note that this does
201 * not mean that a file actually exists under that location.
203 * This path depends on whether directory hashing is active or not,
204 * i.e. whether the files are all found in the same directory,
205 * or in hashed paths like /images/3/3c.
207 * May return false if the file is not locally accessible.
209 public function getPath() {
210 if ( !isset( $this->path
) ) {
211 $this->path
= $this->repo
->getZonePath('public') . '/' . $this->getRel();
217 * Alias for getPath()
219 public function getFullPath() {
220 return $this->getPath();
224 * Return the width of the image. Returns false if the width is unknown
228 * Overridden by LocalFile, UnregisteredLocalFile
230 public function getWidth( $page = 1 ) { return false; }
233 * Return the height of the image. Returns false if the height is unknown
237 * Overridden by LocalFile, UnregisteredLocalFile
239 public function getHeight( $page = 1 ) { return false; }
242 * Returns ID or name of user who uploaded the file
245 * @param $type string 'text' or 'id'
247 public function getUser( $type='text' ) { return null; }
250 * Get the duration of a media file in seconds
252 public function getLength() {
253 $handler = $this->getHandler();
255 return $handler->getLength( $this );
262 * Get handler-specific metadata
263 * Overridden by LocalFile, UnregisteredLocalFile
266 function getMetadata() { return false; }
269 * Return the size of the image file, in bytes
270 * Overridden by LocalFile, UnregisteredLocalFile
273 public function getSize() { return false; }
276 * Returns the mime type of the file.
277 * Overridden by LocalFile, UnregisteredLocalFile
280 function getMimeType() { return 'unknown/unknown'; }
283 * Return the type of the media in the file.
284 * Use the value returned by this function with the MEDIATYPE_xxx constants.
285 * Overridden by LocalFile,
288 function getMediaType() { return MEDIATYPE_UNKNOWN
; }
291 * Checks if the output of transform() for this file is likely
292 * to be valid. If this is false, various user elements will
293 * display a placeholder instead.
295 * Currently, this checks if the file is an image format
296 * that can be converted to a format
297 * supported by all browsers (namely GIF, PNG and JPEG),
298 * or if it is an SVG image and SVG conversion is enabled.
300 function canRender() {
301 if ( !isset( $this->canRender
) ) {
302 $this->canRender
= $this->getHandler() && $this->handler
->canRender( $this );
304 return $this->canRender
;
308 * Accessor for __get()
310 protected function getCanRender() {
311 return $this->canRender();
315 * Return true if the file is of a type that can't be directly
316 * rendered by typical browsers and needs to be re-rasterized.
318 * This returns true for everything but the bitmap types
319 * supported by all browsers, i.e. JPEG; GIF and PNG. It will
320 * also return true for any non-image formats.
324 function mustRender() {
325 return $this->getHandler() && $this->handler
->mustRender( $this );
329 * Alias for canRender()
331 function allowInlineDisplay() {
332 return $this->canRender();
336 * Determines if this media file is in a format that is unlikely to
337 * contain viruses or malicious content. It uses the global
338 * $wgTrustedMediaFormats list to determine if the file is safe.
340 * This is used to show a warning on the description page of non-safe files.
341 * It may also be used to disallow direct [[media:...]] links to such files.
343 * Note that this function will always return true if allowInlineDisplay()
344 * or isTrustedFile() is true for this file.
346 function isSafeFile() {
347 if ( !isset( $this->isSafeFile
) ) {
348 $this->isSafeFile
= $this->_getIsSafeFile();
350 return $this->isSafeFile
;
353 /** Accessor for __get() */
354 protected function getIsSafeFile() {
355 return $this->isSafeFile();
358 /** Uncached accessor */
359 protected function _getIsSafeFile() {
360 if ($this->allowInlineDisplay()) return true;
361 if ($this->isTrustedFile()) return true;
363 global $wgTrustedMediaFormats;
365 $type= $this->getMediaType();
366 $mime= $this->getMimeType();
367 #wfDebug("LocalFile::isSafeFile: type= $type, mime= $mime\n");
369 if (!$type ||
$type===MEDIATYPE_UNKNOWN
) return false; #unknown type, not trusted
370 if ( in_array( $type, $wgTrustedMediaFormats) ) return true;
372 if ($mime==="unknown/unknown") return false; #unknown type, not trusted
373 if ( in_array( $mime, $wgTrustedMediaFormats) ) return true;
378 /** Returns true if the file is flagged as trusted. Files flagged that way
379 * can be linked to directly, even if that is not allowed for this type of
382 * This is a dummy function right now and always returns false. It could be
383 * implemented to extract a flag from the database. The trusted flag could be
384 * set on upload, if the user has sufficient privileges, to bypass script-
385 * and html-filters. It may even be coupled with cryptographics signatures
388 function isTrustedFile() {
389 #this could be implemented to check a flag in the databas,
390 #look for signatures, etc
395 * Returns true if file exists in the repository.
397 * Overridden by LocalFile to avoid unnecessary stat calls.
399 * @return boolean Whether file exists in the repository.
401 public function exists() {
402 return $this->getPath() && file_exists( $this->path
);
406 * Returns true if file exists in the repository and can be included in a page.
407 * It would be unsafe to include private images, making public thumbnails inadvertently
409 * @return boolean Whether file exists in the repository and is includable.
412 function isVisible() {
413 return $this->exists();
416 function getTransformScript() {
417 if ( !isset( $this->transformScript
) ) {
418 $this->transformScript
= false;
420 $script = $this->repo
->getThumbScriptUrl();
422 $this->transformScript
= "$script?f=" . urlencode( $this->getName() );
426 return $this->transformScript
;
430 * Get a ThumbnailImage which is the same size as the source
432 function getUnscaledThumb( $page = false ) {
433 $width = $this->getWidth( $page );
435 return $this->iconThumb();
440 'width' => $this->getWidth( $page )
443 $params = array( 'width' => $this->getWidth() );
445 return $this->transform( $params );
449 * Return the file name of a thumbnail with the specified parameters
451 * @param array $params Handler-specific parameters
454 function thumbName( $params ) {
455 if ( !$this->getHandler() ) {
458 $extension = $this->getExtension();
459 list( $thumbExt, $thumbMime ) = $this->handler
->getThumbType( $extension, $this->getMimeType() );
460 $thumbName = $this->handler
->makeParamString( $params ) . '-' . $this->getName();
461 if ( $thumbExt != $extension ) {
462 $thumbName .= ".$thumbExt";
468 * Create a thumbnail of the image having the specified width/height.
469 * The thumbnail will not be created if the width is larger than the
470 * image's width. Let the browser do the scaling in this case.
471 * The thumbnail is stored on disk and is only computed if the thumbnail
472 * file does not exist OR if it is older than the image.
475 * Keeps aspect ratio of original image. If both width and height are
476 * specified, the generated image will be no bigger than width x height,
477 * and will also have correct aspect ratio.
479 * @param integer $width maximum width of the generated thumbnail
480 * @param integer $height maximum height of the image (optional)
482 public function createThumb( $width, $height = -1 ) {
483 $params = array( 'width' => $width );
484 if ( $height != -1 ) {
485 $params['height'] = $height;
487 $thumb = $this->transform( $params );
488 if( is_null( $thumb ) ||
$thumb->isError() ) return '';
489 return $thumb->getUrl();
493 * As createThumb, but returns a ThumbnailImage object. This can
494 * provide access to the actual file, the real size of the thumb,
495 * and can produce a convenient <img> tag for you.
497 * For non-image formats, this may return a filetype-specific icon.
499 * @param integer $width maximum width of the generated thumbnail
500 * @param integer $height maximum height of the image (optional)
501 * @param boolean $render True to render the thumbnail if it doesn't exist,
502 * false to just return the URL
504 * @return ThumbnailImage or null on failure
506 * @deprecated use transform()
508 public function getThumbnail( $width, $height=-1, $render = true ) {
509 $params = array( 'width' => $width );
510 if ( $height != -1 ) {
511 $params['height'] = $height;
513 $flags = $render ? self
::RENDER_NOW
: 0;
514 return $this->transform( $params, $flags );
518 * Transform a media file
520 * @param array $params An associative array of handler-specific parameters. Typical
521 * keys are width, height and page.
522 * @param integer $flags A bitfield, may contain self::RENDER_NOW to force rendering
523 * @return MediaTransformOutput
525 function transform( $params, $flags = 0 ) {
526 global $wgUseSquid, $wgIgnoreImageErrors;
528 wfProfileIn( __METHOD__
);
530 if ( !$this->canRender() ) {
531 // not a bitmap or renderable image, don't try.
532 $thumb = $this->iconThumb();
536 $script = $this->getTransformScript();
537 if ( $script && !($flags & self
::RENDER_NOW
) ) {
538 // Use a script to transform on client request, if possible
539 $thumb = $this->handler
->getScriptedTransform( $this, $script, $params );
545 $normalisedParams = $params;
546 $this->handler
->normaliseParams( $this, $normalisedParams );
547 $thumbName = $this->thumbName( $normalisedParams );
548 $thumbPath = $this->getThumbPath( $thumbName );
549 $thumbUrl = $this->getThumbUrl( $thumbName );
551 if ( $this->repo
->canTransformVia404() && !($flags & self
::RENDER_NOW
) ) {
552 $thumb = $this->handler
->getTransform( $this, $thumbPath, $thumbUrl, $params );
556 wfDebug( __METHOD__
.": Doing stat for $thumbPath\n" );
557 $this->migrateThumbFile( $thumbName );
558 if ( file_exists( $thumbPath ) ) {
559 $thumb = $this->handler
->getTransform( $this, $thumbPath, $thumbUrl, $params );
562 $thumb = $this->handler
->doTransform( $this, $thumbPath, $thumbUrl, $params );
564 // Ignore errors if requested
567 } elseif ( $thumb->isError() ) {
568 $this->lastError
= $thumb->toText();
569 if ( $wgIgnoreImageErrors && !($flags & self
::RENDER_NOW
) ) {
570 $thumb = $this->handler
->getTransform( $this, $thumbPath, $thumbUrl, $params );
574 // Purge. Useful in the event of Core -> Squid connection failure or squid
575 // purge collisions from elsewhere during failure. Don't keep triggering for
576 // "thumbs" which have the main image URL though (bug 13776)
577 if ( $wgUseSquid && ($thumb->isError() ||
$thumb->getUrl() != $this->getURL()) ) {
578 SquidUpdate
::purge( array( $thumbUrl ) );
582 wfProfileOut( __METHOD__
);
587 * Hook into transform() to allow migration of thumbnail files
589 * Overridden by LocalFile
591 function migrateThumbFile( $thumbName ) {}
594 * Get a MediaHandler instance for this file
596 function getHandler() {
597 if ( !isset( $this->handler
) ) {
598 $this->handler
= MediaHandler
::getHandler( $this->getMimeType() );
600 return $this->handler
;
604 * Get a ThumbnailImage representing a file type icon
605 * @return ThumbnailImage
607 function iconThumb() {
608 global $wgStylePath, $wgStyleDirectory;
610 $try = array( 'fileicon-' . $this->getExtension() . '.png', 'fileicon.png' );
611 foreach( $try as $icon ) {
612 $path = '/common/images/icons/' . $icon;
613 $filepath = $wgStyleDirectory . $path;
614 if( file_exists( $filepath ) ) {
615 return new ThumbnailImage( $this, $wgStylePath . $path, 120, 120 );
622 * Get last thumbnailing error.
625 function getLastError() {
626 return $this->lastError
;
630 * Get all thumbnail names previously generated for this file
632 * Overridden by LocalFile
634 function getThumbnails() { return array(); }
637 * Purge shared caches such as thumbnails and DB data caching
639 * Overridden by LocalFile
641 function purgeCache() {}
644 * Purge the file description page, but don't go after
645 * pages using the file. Use when modifying file history
646 * but not the current data.
648 function purgeDescription() {
649 $title = $this->getTitle();
651 $title->invalidateCache();
652 $title->purgeSquid();
657 * Purge metadata and all affected pages when the file is created,
658 * deleted, or majorly updated.
660 function purgeEverything() {
661 // Delete thumbnails and refresh file metadata cache
663 $this->purgeDescription();
665 // Purge cache of all pages using this file
666 $title = $this->getTitle();
668 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
674 * Return a fragment of the history of file.
677 * @param $limit integer Limit of rows to return
678 * @param $start timestamp Only revisions older than $start will be returned
679 * @param $end timestamp Only revisions newer than $end will be returned
681 function getHistory($limit = null, $start = null, $end = null) {
686 * Return the history of this file, line by line. Starts with current version,
687 * then old versions. Should return an object similar to an image/oldimage
691 * Overridden in LocalFile
693 public function nextHistoryLine() {
698 * Reset the history pointer to the first element of the history.
699 * Always call this function after using nextHistoryLine() to free db resources
701 * Overridden in LocalFile.
703 public function resetHistory() {}
706 * Get the filename hash component of the directory including trailing slash,
708 * If the repository is not hashed, returns an empty string.
710 function getHashPath() {
711 if ( !isset( $this->hashPath
) ) {
712 $this->hashPath
= $this->repo
->getHashPath( $this->getName() );
714 return $this->hashPath
;
718 * Get the path of the file relative to the public zone root
721 return $this->getHashPath() . $this->getName();
725 * Get urlencoded relative path of the file
727 function getUrlRel() {
728 return $this->getHashPath() . rawurlencode( $this->getName() );
731 /** Get the relative path for an archive file */
732 function getArchiveRel( $suffix = false ) {
733 $path = 'archive/' . $this->getHashPath();
734 if ( $suffix === false ) {
735 $path = substr( $path, 0, -1 );
742 /** Get relative path for a thumbnail file */
743 function getThumbRel( $suffix = false ) {
744 $path = 'thumb/' . $this->getRel();
745 if ( $suffix !== false ) {
746 $path .= '/' . $suffix;
751 /** Get the path of the archive directory, or a particular file if $suffix is specified */
752 function getArchivePath( $suffix = false ) {
753 return $this->repo
->getZonePath('public') . '/' . $this->getArchiveRel( $suffix );
756 /** Get the path of the thumbnail directory, or a particular file if $suffix is specified */
757 function getThumbPath( $suffix = false ) {
758 return $this->repo
->getZonePath('public') . '/' . $this->getThumbRel( $suffix );
761 /** Get the URL of the archive directory, or a particular file if $suffix is specified */
762 function getArchiveUrl( $suffix = false ) {
763 $path = $this->repo
->getZoneUrl('public') . '/archive/' . $this->getHashPath();
764 if ( $suffix === false ) {
765 $path = substr( $path, 0, -1 );
767 $path .= rawurlencode( $suffix );
772 /** Get the URL of the thumbnail directory, or a particular file if $suffix is specified */
773 function getThumbUrl( $suffix = false ) {
774 $path = $this->repo
->getZoneUrl('public') . '/thumb/' . $this->getUrlRel();
775 if ( $suffix !== false ) {
776 $path .= '/' . rawurlencode( $suffix );
781 /** Get the virtual URL for an archive file or directory */
782 function getArchiveVirtualUrl( $suffix = false ) {
783 $path = $this->repo
->getVirtualUrl() . '/public/archive/' . $this->getHashPath();
784 if ( $suffix === false ) {
785 $path = substr( $path, 0, -1 );
787 $path .= rawurlencode( $suffix );
792 /** Get the virtual URL for a thumbnail file or directory */
793 function getThumbVirtualUrl( $suffix = false ) {
794 $path = $this->repo
->getVirtualUrl() . '/public/thumb/' . $this->getUrlRel();
795 if ( $suffix !== false ) {
796 $path .= '/' . rawurlencode( $suffix );
801 /** Get the virtual URL for the file itself */
802 function getVirtualUrl( $suffix = false ) {
803 $path = $this->repo
->getVirtualUrl() . '/public/' . $this->getUrlRel();
804 if ( $suffix !== false ) {
805 $path .= '/' . rawurlencode( $suffix );
813 function isHashed() {
814 return $this->repo
->isHashed();
817 function readOnlyError() {
818 throw new MWException( get_class($this) . ': write operations are not supported' );
822 * Record a file upload in the upload log and the image table
824 * Overridden by LocalFile
826 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '', $watch = false ) {
827 $this->readOnlyError();
831 * Move or copy a file to its public location. If a file exists at the
832 * destination, move it to an archive. Returns the archive name on success
833 * or an empty string if it was a new file, and a wikitext-formatted
834 * WikiError object on failure.
836 * The archive name should be passed through to recordUpload for database
839 * @param string $sourcePath Local filesystem path to the source image
840 * @param integer $flags A bitwise combination of:
841 * File::DELETE_SOURCE Delete the source file, i.e. move
843 * @return The archive name on success or an empty string if it was a new
844 * file, and a wikitext-formatted WikiError object on failure.
847 * Overridden by LocalFile
849 function publish( $srcPath, $flags = 0 ) {
850 $this->readOnlyError();
854 * Get an array of Title objects which are articles which use this file
855 * Also adds their IDs to the link cache
857 * This is mostly copied from Title::getLinksTo()
859 * @deprecated Use HTMLCacheUpdate, this function uses too much memory
861 function getLinksTo( $options = '' ) {
862 wfProfileIn( __METHOD__
);
864 // Note: use local DB not repo DB, we want to know local links
866 $db = wfGetDB( DB_MASTER
);
868 $db = wfGetDB( DB_SLAVE
);
870 $linkCache = LinkCache
::singleton();
872 list( $page, $imagelinks ) = $db->tableNamesN( 'page', 'imagelinks' );
873 $encName = $db->addQuotes( $this->getName() );
874 $sql = "SELECT page_namespace,page_title,page_id,page_len,page_is_redirect,
875 FROM $page,$imagelinks WHERE page_id=il_from AND il_to=$encName $options";
876 $res = $db->query( $sql, __METHOD__
);
879 if ( $db->numRows( $res ) ) {
880 while ( $row = $db->fetchObject( $res ) ) {
881 if ( $titleObj = Title
::newFromRow( $row ) ) {
882 $linkCache->addGoodLinkObj( $row->page_id
, $titleObj, $row->page_len
, $row->page_is_redirect
);
883 $retVal[] = $titleObj;
887 $db->freeResult( $res );
888 wfProfileOut( __METHOD__
);
892 function formatMetadata() {
893 if ( !$this->getHandler() ) {
896 return $this->getHandler()->formatMetadata( $this, $this->getMetadata() );
900 * Returns true if the file comes from the local file repository.
905 return $this->getRepoName() == 'local';
909 * Returns the name of the repository.
913 function getRepoName() {
914 return $this->repo ?
$this->repo
->getName() : 'unknown';
917 * Returns the repository
924 * Returns true if the image is an old version
932 * Is this file a "deleted" file in a private archive?
935 function isDeleted( $field ) {
940 * Was this file ever deleted from the wiki?
944 function wasDeleted() {
945 $title = $this->getTitle();
946 return $title && $title->isDeleted() > 0;
950 * Move file to the new title
952 * Move current, old version and all thumbnails
953 * to the new filename. Old file is deleted.
955 * Cache purging is done; checks for validity
956 * and logging are caller's responsibility
958 * @param $target Title New file name
959 * @return FileRepoStatus object.
961 function move( $target ) {
962 $this->readOnlyError();
966 * Delete all versions of the file.
968 * Moves the files into an archive directory (or deletes them)
969 * and removes the database rows.
971 * Cache purging is done; logging is caller's responsibility.
974 * @param $suppress, hide content from sysops?
975 * @return true on success, false on some kind of failure
977 * Overridden by LocalFile
979 function delete( $reason, $suppress = false ) {
980 $this->readOnlyError();
984 * Restore all or specified deleted revisions to the given file.
985 * Permissions and logging are left to the caller.
987 * May throw database exceptions on error.
989 * @param $versions set of record ids of deleted items to restore,
990 * or empty to restore all revisions.
991 * @param $unsuppress, remove restrictions on content upon restoration?
992 * @return the number of file revisions restored if successful,
993 * or false on failure
995 * Overridden by LocalFile
997 function restore( $versions=array(), $unsuppress=false ) {
998 $this->readOnlyError();
1002 * Returns 'true' if this image is a multipage document, e.g. a DJVU
1007 function isMultipage() {
1008 return $this->getHandler() && $this->handler
->isMultiPage( $this );
1012 * Returns the number of pages of a multipage document, or NULL for
1013 * documents which aren't multipage documents
1015 function pageCount() {
1016 if ( !isset( $this->pageCount
) ) {
1017 if ( $this->getHandler() && $this->handler
->isMultiPage( $this ) ) {
1018 $this->pageCount
= $this->handler
->pageCount( $this );
1020 $this->pageCount
= false;
1023 return $this->pageCount
;
1027 * Calculate the height of a thumbnail using the source and destination width
1029 static function scaleHeight( $srcWidth, $srcHeight, $dstWidth ) {
1030 // Exact integer multiply followed by division
1031 if ( $srcWidth == 0 ) {
1034 return round( $srcHeight * $dstWidth / $srcWidth );
1039 * Get an image size array like that returned by getimagesize(), or false if it
1040 * can't be determined.
1042 * @param string $fileName The filename
1045 function getImageSize( $fileName ) {
1046 if ( !$this->getHandler() ) {
1049 return $this->handler
->getImageSize( $this, $fileName );
1053 * Get the URL of the image description page. May return false if it is
1054 * unknown or not applicable.
1056 function getDescriptionUrl() {
1057 return $this->repo
->getDescriptionUrl( $this->getName() );
1061 * Get the HTML text of the description page, if available
1063 function getDescriptionText() {
1064 if ( !$this->repo
->fetchDescription
) {
1067 $renderUrl = $this->repo
->getDescriptionRenderUrl( $this->getName() );
1069 wfDebug( "Fetching shared description from $renderUrl\n" );
1070 return Http
::get( $renderUrl );
1077 * Get discription of file revision
1080 function getDescription() {
1085 * Get the 14-character timestamp of the file upload, or false if
1088 function getTimestamp() {
1089 $path = $this->getPath();
1090 if ( !file_exists( $path ) ) {
1093 return wfTimestamp( TS_MW
, filemtime( $path ) );
1097 * Get the SHA-1 base 36 hash of the file
1099 function getSha1() {
1100 return self
::sha1Base36( $this->getPath() );
1104 * Determine if the current user is allowed to view a particular
1105 * field of this file, if it's marked as deleted.
1110 function userCan( $field ) {
1115 * Get an associative array containing information about a file in the local filesystem.
1117 * @param string $path Absolute local filesystem path
1118 * @param mixed $ext The file extension, or true to extract it from the filename.
1119 * Set it to false to ignore the extension.
1121 static function getPropsFromPath( $path, $ext = true ) {
1122 wfProfileIn( __METHOD__
);
1123 wfDebug( __METHOD__
.": Getting file info for $path\n" );
1125 'fileExists' => file_exists( $path ) && !is_dir( $path )
1128 if ( $info['fileExists'] ) {
1129 $magic = MimeMagic
::singleton();
1131 $info['mime'] = $magic->guessMimeType( $path, $ext );
1132 list( $info['major_mime'], $info['minor_mime'] ) = self
::splitMime( $info['mime'] );
1133 $info['media_type'] = $magic->getMediaType( $path, $info['mime'] );
1136 $info['size'] = filesize( $path );
1138 # Height, width and metadata
1139 $handler = MediaHandler
::getHandler( $info['mime'] );
1141 $tempImage = (object)array();
1142 $info['metadata'] = $handler->getMetadata( $tempImage, $path );
1143 $gis = $handler->getImageSize( $tempImage, $path, $info['metadata'] );
1146 $info['metadata'] = '';
1148 $info['sha1'] = self
::sha1Base36( $path );
1150 wfDebug(__METHOD__
.": $path loaded, {$info['size']} bytes, {$info['mime']}.\n");
1152 $info['mime'] = NULL;
1153 $info['media_type'] = MEDIATYPE_UNKNOWN
;
1154 $info['metadata'] = '';
1156 wfDebug(__METHOD__
.": $path NOT FOUND!\n");
1159 # NOTE: $gis[2] contains a code for the image type. This is no longer used.
1160 $info['width'] = $gis[0];
1161 $info['height'] = $gis[1];
1162 if ( isset( $gis['bits'] ) ) {
1163 $info['bits'] = $gis['bits'];
1169 $info['height'] = 0;
1172 wfProfileOut( __METHOD__
);
1177 * Get a SHA-1 hash of a file in the local filesystem, in base-36 lower case
1178 * encoding, zero padded to 31 digits.
1180 * 160 log 2 / log 36 = 30.95, so the 160-bit hash fills 31 digits in base 36
1183 * Returns false on failure
1185 static function sha1Base36( $path ) {
1186 wfSuppressWarnings();
1187 $hash = sha1_file( $path );
1188 wfRestoreWarnings();
1189 if ( $hash === false ) {
1192 return wfBaseConvert( $hash, 16, 36, 31 );
1196 function getLongDesc() {
1197 $handler = $this->getHandler();
1199 return $handler->getLongDesc( $this );
1201 return MediaHandler
::getLongDesc( $this );
1205 function getShortDesc() {
1206 $handler = $this->getHandler();
1208 return $handler->getShortDesc( $this );
1210 return MediaHandler
::getShortDesc( $this );
1214 function getDimensionsString() {
1215 $handler = $this->getHandler();
1217 return $handler->getDimensionsString( $this );
1223 function getRedirected() {
1224 return $this->redirected
;
1227 function getRedirectedTitle() {
1228 if ( $this->redirected
) {
1229 if ( !$this->redirectTitle
)
1230 $this->redirectTitle
= Title
::makeTitle( NS_IMAGE
, $this->redirected
);
1231 return $this->redirectTitle
;
1235 function redirectedFrom( $from ) {
1236 $this->redirected
= $from;
1240 * Aliases for backwards compatibility with 1.6
1242 define( 'MW_IMG_DELETED_FILE', File
::DELETED_FILE
);
1243 define( 'MW_IMG_DELETED_COMMENT', File
::DELETED_COMMENT
);
1244 define( 'MW_IMG_DELETED_USER', File
::DELETED_USER
);
1245 define( 'MW_IMG_DELETED_RESTRICTED', File
::DELETED_RESTRICTED
);