Localisation updates from http://translatewiki.net.
[mediawiki.git] / includes / filerepo / file / File.php
blob065679a87afd3d68b270a31791093476c60f3bc4
1 <?php
2 /**
3 * @defgroup FileAbstraction File abstraction
4 * @ingroup FileRepo
6 * Represents files in a repository.
7 */
9 /**
10 * Base code for files.
12 * This program is free software; you can redistribute it and/or modify
13 * it under the terms of the GNU General Public License as published by
14 * the Free Software Foundation; either version 2 of the License, or
15 * (at your option) any later version.
17 * This program is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 * GNU General Public License for more details.
22 * You should have received a copy of the GNU General Public License along
23 * with this program; if not, write to the Free Software Foundation, Inc.,
24 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
25 * http://www.gnu.org/copyleft/gpl.html
27 * @file
28 * @ingroup FileAbstraction
31 /**
32 * Implements some public methods and some protected utility functions which
33 * are required by multiple child classes. Contains stub functionality for
34 * unimplemented public methods.
36 * Stub functions which should be overridden are marked with STUB. Some more
37 * concrete functions are also typically overridden by child classes.
39 * Note that only the repo object knows what its file class is called. You should
40 * never name a file class explictly outside of the repo class. Instead use the
41 * repo's factory functions to generate file objects, for example:
43 * RepoGroup::singleton()->getLocalRepo()->newFile($title);
45 * The convenience functions wfLocalFile() and wfFindFile() should be sufficient
46 * in most cases.
48 * @ingroup FileAbstraction
50 abstract class File {
51 const DELETED_FILE = 1;
52 const DELETED_COMMENT = 2;
53 const DELETED_USER = 4;
54 const DELETED_RESTRICTED = 8;
56 /** Force rendering in the current process */
57 const RENDER_NOW = 1;
58 /**
59 * Force rendering even if thumbnail already exist and using RENDER_NOW
60 * I.e. you have to pass both flags: File::RENDER_NOW | File::RENDER_FORCE
62 const RENDER_FORCE = 2;
64 const DELETE_SOURCE = 1;
66 // Audience options for File::getDescription()
67 const FOR_PUBLIC = 1;
68 const FOR_THIS_USER = 2;
69 const RAW = 3;
71 /**
72 * Some member variables can be lazy-initialised using __get(). The
73 * initialisation function for these variables is always a function named
74 * like getVar(), where Var is the variable name with upper-case first
75 * letter.
77 * The following variables are initialised in this way in this base class:
78 * name, extension, handler, path, canRender, isSafeFile,
79 * transformScript, hashPath, pageCount, url
81 * Code within this class should generally use the accessor function
82 * directly, since __get() isn't re-entrant and therefore causes bugs that
83 * depend on initialisation order.
86 /**
87 * The following member variables are not lazy-initialised
90 /**
91 * @var FileRepo|bool
93 var $repo;
95 /**
96 * @var Title
98 var $title;
100 var $lastError, $redirected, $redirectedTitle;
103 * @var FSFile|bool False if undefined
105 protected $fsFile;
108 * @var MediaHandler
110 protected $handler;
113 * @var string
115 protected $url, $extension, $name, $path, $hashPath, $pageCount, $transformScript;
117 protected $redirectTitle;
120 * @var bool
122 protected $canRender, $isSafeFile;
125 * @var string Required Repository class type
127 protected $repoClass = 'FileRepo';
130 * Call this constructor from child classes.
132 * Both $title and $repo are optional, though some functions
133 * may return false or throw exceptions if they are not set.
134 * Most subclasses will want to call assertRepoDefined() here.
136 * @param $title Title|string|bool
137 * @param $repo FileRepo|bool
139 function __construct( $title, $repo ) {
140 if ( $title !== false ) { // subclasses may not use MW titles
141 $title = self::normalizeTitle( $title, 'exception' );
143 $this->title = $title;
144 $this->repo = $repo;
148 * Given a string or Title object return either a
149 * valid Title object with namespace NS_FILE or null
151 * @param $title Title|string
152 * @param $exception string|bool Use 'exception' to throw an error on bad titles
153 * @throws MWException
154 * @return Title|null
156 static function normalizeTitle( $title, $exception = false ) {
157 $ret = $title;
158 if ( $ret instanceof Title ) {
159 # Normalize NS_MEDIA -> NS_FILE
160 if ( $ret->getNamespace() == NS_MEDIA ) {
161 $ret = Title::makeTitleSafe( NS_FILE, $ret->getDBkey() );
162 # Sanity check the title namespace
163 } elseif ( $ret->getNamespace() !== NS_FILE ) {
164 $ret = null;
166 } else {
167 # Convert strings to Title objects
168 $ret = Title::makeTitleSafe( NS_FILE, (string)$ret );
170 if ( !$ret && $exception !== false ) {
171 throw new MWException( "`$title` is not a valid file title." );
173 return $ret;
176 function __get( $name ) {
177 $function = array( $this, 'get' . ucfirst( $name ) );
178 if ( !is_callable( $function ) ) {
179 return null;
180 } else {
181 $this->$name = call_user_func( $function );
182 return $this->$name;
187 * Normalize a file extension to the common form, and ensure it's clean.
188 * Extensions with non-alphanumeric characters will be discarded.
190 * @param $ext string (without the .)
191 * @return string
193 static function normalizeExtension( $ext ) {
194 $lower = strtolower( $ext );
195 $squish = array(
196 'htm' => 'html',
197 'jpeg' => 'jpg',
198 'mpeg' => 'mpg',
199 'tiff' => 'tif',
200 'ogv' => 'ogg' );
201 if( isset( $squish[$lower] ) ) {
202 return $squish[$lower];
203 } elseif( preg_match( '/^[0-9a-z]+$/', $lower ) ) {
204 return $lower;
205 } else {
206 return '';
211 * Checks if file extensions are compatible
213 * @param $old File Old file
214 * @param $new string New name
216 * @return bool|null
218 static function checkExtensionCompatibility( File $old, $new ) {
219 $oldMime = $old->getMimeType();
220 $n = strrpos( $new, '.' );
221 $newExt = self::normalizeExtension( $n ? substr( $new, $n + 1 ) : '' );
222 $mimeMagic = MimeMagic::singleton();
223 return $mimeMagic->isMatchingExtension( $newExt, $oldMime );
227 * Upgrade the database row if there is one
228 * Called by ImagePage
229 * STUB
231 function upgradeRow() {}
234 * Split an internet media type into its two components; if not
235 * a two-part name, set the minor type to 'unknown'.
237 * @param string $mime "text/html" etc
238 * @return array ("text", "html") etc
240 public static function splitMime( $mime ) {
241 if( strpos( $mime, '/' ) !== false ) {
242 return explode( '/', $mime, 2 );
243 } else {
244 return array( $mime, 'unknown' );
249 * Return the name of this file
251 * @return string
253 public function getName() {
254 if ( !isset( $this->name ) ) {
255 $this->assertRepoDefined();
256 $this->name = $this->repo->getNameFromTitle( $this->title );
258 return $this->name;
262 * Get the file extension, e.g. "svg"
264 * @return string
266 function getExtension() {
267 if ( !isset( $this->extension ) ) {
268 $n = strrpos( $this->getName(), '.' );
269 $this->extension = self::normalizeExtension(
270 $n ? substr( $this->getName(), $n + 1 ) : '' );
272 return $this->extension;
276 * Return the associated title object
278 * @return Title
280 public function getTitle() {
281 return $this->title;
285 * Return the title used to find this file
287 * @return Title
289 public function getOriginalTitle() {
290 if ( $this->redirected ) {
291 return $this->getRedirectedTitle();
293 return $this->title;
297 * Return the URL of the file
299 * @return string
301 public function getUrl() {
302 if ( !isset( $this->url ) ) {
303 $this->assertRepoDefined();
304 $this->url = $this->repo->getZoneUrl( 'public' ) . '/' . $this->getUrlRel();
306 return $this->url;
310 * Return a fully-qualified URL to the file.
311 * Upload URL paths _may or may not_ be fully qualified, so
312 * we check. Local paths are assumed to belong on $wgServer.
314 * @return String
316 public function getFullUrl() {
317 return wfExpandUrl( $this->getUrl(), PROTO_RELATIVE );
321 * @return string
323 public function getCanonicalUrl() {
324 return wfExpandUrl( $this->getUrl(), PROTO_CANONICAL );
328 * @return string
330 function getViewURL() {
331 if ( $this->mustRender() ) {
332 if ( $this->canRender() ) {
333 return $this->createThumb( $this->getWidth() );
334 } else {
335 wfDebug( __METHOD__.': supposed to render ' . $this->getName() .
336 ' (' . $this->getMimeType() . "), but can't!\n" );
337 return $this->getURL(); #hm... return NULL?
339 } else {
340 return $this->getURL();
345 * Return the storage path to the file. Note that this does
346 * not mean that a file actually exists under that location.
348 * This path depends on whether directory hashing is active or not,
349 * i.e. whether the files are all found in the same directory,
350 * or in hashed paths like /images/3/3c.
352 * Most callers don't check the return value, but ForeignAPIFile::getPath
353 * returns false.
355 * @return string|bool ForeignAPIFile::getPath can return false
357 public function getPath() {
358 if ( !isset( $this->path ) ) {
359 $this->assertRepoDefined();
360 $this->path = $this->repo->getZonePath( 'public' ) . '/' . $this->getRel();
362 return $this->path;
366 * Get an FS copy or original of this file and return the path.
367 * Returns false on failure. Callers must not alter the file.
368 * Temporary files are cleared automatically.
370 * @return string|bool False on failure
372 public function getLocalRefPath() {
373 $this->assertRepoDefined();
374 if ( !isset( $this->fsFile ) ) {
375 $this->fsFile = $this->repo->getLocalReference( $this->getPath() );
376 if ( !$this->fsFile ) {
377 $this->fsFile = false; // null => false; cache negative hits
380 return ( $this->fsFile )
381 ? $this->fsFile->getPath()
382 : false;
386 * Return the width of the image. Returns false if the width is unknown
387 * or undefined.
389 * STUB
390 * Overridden by LocalFile, UnregisteredLocalFile
392 * @param $page int
394 * @return number
396 public function getWidth( $page = 1 ) {
397 return false;
401 * Return the height of the image. Returns false if the height is unknown
402 * or undefined
404 * STUB
405 * Overridden by LocalFile, UnregisteredLocalFile
407 * @param $page int
409 * @return bool|number False on failure
411 public function getHeight( $page = 1 ) {
412 return false;
416 * Returns ID or name of user who uploaded the file
417 * STUB
419 * @param $type string 'text' or 'id'
421 * @return string|int
423 public function getUser( $type = 'text' ) {
424 return null;
428 * Get the duration of a media file in seconds
430 * @return number
432 public function getLength() {
433 $handler = $this->getHandler();
434 if ( $handler ) {
435 return $handler->getLength( $this );
436 } else {
437 return 0;
442 * Return true if the file is vectorized
444 * @return bool
446 public function isVectorized() {
447 $handler = $this->getHandler();
448 if ( $handler ) {
449 return $handler->isVectorized( $this );
450 } else {
451 return false;
456 * Get handler-specific metadata
457 * Overridden by LocalFile, UnregisteredLocalFile
458 * STUB
459 * @return bool
461 public function getMetadata() {
462 return false;
466 * get versioned metadata
468 * @param $metadata Mixed Array or String of (serialized) metadata
469 * @param $version integer version number.
470 * @return Array containing metadata, or what was passed to it on fail (unserializing if not array)
472 public function convertMetadataVersion($metadata, $version) {
473 $handler = $this->getHandler();
474 if ( !is_array( $metadata ) ) {
475 // Just to make the return type consistent
476 $metadata = unserialize( $metadata );
478 if ( $handler ) {
479 return $handler->convertMetadataVersion( $metadata, $version );
480 } else {
481 return $metadata;
486 * Return the bit depth of the file
487 * Overridden by LocalFile
488 * STUB
489 * @return int
491 public function getBitDepth() {
492 return 0;
496 * Return the size of the image file, in bytes
497 * Overridden by LocalFile, UnregisteredLocalFile
498 * STUB
499 * @return bool
501 public function getSize() {
502 return false;
506 * Returns the mime type of the file.
507 * Overridden by LocalFile, UnregisteredLocalFile
508 * STUB
510 * @return string
512 function getMimeType() {
513 return 'unknown/unknown';
517 * Return the type of the media in the file.
518 * Use the value returned by this function with the MEDIATYPE_xxx constants.
519 * Overridden by LocalFile,
520 * STUB
521 * @return string
523 function getMediaType() {
524 return MEDIATYPE_UNKNOWN;
528 * Checks if the output of transform() for this file is likely
529 * to be valid. If this is false, various user elements will
530 * display a placeholder instead.
532 * Currently, this checks if the file is an image format
533 * that can be converted to a format
534 * supported by all browsers (namely GIF, PNG and JPEG),
535 * or if it is an SVG image and SVG conversion is enabled.
537 * @return bool
539 function canRender() {
540 if ( !isset( $this->canRender ) ) {
541 $this->canRender = $this->getHandler() && $this->handler->canRender( $this );
543 return $this->canRender;
547 * Accessor for __get()
548 * @return bool
550 protected function getCanRender() {
551 return $this->canRender();
555 * Return true if the file is of a type that can't be directly
556 * rendered by typical browsers and needs to be re-rasterized.
558 * This returns true for everything but the bitmap types
559 * supported by all browsers, i.e. JPEG; GIF and PNG. It will
560 * also return true for any non-image formats.
562 * @return bool
564 function mustRender() {
565 return $this->getHandler() && $this->handler->mustRender( $this );
569 * Alias for canRender()
571 * @return bool
573 function allowInlineDisplay() {
574 return $this->canRender();
578 * Determines if this media file is in a format that is unlikely to
579 * contain viruses or malicious content. It uses the global
580 * $wgTrustedMediaFormats list to determine if the file is safe.
582 * This is used to show a warning on the description page of non-safe files.
583 * It may also be used to disallow direct [[media:...]] links to such files.
585 * Note that this function will always return true if allowInlineDisplay()
586 * or isTrustedFile() is true for this file.
588 * @return bool
590 function isSafeFile() {
591 if ( !isset( $this->isSafeFile ) ) {
592 $this->isSafeFile = $this->_getIsSafeFile();
594 return $this->isSafeFile;
598 * Accessor for __get()
600 * @return bool
602 protected function getIsSafeFile() {
603 return $this->isSafeFile();
607 * Uncached accessor
609 * @return bool
611 protected function _getIsSafeFile() {
612 global $wgTrustedMediaFormats;
614 if ( $this->allowInlineDisplay() ) {
615 return true;
617 if ($this->isTrustedFile()) {
618 return true;
621 $type = $this->getMediaType();
622 $mime = $this->getMimeType();
623 #wfDebug("LocalFile::isSafeFile: type= $type, mime= $mime\n");
625 if ( !$type || $type === MEDIATYPE_UNKNOWN ) {
626 return false; #unknown type, not trusted
628 if ( in_array( $type, $wgTrustedMediaFormats ) ) {
629 return true;
632 if ( $mime === "unknown/unknown" ) {
633 return false; #unknown type, not trusted
635 if ( in_array( $mime, $wgTrustedMediaFormats) ) {
636 return true;
639 return false;
643 * Returns true if the file is flagged as trusted. Files flagged that way
644 * can be linked to directly, even if that is not allowed for this type of
645 * file normally.
647 * This is a dummy function right now and always returns false. It could be
648 * implemented to extract a flag from the database. The trusted flag could be
649 * set on upload, if the user has sufficient privileges, to bypass script-
650 * and html-filters. It may even be coupled with cryptographics signatures
651 * or such.
653 * @return bool
655 function isTrustedFile() {
656 #this could be implemented to check a flag in the database,
657 #look for signatures, etc
658 return false;
662 * Returns true if file exists in the repository.
664 * Overridden by LocalFile to avoid unnecessary stat calls.
666 * @return boolean Whether file exists in the repository.
668 public function exists() {
669 return $this->getPath() && $this->repo->fileExists( $this->path );
673 * Returns true if file exists in the repository and can be included in a page.
674 * It would be unsafe to include private images, making public thumbnails inadvertently
676 * @return boolean Whether file exists in the repository and is includable.
678 public function isVisible() {
679 return $this->exists();
683 * @return string
685 function getTransformScript() {
686 if ( !isset( $this->transformScript ) ) {
687 $this->transformScript = false;
688 if ( $this->repo ) {
689 $script = $this->repo->getThumbScriptUrl();
690 if ( $script ) {
691 $this->transformScript = "$script?f=" . urlencode( $this->getName() );
695 return $this->transformScript;
699 * Get a ThumbnailImage which is the same size as the source
701 * @param $handlerParams array
703 * @return string
705 function getUnscaledThumb( $handlerParams = array() ) {
706 $hp =& $handlerParams;
707 $page = isset( $hp['page'] ) ? $hp['page'] : false;
708 $width = $this->getWidth( $page );
709 if ( !$width ) {
710 return $this->iconThumb();
712 $hp['width'] = $width;
713 return $this->transform( $hp );
717 * Return the file name of a thumbnail with the specified parameters
719 * @param $params Array: handler-specific parameters
720 * @private -ish
722 * @return string
724 function thumbName( $params ) {
725 return $this->generateThumbName( $this->getName(), $params );
729 * Generate a thumbnail file name from a name and specified parameters
731 * @param string $name
732 * @param array $params Parameters which will be passed to MediaHandler::makeParamString
734 * @return string
736 function generateThumbName( $name, $params ) {
737 if ( !$this->getHandler() ) {
738 return null;
740 $extension = $this->getExtension();
741 list( $thumbExt, $thumbMime ) = $this->handler->getThumbType(
742 $extension, $this->getMimeType(), $params );
743 $thumbName = $this->handler->makeParamString( $params ) . '-' . $name;
744 if ( $thumbExt != $extension ) {
745 $thumbName .= ".$thumbExt";
747 return $thumbName;
751 * Create a thumbnail of the image having the specified width/height.
752 * The thumbnail will not be created if the width is larger than the
753 * image's width. Let the browser do the scaling in this case.
754 * The thumbnail is stored on disk and is only computed if the thumbnail
755 * file does not exist OR if it is older than the image.
756 * Returns the URL.
758 * Keeps aspect ratio of original image. If both width and height are
759 * specified, the generated image will be no bigger than width x height,
760 * and will also have correct aspect ratio.
762 * @param $width Integer: maximum width of the generated thumbnail
763 * @param $height Integer: maximum height of the image (optional)
765 * @return string
767 public function createThumb( $width, $height = -1 ) {
768 $params = array( 'width' => $width );
769 if ( $height != -1 ) {
770 $params['height'] = $height;
772 $thumb = $this->transform( $params );
773 if ( is_null( $thumb ) || $thumb->isError() ) {
774 return '';
776 return $thumb->getUrl();
780 * Return either a MediaTransformError or placeholder thumbnail (if $wgIgnoreImageErrors)
782 * @param $thumbPath string Thumbnail storage path
783 * @param $thumbUrl string Thumbnail URL
784 * @param $params Array
785 * @param $flags integer
786 * @return MediaTransformOutput
788 protected function transformErrorOutput( $thumbPath, $thumbUrl, $params, $flags ) {
789 global $wgIgnoreImageErrors;
791 if ( $wgIgnoreImageErrors && !( $flags & self::RENDER_NOW ) ) {
792 return $this->handler->getTransform( $this, $thumbPath, $thumbUrl, $params );
793 } else {
794 return new MediaTransformError( 'thumbnail_error',
795 $params['width'], 0, wfMsg( 'thumbnail-dest-create' ) );
800 * Transform a media file
802 * @param $params Array: an associative array of handler-specific parameters.
803 * Typical keys are width, height and page.
804 * @param $flags Integer: a bitfield, may contain self::RENDER_NOW to force rendering
805 * @return MediaTransformOutput|bool False on failure
807 function transform( $params, $flags = 0 ) {
808 global $wgUseSquid, $wgIgnoreImageErrors, $wgThumbnailEpoch;
810 wfProfileIn( __METHOD__ );
811 do {
812 if ( !$this->canRender() ) {
813 $thumb = $this->iconThumb();
814 break; // not a bitmap or renderable image, don't try
817 // Get the descriptionUrl to embed it as comment into the thumbnail. Bug 19791.
818 $descriptionUrl = $this->getDescriptionUrl();
819 if ( $descriptionUrl ) {
820 $params['descriptionUrl'] = wfExpandUrl( $descriptionUrl, PROTO_CANONICAL );
823 $script = $this->getTransformScript();
824 if ( $script && !( $flags & self::RENDER_NOW ) ) {
825 // Use a script to transform on client request, if possible
826 $thumb = $this->handler->getScriptedTransform( $this, $script, $params );
827 if ( $thumb ) {
828 break;
832 $normalisedParams = $params;
833 $this->handler->normaliseParams( $this, $normalisedParams );
835 $thumbName = $this->thumbName( $normalisedParams );
836 $thumbUrl = $this->getThumbUrl( $thumbName );
837 $thumbPath = $this->getThumbPath( $thumbName ); // final thumb path
839 if ( $this->repo ) {
840 // Defer rendering if a 404 handler is set up...
841 if ( $this->repo->canTransformVia404() && !( $flags & self::RENDER_NOW ) ) {
842 wfDebug( __METHOD__ . " transformation deferred." );
843 // XXX: Pass in the storage path even though we are not rendering anything
844 // and the path is supposed to be an FS path. This is due to getScalerType()
845 // getting called on the path and clobbering $thumb->getUrl() if it's false.
846 $thumb = $this->handler->getTransform( $this, $thumbPath, $thumbUrl, $params );
847 break;
849 // Clean up broken thumbnails as needed
850 $this->migrateThumbFile( $thumbName );
851 // Check if an up-to-date thumbnail already exists...
852 wfDebug( __METHOD__.": Doing stat for $thumbPath\n" );
853 if ( $this->repo->fileExists( $thumbPath ) && !( $flags & self::RENDER_FORCE ) ) {
854 $timestamp = $this->repo->getFileTimestamp( $thumbPath );
855 if ( $timestamp !== false && $timestamp >= $wgThumbnailEpoch ) {
856 // XXX: Pass in the storage path even though we are not rendering anything
857 // and the path is supposed to be an FS path. This is due to getScalerType()
858 // getting called on the path and clobbering $thumb->getUrl() if it's false.
859 $thumb = $this->handler->getTransform( $this, $thumbPath, $thumbUrl, $params );
860 $thumb->setStoragePath( $thumbPath );
861 break;
863 } elseif ( $flags & self::RENDER_FORCE ) {
864 wfDebug( __METHOD__ . " forcing rendering per flag File::RENDER_FORCE\n" );
868 // If the backend is ready-only, don't keep generating thumbnails
869 // only to return transformation errors, just return the error now.
870 if ( $this->repo->getReadOnlyReason() !== false ) {
871 $thumb = $this->transformErrorOutput( $thumbPath, $thumbUrl, $params, $flags );
872 break;
875 // Create a temp FS file with the same extension and the thumbnail
876 $thumbExt = FileBackend::extensionFromPath( $thumbPath );
877 $tmpFile = TempFSFile::factory( 'transform_', $thumbExt );
878 if ( !$tmpFile ) {
879 $thumb = $this->transformErrorOutput( $thumbPath, $thumbUrl, $params, $flags );
880 break;
882 $tmpThumbPath = $tmpFile->getPath(); // path of 0-byte temp file
884 // Actually render the thumbnail...
885 $thumb = $this->handler->doTransform( $this, $tmpThumbPath, $thumbUrl, $params );
886 $tmpFile->bind( $thumb ); // keep alive with $thumb
888 if ( !$thumb ) { // bad params?
889 $thumb = null;
890 } elseif ( $thumb->isError() ) { // transform error
891 $this->lastError = $thumb->toText();
892 // Ignore errors if requested
893 if ( $wgIgnoreImageErrors && !( $flags & self::RENDER_NOW ) ) {
894 $thumb = $this->handler->getTransform( $this, $tmpThumbPath, $thumbUrl, $params );
896 } elseif ( $this->repo && $thumb->hasFile() && !$thumb->fileIsSource() ) {
897 // Copy the thumbnail from the file system into storage...
898 $status = $this->repo->quickImport( $tmpThumbPath, $thumbPath );
899 if ( $status->isOK() ) {
900 $thumb->setStoragePath( $thumbPath );
901 } else {
902 $thumb = $this->transformErrorOutput( $thumbPath, $thumbUrl, $params, $flags );
904 // Give extensions a chance to do something with this thumbnail...
905 wfRunHooks( 'FileTransformed', array( $this, $thumb, $tmpThumbPath, $thumbPath ) );
908 // Purge. Useful in the event of Core -> Squid connection failure or squid
909 // purge collisions from elsewhere during failure. Don't keep triggering for
910 // "thumbs" which have the main image URL though (bug 13776)
911 if ( $wgUseSquid ) {
912 if ( !$thumb || $thumb->isError() || $thumb->getUrl() != $this->getURL() ) {
913 SquidUpdate::purge( array( $thumbUrl ) );
916 } while ( false );
918 wfProfileOut( __METHOD__ );
919 return is_object( $thumb ) ? $thumb : false;
923 * Hook into transform() to allow migration of thumbnail files
924 * STUB
925 * Overridden by LocalFile
927 function migrateThumbFile( $thumbName ) {}
930 * Get a MediaHandler instance for this file
932 * @return MediaHandler
934 function getHandler() {
935 if ( !isset( $this->handler ) ) {
936 $this->handler = MediaHandler::getHandler( $this->getMimeType() );
938 return $this->handler;
942 * Get a ThumbnailImage representing a file type icon
944 * @return ThumbnailImage
946 function iconThumb() {
947 global $wgStylePath, $wgStyleDirectory;
949 $try = array( 'fileicon-' . $this->getExtension() . '.png', 'fileicon.png' );
950 foreach ( $try as $icon ) {
951 $path = '/common/images/icons/' . $icon;
952 $filepath = $wgStyleDirectory . $path;
953 if ( file_exists( $filepath ) ) { // always FS
954 return new ThumbnailImage( $this, $wgStylePath . $path, 120, 120 );
957 return null;
961 * Get last thumbnailing error.
962 * Largely obsolete.
964 function getLastError() {
965 return $this->lastError;
969 * Get all thumbnail names previously generated for this file
970 * STUB
971 * Overridden by LocalFile
972 * @return array
974 function getThumbnails() {
975 return array();
979 * Purge shared caches such as thumbnails and DB data caching
980 * STUB
981 * Overridden by LocalFile
982 * @param $options Array Options, which include:
983 * 'forThumbRefresh' : The purging is only to refresh thumbnails
985 function purgeCache( $options = array() ) {}
988 * Purge the file description page, but don't go after
989 * pages using the file. Use when modifying file history
990 * but not the current data.
992 function purgeDescription() {
993 $title = $this->getTitle();
994 if ( $title ) {
995 $title->invalidateCache();
996 $title->purgeSquid();
1001 * Purge metadata and all affected pages when the file is created,
1002 * deleted, or majorly updated.
1004 function purgeEverything() {
1005 // Delete thumbnails and refresh file metadata cache
1006 $this->purgeCache();
1007 $this->purgeDescription();
1009 // Purge cache of all pages using this file
1010 $title = $this->getTitle();
1011 if ( $title ) {
1012 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
1013 $update->doUpdate();
1018 * Return a fragment of the history of file.
1020 * STUB
1021 * @param $limit integer Limit of rows to return
1022 * @param $start string timestamp Only revisions older than $start will be returned
1023 * @param $end string timestamp Only revisions newer than $end will be returned
1024 * @param $inc bool Include the endpoints of the time range
1026 * @return array
1028 function getHistory( $limit = null, $start = null, $end = null, $inc=true ) {
1029 return array();
1033 * Return the history of this file, line by line. Starts with current version,
1034 * then old versions. Should return an object similar to an image/oldimage
1035 * database row.
1037 * STUB
1038 * Overridden in LocalFile
1039 * @return bool
1041 public function nextHistoryLine() {
1042 return false;
1046 * Reset the history pointer to the first element of the history.
1047 * Always call this function after using nextHistoryLine() to free db resources
1048 * STUB
1049 * Overridden in LocalFile.
1051 public function resetHistory() {}
1054 * Get the filename hash component of the directory including trailing slash,
1055 * e.g. f/fa/
1056 * If the repository is not hashed, returns an empty string.
1058 * @return string
1060 function getHashPath() {
1061 if ( !isset( $this->hashPath ) ) {
1062 $this->assertRepoDefined();
1063 $this->hashPath = $this->repo->getHashPath( $this->getName() );
1065 return $this->hashPath;
1069 * Get the path of the file relative to the public zone root.
1070 * This function is overriden in OldLocalFile to be like getArchiveRel().
1072 * @return string
1074 function getRel() {
1075 return $this->getHashPath() . $this->getName();
1079 * Get the path of an archived file relative to the public zone root
1081 * @param $suffix bool|string if not false, the name of an archived thumbnail file
1083 * @return string
1085 function getArchiveRel( $suffix = false ) {
1086 $path = 'archive/' . $this->getHashPath();
1087 if ( $suffix === false ) {
1088 $path = substr( $path, 0, -1 );
1089 } else {
1090 $path .= $suffix;
1092 return $path;
1096 * Get the path, relative to the thumbnail zone root, of the
1097 * thumbnail directory or a particular file if $suffix is specified
1099 * @param $suffix bool|string if not false, the name of a thumbnail file
1101 * @return string
1103 function getThumbRel( $suffix = false ) {
1104 $path = $this->getRel();
1105 if ( $suffix !== false ) {
1106 $path .= '/' . $suffix;
1108 return $path;
1112 * Get urlencoded path of the file relative to the public zone root.
1113 * This function is overriden in OldLocalFile to be like getArchiveUrl().
1115 * @return string
1117 function getUrlRel() {
1118 return $this->getHashPath() . rawurlencode( $this->getName() );
1122 * Get the path, relative to the thumbnail zone root, for an archived file's thumbs directory
1123 * or a specific thumb if the $suffix is given.
1125 * @param $archiveName string the timestamped name of an archived image
1126 * @param $suffix bool|string if not false, the name of a thumbnail file
1128 * @return string
1130 function getArchiveThumbRel( $archiveName, $suffix = false ) {
1131 $path = 'archive/' . $this->getHashPath() . $archiveName . "/";
1132 if ( $suffix === false ) {
1133 $path = substr( $path, 0, -1 );
1134 } else {
1135 $path .= $suffix;
1137 return $path;
1141 * Get the path of the archived file.
1143 * @param $suffix bool|string if not false, the name of an archived file.
1145 * @return string
1147 function getArchivePath( $suffix = false ) {
1148 $this->assertRepoDefined();
1149 return $this->repo->getZonePath( 'public' ) . '/' . $this->getArchiveRel( $suffix );
1153 * Get the path of an archived file's thumbs, or a particular thumb if $suffix is specified
1155 * @param $archiveName string the timestamped name of an archived image
1156 * @param $suffix bool|string if not false, the name of a thumbnail file
1158 * @return string
1160 function getArchiveThumbPath( $archiveName, $suffix = false ) {
1161 $this->assertRepoDefined();
1162 return $this->repo->getZonePath( 'thumb' ) . '/' .
1163 $this->getArchiveThumbRel( $archiveName, $suffix );
1167 * Get the path of the thumbnail directory, or a particular file if $suffix is specified
1169 * @param $suffix bool|string if not false, the name of a thumbnail file
1171 * @return string
1173 function getThumbPath( $suffix = false ) {
1174 $this->assertRepoDefined();
1175 return $this->repo->getZonePath( 'thumb' ) . '/' . $this->getThumbRel( $suffix );
1179 * Get the URL of the archive directory, or a particular file if $suffix is specified
1181 * @param $suffix bool|string if not false, the name of an archived file
1183 * @return string
1185 function getArchiveUrl( $suffix = false ) {
1186 $this->assertRepoDefined();
1187 $path = $this->repo->getZoneUrl( 'public' ) . '/archive/' . $this->getHashPath();
1188 if ( $suffix === false ) {
1189 $path = substr( $path, 0, -1 );
1190 } else {
1191 $path .= rawurlencode( $suffix );
1193 return $path;
1197 * Get the URL of the archived file's thumbs, or a particular thumb if $suffix is specified
1199 * @param $archiveName string the timestamped name of an archived image
1200 * @param $suffix bool|string if not false, the name of a thumbnail file
1202 * @return string
1204 function getArchiveThumbUrl( $archiveName, $suffix = false ) {
1205 $this->assertRepoDefined();
1206 $path = $this->repo->getZoneUrl( 'thumb' ) . '/archive/' .
1207 $this->getHashPath() . rawurlencode( $archiveName ) . "/";
1208 if ( $suffix === false ) {
1209 $path = substr( $path, 0, -1 );
1210 } else {
1211 $path .= rawurlencode( $suffix );
1213 return $path;
1217 * Get the URL of the thumbnail directory, or a particular file if $suffix is specified
1219 * @param $suffix bool|string if not false, the name of a thumbnail file
1221 * @return string path
1223 function getThumbUrl( $suffix = false ) {
1224 $this->assertRepoDefined();
1225 $path = $this->repo->getZoneUrl( 'thumb' ) . '/' . $this->getUrlRel();
1226 if ( $suffix !== false ) {
1227 $path .= '/' . rawurlencode( $suffix );
1229 return $path;
1233 * Get the public zone virtual URL for a current version source file
1235 * @param $suffix bool|string if not false, the name of a thumbnail file
1237 * @return string
1239 function getVirtualUrl( $suffix = false ) {
1240 $this->assertRepoDefined();
1241 $path = $this->repo->getVirtualUrl() . '/public/' . $this->getUrlRel();
1242 if ( $suffix !== false ) {
1243 $path .= '/' . rawurlencode( $suffix );
1245 return $path;
1249 * Get the public zone virtual URL for an archived version source file
1251 * @param $suffix bool|string if not false, the name of a thumbnail file
1253 * @return string
1255 function getArchiveVirtualUrl( $suffix = false ) {
1256 $this->assertRepoDefined();
1257 $path = $this->repo->getVirtualUrl() . '/public/archive/' . $this->getHashPath();
1258 if ( $suffix === false ) {
1259 $path = substr( $path, 0, -1 );
1260 } else {
1261 $path .= rawurlencode( $suffix );
1263 return $path;
1267 * Get the virtual URL for a thumbnail file or directory
1269 * @param $suffix bool|string if not false, the name of a thumbnail file
1271 * @return string
1273 function getThumbVirtualUrl( $suffix = false ) {
1274 $this->assertRepoDefined();
1275 $path = $this->repo->getVirtualUrl() . '/thumb/' . $this->getUrlRel();
1276 if ( $suffix !== false ) {
1277 $path .= '/' . rawurlencode( $suffix );
1279 return $path;
1283 * @return bool
1285 function isHashed() {
1286 $this->assertRepoDefined();
1287 return (bool)$this->repo->getHashLevels();
1291 * @throws MWException
1293 function readOnlyError() {
1294 throw new MWException( get_class($this) . ': write operations are not supported' );
1298 * Record a file upload in the upload log and the image table
1299 * STUB
1300 * Overridden by LocalFile
1301 * @param $oldver
1302 * @param $desc
1303 * @param $license string
1304 * @param $copyStatus string
1305 * @param $source string
1306 * @param $watch bool
1308 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '', $watch = false ) {
1309 $this->readOnlyError();
1313 * Move or copy a file to its public location. If a file exists at the
1314 * destination, move it to an archive. Returns a FileRepoStatus object with
1315 * the archive name in the "value" member on success.
1317 * The archive name should be passed through to recordUpload for database
1318 * registration.
1320 * @param $srcPath String: local filesystem path to the source image
1321 * @param $flags Integer: a bitwise combination of:
1322 * File::DELETE_SOURCE Delete the source file, i.e. move
1323 * rather than copy
1324 * @return FileRepoStatus object. On success, the value member contains the
1325 * archive name, or an empty string if it was a new file.
1327 * STUB
1328 * Overridden by LocalFile
1330 function publish( $srcPath, $flags = 0 ) {
1331 $this->readOnlyError();
1335 * @return bool
1337 function formatMetadata() {
1338 if ( !$this->getHandler() ) {
1339 return false;
1341 return $this->getHandler()->formatMetadata( $this, $this->getMetadata() );
1345 * Returns true if the file comes from the local file repository.
1347 * @return bool
1349 function isLocal() {
1350 return $this->repo && $this->repo->isLocal();
1354 * Returns the name of the repository.
1356 * @return string
1358 function getRepoName() {
1359 return $this->repo ? $this->repo->getName() : 'unknown';
1363 * Returns the repository
1365 * @return FileRepo|bool
1367 function getRepo() {
1368 return $this->repo;
1372 * Returns true if the image is an old version
1373 * STUB
1375 * @return bool
1377 function isOld() {
1378 return false;
1382 * Is this file a "deleted" file in a private archive?
1383 * STUB
1385 * @param $field
1387 * @return bool
1389 function isDeleted( $field ) {
1390 return false;
1394 * Return the deletion bitfield
1395 * STUB
1396 * @return int
1398 function getVisibility() {
1399 return 0;
1403 * Was this file ever deleted from the wiki?
1405 * @return bool
1407 function wasDeleted() {
1408 $title = $this->getTitle();
1409 return $title && $title->isDeletedQuick();
1413 * Move file to the new title
1415 * Move current, old version and all thumbnails
1416 * to the new filename. Old file is deleted.
1418 * Cache purging is done; checks for validity
1419 * and logging are caller's responsibility
1421 * @param $target Title New file name
1422 * @return FileRepoStatus object.
1424 function move( $target ) {
1425 $this->readOnlyError();
1429 * Delete all versions of the file.
1431 * Moves the files into an archive directory (or deletes them)
1432 * and removes the database rows.
1434 * Cache purging is done; logging is caller's responsibility.
1436 * @param $reason String
1437 * @param $suppress Boolean: hide content from sysops?
1438 * @return bool on success, false on some kind of failure
1439 * STUB
1440 * Overridden by LocalFile
1442 function delete( $reason, $suppress = false ) {
1443 $this->readOnlyError();
1447 * Restore all or specified deleted revisions to the given file.
1448 * Permissions and logging are left to the caller.
1450 * May throw database exceptions on error.
1452 * @param $versions array set of record ids of deleted items to restore,
1453 * or empty to restore all revisions.
1454 * @param $unsuppress bool remove restrictions on content upon restoration?
1455 * @return int|bool the number of file revisions restored if successful,
1456 * or false on failure
1457 * STUB
1458 * Overridden by LocalFile
1460 function restore( $versions = array(), $unsuppress = false ) {
1461 $this->readOnlyError();
1465 * Returns 'true' if this file is a type which supports multiple pages,
1466 * e.g. DJVU or PDF. Note that this may be true even if the file in
1467 * question only has a single page.
1469 * @return Bool
1471 function isMultipage() {
1472 return $this->getHandler() && $this->handler->isMultiPage( $this );
1476 * Returns the number of pages of a multipage document, or false for
1477 * documents which aren't multipage documents
1479 * @return bool|int
1481 function pageCount() {
1482 if ( !isset( $this->pageCount ) ) {
1483 if ( $this->getHandler() && $this->handler->isMultiPage( $this ) ) {
1484 $this->pageCount = $this->handler->pageCount( $this );
1485 } else {
1486 $this->pageCount = false;
1489 return $this->pageCount;
1493 * Calculate the height of a thumbnail using the source and destination width
1495 * @param $srcWidth
1496 * @param $srcHeight
1497 * @param $dstWidth
1499 * @return int
1501 static function scaleHeight( $srcWidth, $srcHeight, $dstWidth ) {
1502 // Exact integer multiply followed by division
1503 if ( $srcWidth == 0 ) {
1504 return 0;
1505 } else {
1506 return round( $srcHeight * $dstWidth / $srcWidth );
1511 * Get an image size array like that returned by getImageSize(), or false if it
1512 * can't be determined.
1514 * @param $fileName String: The filename
1515 * @return Array
1517 function getImageSize( $fileName ) {
1518 if ( !$this->getHandler() ) {
1519 return false;
1521 return $this->handler->getImageSize( $this, $fileName );
1525 * Get the URL of the image description page. May return false if it is
1526 * unknown or not applicable.
1528 * @return string
1530 function getDescriptionUrl() {
1531 if ( $this->repo ) {
1532 return $this->repo->getDescriptionUrl( $this->getName() );
1533 } else {
1534 return false;
1539 * Get the HTML text of the description page, if available
1541 * @return string
1543 function getDescriptionText() {
1544 global $wgMemc, $wgLang;
1545 if ( !$this->repo || !$this->repo->fetchDescription ) {
1546 return false;
1548 $renderUrl = $this->repo->getDescriptionRenderUrl( $this->getName(), $wgLang->getCode() );
1549 if ( $renderUrl ) {
1550 if ( $this->repo->descriptionCacheExpiry > 0 ) {
1551 wfDebug("Attempting to get the description from cache...");
1552 $key = $this->repo->getLocalCacheKey( 'RemoteFileDescription', 'url', $wgLang->getCode(),
1553 $this->getName() );
1554 $obj = $wgMemc->get($key);
1555 if ($obj) {
1556 wfDebug("success!\n");
1557 return $obj;
1559 wfDebug("miss\n");
1561 wfDebug( "Fetching shared description from $renderUrl\n" );
1562 $res = Http::get( $renderUrl );
1563 if ( $res && $this->repo->descriptionCacheExpiry > 0 ) {
1564 $wgMemc->set( $key, $res, $this->repo->descriptionCacheExpiry );
1566 return $res;
1567 } else {
1568 return false;
1573 * Get description of file revision
1574 * STUB
1576 * @param $audience Integer: one of:
1577 * File::FOR_PUBLIC to be displayed to all users
1578 * File::FOR_THIS_USER to be displayed to the given user
1579 * File::RAW get the description regardless of permissions
1580 * @param $user User object to check for, only if FOR_THIS_USER is passed
1581 * to the $audience parameter
1582 * @return string
1584 function getDescription( $audience = self::FOR_PUBLIC, User $user = null ) {
1585 return null;
1589 * Get the 14-character timestamp of the file upload
1591 * @return string|bool TS_MW timestamp or false on failure
1593 function getTimestamp() {
1594 $this->assertRepoDefined();
1595 return $this->repo->getFileTimestamp( $this->getPath() );
1599 * Get the SHA-1 base 36 hash of the file
1601 * @return string
1603 function getSha1() {
1604 $this->assertRepoDefined();
1605 return $this->repo->getFileSha1( $this->getPath() );
1609 * Get the deletion archive key, <sha1>.<ext>
1611 * @return string
1613 function getStorageKey() {
1614 $hash = $this->getSha1();
1615 if ( !$hash ) {
1616 return false;
1618 $ext = $this->getExtension();
1619 $dotExt = $ext === '' ? '' : ".$ext";
1620 return $hash . $dotExt;
1624 * Determine if the current user is allowed to view a particular
1625 * field of this file, if it's marked as deleted.
1626 * STUB
1627 * @param $field Integer
1628 * @param $user User object to check, or null to use $wgUser
1629 * @return Boolean
1631 function userCan( $field, User $user = null ) {
1632 return true;
1636 * Get an associative array containing information about a file in the local filesystem.
1638 * @param $path String: absolute local filesystem path
1639 * @param $ext Mixed: the file extension, or true to extract it from the filename.
1640 * Set it to false to ignore the extension.
1642 * @return array
1644 static function getPropsFromPath( $path, $ext = true ) {
1645 wfDebug( __METHOD__.": Getting file info for $path\n" );
1646 wfDeprecated( __METHOD__, '1.19' );
1648 $fsFile = new FSFile( $path );
1649 return $fsFile->getProps();
1653 * Get a SHA-1 hash of a file in the local filesystem, in base-36 lower case
1654 * encoding, zero padded to 31 digits.
1656 * 160 log 2 / log 36 = 30.95, so the 160-bit hash fills 31 digits in base 36
1657 * fairly neatly.
1659 * @param $path string
1661 * @return bool|string False on failure
1663 static function sha1Base36( $path ) {
1664 wfDeprecated( __METHOD__, '1.19' );
1666 $fsFile = new FSFile( $path );
1667 return $fsFile->getSha1Base36();
1671 * @return string
1673 function getLongDesc() {
1674 $handler = $this->getHandler();
1675 if ( $handler ) {
1676 return $handler->getLongDesc( $this );
1677 } else {
1678 return MediaHandler::getGeneralLongDesc( $this );
1683 * @return string
1685 function getShortDesc() {
1686 $handler = $this->getHandler();
1687 if ( $handler ) {
1688 return $handler->getShortDesc( $this );
1689 } else {
1690 return MediaHandler::getGeneralShortDesc( $this );
1695 * @return string
1697 function getDimensionsString() {
1698 $handler = $this->getHandler();
1699 if ( $handler ) {
1700 return $handler->getDimensionsString( $this );
1701 } else {
1702 return '';
1707 * @return
1709 function getRedirected() {
1710 return $this->redirected;
1714 * @return Title
1716 function getRedirectedTitle() {
1717 if ( $this->redirected ) {
1718 if ( !$this->redirectTitle ) {
1719 $this->redirectTitle = Title::makeTitle( NS_FILE, $this->redirected );
1721 return $this->redirectTitle;
1726 * @param $from
1727 * @return void
1729 function redirectedFrom( $from ) {
1730 $this->redirected = $from;
1734 * @return bool
1736 function isMissing() {
1737 return false;
1741 * Check if this file object is small and can be cached
1742 * @return boolean
1744 public function isCacheable() {
1745 return true;
1749 * Assert that $this->repo is set to a valid FileRepo instance
1750 * @throws MWException
1752 protected function assertRepoDefined() {
1753 if ( !( $this->repo instanceof $this->repoClass ) ) {
1754 throw new MWException( "A {$this->repoClass} object is not set for this File.\n" );
1759 * Assert that $this->title is set to a Title
1760 * @throws MWException
1762 protected function assertTitleDefined() {
1763 if ( !( $this->title instanceof Title ) ) {
1764 throw new MWException( "A Title object is not set for this File.\n" );