*Tweak rev_deleted message
[mediawiki.git] / includes / filerepo / File.php
blob7e222a0846ec42368f6391237fcf0f94d8ee0379
1 <?php
3 /**
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
18 * in most cases.
20 * @addtogroup FileRepo
22 abstract class File {
23 const DELETED_FILE = 1;
24 const DELETED_COMMENT = 2;
25 const DELETED_USER = 4;
26 const DELETED_RESTRICTED = 8;
27 const RENDER_NOW = 1;
29 const DELETE_SOURCE = 1;
31 /**
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
35 * letter.
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.
46 /**
47 * The following member variables are not lazy-initialised
49 var $repo, $title, $lastError;
51 /**
52 * Call this constructor from child classes
54 function __construct( $title, $repo ) {
55 $this->title = $title;
56 $this->repo = $repo;
59 function __get( $name ) {
60 $function = array( $this, 'get' . ucfirst( $name ) );
61 if ( !is_callable( $function ) ) {
62 return null;
63 } else {
64 $this->$name = call_user_func( $function );
65 return $this->$name;
69 /**
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 .)
74 * @return string
76 static function normalizeExtension( $ext ) {
77 $lower = strtolower( $ext );
78 $squish = array(
79 'htm' => 'html',
80 'jpeg' => 'jpg',
81 'mpeg' => 'mpg',
82 'tiff' => 'tif' );
83 if( isset( $squish[$lower] ) ) {
84 return $squish[$lower];
85 } elseif( preg_match( '/^[0-9a-z]+$/', $lower ) ) {
86 return $lower;
87 } else {
88 return '';
92 /**
93 * Upgrade the database row if there is one
94 * Called by ImagePage
95 * STUB
97 function upgradeRow() {}
99 /**
100 * Split an internet media type into its two components; if not
101 * a two-part name, set the minor type to 'unknown'.
103 * @param $mime "text/html" etc
104 * @return array ("text", "html") etc
106 static function splitMime( $mime ) {
107 if( strpos( $mime, '/' ) !== false ) {
108 return explode( '/', $mime, 2 );
109 } else {
110 return array( $mime, 'unknown' );
115 * Return the name of this file
117 public function getName() {
118 if ( !isset( $this->name ) ) {
119 $this->name = $this->repo->getNameFromTitle( $this->title );
121 return $this->name;
125 * Get the file extension, e.g. "svg"
127 function getExtension() {
128 if ( !isset( $this->extension ) ) {
129 $n = strrpos( $this->getName(), '.' );
130 $this->extension = self::normalizeExtension(
131 $n ? substr( $this->getName(), $n + 1 ) : '' );
133 return $this->extension;
137 * Return the associated title object
138 * @public
140 function getTitle() { return $this->title; }
143 * Return the URL of the file
144 * @public
146 function getUrl() {
147 if ( !isset( $this->url ) ) {
148 $this->url = $this->repo->getZoneUrl( 'public' ) . '/' . $this->getUrlRel();
150 return $this->url;
154 * Return a fully-qualified URL to the file.
155 * Upload URL paths _may or may not_ be fully qualified, so
156 * we check. Local paths are assumed to belong on $wgServer.
157 * @return string
159 public function getFullUrl() {
160 $url = $this->getUrl();
161 if( substr( $url, 0, 1 ) == '/' ) {
162 global $wgServer;
163 return $wgServer . $url;
165 return $url;
168 function getViewURL() {
169 if( $this->mustRender()) {
170 if( $this->canRender() ) {
171 return $this->createThumb( $this->getWidth() );
173 else {
174 wfDebug(__METHOD__.': supposed to render '.$this->getName().' ('.$this->getMimeType()."), but can't!\n");
175 return $this->getURL(); #hm... return NULL?
177 } else {
178 return $this->getURL();
183 * Return the full filesystem path to the file. Note that this does
184 * not mean that a file actually exists under that location.
186 * This path depends on whether directory hashing is active or not,
187 * i.e. whether the files are all found in the same directory,
188 * or in hashed paths like /images/3/3c.
190 * May return false if the file is not locally accessible.
192 * @public
194 function getPath() {
195 if ( !isset( $this->path ) ) {
196 $this->path = $this->repo->getZonePath('public') . '/' . $this->getRel();
198 return $this->path;
202 * Alias for getPath()
203 * @public
205 function getFullPath() {
206 return $this->getPath();
210 * Return the width of the image. Returns false if the width is unknown
211 * or undefined.
213 * STUB
214 * Overridden by LocalFile, UnregisteredLocalFile
216 public function getWidth( $page = 1 ) { return false; }
219 * Return the height of the image. Returns false if the height is unknown
220 * or undefined
222 * STUB
223 * Overridden by LocalFile, UnregisteredLocalFile
225 public function getHeight( $page = 1 ) { return false; }
228 * Get the duration of a media file in seconds
230 public function getLength() {
231 $handler = $this->getHandler();
232 if ( $handler ) {
233 return $handler->getLength( $this );
234 } else {
235 return 0;
240 * Get handler-specific metadata
241 * Overridden by LocalFile, UnregisteredLocalFile
242 * STUB
244 function getMetadata() { return false; }
247 * Return the size of the image file, in bytes
248 * Overridden by LocalFile, UnregisteredLocalFile
249 * STUB
251 public function getSize() { return false; }
254 * Returns the mime type of the file.
255 * Overridden by LocalFile, UnregisteredLocalFile
256 * STUB
258 function getMimeType() { return 'unknown/unknown'; }
261 * Return the type of the media in the file.
262 * Use the value returned by this function with the MEDIATYPE_xxx constants.
263 * Overridden by LocalFile,
264 * STUB
266 function getMediaType() { return MEDIATYPE_UNKNOWN; }
269 * Checks if the output of transform() for this file is likely
270 * to be valid. If this is false, various user elements will
271 * display a placeholder instead.
273 * Currently, this checks if the file is an image format
274 * that can be converted to a format
275 * supported by all browsers (namely GIF, PNG and JPEG),
276 * or if it is an SVG image and SVG conversion is enabled.
278 function canRender() {
279 if ( !isset( $this->canRender ) ) {
280 $this->canRender = $this->getHandler() && $this->handler->canRender( $this );
282 return $this->canRender;
286 * Accessor for __get()
288 protected function getCanRender() {
289 return $this->canRender();
293 * Return true if the file is of a type that can't be directly
294 * rendered by typical browsers and needs to be re-rasterized.
296 * This returns true for everything but the bitmap types
297 * supported by all browsers, i.e. JPEG; GIF and PNG. It will
298 * also return true for any non-image formats.
300 * @return bool
302 function mustRender() {
303 return $this->getHandler() && $this->handler->mustRender( $this );
307 * Alias for canRender()
309 function allowInlineDisplay() {
310 return $this->canRender();
314 * Determines if this media file is in a format that is unlikely to
315 * contain viruses or malicious content. It uses the global
316 * $wgTrustedMediaFormats list to determine if the file is safe.
318 * This is used to show a warning on the description page of non-safe files.
319 * It may also be used to disallow direct [[media:...]] links to such files.
321 * Note that this function will always return true if allowInlineDisplay()
322 * or isTrustedFile() is true for this file.
324 function isSafeFile() {
325 if ( !isset( $this->isSafeFile ) ) {
326 $this->isSafeFile = $this->_getIsSafeFile();
328 return $this->isSafeFile;
331 /** Accessor for __get() */
332 protected function getIsSafeFile() {
333 return $this->isSafeFile();
336 /** Uncached accessor */
337 protected function _getIsSafeFile() {
338 if ($this->allowInlineDisplay()) return true;
339 if ($this->isTrustedFile()) return true;
341 global $wgTrustedMediaFormats;
343 $type= $this->getMediaType();
344 $mime= $this->getMimeType();
345 #wfDebug("LocalFile::isSafeFile: type= $type, mime= $mime\n");
347 if (!$type || $type===MEDIATYPE_UNKNOWN) return false; #unknown type, not trusted
348 if ( in_array( $type, $wgTrustedMediaFormats) ) return true;
350 if ($mime==="unknown/unknown") return false; #unknown type, not trusted
351 if ( in_array( $mime, $wgTrustedMediaFormats) ) return true;
353 return false;
356 /** Returns true if the file is flagged as trusted. Files flagged that way
357 * can be linked to directly, even if that is not allowed for this type of
358 * file normally.
360 * This is a dummy function right now and always returns false. It could be
361 * implemented to extract a flag from the database. The trusted flag could be
362 * set on upload, if the user has sufficient privileges, to bypass script-
363 * and html-filters. It may even be coupled with cryptographics signatures
364 * or such.
366 function isTrustedFile() {
367 #this could be implemented to check a flag in the databas,
368 #look for signatures, etc
369 return false;
373 * Returns true if file exists in the repository.
375 * Overridden by LocalFile to avoid unnecessary stat calls.
377 * @return boolean Whether file exists in the repository.
379 public function exists() {
380 return $this->getPath() && file_exists( $this->path );
383 function getTransformScript() {
384 if ( !isset( $this->transformScript ) ) {
385 $this->transformScript = false;
386 if ( $this->repo ) {
387 $script = $this->repo->getThumbScriptUrl();
388 if ( $script ) {
389 $this->transformScript = "$script?f=" . urlencode( $this->getName() );
393 return $this->transformScript;
397 * Get a ThumbnailImage which is the same size as the source
399 function getUnscaledThumb( $page = false ) {
400 $width = $this->getWidth( $page );
401 if ( !$width ) {
402 return $this->iconThumb();
404 if ( $page ) {
405 $params = array(
406 'page' => $page,
407 'width' => $this->getWidth( $page )
409 } else {
410 $params = array( 'width' => $this->getWidth() );
412 return $this->transform( $params );
416 * Return the file name of a thumbnail with the specified parameters
418 * @param array $params Handler-specific parameters
419 * @private -ish
421 function thumbName( $params ) {
422 if ( !$this->getHandler() ) {
423 return null;
425 $extension = $this->getExtension();
426 list( $thumbExt, $thumbMime ) = $this->handler->getThumbType( $extension, $this->getMimeType() );
427 $thumbName = $this->handler->makeParamString( $params ) . '-' . $this->getName();
428 if ( $thumbExt != $extension ) {
429 $thumbName .= ".$thumbExt";
431 return $thumbName;
435 * Create a thumbnail of the image having the specified width/height.
436 * The thumbnail will not be created if the width is larger than the
437 * image's width. Let the browser do the scaling in this case.
438 * The thumbnail is stored on disk and is only computed if the thumbnail
439 * file does not exist OR if it is older than the image.
440 * Returns the URL.
442 * Keeps aspect ratio of original image. If both width and height are
443 * specified, the generated image will be no bigger than width x height,
444 * and will also have correct aspect ratio.
446 * @param integer $width maximum width of the generated thumbnail
447 * @param integer $height maximum height of the image (optional)
449 public function createThumb( $width, $height = -1 ) {
450 $params = array( 'width' => $width );
451 if ( $height != -1 ) {
452 $params['height'] = $height;
454 $thumb = $this->transform( $params );
455 if( is_null( $thumb ) || $thumb->isError() ) return '';
456 return $thumb->getUrl();
460 * As createThumb, but returns a ThumbnailImage object. This can
461 * provide access to the actual file, the real size of the thumb,
462 * and can produce a convenient <img> tag for you.
464 * For non-image formats, this may return a filetype-specific icon.
466 * @param integer $width maximum width of the generated thumbnail
467 * @param integer $height maximum height of the image (optional)
468 * @param boolean $render True to render the thumbnail if it doesn't exist,
469 * false to just return the URL
471 * @return ThumbnailImage or null on failure
473 * @deprecated use transform()
475 public function getThumbnail( $width, $height=-1, $render = true ) {
476 $params = array( 'width' => $width );
477 if ( $height != -1 ) {
478 $params['height'] = $height;
480 $flags = $render ? self::RENDER_NOW : 0;
481 return $this->transform( $params, $flags );
485 * Transform a media file
487 * @param array $params An associative array of handler-specific parameters. Typical
488 * keys are width, height and page.
489 * @param integer $flags A bitfield, may contain self::RENDER_NOW to force rendering
490 * @return MediaTransformOutput
492 function transform( $params, $flags = 0 ) {
493 global $wgUseSquid, $wgIgnoreImageErrors;
495 wfProfileIn( __METHOD__ );
496 do {
497 if ( !$this->canRender() ) {
498 // not a bitmap or renderable image, don't try.
499 $thumb = $this->iconThumb();
500 break;
503 $script = $this->getTransformScript();
504 if ( $script && !($flags & self::RENDER_NOW) ) {
505 // Use a script to transform on client request
506 $thumb = $this->handler->getScriptedTransform( $this, $script, $params );
507 break;
510 $normalisedParams = $params;
511 $this->handler->normaliseParams( $this, $normalisedParams );
512 $thumbName = $this->thumbName( $normalisedParams );
513 $thumbPath = $this->getThumbPath( $thumbName );
514 $thumbUrl = $this->getThumbUrl( $thumbName );
516 if ( $this->repo->canTransformVia404() && !($flags & self::RENDER_NOW ) ) {
517 $thumb = $this->handler->getTransform( $this, $thumbPath, $thumbUrl, $params );
518 break;
521 wfDebug( __METHOD__.": Doing stat for $thumbPath\n" );
522 $this->migrateThumbFile( $thumbName );
523 if ( file_exists( $thumbPath ) ) {
524 $thumb = $this->handler->getTransform( $this, $thumbPath, $thumbUrl, $params );
525 break;
527 $thumb = $this->handler->doTransform( $this, $thumbPath, $thumbUrl, $params );
529 // Ignore errors if requested
530 if ( !$thumb ) {
531 $thumb = null;
532 } elseif ( $thumb->isError() ) {
533 $this->lastError = $thumb->toText();
534 if ( $wgIgnoreImageErrors && !($flags & self::RENDER_NOW) ) {
535 $thumb = $this->handler->getTransform( $this, $thumbPath, $thumbUrl, $params );
539 if ( $wgUseSquid ) {
540 wfPurgeSquidServers( array( $thumbUrl ) );
542 } while (false);
544 wfProfileOut( __METHOD__ );
545 return $thumb;
548 /**
549 * Hook into transform() to allow migration of thumbnail files
550 * STUB
551 * Overridden by LocalFile
553 function migrateThumbFile( $thumbName ) {}
556 * Get a MediaHandler instance for this file
558 function getHandler() {
559 if ( !isset( $this->handler ) ) {
560 $this->handler = MediaHandler::getHandler( $this->getMimeType() );
562 return $this->handler;
566 * Get a ThumbnailImage representing a file type icon
567 * @return ThumbnailImage
569 function iconThumb() {
570 global $wgStylePath, $wgStyleDirectory;
572 $try = array( 'fileicon-' . $this->getExtension() . '.png', 'fileicon.png' );
573 foreach( $try as $icon ) {
574 $path = '/common/images/icons/' . $icon;
575 $filepath = $wgStyleDirectory . $path;
576 if( file_exists( $filepath ) ) {
577 return new ThumbnailImage( $this, $wgStylePath . $path, 120, 120 );
580 return null;
584 * Get last thumbnailing error.
585 * Largely obsolete.
587 function getLastError() {
588 return $this->lastError;
592 * Get all thumbnail names previously generated for this file
593 * STUB
594 * Overridden by LocalFile
596 function getThumbnails() { return array(); }
599 * Purge shared caches such as thumbnails and DB data caching
600 * STUB
601 * Overridden by LocalFile
603 function purgeCache( $archiveFiles = array() ) {}
606 * Purge the file description page, but don't go after
607 * pages using the file. Use when modifying file history
608 * but not the current data.
610 function purgeDescription() {
611 $title = $this->getTitle();
612 if ( $title ) {
613 $title->invalidateCache();
614 $title->purgeSquid();
619 * Purge metadata and all affected pages when the file is created,
620 * deleted, or majorly updated.
622 function purgeEverything() {
623 // Delete thumbnails and refresh file metadata cache
624 $this->purgeCache();
625 $this->purgeDescription();
627 // Purge cache of all pages using this file
628 $title = $this->getTitle();
629 if ( $title ) {
630 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
631 $update->doUpdate();
636 * Return the history of this file, line by line. Starts with current version,
637 * then old versions. Should return an object similar to an image/oldimage
638 * database row.
640 * STUB
641 * Overridden in LocalFile
643 public function nextHistoryLine() {
644 return false;
648 * Reset the history pointer to the first element of the history.
649 * Always call this function after using nextHistoryLine() to free db resources
650 * STUB
651 * Overridden in LocalFile.
653 public function resetHistory() {}
656 * Get the filename hash component of the directory including trailing slash,
657 * e.g. f/fa/
658 * If the repository is not hashed, returns an empty string.
660 function getHashPath() {
661 if ( !isset( $this->hashPath ) ) {
662 $this->hashPath = $this->repo->getHashPath( $this->getName() );
664 return $this->hashPath;
668 * Get the path of the file relative to the public zone root
670 function getRel() {
671 return $this->getHashPath() . $this->getName();
675 * Get urlencoded relative path of the file
677 function getUrlRel() {
678 return $this->getHashPath() . rawurlencode( $this->getName() );
681 /** Get the relative path for an archive file */
682 function getArchiveRel( $suffix = false ) {
683 $path = 'archive/' . $this->getHashPath();
684 if ( $suffix === false ) {
685 $path = substr( $path, 0, -1 );
686 } else {
687 $path .= $suffix;
689 return $path;
692 /** Get relative path for a thumbnail file */
693 function getThumbRel( $suffix = false ) {
694 $path = 'thumb/' . $this->getRel();
695 if ( $suffix !== false ) {
696 $path .= '/' . $suffix;
698 return $path;
701 /** Get the path of the archive directory, or a particular file if $suffix is specified */
702 function getArchivePath( $suffix = false ) {
703 return $this->repo->getZonePath('public') . '/' . $this->getArchiveRel();
706 /** Get the path of the thumbnail directory, or a particular file if $suffix is specified */
707 function getThumbPath( $suffix = false ) {
708 return $this->repo->getZonePath('public') . '/' . $this->getThumbRel( $suffix );
711 /** Get the URL of the archive directory, or a particular file if $suffix is specified */
712 function getArchiveUrl( $suffix = false ) {
713 $path = $this->repo->getZoneUrl('public') . '/archive/' . $this->getHashPath();
714 if ( $suffix === false ) {
715 $path = substr( $path, 0, -1 );
716 } else {
717 $path .= rawurlencode( $suffix );
719 return $path;
722 /** Get the URL of the thumbnail directory, or a particular file if $suffix is specified */
723 function getThumbUrl( $suffix = false ) {
724 $path = $this->repo->getZoneUrl('public') . '/thumb/' . $this->getUrlRel();
725 if ( $suffix !== false ) {
726 $path .= '/' . rawurlencode( $suffix );
728 return $path;
731 /** Get the virtual URL for an archive file or directory */
732 function getArchiveVirtualUrl( $suffix = false ) {
733 $path = $this->repo->getVirtualUrl() . '/public/archive/' . $this->getHashPath();
734 if ( $suffix === false ) {
735 $path = substr( $path, 0, -1 );
736 } else {
737 $path .= rawurlencode( $suffix );
739 return $path;
742 /** Get the virtual URL for a thumbnail file or directory */
743 function getThumbVirtualUrl( $suffix = false ) {
744 $path = $this->repo->getVirtualUrl() . '/public/thumb/' . $this->getUrlRel();
745 if ( $suffix !== false ) {
746 $path .= '/' . rawurlencode( $suffix );
748 return $path;
751 /** Get the virtual URL for the file itself */
752 function getVirtualUrl( $suffix = false ) {
753 $path = $this->repo->getVirtualUrl() . '/public/' . $this->getUrlRel();
754 if ( $suffix !== false ) {
755 $path .= '/' . rawurlencode( $suffix );
757 return $path;
761 * @return bool
763 function isHashed() {
764 return $this->repo->isHashed();
767 function readOnlyError() {
768 throw new MWException( get_class($this) . ': write operations are not supported' );
772 * Record a file upload in the upload log and the image table
773 * STUB
774 * Overridden by LocalFile
776 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '', $watch = false ) {
777 $this->readOnlyError();
781 * Move or copy a file to its public location. If a file exists at the
782 * destination, move it to an archive. Returns the archive name on success
783 * or an empty string if it was a new file, and a wikitext-formatted
784 * WikiError object on failure.
786 * The archive name should be passed through to recordUpload for database
787 * registration.
789 * @param string $sourcePath Local filesystem path to the source image
790 * @param integer $flags A bitwise combination of:
791 * File::DELETE_SOURCE Delete the source file, i.e. move
792 * rather than copy
793 * @return The archive name on success or an empty string if it was a new
794 * file, and a wikitext-formatted WikiError object on failure.
796 * STUB
797 * Overridden by LocalFile
799 function publish( $srcPath, $flags = 0 ) {
800 $this->readOnlyError();
804 * Get an array of Title objects which are articles which use this file
805 * Also adds their IDs to the link cache
807 * This is mostly copied from Title::getLinksTo()
809 * @deprecated Use HTMLCacheUpdate, this function uses too much memory
811 function getLinksTo( $options = '' ) {
812 wfProfileIn( __METHOD__ );
814 // Note: use local DB not repo DB, we want to know local links
815 if ( $options ) {
816 $db = wfGetDB( DB_MASTER );
817 } else {
818 $db = wfGetDB( DB_SLAVE );
820 $linkCache =& LinkCache::singleton();
822 list( $page, $imagelinks ) = $db->tableNamesN( 'page', 'imagelinks' );
823 $encName = $db->addQuotes( $this->getName() );
824 $sql = "SELECT page_namespace,page_title,page_id FROM $page,$imagelinks WHERE page_id=il_from AND il_to=$encName $options";
825 $res = $db->query( $sql, __METHOD__ );
827 $retVal = array();
828 if ( $db->numRows( $res ) ) {
829 while ( $row = $db->fetchObject( $res ) ) {
830 if ( $titleObj = Title::makeTitle( $row->page_namespace, $row->page_title ) ) {
831 $linkCache->addGoodLinkObj( $row->page_id, $titleObj );
832 $retVal[] = $titleObj;
836 $db->freeResult( $res );
837 wfProfileOut( __METHOD__ );
838 return $retVal;
841 function formatMetadata() {
842 if ( !$this->getHandler() ) {
843 return false;
845 return $this->getHandler()->formatMetadata( $this, $this->getMetadata() );
849 * Returns true if the file comes from the local file repository.
851 * @return bool
853 function isLocal() {
854 return $this->getRepoName() == 'local';
858 * Returns the name of the repository.
860 * @return string
862 function getRepoName() {
863 return $this->repo ? $this->repo->getName() : 'unknown';
867 * Returns true if the image is an old version
868 * STUB
870 function isOld() {
871 return false;
875 * Is this file a "deleted" file in a private archive?
876 * STUB
878 function isDeleted( $field ) {
879 return false;
883 * Was this file ever deleted from the wiki?
885 * @return bool
887 function wasDeleted() {
888 $title = $this->getTitle();
889 return $title && $title->isDeleted() > 0;
893 * Delete all versions of the file.
895 * Moves the files into an archive directory (or deletes them)
896 * and removes the database rows.
898 * Cache purging is done; logging is caller's responsibility.
900 * @param $reason
901 * @return true on success, false on some kind of failure
902 * STUB
903 * Overridden by LocalFile
905 function delete( $reason, $suppress=false ) {
906 $this->readOnlyError();
910 * Restore all or specified deleted revisions to the given file.
911 * Permissions and logging are left to the caller.
913 * May throw database exceptions on error.
915 * @param $versions set of record ids of deleted items to restore,
916 * or empty to restore all revisions.
917 * @return the number of file revisions restored if successful,
918 * or false on failure
919 * STUB
920 * Overridden by LocalFile
922 function restore( $versions=array(), $Unsuppress=false ) {
923 $this->readOnlyError();
927 * Returns 'true' if this image is a multipage document, e.g. a DJVU
928 * document.
930 * @return Bool
932 function isMultipage() {
933 return $this->getHandler() && $this->handler->isMultiPage( $this );
937 * Returns the number of pages of a multipage document, or NULL for
938 * documents which aren't multipage documents
940 function pageCount() {
941 if ( !isset( $this->pageCount ) ) {
942 if ( $this->getHandler() && $this->handler->isMultiPage( $this ) ) {
943 $this->pageCount = $this->handler->pageCount( $this );
944 } else {
945 $this->pageCount = false;
948 return $this->pageCount;
952 * Calculate the height of a thumbnail using the source and destination width
954 static function scaleHeight( $srcWidth, $srcHeight, $dstWidth ) {
955 // Exact integer multiply followed by division
956 if ( $srcWidth == 0 ) {
957 return 0;
958 } else {
959 return round( $srcHeight * $dstWidth / $srcWidth );
964 * Get an image size array like that returned by getimagesize(), or false if it
965 * can't be determined.
967 * @param string $fileName The filename
968 * @return array
970 function getImageSize( $fileName ) {
971 if ( !$this->getHandler() ) {
972 return false;
974 return $this->handler->getImageSize( $this, $fileName );
978 * Get the URL of the image description page. May return false if it is
979 * unknown or not applicable.
981 function getDescriptionUrl() {
982 return $this->repo->getDescriptionUrl( $this->getName() );
986 * Get the HTML text of the description page, if available
988 function getDescriptionText() {
989 if ( !$this->repo->fetchDescription ) {
990 return false;
992 $renderUrl = $this->repo->getDescriptionRenderUrl( $this->getName() );
993 if ( $renderUrl ) {
994 wfDebug( "Fetching shared description from $renderUrl\n" );
995 return Http::get( $renderUrl );
996 } else {
997 return false;
1002 * Get the 14-character timestamp of the file upload, or false if
1003 * it doesn't exist
1005 function getTimestamp() {
1006 $path = $this->getPath();
1007 if ( !file_exists( $path ) ) {
1008 return false;
1010 return wfTimestamp( filemtime( $path ) );
1014 * Get the SHA-1 base 36 hash of the file
1016 function getSha1() {
1017 return self::sha1Base36( $this->getPath() );
1021 * Determine if the current user is allowed to view a particular
1022 * field of this file, if it's marked as deleted.
1023 * STUB
1024 * @param int $field
1025 * @return bool
1027 function userCan( $field ) {
1028 return true;
1032 * Get an associative array containing information about a file in the local filesystem.
1034 * @param string $path Absolute local filesystem path
1035 * @param mixed $ext The file extension, or true to extract it from the filename.
1036 * Set it to false to ignore the extension.
1038 static function getPropsFromPath( $path, $ext = true ) {
1039 wfProfileIn( __METHOD__ );
1040 wfDebug( __METHOD__.": Getting file info for $path\n" );
1041 $info = array(
1042 'fileExists' => file_exists( $path ) && !is_dir( $path )
1044 $gis = false;
1045 if ( $info['fileExists'] ) {
1046 $magic = MimeMagic::singleton();
1048 $info['mime'] = $magic->guessMimeType( $path, $ext );
1049 list( $info['major_mime'], $info['minor_mime'] ) = self::splitMime( $info['mime'] );
1050 $info['media_type'] = $magic->getMediaType( $path, $info['mime'] );
1052 # Get size in bytes
1053 $info['size'] = filesize( $path );
1055 # Height, width and metadata
1056 $handler = MediaHandler::getHandler( $info['mime'] );
1057 if ( $handler ) {
1058 $tempImage = (object)array();
1059 $info['metadata'] = $handler->getMetadata( $tempImage, $path );
1060 $gis = $handler->getImageSize( $tempImage, $path, $info['metadata'] );
1061 } else {
1062 $gis = false;
1063 $info['metadata'] = '';
1065 $info['sha1'] = self::sha1Base36( $path );
1067 wfDebug(__METHOD__.": $path loaded, {$info['size']} bytes, {$info['mime']}.\n");
1068 } else {
1069 $info['mime'] = NULL;
1070 $info['media_type'] = MEDIATYPE_UNKNOWN;
1071 $info['metadata'] = '';
1072 $info['sha1'] = '';
1073 wfDebug(__METHOD__.": $path NOT FOUND!\n");
1075 if( $gis ) {
1076 # NOTE: $gis[2] contains a code for the image type. This is no longer used.
1077 $info['width'] = $gis[0];
1078 $info['height'] = $gis[1];
1079 if ( isset( $gis['bits'] ) ) {
1080 $info['bits'] = $gis['bits'];
1081 } else {
1082 $info['bits'] = 0;
1084 } else {
1085 $info['width'] = 0;
1086 $info['height'] = 0;
1087 $info['bits'] = 0;
1089 wfProfileOut( __METHOD__ );
1090 return $info;
1094 * Get a SHA-1 hash of a file in the local filesystem, in base-36 lower case
1095 * encoding, zero padded to 31 digits.
1097 * 160 log 2 / log 36 = 30.95, so the 160-bit hash fills 31 digits in base 36
1098 * fairly neatly.
1100 * Returns false on failure
1102 static function sha1Base36( $path ) {
1103 wfSuppressWarnings();
1104 $hash = sha1_file( $path );
1105 wfRestoreWarnings();
1106 if ( $hash === false ) {
1107 return false;
1108 } else {
1109 return wfBaseConvert( $hash, 16, 36, 31 );
1113 function getLongDesc() {
1114 $handler = $this->getHandler();
1115 if ( $handler ) {
1116 return $handler->getLongDesc( $this );
1117 } else {
1118 return MediaHandler::getLongDesc( $this );
1122 function getShortDesc() {
1123 $handler = $this->getHandler();
1124 if ( $handler ) {
1125 return $handler->getShortDesc( $this );
1126 } else {
1127 return MediaHandler::getShortDesc( $this );
1131 function getDimensionsString() {
1132 $handler = $this->getHandler();
1133 if ( $handler ) {
1134 return $handler->getDimensionsString( $this );
1135 } else {
1136 return '';
1141 * Aliases for backwards compatibility with 1.6
1143 define( 'MW_IMG_DELETED_FILE', File::DELETED_FILE );
1144 define( 'MW_IMG_DELETED_COMMENT', File::DELETED_COMMENT );
1145 define( 'MW_IMG_DELETED_USER', File::DELETED_USER );
1146 define( 'MW_IMG_DELETED_RESTRICTED', File::DELETED_RESTRICTED );