Put image redirects behind $wgFileRedirects config option for now (defaulting off).
[mediawiki.git] / includes / filerepo / File.php
bloba81abcb57a96d6943dae33092009037a923e9426
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, $redirected;
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
139 public function getTitle() { return $this->title; }
142 * Return the URL of the file
144 public function getUrl() {
145 if ( !isset( $this->url ) ) {
146 $this->url = $this->repo->getZoneUrl( 'public' ) . '/' . $this->getUrlRel();
148 return $this->url;
152 * Return a fully-qualified URL to the file.
153 * Upload URL paths _may or may not_ be fully qualified, so
154 * we check. Local paths are assumed to belong on $wgServer.
155 * @return string
157 public function getFullUrl() {
158 $url = $this->getUrl();
159 if( substr( $url, 0, 1 ) == '/' ) {
160 global $wgServer;
161 return $wgServer . $url;
163 return $url;
166 function getViewURL() {
167 if( $this->mustRender()) {
168 if( $this->canRender() ) {
169 return $this->createThumb( $this->getWidth() );
171 else {
172 wfDebug(__METHOD__.': supposed to render '.$this->getName().' ('.$this->getMimeType()."), but can't!\n");
173 return $this->getURL(); #hm... return NULL?
175 } else {
176 return $this->getURL();
181 * Return the full filesystem path to the file. Note that this does
182 * not mean that a file actually exists under that location.
184 * This path depends on whether directory hashing is active or not,
185 * i.e. whether the files are all found in the same directory,
186 * or in hashed paths like /images/3/3c.
188 * May return false if the file is not locally accessible.
190 public function getPath() {
191 if ( !isset( $this->path ) ) {
192 $this->path = $this->repo->getZonePath('public') . '/' . $this->getRel();
194 return $this->path;
198 * Alias for getPath()
200 public function getFullPath() {
201 return $this->getPath();
205 * Return the width of the image. Returns false if the width is unknown
206 * or undefined.
208 * STUB
209 * Overridden by LocalFile, UnregisteredLocalFile
211 public function getWidth( $page = 1 ) { return false; }
214 * Return the height of the image. Returns false if the height is unknown
215 * or undefined
217 * STUB
218 * Overridden by LocalFile, UnregisteredLocalFile
220 public function getHeight( $page = 1 ) { return false; }
223 * Get the duration of a media file in seconds
225 public function getLength() {
226 $handler = $this->getHandler();
227 if ( $handler ) {
228 return $handler->getLength( $this );
229 } else {
230 return 0;
235 * Get handler-specific metadata
236 * Overridden by LocalFile, UnregisteredLocalFile
237 * STUB
239 function getMetadata() { return false; }
242 * Return the size of the image file, in bytes
243 * Overridden by LocalFile, UnregisteredLocalFile
244 * STUB
246 public function getSize() { return false; }
249 * Returns the mime type of the file.
250 * Overridden by LocalFile, UnregisteredLocalFile
251 * STUB
253 function getMimeType() { return 'unknown/unknown'; }
256 * Return the type of the media in the file.
257 * Use the value returned by this function with the MEDIATYPE_xxx constants.
258 * Overridden by LocalFile,
259 * STUB
261 function getMediaType() { return MEDIATYPE_UNKNOWN; }
264 * Checks if the output of transform() for this file is likely
265 * to be valid. If this is false, various user elements will
266 * display a placeholder instead.
268 * Currently, this checks if the file is an image format
269 * that can be converted to a format
270 * supported by all browsers (namely GIF, PNG and JPEG),
271 * or if it is an SVG image and SVG conversion is enabled.
273 function canRender() {
274 if ( !isset( $this->canRender ) ) {
275 $this->canRender = $this->getHandler() && $this->handler->canRender( $this );
277 return $this->canRender;
281 * Accessor for __get()
283 protected function getCanRender() {
284 return $this->canRender();
288 * Return true if the file is of a type that can't be directly
289 * rendered by typical browsers and needs to be re-rasterized.
291 * This returns true for everything but the bitmap types
292 * supported by all browsers, i.e. JPEG; GIF and PNG. It will
293 * also return true for any non-image formats.
295 * @return bool
297 function mustRender() {
298 return $this->getHandler() && $this->handler->mustRender( $this );
302 * Alias for canRender()
304 function allowInlineDisplay() {
305 return $this->canRender();
309 * Determines if this media file is in a format that is unlikely to
310 * contain viruses or malicious content. It uses the global
311 * $wgTrustedMediaFormats list to determine if the file is safe.
313 * This is used to show a warning on the description page of non-safe files.
314 * It may also be used to disallow direct [[media:...]] links to such files.
316 * Note that this function will always return true if allowInlineDisplay()
317 * or isTrustedFile() is true for this file.
319 function isSafeFile() {
320 if ( !isset( $this->isSafeFile ) ) {
321 $this->isSafeFile = $this->_getIsSafeFile();
323 return $this->isSafeFile;
326 /** Accessor for __get() */
327 protected function getIsSafeFile() {
328 return $this->isSafeFile();
331 /** Uncached accessor */
332 protected function _getIsSafeFile() {
333 if ($this->allowInlineDisplay()) return true;
334 if ($this->isTrustedFile()) return true;
336 global $wgTrustedMediaFormats;
338 $type= $this->getMediaType();
339 $mime= $this->getMimeType();
340 #wfDebug("LocalFile::isSafeFile: type= $type, mime= $mime\n");
342 if (!$type || $type===MEDIATYPE_UNKNOWN) return false; #unknown type, not trusted
343 if ( in_array( $type, $wgTrustedMediaFormats) ) return true;
345 if ($mime==="unknown/unknown") return false; #unknown type, not trusted
346 if ( in_array( $mime, $wgTrustedMediaFormats) ) return true;
348 return false;
351 /** Returns true if the file is flagged as trusted. Files flagged that way
352 * can be linked to directly, even if that is not allowed for this type of
353 * file normally.
355 * This is a dummy function right now and always returns false. It could be
356 * implemented to extract a flag from the database. The trusted flag could be
357 * set on upload, if the user has sufficient privileges, to bypass script-
358 * and html-filters. It may even be coupled with cryptographics signatures
359 * or such.
361 function isTrustedFile() {
362 #this could be implemented to check a flag in the databas,
363 #look for signatures, etc
364 return false;
368 * Returns true if file exists in the repository.
370 * Overridden by LocalFile to avoid unnecessary stat calls.
372 * @return boolean Whether file exists in the repository.
374 public function exists() {
375 return $this->getPath() && file_exists( $this->path );
378 function getTransformScript() {
379 if ( !isset( $this->transformScript ) ) {
380 $this->transformScript = false;
381 if ( $this->repo ) {
382 $script = $this->repo->getThumbScriptUrl();
383 if ( $script ) {
384 $this->transformScript = "$script?f=" . urlencode( $this->getName() );
388 return $this->transformScript;
392 * Get a ThumbnailImage which is the same size as the source
394 function getUnscaledThumb( $page = false ) {
395 $width = $this->getWidth( $page );
396 if ( !$width ) {
397 return $this->iconThumb();
399 if ( $page ) {
400 $params = array(
401 'page' => $page,
402 'width' => $this->getWidth( $page )
404 } else {
405 $params = array( 'width' => $this->getWidth() );
407 return $this->transform( $params );
411 * Return the file name of a thumbnail with the specified parameters
413 * @param array $params Handler-specific parameters
414 * @private -ish
416 function thumbName( $params ) {
417 if ( !$this->getHandler() ) {
418 return null;
420 $extension = $this->getExtension();
421 list( $thumbExt, $thumbMime ) = $this->handler->getThumbType( $extension, $this->getMimeType() );
422 $thumbName = $this->handler->makeParamString( $params ) . '-' . $this->getName();
423 if ( $thumbExt != $extension ) {
424 $thumbName .= ".$thumbExt";
426 return $thumbName;
430 * Create a thumbnail of the image having the specified width/height.
431 * The thumbnail will not be created if the width is larger than the
432 * image's width. Let the browser do the scaling in this case.
433 * The thumbnail is stored on disk and is only computed if the thumbnail
434 * file does not exist OR if it is older than the image.
435 * Returns the URL.
437 * Keeps aspect ratio of original image. If both width and height are
438 * specified, the generated image will be no bigger than width x height,
439 * and will also have correct aspect ratio.
441 * @param integer $width maximum width of the generated thumbnail
442 * @param integer $height maximum height of the image (optional)
444 public function createThumb( $width, $height = -1 ) {
445 $params = array( 'width' => $width );
446 if ( $height != -1 ) {
447 $params['height'] = $height;
449 $thumb = $this->transform( $params );
450 if( is_null( $thumb ) || $thumb->isError() ) return '';
451 return $thumb->getUrl();
455 * As createThumb, but returns a ThumbnailImage object. This can
456 * provide access to the actual file, the real size of the thumb,
457 * and can produce a convenient <img> tag for you.
459 * For non-image formats, this may return a filetype-specific icon.
461 * @param integer $width maximum width of the generated thumbnail
462 * @param integer $height maximum height of the image (optional)
463 * @param boolean $render True to render the thumbnail if it doesn't exist,
464 * false to just return the URL
466 * @return ThumbnailImage or null on failure
468 * @deprecated use transform()
470 public function getThumbnail( $width, $height=-1, $render = true ) {
471 $params = array( 'width' => $width );
472 if ( $height != -1 ) {
473 $params['height'] = $height;
475 $flags = $render ? self::RENDER_NOW : 0;
476 return $this->transform( $params, $flags );
480 * Transform a media file
482 * @param array $params An associative array of handler-specific parameters. Typical
483 * keys are width, height and page.
484 * @param integer $flags A bitfield, may contain self::RENDER_NOW to force rendering
485 * @return MediaTransformOutput
487 function transform( $params, $flags = 0 ) {
488 global $wgUseSquid, $wgIgnoreImageErrors;
490 wfProfileIn( __METHOD__ );
491 do {
492 if ( !$this->canRender() ) {
493 // not a bitmap or renderable image, don't try.
494 $thumb = $this->iconThumb();
495 break;
498 $script = $this->getTransformScript();
499 if ( $script && !($flags & self::RENDER_NOW) ) {
500 // Use a script to transform on client request
501 $thumb = $this->handler->getScriptedTransform( $this, $script, $params );
502 break;
505 $normalisedParams = $params;
506 $this->handler->normaliseParams( $this, $normalisedParams );
507 $thumbName = $this->thumbName( $normalisedParams );
508 $thumbPath = $this->getThumbPath( $thumbName );
509 $thumbUrl = $this->getThumbUrl( $thumbName );
511 if ( $this->repo->canTransformVia404() && !($flags & self::RENDER_NOW ) ) {
512 $thumb = $this->handler->getTransform( $this, $thumbPath, $thumbUrl, $params );
513 break;
516 wfDebug( __METHOD__.": Doing stat for $thumbPath\n" );
517 $this->migrateThumbFile( $thumbName );
518 if ( file_exists( $thumbPath ) ) {
519 $thumb = $this->handler->getTransform( $this, $thumbPath, $thumbUrl, $params );
520 break;
522 $thumb = $this->handler->doTransform( $this, $thumbPath, $thumbUrl, $params );
524 // Ignore errors if requested
525 if ( !$thumb ) {
526 $thumb = null;
527 } elseif ( $thumb->isError() ) {
528 $this->lastError = $thumb->toText();
529 if ( $wgIgnoreImageErrors && !($flags & self::RENDER_NOW) ) {
530 $thumb = $this->handler->getTransform( $this, $thumbPath, $thumbUrl, $params );
534 if ( $wgUseSquid ) {
535 wfPurgeSquidServers( array( $thumbUrl ) );
537 } while (false);
539 wfProfileOut( __METHOD__ );
540 return $thumb;
543 /**
544 * Hook into transform() to allow migration of thumbnail files
545 * STUB
546 * Overridden by LocalFile
548 function migrateThumbFile( $thumbName ) {}
551 * Get a MediaHandler instance for this file
553 function getHandler() {
554 if ( !isset( $this->handler ) ) {
555 $this->handler = MediaHandler::getHandler( $this->getMimeType() );
557 return $this->handler;
561 * Get a ThumbnailImage representing a file type icon
562 * @return ThumbnailImage
564 function iconThumb() {
565 global $wgStylePath, $wgStyleDirectory;
567 $try = array( 'fileicon-' . $this->getExtension() . '.png', 'fileicon.png' );
568 foreach( $try as $icon ) {
569 $path = '/common/images/icons/' . $icon;
570 $filepath = $wgStyleDirectory . $path;
571 if( file_exists( $filepath ) ) {
572 return new ThumbnailImage( $this, $wgStylePath . $path, 120, 120 );
575 return null;
579 * Get last thumbnailing error.
580 * Largely obsolete.
582 function getLastError() {
583 return $this->lastError;
587 * Get all thumbnail names previously generated for this file
588 * STUB
589 * Overridden by LocalFile
591 function getThumbnails() { return array(); }
594 * Purge shared caches such as thumbnails and DB data caching
595 * STUB
596 * Overridden by LocalFile
598 function purgeCache() {}
601 * Purge the file description page, but don't go after
602 * pages using the file. Use when modifying file history
603 * but not the current data.
605 function purgeDescription() {
606 $title = $this->getTitle();
607 if ( $title ) {
608 $title->invalidateCache();
609 $title->purgeSquid();
614 * Purge metadata and all affected pages when the file is created,
615 * deleted, or majorly updated.
617 function purgeEverything() {
618 // Delete thumbnails and refresh file metadata cache
619 $this->purgeCache();
620 $this->purgeDescription();
622 // Purge cache of all pages using this file
623 $title = $this->getTitle();
624 if ( $title ) {
625 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
626 $update->doUpdate();
631 * Return the history of this file, line by line. Starts with current version,
632 * then old versions. Should return an object similar to an image/oldimage
633 * database row.
635 * STUB
636 * Overridden in LocalFile
638 public function nextHistoryLine() {
639 return false;
643 * Reset the history pointer to the first element of the history.
644 * Always call this function after using nextHistoryLine() to free db resources
645 * STUB
646 * Overridden in LocalFile.
648 public function resetHistory() {}
651 * Get the filename hash component of the directory including trailing slash,
652 * e.g. f/fa/
653 * If the repository is not hashed, returns an empty string.
655 function getHashPath() {
656 if ( !isset( $this->hashPath ) ) {
657 $this->hashPath = $this->repo->getHashPath( $this->getName() );
659 return $this->hashPath;
663 * Get the path of the file relative to the public zone root
665 function getRel() {
666 return $this->getHashPath() . $this->getName();
670 * Get urlencoded relative path of the file
672 function getUrlRel() {
673 return $this->getHashPath() . rawurlencode( $this->getName() );
676 /** Get the relative path for an archive file */
677 function getArchiveRel( $suffix = false ) {
678 $path = 'archive/' . $this->getHashPath();
679 if ( $suffix === false ) {
680 $path = substr( $path, 0, -1 );
681 } else {
682 $path .= $suffix;
684 return $path;
687 /** Get relative path for a thumbnail file */
688 function getThumbRel( $suffix = false ) {
689 $path = 'thumb/' . $this->getRel();
690 if ( $suffix !== false ) {
691 $path .= '/' . $suffix;
693 return $path;
696 /** Get the path of the archive directory, or a particular file if $suffix is specified */
697 function getArchivePath( $suffix = false ) {
698 return $this->repo->getZonePath('public') . '/' . $this->getArchiveRel();
701 /** Get the path of the thumbnail directory, or a particular file if $suffix is specified */
702 function getThumbPath( $suffix = false ) {
703 return $this->repo->getZonePath('public') . '/' . $this->getThumbRel( $suffix );
706 /** Get the URL of the archive directory, or a particular file if $suffix is specified */
707 function getArchiveUrl( $suffix = false ) {
708 $path = $this->repo->getZoneUrl('public') . '/archive/' . $this->getHashPath();
709 if ( $suffix === false ) {
710 $path = substr( $path, 0, -1 );
711 } else {
712 $path .= rawurlencode( $suffix );
714 return $path;
717 /** Get the URL of the thumbnail directory, or a particular file if $suffix is specified */
718 function getThumbUrl( $suffix = false ) {
719 $path = $this->repo->getZoneUrl('public') . '/thumb/' . $this->getUrlRel();
720 if ( $suffix !== false ) {
721 $path .= '/' . rawurlencode( $suffix );
723 return $path;
726 /** Get the virtual URL for an archive file or directory */
727 function getArchiveVirtualUrl( $suffix = false ) {
728 $path = $this->repo->getVirtualUrl() . '/public/archive/' . $this->getHashPath();
729 if ( $suffix === false ) {
730 $path = substr( $path, 0, -1 );
731 } else {
732 $path .= rawurlencode( $suffix );
734 return $path;
737 /** Get the virtual URL for a thumbnail file or directory */
738 function getThumbVirtualUrl( $suffix = false ) {
739 $path = $this->repo->getVirtualUrl() . '/public/thumb/' . $this->getUrlRel();
740 if ( $suffix !== false ) {
741 $path .= '/' . rawurlencode( $suffix );
743 return $path;
746 /** Get the virtual URL for the file itself */
747 function getVirtualUrl( $suffix = false ) {
748 $path = $this->repo->getVirtualUrl() . '/public/' . $this->getUrlRel();
749 if ( $suffix !== false ) {
750 $path .= '/' . rawurlencode( $suffix );
752 return $path;
756 * @return bool
758 function isHashed() {
759 return $this->repo->isHashed();
762 function readOnlyError() {
763 throw new MWException( get_class($this) . ': write operations are not supported' );
767 * Record a file upload in the upload log and the image table
768 * STUB
769 * Overridden by LocalFile
771 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '', $watch = false ) {
772 $this->readOnlyError();
776 * Move or copy a file to its public location. If a file exists at the
777 * destination, move it to an archive. Returns the archive name on success
778 * or an empty string if it was a new file, and a wikitext-formatted
779 * WikiError object on failure.
781 * The archive name should be passed through to recordUpload for database
782 * registration.
784 * @param string $sourcePath Local filesystem path to the source image
785 * @param integer $flags A bitwise combination of:
786 * File::DELETE_SOURCE Delete the source file, i.e. move
787 * rather than copy
788 * @return The archive name on success or an empty string if it was a new
789 * file, and a wikitext-formatted WikiError object on failure.
791 * STUB
792 * Overridden by LocalFile
794 function publish( $srcPath, $flags = 0 ) {
795 $this->readOnlyError();
799 * Get an array of Title objects which are articles which use this file
800 * Also adds their IDs to the link cache
802 * This is mostly copied from Title::getLinksTo()
804 * @deprecated Use HTMLCacheUpdate, this function uses too much memory
806 function getLinksTo( $options = '' ) {
807 wfProfileIn( __METHOD__ );
809 // Note: use local DB not repo DB, we want to know local links
810 if ( $options ) {
811 $db = wfGetDB( DB_MASTER );
812 } else {
813 $db = wfGetDB( DB_SLAVE );
815 $linkCache =& LinkCache::singleton();
817 list( $page, $imagelinks ) = $db->tableNamesN( 'page', 'imagelinks' );
818 $encName = $db->addQuotes( $this->getName() );
819 $sql = "SELECT page_namespace,page_title,page_id FROM $page,$imagelinks WHERE page_id=il_from AND il_to=$encName $options";
820 $res = $db->query( $sql, __METHOD__ );
822 $retVal = array();
823 if ( $db->numRows( $res ) ) {
824 while ( $row = $db->fetchObject( $res ) ) {
825 if ( $titleObj = Title::makeTitle( $row->page_namespace, $row->page_title ) ) {
826 $linkCache->addGoodLinkObj( $row->page_id, $titleObj );
827 $retVal[] = $titleObj;
831 $db->freeResult( $res );
832 wfProfileOut( __METHOD__ );
833 return $retVal;
836 function formatMetadata() {
837 if ( !$this->getHandler() ) {
838 return false;
840 return $this->getHandler()->formatMetadata( $this, $this->getMetadata() );
844 * Returns true if the file comes from the local file repository.
846 * @return bool
848 function isLocal() {
849 return $this->getRepoName() == 'local';
853 * Returns the name of the repository.
855 * @return string
857 function getRepoName() {
858 return $this->repo ? $this->repo->getName() : 'unknown';
862 * Returns true if the image is an old version
863 * STUB
865 function isOld() {
866 return false;
870 * Is this file a "deleted" file in a private archive?
871 * STUB
873 function isDeleted( $field ) {
874 return false;
878 * Was this file ever deleted from the wiki?
880 * @return bool
882 function wasDeleted() {
883 $title = $this->getTitle();
884 return $title && $title->isDeleted() > 0;
888 * Delete all versions of the file.
890 * Moves the files into an archive directory (or deletes them)
891 * and removes the database rows.
893 * Cache purging is done; logging is caller's responsibility.
895 * @param $reason
896 * @return true on success, false on some kind of failure
897 * STUB
898 * Overridden by LocalFile
900 function delete( $reason ) {
901 $this->readOnlyError();
905 * Restore all or specified deleted revisions to the given file.
906 * Permissions and logging are left to the caller.
908 * May throw database exceptions on error.
910 * @param $versions set of record ids of deleted items to restore,
911 * or empty to restore all revisions.
912 * @return the number of file revisions restored if successful,
913 * or false on failure
914 * STUB
915 * Overridden by LocalFile
917 function restore( $versions=array(), $Unsuppress=false ) {
918 $this->readOnlyError();
922 * Returns 'true' if this image is a multipage document, e.g. a DJVU
923 * document.
925 * @return Bool
927 function isMultipage() {
928 return $this->getHandler() && $this->handler->isMultiPage( $this );
932 * Returns the number of pages of a multipage document, or NULL for
933 * documents which aren't multipage documents
935 function pageCount() {
936 if ( !isset( $this->pageCount ) ) {
937 if ( $this->getHandler() && $this->handler->isMultiPage( $this ) ) {
938 $this->pageCount = $this->handler->pageCount( $this );
939 } else {
940 $this->pageCount = false;
943 return $this->pageCount;
947 * Calculate the height of a thumbnail using the source and destination width
949 static function scaleHeight( $srcWidth, $srcHeight, $dstWidth ) {
950 // Exact integer multiply followed by division
951 if ( $srcWidth == 0 ) {
952 return 0;
953 } else {
954 return round( $srcHeight * $dstWidth / $srcWidth );
959 * Get an image size array like that returned by getimagesize(), or false if it
960 * can't be determined.
962 * @param string $fileName The filename
963 * @return array
965 function getImageSize( $fileName ) {
966 if ( !$this->getHandler() ) {
967 return false;
969 return $this->handler->getImageSize( $this, $fileName );
973 * Get the URL of the image description page. May return false if it is
974 * unknown or not applicable.
976 function getDescriptionUrl() {
977 return $this->repo->getDescriptionUrl( $this->getName() );
981 * Get the HTML text of the description page, if available
983 function getDescriptionText() {
984 if ( !$this->repo->fetchDescription ) {
985 return false;
987 $renderUrl = $this->repo->getDescriptionRenderUrl( $this->getName() );
988 if ( $renderUrl ) {
989 wfDebug( "Fetching shared description from $renderUrl\n" );
990 return Http::get( $renderUrl );
991 } else {
992 return false;
997 * Get the 14-character timestamp of the file upload, or false if
998 * it doesn't exist
1000 function getTimestamp() {
1001 $path = $this->getPath();
1002 if ( !file_exists( $path ) ) {
1003 return false;
1005 return wfTimestamp( filemtime( $path ) );
1009 * Get the SHA-1 base 36 hash of the file
1011 function getSha1() {
1012 return self::sha1Base36( $this->getPath() );
1016 * Determine if the current user is allowed to view a particular
1017 * field of this file, if it's marked as deleted.
1018 * STUB
1019 * @param int $field
1020 * @return bool
1022 function userCan( $field ) {
1023 return true;
1027 * Get an associative array containing information about a file in the local filesystem.
1029 * @param string $path Absolute local filesystem path
1030 * @param mixed $ext The file extension, or true to extract it from the filename.
1031 * Set it to false to ignore the extension.
1033 static function getPropsFromPath( $path, $ext = true ) {
1034 wfProfileIn( __METHOD__ );
1035 wfDebug( __METHOD__.": Getting file info for $path\n" );
1036 $info = array(
1037 'fileExists' => file_exists( $path ) && !is_dir( $path )
1039 $gis = false;
1040 if ( $info['fileExists'] ) {
1041 $magic = MimeMagic::singleton();
1043 $info['mime'] = $magic->guessMimeType( $path, $ext );
1044 list( $info['major_mime'], $info['minor_mime'] ) = self::splitMime( $info['mime'] );
1045 $info['media_type'] = $magic->getMediaType( $path, $info['mime'] );
1047 # Get size in bytes
1048 $info['size'] = filesize( $path );
1050 # Height, width and metadata
1051 $handler = MediaHandler::getHandler( $info['mime'] );
1052 if ( $handler ) {
1053 $tempImage = (object)array();
1054 $info['metadata'] = $handler->getMetadata( $tempImage, $path );
1055 $gis = $handler->getImageSize( $tempImage, $path, $info['metadata'] );
1056 } else {
1057 $gis = false;
1058 $info['metadata'] = '';
1060 $info['sha1'] = self::sha1Base36( $path );
1062 wfDebug(__METHOD__.": $path loaded, {$info['size']} bytes, {$info['mime']}.\n");
1063 } else {
1064 $info['mime'] = NULL;
1065 $info['media_type'] = MEDIATYPE_UNKNOWN;
1066 $info['metadata'] = '';
1067 $info['sha1'] = '';
1068 wfDebug(__METHOD__.": $path NOT FOUND!\n");
1070 if( $gis ) {
1071 # NOTE: $gis[2] contains a code for the image type. This is no longer used.
1072 $info['width'] = $gis[0];
1073 $info['height'] = $gis[1];
1074 if ( isset( $gis['bits'] ) ) {
1075 $info['bits'] = $gis['bits'];
1076 } else {
1077 $info['bits'] = 0;
1079 } else {
1080 $info['width'] = 0;
1081 $info['height'] = 0;
1082 $info['bits'] = 0;
1084 wfProfileOut( __METHOD__ );
1085 return $info;
1089 * Get a SHA-1 hash of a file in the local filesystem, in base-36 lower case
1090 * encoding, zero padded to 31 digits.
1092 * 160 log 2 / log 36 = 30.95, so the 160-bit hash fills 31 digits in base 36
1093 * fairly neatly.
1095 * Returns false on failure
1097 static function sha1Base36( $path ) {
1098 wfSuppressWarnings();
1099 $hash = sha1_file( $path );
1100 wfRestoreWarnings();
1101 if ( $hash === false ) {
1102 return false;
1103 } else {
1104 return wfBaseConvert( $hash, 16, 36, 31 );
1108 function getLongDesc() {
1109 $handler = $this->getHandler();
1110 if ( $handler ) {
1111 return $handler->getLongDesc( $this );
1112 } else {
1113 return MediaHandler::getLongDesc( $this );
1117 function getShortDesc() {
1118 $handler = $this->getHandler();
1119 if ( $handler ) {
1120 return $handler->getShortDesc( $this );
1121 } else {
1122 return MediaHandler::getShortDesc( $this );
1126 function getDimensionsString() {
1127 $handler = $this->getHandler();
1128 if ( $handler ) {
1129 return $handler->getDimensionsString( $this );
1130 } else {
1131 return '';
1135 function getRedirected() {
1136 return $this->redirected;
1139 function redirectedFrom( $from ) {
1140 $this->redirected = $from;
1144 * Aliases for backwards compatibility with 1.6
1146 define( 'MW_IMG_DELETED_FILE', File::DELETED_FILE );
1147 define( 'MW_IMG_DELETED_COMMENT', File::DELETED_COMMENT );
1148 define( 'MW_IMG_DELETED_USER', File::DELETED_USER );
1149 define( 'MW_IMG_DELETED_RESTRICTED', File::DELETED_RESTRICTED );