(bug 26360) $wgSessionHandler was overriding system settings unconditionally. Regress...
[mediawiki.git] / includes / filerepo / File.php
blobd03016f7b5ddd97502f8ff0b97b02a1a2c68fc12
1 <?php
2 /**
3 * Base code for files.
5 * @file
6 * @ingroup FileRepo
7 */
9 /**
10 * Implements some public methods and some protected utility functions which
11 * are required by multiple child classes. Contains stub functionality for
12 * unimplemented public methods.
14 * Stub functions which should be overridden are marked with STUB. Some more
15 * concrete functions are also typically overridden by child classes.
17 * Note that only the repo object knows what its file class is called. You should
18 * never name a file class explictly outside of the repo class. Instead use the
19 * repo's factory functions to generate file objects, for example:
21 * RepoGroup::singleton()->getLocalRepo()->newFile($title);
23 * The convenience functions wfLocalFile() and wfFindFile() should be sufficient
24 * in most cases.
26 * @ingroup FileRepo
28 abstract class File {
29 const DELETED_FILE = 1;
30 const DELETED_COMMENT = 2;
31 const DELETED_USER = 4;
32 const DELETED_RESTRICTED = 8;
33 const RENDER_NOW = 1;
35 const DELETE_SOURCE = 1;
37 /**
38 * Some member variables can be lazy-initialised using __get(). The
39 * initialisation function for these variables is always a function named
40 * like getVar(), where Var is the variable name with upper-case first
41 * letter.
43 * The following variables are initialised in this way in this base class:
44 * name, extension, handler, path, canRender, isSafeFile,
45 * transformScript, hashPath, pageCount, url
47 * Code within this class should generally use the accessor function
48 * directly, since __get() isn't re-entrant and therefore causes bugs that
49 * depend on initialisation order.
52 /**
53 * The following member variables are not lazy-initialised
56 /**
57 * @var LocalRepo
59 var $repo;
61 /**
62 * @var Title
64 var $title;
66 var $lastError, $redirected, $redirectedTitle;
68 /**
69 * @var MediaHandler
71 protected $handler;
73 /**
74 * Call this constructor from child classes
76 function __construct( $title, $repo ) {
77 $this->title = $title;
78 $this->repo = $repo;
81 function __get( $name ) {
82 $function = array( $this, 'get' . ucfirst( $name ) );
83 if ( !is_callable( $function ) ) {
84 return null;
85 } else {
86 $this->$name = call_user_func( $function );
87 return $this->$name;
91 /**
92 * Normalize a file extension to the common form, and ensure it's clean.
93 * Extensions with non-alphanumeric characters will be discarded.
95 * @param $ext string (without the .)
96 * @return string
98 static function normalizeExtension( $ext ) {
99 $lower = strtolower( $ext );
100 $squish = array(
101 'htm' => 'html',
102 'jpeg' => 'jpg',
103 'mpeg' => 'mpg',
104 'tiff' => 'tif',
105 'ogv' => 'ogg' );
106 if( isset( $squish[$lower] ) ) {
107 return $squish[$lower];
108 } elseif( preg_match( '/^[0-9a-z]+$/', $lower ) ) {
109 return $lower;
110 } else {
111 return '';
116 * Checks if file extensions are compatible
118 * @param $old File Old file
119 * @param $new string New name
121 * @return bool|null
123 static function checkExtensionCompatibility( File $old, $new ) {
124 $oldMime = $old->getMimeType();
125 $n = strrpos( $new, '.' );
126 $newExt = self::normalizeExtension(
127 $n ? substr( $new, $n + 1 ) : '' );
128 $mimeMagic = MimeMagic::singleton();
129 return $mimeMagic->isMatchingExtension( $newExt, $oldMime );
133 * Upgrade the database row if there is one
134 * Called by ImagePage
135 * STUB
137 function upgradeRow() {}
140 * Split an internet media type into its two components; if not
141 * a two-part name, set the minor type to 'unknown'.
143 * @param string $mime "text/html" etc
144 * @return array ("text", "html") etc
146 public static function splitMime( $mime ) {
147 if( strpos( $mime, '/' ) !== false ) {
148 return explode( '/', $mime, 2 );
149 } else {
150 return array( $mime, 'unknown' );
155 * Return the name of this file
157 * @return string
159 public function getName() {
160 if ( !isset( $this->name ) ) {
161 $this->name = $this->repo->getNameFromTitle( $this->title );
163 return $this->name;
167 * Get the file extension, e.g. "svg"
169 * @return string
171 function getExtension() {
172 if ( !isset( $this->extension ) ) {
173 $n = strrpos( $this->getName(), '.' );
174 $this->extension = self::normalizeExtension(
175 $n ? substr( $this->getName(), $n + 1 ) : '' );
177 return $this->extension;
181 * Return the associated title object
182 * @return Title
184 public function getTitle() { return $this->title; }
187 * Return the title used to find this file
189 * @return Title
191 public function getOriginalTitle() {
192 if ( $this->redirected ) {
193 return $this->getRedirectedTitle();
195 return $this->title;
199 * Return the URL of the file
201 * @return string
203 public function getUrl() {
204 if ( !isset( $this->url ) ) {
205 $this->url = $this->repo->getZoneUrl( 'public' ) . '/' . $this->getUrlRel();
207 return $this->url;
211 * Return a fully-qualified URL to the file.
212 * Upload URL paths _may or may not_ be fully qualified, so
213 * we check. Local paths are assumed to belong on $wgServer.
215 * @return String
217 public function getFullUrl() {
218 return wfExpandUrl( $this->getUrl() );
222 * @return string
224 function getViewURL() {
225 if( $this->mustRender()) {
226 if( $this->canRender() ) {
227 return $this->createThumb( $this->getWidth() );
228 } else {
229 wfDebug(__METHOD__.': supposed to render '.$this->getName().' ('.$this->getMimeType()."), but can't!\n");
230 return $this->getURL(); #hm... return NULL?
232 } else {
233 return $this->getURL();
238 * Return the full filesystem path to the file. Note that this does
239 * not mean that a file actually exists under that location.
241 * This path depends on whether directory hashing is active or not,
242 * i.e. whether the files are all found in the same directory,
243 * or in hashed paths like /images/3/3c.
245 * Most callers don't check the return value, but ForeignAPIFile::getPath
246 * returns false.
248 * @return string|false
250 public function getPath() {
251 if ( !isset( $this->path ) ) {
252 $this->path = $this->repo->getZonePath('public') . '/' . $this->getRel();
254 return $this->path;
258 * Alias for getPath()
260 * @deprecated since 1.18 Use getPath().
262 * @return string
264 public function getFullPath() {
265 wfDeprecated( __METHOD__ );
266 return $this->getPath();
270 * Return the width of the image. Returns false if the width is unknown
271 * or undefined.
273 * STUB
274 * Overridden by LocalFile, UnregisteredLocalFile
276 * @param $page int
278 * @return number
280 public function getWidth( $page = 1 ) {
281 return false;
285 * Return the height of the image. Returns false if the height is unknown
286 * or undefined
288 * STUB
289 * Overridden by LocalFile, UnregisteredLocalFile
291 * @return false|number
293 public function getHeight( $page = 1 ) {
294 return false;
298 * Returns ID or name of user who uploaded the file
299 * STUB
301 * @param $type string 'text' or 'id'
303 * @return string|int
305 public function getUser( $type = 'text' ) {
306 return null;
310 * Get the duration of a media file in seconds
312 * @return number
314 public function getLength() {
315 $handler = $this->getHandler();
316 if ( $handler ) {
317 return $handler->getLength( $this );
318 } else {
319 return 0;
324 * Return true if the file is vectorized
326 * @return bool
328 public function isVectorized() {
329 $handler = $this->getHandler();
330 if ( $handler ) {
331 return $handler->isVectorized( $this );
332 } else {
333 return false;
338 * Get handler-specific metadata
339 * Overridden by LocalFile, UnregisteredLocalFile
340 * STUB
342 public function getMetadata() {
343 return false;
347 * get versioned metadata
349 * @param $metadata Mixed Array or String of (serialized) metadata
350 * @param $version integer version number.
351 * @return Array containing metadata, or what was passed to it on fail (unserializing if not array)
353 public function convertMetadataVersion($metadata, $version) {
354 $handler = $this->getHandler();
355 if ( !is_array( $metadata ) ) {
356 //just to make the return type consistant
357 $metadata = unserialize( $metadata );
359 if ( $handler ) {
360 return $handler->convertMetadataVersion( $metadata, $version );
361 } else {
362 return $metadata;
367 * Return the bit depth of the file
368 * Overridden by LocalFile
369 * STUB
371 public function getBitDepth() {
372 return 0;
376 * Return the size of the image file, in bytes
377 * Overridden by LocalFile, UnregisteredLocalFile
378 * STUB
380 public function getSize() {
381 return false;
385 * Returns the mime type of the file.
386 * Overridden by LocalFile, UnregisteredLocalFile
387 * STUB
389 * @return string
391 function getMimeType() {
392 return 'unknown/unknown';
396 * Return the type of the media in the file.
397 * Use the value returned by this function with the MEDIATYPE_xxx constants.
398 * Overridden by LocalFile,
399 * STUB
401 function getMediaType() { return MEDIATYPE_UNKNOWN; }
404 * Checks if the output of transform() for this file is likely
405 * to be valid. If this is false, various user elements will
406 * display a placeholder instead.
408 * Currently, this checks if the file is an image format
409 * that can be converted to a format
410 * supported by all browsers (namely GIF, PNG and JPEG),
411 * or if it is an SVG image and SVG conversion is enabled.
413 * @return bool
415 function canRender() {
416 if ( !isset( $this->canRender ) ) {
417 $this->canRender = $this->getHandler() && $this->handler->canRender( $this );
419 return $this->canRender;
423 * Accessor for __get()
425 protected function getCanRender() {
426 return $this->canRender();
430 * Return true if the file is of a type that can't be directly
431 * rendered by typical browsers and needs to be re-rasterized.
433 * This returns true for everything but the bitmap types
434 * supported by all browsers, i.e. JPEG; GIF and PNG. It will
435 * also return true for any non-image formats.
437 * @return bool
439 function mustRender() {
440 return $this->getHandler() && $this->handler->mustRender( $this );
444 * Alias for canRender()
446 * @return bool
448 function allowInlineDisplay() {
449 return $this->canRender();
453 * Determines if this media file is in a format that is unlikely to
454 * contain viruses or malicious content. It uses the global
455 * $wgTrustedMediaFormats list to determine if the file is safe.
457 * This is used to show a warning on the description page of non-safe files.
458 * It may also be used to disallow direct [[media:...]] links to such files.
460 * Note that this function will always return true if allowInlineDisplay()
461 * or isTrustedFile() is true for this file.
463 * @return bool
465 function isSafeFile() {
466 if ( !isset( $this->isSafeFile ) ) {
467 $this->isSafeFile = $this->_getIsSafeFile();
469 return $this->isSafeFile;
473 * Accessor for __get()
475 * @return bool
477 protected function getIsSafeFile() {
478 return $this->isSafeFile();
482 * Uncached accessor
484 * @return bool
486 protected function _getIsSafeFile() {
487 if ( $this->allowInlineDisplay() ) {
488 return true;
490 if ($this->isTrustedFile()) {
491 return true;
494 global $wgTrustedMediaFormats;
496 $type = $this->getMediaType();
497 $mime = $this->getMimeType();
498 #wfDebug("LocalFile::isSafeFile: type= $type, mime= $mime\n");
500 if ( !$type || $type === MEDIATYPE_UNKNOWN ) {
501 return false; #unknown type, not trusted
503 if ( in_array( $type, $wgTrustedMediaFormats ) ) {
504 return true;
507 if ( $mime === "unknown/unknown" ) {
508 return false; #unknown type, not trusted
510 if ( in_array( $mime, $wgTrustedMediaFormats) ) {
511 return true;
514 return false;
518 * Returns true if the file is flagged as trusted. Files flagged that way
519 * can be linked to directly, even if that is not allowed for this type of
520 * file normally.
522 * This is a dummy function right now and always returns false. It could be
523 * implemented to extract a flag from the database. The trusted flag could be
524 * set on upload, if the user has sufficient privileges, to bypass script-
525 * and html-filters. It may even be coupled with cryptographics signatures
526 * or such.
528 * @return bool
530 function isTrustedFile() {
531 #this could be implemented to check a flag in the databas,
532 #look for signatures, etc
533 return false;
537 * Returns true if file exists in the repository.
539 * Overridden by LocalFile to avoid unnecessary stat calls.
541 * @return boolean Whether file exists in the repository.
543 public function exists() {
544 return $this->getPath() && file_exists( $this->path );
548 * Returns true if file exists in the repository and can be included in a page.
549 * It would be unsafe to include private images, making public thumbnails inadvertently
551 * @return boolean Whether file exists in the repository and is includable.
553 public function isVisible() {
554 return $this->exists();
558 * @return string
560 function getTransformScript() {
561 if ( !isset( $this->transformScript ) ) {
562 $this->transformScript = false;
563 if ( $this->repo ) {
564 $script = $this->repo->getThumbScriptUrl();
565 if ( $script ) {
566 $this->transformScript = "$script?f=" . urlencode( $this->getName() );
570 return $this->transformScript;
574 * Get a ThumbnailImage which is the same size as the source
576 * @param $handlerParams array
578 * @return string
580 function getUnscaledThumb( $handlerParams = array() ) {
581 $hp =& $handlerParams;
582 $page = isset( $hp['page'] ) ? $hp['page'] : false;
583 $width = $this->getWidth( $page );
584 if ( !$width ) {
585 return $this->iconThumb();
587 $hp['width'] = $width;
588 return $this->transform( $hp );
592 * Return the file name of a thumbnail with the specified parameters
594 * @param $params Array: handler-specific parameters
595 * @private -ish
597 * @return string
599 function thumbName( $params ) {
600 return $this->generateThumbName( $this->getName(), $params );
604 * Generate a thumbnail file name from a name and specified parameters
606 * @param string $name
607 * @param array $params Parameters which will be passed to MediaHandler::makeParamString
609 * @return string
611 function generateThumbName( $name, $params ) {
612 if ( !$this->getHandler() ) {
613 return null;
615 $extension = $this->getExtension();
616 list( $thumbExt, $thumbMime ) = $this->handler->getThumbType( $extension, $this->getMimeType(), $params );
617 $thumbName = $this->handler->makeParamString( $params ) . '-' . $name;
618 if ( $thumbExt != $extension ) {
619 $thumbName .= ".$thumbExt";
621 return $thumbName;
625 * Create a thumbnail of the image having the specified width/height.
626 * The thumbnail will not be created if the width is larger than the
627 * image's width. Let the browser do the scaling in this case.
628 * The thumbnail is stored on disk and is only computed if the thumbnail
629 * file does not exist OR if it is older than the image.
630 * Returns the URL.
632 * Keeps aspect ratio of original image. If both width and height are
633 * specified, the generated image will be no bigger than width x height,
634 * and will also have correct aspect ratio.
636 * @param $width Integer: maximum width of the generated thumbnail
637 * @param $height Integer: maximum height of the image (optional)
639 * @return string
641 public function createThumb( $width, $height = -1 ) {
642 $params = array( 'width' => $width );
643 if ( $height != -1 ) {
644 $params['height'] = $height;
646 $thumb = $this->transform( $params );
647 if( is_null( $thumb ) || $thumb->isError() ) return '';
648 return $thumb->getUrl();
652 * Transform a media file
654 * @param $params Array: an associative array of handler-specific parameters.
655 * Typical keys are width, height and page.
656 * @param $flags Integer: a bitfield, may contain self::RENDER_NOW to force rendering
657 * @return MediaTransformOutput | false
659 function transform( $params, $flags = 0 ) {
660 global $wgUseSquid, $wgIgnoreImageErrors, $wgThumbnailEpoch, $wgServer;
662 wfProfileIn( __METHOD__ );
663 do {
664 if ( !$this->canRender() ) {
665 // not a bitmap or renderable image, don't try.
666 $thumb = $this->iconThumb();
667 break;
670 // Get the descriptionUrl to embed it as comment into the thumbnail. Bug 19791.
671 $descriptionUrl = $this->getDescriptionUrl();
672 if ( $descriptionUrl ) {
673 $params['descriptionUrl'] = $wgServer . $descriptionUrl;
676 $script = $this->getTransformScript();
677 if ( $script && !($flags & self::RENDER_NOW) ) {
678 // Use a script to transform on client request, if possible
679 $thumb = $this->handler->getScriptedTransform( $this, $script, $params );
680 if( $thumb ) {
681 break;
685 $normalisedParams = $params;
686 $this->handler->normaliseParams( $this, $normalisedParams );
687 $thumbName = $this->thumbName( $normalisedParams );
688 $thumbPath = $this->getThumbPath( $thumbName );
689 $thumbUrl = $this->getThumbUrl( $thumbName );
691 if ( $this->repo && $this->repo->canTransformVia404() && !($flags & self::RENDER_NOW ) ) {
692 $thumb = $this->handler->getTransform( $this, $thumbPath, $thumbUrl, $params );
693 break;
696 wfDebug( __METHOD__.": Doing stat for $thumbPath\n" );
697 $this->migrateThumbFile( $thumbName );
698 if ( file_exists( $thumbPath )) {
699 $thumbTime = filemtime( $thumbPath );
700 if ( $thumbTime !== FALSE &&
701 gmdate( 'YmdHis', $thumbTime ) >= $wgThumbnailEpoch ) {
703 $thumb = $this->handler->getTransform( $this, $thumbPath, $thumbUrl, $params );
704 break;
707 $thumb = $this->handler->doTransform( $this, $thumbPath, $thumbUrl, $params );
709 // Ignore errors if requested
710 if ( !$thumb ) {
711 $thumb = null;
712 } elseif ( $thumb->isError() ) {
713 $this->lastError = $thumb->toText();
714 if ( $wgIgnoreImageErrors && !($flags & self::RENDER_NOW) ) {
715 $thumb = $this->handler->getTransform( $this, $thumbPath, $thumbUrl, $params );
719 // Purge. Useful in the event of Core -> Squid connection failure or squid
720 // purge collisions from elsewhere during failure. Don't keep triggering for
721 // "thumbs" which have the main image URL though (bug 13776)
722 if ( $wgUseSquid && ( !$thumb || $thumb->isError() || $thumb->getUrl() != $this->getURL()) ) {
723 SquidUpdate::purge( array( $thumbUrl ) );
725 } while (false);
727 wfProfileOut( __METHOD__ );
728 return is_object( $thumb ) ? $thumb : false;
732 * Hook into transform() to allow migration of thumbnail files
733 * STUB
734 * Overridden by LocalFile
736 function migrateThumbFile( $thumbName ) {}
739 * Get a MediaHandler instance for this file
740 * @return MediaHandler
742 function getHandler() {
743 if ( !isset( $this->handler ) ) {
744 $this->handler = MediaHandler::getHandler( $this->getMimeType() );
746 return $this->handler;
750 * Get a ThumbnailImage representing a file type icon
751 * @return ThumbnailImage
753 function iconThumb() {
754 global $wgStylePath, $wgStyleDirectory;
756 $try = array( 'fileicon-' . $this->getExtension() . '.png', 'fileicon.png' );
757 foreach( $try as $icon ) {
758 $path = '/common/images/icons/' . $icon;
759 $filepath = $wgStyleDirectory . $path;
760 if( file_exists( $filepath ) ) {
761 return new ThumbnailImage( $this, $wgStylePath . $path, 120, 120 );
764 return null;
768 * Get last thumbnailing error.
769 * Largely obsolete.
771 function getLastError() {
772 return $this->lastError;
776 * Get all thumbnail names previously generated for this file
777 * STUB
778 * Overridden by LocalFile
780 function getThumbnails() {
781 return array();
785 * Purge shared caches such as thumbnails and DB data caching
786 * STUB
787 * Overridden by LocalFile
789 function purgeCache() {}
792 * Purge the file description page, but don't go after
793 * pages using the file. Use when modifying file history
794 * but not the current data.
796 function purgeDescription() {
797 $title = $this->getTitle();
798 if ( $title ) {
799 $title->invalidateCache();
800 $title->purgeSquid();
805 * Purge metadata and all affected pages when the file is created,
806 * deleted, or majorly updated.
808 function purgeEverything() {
809 // Delete thumbnails and refresh file metadata cache
810 $this->purgeCache();
811 $this->purgeDescription();
813 // Purge cache of all pages using this file
814 $title = $this->getTitle();
815 if ( $title ) {
816 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
817 $update->doUpdate();
822 * Return a fragment of the history of file.
824 * STUB
825 * @param $limit integer Limit of rows to return
826 * @param $start timestamp Only revisions older than $start will be returned
827 * @param $end timestamp Only revisions newer than $end will be returned
828 * @param $inc bool Include the endpoints of the time range
830 * @return array
832 function getHistory($limit = null, $start = null, $end = null, $inc=true) {
833 return array();
837 * Return the history of this file, line by line. Starts with current version,
838 * then old versions. Should return an object similar to an image/oldimage
839 * database row.
841 * STUB
842 * Overridden in LocalFile
844 public function nextHistoryLine() {
845 return false;
849 * Reset the history pointer to the first element of the history.
850 * Always call this function after using nextHistoryLine() to free db resources
851 * STUB
852 * Overridden in LocalFile.
854 public function resetHistory() {}
857 * Get the filename hash component of the directory including trailing slash,
858 * e.g. f/fa/
859 * If the repository is not hashed, returns an empty string.
861 * @return string
863 function getHashPath() {
864 if ( !isset( $this->hashPath ) ) {
865 $this->hashPath = $this->repo->getHashPath( $this->getName() );
867 return $this->hashPath;
871 * Get the path of the file relative to the public zone root
873 * @return string
875 function getRel() {
876 return $this->getHashPath() . $this->getName();
880 * Get urlencoded relative path of the file
882 * @return string
884 function getUrlRel() {
885 return $this->getHashPath() . rawurlencode( $this->getName() );
889 * Get the relative path for an archive file
891 * @param $suffix bool
893 * @return string
895 function getArchiveRel( $suffix = false ) {
896 $path = 'archive/' . $this->getHashPath();
897 if ( $suffix === false ) {
898 $path = substr( $path, 0, -1 );
899 } else {
900 $path .= $suffix;
902 return $path;
906 * Get the path of the archive directory, or a particular file if $suffix is specified
908 * @param $suffix bool
910 * @return string
912 function getArchivePath( $suffix = false ) {
913 return $this->repo->getZonePath( 'public' ) . '/' . $this->getArchiveRel( $suffix );
917 * Get the path of the thumbnail directory, or a particular file if $suffix is specified
919 * @param $suffix bool
921 * @return string
923 function getThumbPath( $suffix = false ) {
924 $path = $this->repo->getZonePath( 'thumb' ) . '/' . $this->getRel();
925 if ( $suffix !== false ) {
926 $path .= '/' . $suffix;
928 return $path;
932 * Get the URL of the archive directory, or a particular file if $suffix is specified
934 * @param $suffix bool
936 * @return string
938 function getArchiveUrl( $suffix = false ) {
939 $path = $this->repo->getZoneUrl('public') . '/archive/' . $this->getHashPath();
940 if ( $suffix === false ) {
941 $path = substr( $path, 0, -1 );
942 } else {
943 $path .= rawurlencode( $suffix );
945 return $path;
949 * Get the URL of the thumbnail directory, or a particular file if $suffix is specified
951 * @param $suffix bool
953 * @return path
955 function getThumbUrl( $suffix = false ) {
956 $path = $this->repo->getZoneUrl('thumb') . '/' . $this->getUrlRel();
957 if ( $suffix !== false ) {
958 $path .= '/' . rawurlencode( $suffix );
960 return $path;
964 * Get the virtual URL for an archive file or directory
966 * @param bool|string $suffix
968 * @return string
970 function getArchiveVirtualUrl( $suffix = false ) {
971 $path = $this->repo->getVirtualUrl() . '/public/archive/' . $this->getHashPath();
972 if ( $suffix === false ) {
973 $path = substr( $path, 0, -1 );
974 } else {
975 $path .= rawurlencode( $suffix );
977 return $path;
981 * Get the virtual URL for a thumbnail file or directory
983 * @param $suffix bool
985 * @return string
987 function getThumbVirtualUrl( $suffix = false ) {
988 $path = $this->repo->getVirtualUrl() . '/thumb/' . $this->getUrlRel();
989 if ( $suffix !== false ) {
990 $path .= '/' . rawurlencode( $suffix );
992 return $path;
996 * Get the virtual URL for the file itself
998 * @param $suffix bool
1000 * @return string
1002 function getVirtualUrl( $suffix = false ) {
1003 $path = $this->repo->getVirtualUrl() . '/public/' . $this->getUrlRel();
1004 if ( $suffix !== false ) {
1005 $path .= '/' . rawurlencode( $suffix );
1007 return $path;
1011 * @return bool
1013 function isHashed() {
1014 return $this->repo->isHashed();
1018 * @throws MWException
1020 function readOnlyError() {
1021 throw new MWException( get_class($this) . ': write operations are not supported' );
1025 * Record a file upload in the upload log and the image table
1026 * STUB
1027 * Overridden by LocalFile
1028 * @param $oldver
1029 * @param $desc
1030 * @param $license string
1031 * @param $copyStatus string
1032 * @param $source string
1033 * @param $watch bool
1035 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '', $watch = false ) {
1036 $this->readOnlyError();
1040 * Move or copy a file to its public location. If a file exists at the
1041 * destination, move it to an archive. Returns a FileRepoStatus object with
1042 * the archive name in the "value" member on success.
1044 * The archive name should be passed through to recordUpload for database
1045 * registration.
1047 * @param $srcPath String: local filesystem path to the source image
1048 * @param $flags Integer: a bitwise combination of:
1049 * File::DELETE_SOURCE Delete the source file, i.e. move
1050 * rather than copy
1051 * @return FileRepoStatus object. On success, the value member contains the
1052 * archive name, or an empty string if it was a new file.
1054 * STUB
1055 * Overridden by LocalFile
1057 function publish( $srcPath, $flags = 0 ) {
1058 $this->readOnlyError();
1062 * @return bool
1064 function formatMetadata() {
1065 if ( !$this->getHandler() ) {
1066 return false;
1068 return $this->getHandler()->formatMetadata( $this, $this->getMetadata() );
1072 * Returns true if the file comes from the local file repository.
1074 * @return bool
1076 function isLocal() {
1077 $repo = $this->getRepo();
1078 return $repo && $repo->isLocal();
1082 * Returns the name of the repository.
1084 * @return string
1086 function getRepoName() {
1087 return $this->repo ? $this->repo->getName() : 'unknown';
1091 * Returns the repository
1093 * @return FileRepo
1095 function getRepo() {
1096 return $this->repo;
1100 * Returns true if the image is an old version
1101 * STUB
1103 * @return bool
1105 function isOld() {
1106 return false;
1110 * Is this file a "deleted" file in a private archive?
1111 * STUB
1113 * @param $field
1115 * @return bool
1117 function isDeleted( $field ) {
1118 return false;
1122 * Return the deletion bitfield
1123 * STUB
1125 function getVisibility() {
1126 return 0;
1130 * Was this file ever deleted from the wiki?
1132 * @return bool
1134 function wasDeleted() {
1135 $title = $this->getTitle();
1136 return $title && $title->isDeletedQuick();
1140 * Move file to the new title
1142 * Move current, old version and all thumbnails
1143 * to the new filename. Old file is deleted.
1145 * Cache purging is done; checks for validity
1146 * and logging are caller's responsibility
1148 * @param $target Title New file name
1149 * @return FileRepoStatus object.
1151 function move( $target ) {
1152 $this->readOnlyError();
1156 * Delete all versions of the file.
1158 * Moves the files into an archive directory (or deletes them)
1159 * and removes the database rows.
1161 * Cache purging is done; logging is caller's responsibility.
1163 * @param $reason String
1164 * @param $suppress Boolean: hide content from sysops?
1165 * @return true on success, false on some kind of failure
1166 * STUB
1167 * Overridden by LocalFile
1169 function delete( $reason, $suppress = false ) {
1170 $this->readOnlyError();
1174 * Restore all or specified deleted revisions to the given file.
1175 * Permissions and logging are left to the caller.
1177 * May throw database exceptions on error.
1179 * @param $versions array set of record ids of deleted items to restore,
1180 * or empty to restore all revisions.
1181 * @param $unsuppress bool remove restrictions on content upon restoration?
1182 * @return int|false the number of file revisions restored if successful,
1183 * or false on failure
1184 * STUB
1185 * Overridden by LocalFile
1187 function restore( $versions = array(), $unsuppress = false ) {
1188 $this->readOnlyError();
1192 * Returns 'true' if this file is a type which supports multiple pages,
1193 * e.g. DJVU or PDF. Note that this may be true even if the file in
1194 * question only has a single page.
1196 * @return Bool
1198 function isMultipage() {
1199 return $this->getHandler() && $this->handler->isMultiPage( $this );
1203 * Returns the number of pages of a multipage document, or false for
1204 * documents which aren't multipage documents
1206 * @return false|int
1208 function pageCount() {
1209 if ( !isset( $this->pageCount ) ) {
1210 if ( $this->getHandler() && $this->handler->isMultiPage( $this ) ) {
1211 $this->pageCount = $this->handler->pageCount( $this );
1212 } else {
1213 $this->pageCount = false;
1216 return $this->pageCount;
1220 * Calculate the height of a thumbnail using the source and destination width
1222 * @param $srcWidth
1223 * @param $srcHeight
1224 * @param $dstWidth
1226 * @return int
1228 static function scaleHeight( $srcWidth, $srcHeight, $dstWidth ) {
1229 // Exact integer multiply followed by division
1230 if ( $srcWidth == 0 ) {
1231 return 0;
1232 } else {
1233 return round( $srcHeight * $dstWidth / $srcWidth );
1238 * Get an image size array like that returned by getImageSize(), or false if it
1239 * can't be determined.
1241 * @param $fileName String: The filename
1242 * @return Array
1244 function getImageSize( $fileName ) {
1245 if ( !$this->getHandler() ) {
1246 return false;
1248 return $this->handler->getImageSize( $this, $fileName );
1252 * Get the URL of the image description page. May return false if it is
1253 * unknown or not applicable.
1255 * @return string
1257 function getDescriptionUrl() {
1258 return $this->repo->getDescriptionUrl( $this->getName() );
1262 * Get the HTML text of the description page, if available
1264 * @return string
1266 function getDescriptionText() {
1267 global $wgMemc, $wgLang;
1268 if ( !$this->repo->fetchDescription ) {
1269 return false;
1271 $renderUrl = $this->repo->getDescriptionRenderUrl( $this->getName(), $wgLang->getCode() );
1272 if ( $renderUrl ) {
1273 if ( $this->repo->descriptionCacheExpiry > 0 ) {
1274 wfDebug("Attempting to get the description from cache...");
1275 $key = $this->repo->getLocalCacheKey( 'RemoteFileDescription', 'url', $wgLang->getCode(),
1276 $this->getName() );
1277 $obj = $wgMemc->get($key);
1278 if ($obj) {
1279 wfDebug("success!\n");
1280 return $obj;
1282 wfDebug("miss\n");
1284 wfDebug( "Fetching shared description from $renderUrl\n" );
1285 $res = Http::get( $renderUrl );
1286 if ( $res && $this->repo->descriptionCacheExpiry > 0 ) {
1287 $wgMemc->set( $key, $res, $this->repo->descriptionCacheExpiry );
1289 return $res;
1290 } else {
1291 return false;
1296 * Get discription of file revision
1297 * STUB
1299 * @return string
1301 function getDescription() {
1302 return null;
1306 * Get the 14-character timestamp of the file upload, or false if
1307 * it doesn't exist
1309 * @return string
1311 function getTimestamp() {
1312 $path = $this->getPath();
1313 if ( !file_exists( $path ) ) {
1314 return false;
1316 return wfTimestamp( TS_MW, filemtime( $path ) );
1320 * Get the SHA-1 base 36 hash of the file
1322 * @return string
1324 function getSha1() {
1325 return self::sha1Base36( $this->getPath() );
1329 * Get the deletion archive key, <sha1>.<ext>
1331 * @return string
1333 function getStorageKey() {
1334 $hash = $this->getSha1();
1335 if ( !$hash ) {
1336 return false;
1338 $ext = $this->getExtension();
1339 $dotExt = $ext === '' ? '' : ".$ext";
1340 return $hash . $dotExt;
1344 * Determine if the current user is allowed to view a particular
1345 * field of this file, if it's marked as deleted.
1346 * STUB
1347 * @param $field Integer
1348 * @return Boolean
1350 function userCan( $field ) {
1351 return true;
1355 * Get an associative array containing information about a file in the local filesystem.
1357 * @param $path String: absolute local filesystem path
1358 * @param $ext Mixed: the file extension, or true to extract it from the filename.
1359 * Set it to false to ignore the extension.
1361 * @return array
1363 static function getPropsFromPath( $path, $ext = true ) {
1364 wfProfileIn( __METHOD__ );
1365 wfDebug( __METHOD__.": Getting file info for $path\n" );
1366 $info = array(
1367 'fileExists' => file_exists( $path ) && !is_dir( $path )
1369 $gis = false;
1370 if ( $info['fileExists'] ) {
1371 $magic = MimeMagic::singleton();
1373 if ( $ext === true ) {
1374 $i = strrpos( $path, '.' );
1375 $ext = strtolower( $i ? substr( $path, $i + 1 ) : '' );
1378 # mime type according to file contents
1379 $info['file-mime'] = $magic->guessMimeType( $path, false );
1380 # logical mime type
1381 $info['mime'] = $magic->improveTypeFromExtension( $info['file-mime'], $ext );
1383 list( $info['major_mime'], $info['minor_mime'] ) = self::splitMime( $info['mime'] );
1384 $info['media_type'] = $magic->getMediaType( $path, $info['mime'] );
1386 # Get size in bytes
1387 $info['size'] = filesize( $path );
1389 # Height, width and metadata
1390 $handler = MediaHandler::getHandler( $info['mime'] );
1391 if ( $handler ) {
1392 $tempImage = (object)array();
1393 $info['metadata'] = $handler->getMetadata( $tempImage, $path );
1394 $gis = $handler->getImageSize( $tempImage, $path, $info['metadata'] );
1395 } else {
1396 $gis = false;
1397 $info['metadata'] = '';
1399 $info['sha1'] = self::sha1Base36( $path );
1401 wfDebug(__METHOD__.": $path loaded, {$info['size']} bytes, {$info['mime']}.\n");
1402 } else {
1403 $info['mime'] = null;
1404 $info['media_type'] = MEDIATYPE_UNKNOWN;
1405 $info['metadata'] = '';
1406 $info['sha1'] = '';
1407 wfDebug(__METHOD__.": $path NOT FOUND!\n");
1409 if( $gis ) {
1410 # NOTE: $gis[2] contains a code for the image type. This is no longer used.
1411 $info['width'] = $gis[0];
1412 $info['height'] = $gis[1];
1413 if ( isset( $gis['bits'] ) ) {
1414 $info['bits'] = $gis['bits'];
1415 } else {
1416 $info['bits'] = 0;
1418 } else {
1419 $info['width'] = 0;
1420 $info['height'] = 0;
1421 $info['bits'] = 0;
1423 wfProfileOut( __METHOD__ );
1424 return $info;
1428 * Get a SHA-1 hash of a file in the local filesystem, in base-36 lower case
1429 * encoding, zero padded to 31 digits.
1431 * 160 log 2 / log 36 = 30.95, so the 160-bit hash fills 31 digits in base 36
1432 * fairly neatly.
1434 * @param $path string
1436 * @return false|string False on failure
1438 static function sha1Base36( $path ) {
1439 wfSuppressWarnings();
1440 $hash = sha1_file( $path );
1441 wfRestoreWarnings();
1442 if ( $hash === false ) {
1443 return false;
1444 } else {
1445 return wfBaseConvert( $hash, 16, 36, 31 );
1450 * @return string
1452 function getLongDesc() {
1453 $handler = $this->getHandler();
1454 if ( $handler ) {
1455 return $handler->getLongDesc( $this );
1456 } else {
1457 return MediaHandler::getGeneralLongDesc( $this );
1462 * @return string
1464 function getShortDesc() {
1465 $handler = $this->getHandler();
1466 if ( $handler ) {
1467 return $handler->getShortDesc( $this );
1468 } else {
1469 return MediaHandler::getGeneralShortDesc( $this );
1474 * @return string
1476 function getDimensionsString() {
1477 $handler = $this->getHandler();
1478 if ( $handler ) {
1479 return $handler->getDimensionsString( $this );
1480 } else {
1481 return '';
1486 * @return
1488 function getRedirected() {
1489 return $this->redirected;
1493 * @return Title
1495 function getRedirectedTitle() {
1496 if ( $this->redirected ) {
1497 if ( !$this->redirectTitle ) {
1498 $this->redirectTitle = Title::makeTitle( NS_FILE, $this->redirected );
1500 return $this->redirectTitle;
1505 * @param $from
1506 * @return void
1508 function redirectedFrom( $from ) {
1509 $this->redirected = $from;
1513 * @return bool
1515 function isMissing() {
1516 return false;
1520 * Aliases for backwards compatibility with 1.6
1522 define( 'MW_IMG_DELETED_FILE', File::DELETED_FILE );
1523 define( 'MW_IMG_DELETED_COMMENT', File::DELETED_COMMENT );
1524 define( 'MW_IMG_DELETED_USER', File::DELETED_USER );
1525 define( 'MW_IMG_DELETED_RESTRICTED', File::DELETED_RESTRICTED );