Localisation updates from https://translatewiki.net.
[mediawiki.git] / includes / filerepo / file / File.php
blob2721693461758742582274255a0ab5e6db60060a
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 // Bitfield values akin to the Revision deletion constants
52 const DELETED_FILE = 1;
53 const DELETED_COMMENT = 2;
54 const DELETED_USER = 4;
55 const DELETED_RESTRICTED = 8;
57 /** Force rendering in the current process */
58 const RENDER_NOW = 1;
59 /**
60 * Force rendering even if thumbnail already exist and using RENDER_NOW
61 * I.e. you have to pass both flags: File::RENDER_NOW | File::RENDER_FORCE
63 const RENDER_FORCE = 2;
65 const DELETE_SOURCE = 1;
67 // Audience options for File::getDescription()
68 const FOR_PUBLIC = 1;
69 const FOR_THIS_USER = 2;
70 const RAW = 3;
72 // Options for File::thumbName()
73 const THUMB_FULL_NAME = 1;
75 /**
76 * Some member variables can be lazy-initialised using __get(). The
77 * initialisation function for these variables is always a function named
78 * like getVar(), where Var is the variable name with upper-case first
79 * letter.
81 * The following variables are initialised in this way in this base class:
82 * name, extension, handler, path, canRender, isSafeFile,
83 * transformScript, hashPath, pageCount, url
85 * Code within this class should generally use the accessor function
86 * directly, since __get() isn't re-entrant and therefore causes bugs that
87 * depend on initialisation order.
90 /**
91 * The following member variables are not lazy-initialised
94 /** @var FileRepo|LocalRepo|ForeignAPIRepo|bool */
95 public $repo;
97 /** @var Title|string|bool */
98 protected $title;
100 /** @var string Text of last error */
101 protected $lastError;
103 /** @var string Main part of the title, with underscores (Title::getDBkey) */
104 protected $redirected;
106 /** @var Title */
107 protected $redirectedTitle;
109 /** @var FSFile|bool False if undefined */
110 protected $fsFile;
112 /** @var MediaHandler */
113 protected $handler;
115 /** @var string The URL corresponding to one of the four basic zones */
116 protected $url;
118 /** @var string File extension */
119 protected $extension;
121 /** @var string The name of a file from its title object */
122 protected $name;
124 /** @var string The storage path corresponding to one of the zones */
125 protected $path;
127 /** @var string Relative path including trailing slash */
128 protected $hashPath;
130 /** @var string Number of pages of a multipage document, or false for
131 * documents which aren't multipage documents
133 protected $pageCount;
135 /** @var string URL of transformscript (for example thumb.php) */
136 protected $transformScript;
138 /** @var Title */
139 protected $redirectTitle;
141 /** @var bool Whether the output of transform() for this file is likely to be valid. */
142 protected $canRender;
144 /** @var bool Whether this media file is in a format that is unlikely to
145 * contain viruses or malicious content
147 protected $isSafeFile;
149 /** @var string Required Repository class type */
150 protected $repoClass = 'FileRepo';
152 /** @var array Cache of tmp filepaths pointing to generated bucket thumbnails, keyed by width */
153 protected $tmpBucketedThumbCache = array();
156 * Call this constructor from child classes.
158 * Both $title and $repo are optional, though some functions
159 * may return false or throw exceptions if they are not set.
160 * Most subclasses will want to call assertRepoDefined() here.
162 * @param Title|string|bool $title
163 * @param FileRepo|bool $repo
165 function __construct( $title, $repo ) {
166 if ( $title !== false ) { // subclasses may not use MW titles
167 $title = self::normalizeTitle( $title, 'exception' );
169 $this->title = $title;
170 $this->repo = $repo;
174 * Given a string or Title object return either a
175 * valid Title object with namespace NS_FILE or null
177 * @param Title|string $title
178 * @param string|bool $exception Use 'exception' to throw an error on bad titles
179 * @throws MWException
180 * @return Title|null
182 static function normalizeTitle( $title, $exception = false ) {
183 $ret = $title;
184 if ( $ret instanceof Title ) {
185 # Normalize NS_MEDIA -> NS_FILE
186 if ( $ret->getNamespace() == NS_MEDIA ) {
187 $ret = Title::makeTitleSafe( NS_FILE, $ret->getDBkey() );
188 # Sanity check the title namespace
189 } elseif ( $ret->getNamespace() !== NS_FILE ) {
190 $ret = null;
192 } else {
193 # Convert strings to Title objects
194 $ret = Title::makeTitleSafe( NS_FILE, (string)$ret );
196 if ( !$ret && $exception !== false ) {
197 throw new MWException( "`$title` is not a valid file title." );
200 return $ret;
203 function __get( $name ) {
204 $function = array( $this, 'get' . ucfirst( $name ) );
205 if ( !is_callable( $function ) ) {
206 return null;
207 } else {
208 $this->$name = call_user_func( $function );
210 return $this->$name;
215 * Normalize a file extension to the common form, and ensure it's clean.
216 * Extensions with non-alphanumeric characters will be discarded.
218 * @param string $ext (without the .)
219 * @return string
221 static function normalizeExtension( $ext ) {
222 $lower = strtolower( $ext );
223 $squish = array(
224 'htm' => 'html',
225 'jpeg' => 'jpg',
226 'mpeg' => 'mpg',
227 'tiff' => 'tif',
228 'ogv' => 'ogg' );
229 if ( isset( $squish[$lower] ) ) {
230 return $squish[$lower];
231 } elseif ( preg_match( '/^[0-9a-z]+$/', $lower ) ) {
232 return $lower;
233 } else {
234 return '';
239 * Checks if file extensions are compatible
241 * @param File $old Old file
242 * @param string $new New name
244 * @return bool|null
246 static function checkExtensionCompatibility( File $old, $new ) {
247 $oldMime = $old->getMimeType();
248 $n = strrpos( $new, '.' );
249 $newExt = self::normalizeExtension( $n ? substr( $new, $n + 1 ) : '' );
250 $mimeMagic = MimeMagic::singleton();
252 return $mimeMagic->isMatchingExtension( $newExt, $oldMime );
256 * Upgrade the database row if there is one
257 * Called by ImagePage
258 * STUB
260 function upgradeRow() {
264 * Split an internet media type into its two components; if not
265 * a two-part name, set the minor type to 'unknown'.
267 * @param string $mime "text/html" etc
268 * @return array ("text", "html") etc
270 public static function splitMime( $mime ) {
271 if ( strpos( $mime, '/' ) !== false ) {
272 return explode( '/', $mime, 2 );
273 } else {
274 return array( $mime, 'unknown' );
279 * Callback for usort() to do file sorts by name
281 * @param File $a
282 * @param File $b
283 * @return int Result of name comparison
285 public static function compare( File $a, File $b ) {
286 return strcmp( $a->getName(), $b->getName() );
290 * Return the name of this file
292 * @return string
294 public function getName() {
295 if ( !isset( $this->name ) ) {
296 $this->assertRepoDefined();
297 $this->name = $this->repo->getNameFromTitle( $this->title );
300 return $this->name;
304 * Get the file extension, e.g. "svg"
306 * @return string
308 function getExtension() {
309 if ( !isset( $this->extension ) ) {
310 $n = strrpos( $this->getName(), '.' );
311 $this->extension = self::normalizeExtension(
312 $n ? substr( $this->getName(), $n + 1 ) : '' );
315 return $this->extension;
319 * Return the associated title object
321 * @return Title
323 public function getTitle() {
324 return $this->title;
328 * Return the title used to find this file
330 * @return Title
332 public function getOriginalTitle() {
333 if ( $this->redirected ) {
334 return $this->getRedirectedTitle();
337 return $this->title;
341 * Return the URL of the file
343 * @return string
345 public function getUrl() {
346 if ( !isset( $this->url ) ) {
347 $this->assertRepoDefined();
348 $ext = $this->getExtension();
349 $this->url = $this->repo->getZoneUrl( 'public', $ext ) . '/' . $this->getUrlRel();
352 return $this->url;
356 * Return a fully-qualified URL to the file.
357 * Upload URL paths _may or may not_ be fully qualified, so
358 * we check. Local paths are assumed to belong on $wgServer.
360 * @return string
362 public function getFullUrl() {
363 return wfExpandUrl( $this->getUrl(), PROTO_RELATIVE );
367 * @return string
369 public function getCanonicalUrl() {
370 return wfExpandUrl( $this->getUrl(), PROTO_CANONICAL );
374 * @return string
376 function getViewURL() {
377 if ( $this->mustRender() ) {
378 if ( $this->canRender() ) {
379 return $this->createThumb( $this->getWidth() );
380 } else {
381 wfDebug( __METHOD__ . ': supposed to render ' . $this->getName() .
382 ' (' . $this->getMimeType() . "), but can't!\n" );
384 return $this->getURL(); #hm... return NULL?
386 } else {
387 return $this->getURL();
392 * Return the storage path to the file. Note that this does
393 * not mean that a file actually exists under that location.
395 * This path depends on whether directory hashing is active or not,
396 * i.e. whether the files are all found in the same directory,
397 * or in hashed paths like /images/3/3c.
399 * Most callers don't check the return value, but ForeignAPIFile::getPath
400 * returns false.
402 * @return string|bool ForeignAPIFile::getPath can return false
404 public function getPath() {
405 if ( !isset( $this->path ) ) {
406 $this->assertRepoDefined();
407 $this->path = $this->repo->getZonePath( 'public' ) . '/' . $this->getRel();
410 return $this->path;
414 * Get an FS copy or original of this file and return the path.
415 * Returns false on failure. Callers must not alter the file.
416 * Temporary files are cleared automatically.
418 * @return string|bool False on failure
420 public function getLocalRefPath() {
421 $this->assertRepoDefined();
422 if ( !isset( $this->fsFile ) ) {
423 $this->fsFile = $this->repo->getLocalReference( $this->getPath() );
424 if ( !$this->fsFile ) {
425 $this->fsFile = false; // null => false; cache negative hits
429 return ( $this->fsFile )
430 ? $this->fsFile->getPath()
431 : false;
435 * Return the width of the image. Returns false if the width is unknown
436 * or undefined.
438 * STUB
439 * Overridden by LocalFile, UnregisteredLocalFile
441 * @param int $page
442 * @return int|bool
444 public function getWidth( $page = 1 ) {
445 return false;
449 * Return the height of the image. Returns false if the height is unknown
450 * or undefined
452 * STUB
453 * Overridden by LocalFile, UnregisteredLocalFile
455 * @param int $page
456 * @return bool|int False on failure
458 public function getHeight( $page = 1 ) {
459 return false;
463 * Return the smallest bucket from $wgThumbnailBuckets which is at least
464 * $wgThumbnailMinimumBucketDistance larger than $desiredWidth. The returned bucket, if any,
465 * will always be bigger than $desiredWidth.
467 * @param int $desiredWidth
468 * @param int $page
469 * @return bool|int
471 public function getThumbnailBucket( $desiredWidth, $page = 1 ) {
472 global $wgThumbnailBuckets, $wgThumbnailMinimumBucketDistance;
474 $imageWidth = $this->getWidth( $page );
476 if ( $imageWidth === false ) {
477 return false;
480 if ( $desiredWidth > $imageWidth ) {
481 return false;
484 if ( !$wgThumbnailBuckets ) {
485 return false;
488 $sortedBuckets = $wgThumbnailBuckets;
490 sort( $sortedBuckets );
492 foreach ( $sortedBuckets as $bucket ) {
493 if ( $bucket >= $imageWidth ) {
494 return false;
497 if ( $bucket - $wgThumbnailMinimumBucketDistance > $desiredWidth ) {
498 return $bucket;
502 // Image is bigger than any available bucket
503 return false;
507 * Returns ID or name of user who uploaded the file
508 * STUB
510 * @param string $type 'text' or 'id'
511 * @return string|int
513 public function getUser( $type = 'text' ) {
514 return null;
518 * Get the duration of a media file in seconds
520 * @return int
522 public function getLength() {
523 $handler = $this->getHandler();
524 if ( $handler ) {
525 return $handler->getLength( $this );
526 } else {
527 return 0;
532 * Return true if the file is vectorized
534 * @return bool
536 public function isVectorized() {
537 $handler = $this->getHandler();
538 if ( $handler ) {
539 return $handler->isVectorized( $this );
540 } else {
541 return false;
546 * Gives a (possibly empty) list of languages to render
547 * the file in.
549 * If the file doesn't have translations, or if the file
550 * format does not support that sort of thing, returns
551 * an empty array.
553 * @return array
554 * @since 1.23
556 public function getAvailableLanguages() {
557 $handler = $this->getHandler();
558 if ( $handler ) {
559 return $handler->getAvailableLanguages( $this );
560 } else {
561 return array();
566 * In files that support multiple language, what is the default language
567 * to use if none specified.
569 * @return string Lang code, or null if filetype doesn't support multiple languages.
570 * @since 1.23
572 public function getDefaultRenderLanguage() {
573 $handler = $this->getHandler();
574 if ( $handler ) {
575 return $handler->getDefaultRenderLanguage( $this );
576 } else {
577 return null;
582 * Will the thumbnail be animated if one would expect it to be.
584 * Currently used to add a warning to the image description page
586 * @return bool False if the main image is both animated
587 * and the thumbnail is not. In all other cases must return
588 * true. If image is not renderable whatsoever, should
589 * return true.
591 public function canAnimateThumbIfAppropriate() {
592 $handler = $this->getHandler();
593 if ( !$handler ) {
594 // We cannot handle image whatsoever, thus
595 // one would not expect it to be animated
596 // so true.
597 return true;
598 } else {
599 if ( $this->allowInlineDisplay()
600 && $handler->isAnimatedImage( $this )
601 && !$handler->canAnimateThumbnail( $this )
603 // Image is animated, but thumbnail isn't.
604 // This is unexpected to the user.
605 return false;
606 } else {
607 // Image is not animated, so one would
608 // not expect thumb to be
609 return true;
615 * Get handler-specific metadata
616 * Overridden by LocalFile, UnregisteredLocalFile
617 * STUB
618 * @return bool|array
620 public function getMetadata() {
621 return false;
625 * Like getMetadata but returns a handler independent array of common values.
626 * @see MediaHandler::getCommonMetaArray()
627 * @return array|bool Array or false if not supported
628 * @since 1.23
630 public function getCommonMetaArray() {
631 $handler = $this->getHandler();
633 if ( !$handler ) {
634 return false;
637 return $handler->getCommonMetaArray( $this );
641 * get versioned metadata
643 * @param array|string $metadata Array or string of (serialized) metadata
644 * @param int $version Version number.
645 * @return array Array containing metadata, or what was passed to it on fail
646 * (unserializing if not array)
648 public function convertMetadataVersion( $metadata, $version ) {
649 $handler = $this->getHandler();
650 if ( !is_array( $metadata ) ) {
651 // Just to make the return type consistent
652 $metadata = unserialize( $metadata );
654 if ( $handler ) {
655 return $handler->convertMetadataVersion( $metadata, $version );
656 } else {
657 return $metadata;
662 * Return the bit depth of the file
663 * Overridden by LocalFile
664 * STUB
665 * @return int
667 public function getBitDepth() {
668 return 0;
672 * Return the size of the image file, in bytes
673 * Overridden by LocalFile, UnregisteredLocalFile
674 * STUB
675 * @return bool
677 public function getSize() {
678 return false;
682 * Returns the MIME type of the file.
683 * Overridden by LocalFile, UnregisteredLocalFile
684 * STUB
686 * @return string
688 function getMimeType() {
689 return 'unknown/unknown';
693 * Return the type of the media in the file.
694 * Use the value returned by this function with the MEDIATYPE_xxx constants.
695 * Overridden by LocalFile,
696 * STUB
697 * @return string
699 function getMediaType() {
700 return MEDIATYPE_UNKNOWN;
704 * Checks if the output of transform() for this file is likely
705 * to be valid. If this is false, various user elements will
706 * display a placeholder instead.
708 * Currently, this checks if the file is an image format
709 * that can be converted to a format
710 * supported by all browsers (namely GIF, PNG and JPEG),
711 * or if it is an SVG image and SVG conversion is enabled.
713 * @return bool
715 function canRender() {
716 if ( !isset( $this->canRender ) ) {
717 $this->canRender = $this->getHandler() && $this->handler->canRender( $this ) && $this->exists();
720 return $this->canRender;
724 * Accessor for __get()
725 * @return bool
727 protected function getCanRender() {
728 return $this->canRender();
732 * Return true if the file is of a type that can't be directly
733 * rendered by typical browsers and needs to be re-rasterized.
735 * This returns true for everything but the bitmap types
736 * supported by all browsers, i.e. JPEG; GIF and PNG. It will
737 * also return true for any non-image formats.
739 * @return bool
741 function mustRender() {
742 return $this->getHandler() && $this->handler->mustRender( $this );
746 * Alias for canRender()
748 * @return bool
750 function allowInlineDisplay() {
751 return $this->canRender();
755 * Determines if this media file is in a format that is unlikely to
756 * contain viruses or malicious content. It uses the global
757 * $wgTrustedMediaFormats list to determine if the file is safe.
759 * This is used to show a warning on the description page of non-safe files.
760 * It may also be used to disallow direct [[media:...]] links to such files.
762 * Note that this function will always return true if allowInlineDisplay()
763 * or isTrustedFile() is true for this file.
765 * @return bool
767 function isSafeFile() {
768 if ( !isset( $this->isSafeFile ) ) {
769 $this->isSafeFile = $this->getIsSafeFileUncached();
772 return $this->isSafeFile;
776 * Accessor for __get()
778 * @return bool
780 protected function getIsSafeFile() {
781 return $this->isSafeFile();
785 * Uncached accessor
787 * @return bool
789 protected function getIsSafeFileUncached() {
790 global $wgTrustedMediaFormats;
792 if ( $this->allowInlineDisplay() ) {
793 return true;
795 if ( $this->isTrustedFile() ) {
796 return true;
799 $type = $this->getMediaType();
800 $mime = $this->getMimeType();
801 #wfDebug( "LocalFile::isSafeFile: type= $type, mime= $mime\n" );
803 if ( !$type || $type === MEDIATYPE_UNKNOWN ) {
804 return false; #unknown type, not trusted
806 if ( in_array( $type, $wgTrustedMediaFormats ) ) {
807 return true;
810 if ( $mime === "unknown/unknown" ) {
811 return false; #unknown type, not trusted
813 if ( in_array( $mime, $wgTrustedMediaFormats ) ) {
814 return true;
817 return false;
821 * Returns true if the file is flagged as trusted. Files flagged that way
822 * can be linked to directly, even if that is not allowed for this type of
823 * file normally.
825 * This is a dummy function right now and always returns false. It could be
826 * implemented to extract a flag from the database. The trusted flag could be
827 * set on upload, if the user has sufficient privileges, to bypass script-
828 * and html-filters. It may even be coupled with cryptographics signatures
829 * or such.
831 * @return bool
833 function isTrustedFile() {
834 #this could be implemented to check a flag in the database,
835 #look for signatures, etc
836 return false;
840 * Returns true if file exists in the repository.
842 * Overridden by LocalFile to avoid unnecessary stat calls.
844 * @return bool Whether file exists in the repository.
846 public function exists() {
847 return $this->getPath() && $this->repo->fileExists( $this->path );
851 * Returns true if file exists in the repository and can be included in a page.
852 * It would be unsafe to include private images, making public thumbnails inadvertently
854 * @return bool Whether file exists in the repository and is includable.
856 public function isVisible() {
857 return $this->exists();
861 * @return string
863 function getTransformScript() {
864 if ( !isset( $this->transformScript ) ) {
865 $this->transformScript = false;
866 if ( $this->repo ) {
867 $script = $this->repo->getThumbScriptUrl();
868 if ( $script ) {
869 $this->transformScript = wfAppendQuery( $script, array( 'f' => $this->getName() ) );
874 return $this->transformScript;
878 * Get a ThumbnailImage which is the same size as the source
880 * @param array $handlerParams
882 * @return string
884 function getUnscaledThumb( $handlerParams = array() ) {
885 $hp =& $handlerParams;
886 $page = isset( $hp['page'] ) ? $hp['page'] : false;
887 $width = $this->getWidth( $page );
888 if ( !$width ) {
889 return $this->iconThumb();
891 $hp['width'] = $width;
892 // be sure to ignore any height specification as well (bug 62258)
893 unset( $hp['height'] );
895 return $this->transform( $hp );
899 * Return the file name of a thumbnail with the specified parameters.
900 * Use File::THUMB_FULL_NAME to always get a name like "<params>-<source>".
901 * Otherwise, the format may be "<params>-<source>" or "<params>-thumbnail.<ext>".
903 * @param array $params Handler-specific parameters
904 * @param int $flags Bitfield that supports THUMB_* constants
905 * @return string
907 public function thumbName( $params, $flags = 0 ) {
908 $name = ( $this->repo && !( $flags & self::THUMB_FULL_NAME ) )
909 ? $this->repo->nameForThumb( $this->getName() )
910 : $this->getName();
912 return $this->generateThumbName( $name, $params );
916 * Generate a thumbnail file name from a name and specified parameters
918 * @param string $name
919 * @param array $params Parameters which will be passed to MediaHandler::makeParamString
920 * @return string
922 public function generateThumbName( $name, $params ) {
923 if ( !$this->getHandler() ) {
924 return null;
926 $extension = $this->getExtension();
927 list( $thumbExt, ) = $this->getHandler()->getThumbType(
928 $extension, $this->getMimeType(), $params );
929 $thumbName = $this->getHandler()->makeParamString( $params ) . '-' . $name;
930 if ( $thumbExt != $extension ) {
931 $thumbName .= ".$thumbExt";
934 return $thumbName;
938 * Create a thumbnail of the image having the specified width/height.
939 * The thumbnail will not be created if the width is larger than the
940 * image's width. Let the browser do the scaling in this case.
941 * The thumbnail is stored on disk and is only computed if the thumbnail
942 * file does not exist OR if it is older than the image.
943 * Returns the URL.
945 * Keeps aspect ratio of original image. If both width and height are
946 * specified, the generated image will be no bigger than width x height,
947 * and will also have correct aspect ratio.
949 * @param int $width Maximum width of the generated thumbnail
950 * @param int $height Maximum height of the image (optional)
952 * @return string
954 public function createThumb( $width, $height = -1 ) {
955 $params = array( 'width' => $width );
956 if ( $height != -1 ) {
957 $params['height'] = $height;
959 $thumb = $this->transform( $params );
960 if ( !$thumb || $thumb->isError() ) {
961 return '';
964 return $thumb->getUrl();
968 * Return either a MediaTransformError or placeholder thumbnail (if $wgIgnoreImageErrors)
970 * @param string $thumbPath Thumbnail storage path
971 * @param string $thumbUrl Thumbnail URL
972 * @param array $params
973 * @param int $flags
974 * @return MediaTransformOutput
976 protected function transformErrorOutput( $thumbPath, $thumbUrl, $params, $flags ) {
977 global $wgIgnoreImageErrors;
979 $handler = $this->getHandler();
980 if ( $handler && $wgIgnoreImageErrors && !( $flags & self::RENDER_NOW ) ) {
981 return $handler->getTransform( $this, $thumbPath, $thumbUrl, $params );
982 } else {
983 return new MediaTransformError( 'thumbnail_error',
984 $params['width'], 0, wfMessage( 'thumbnail-dest-create' )->text() );
989 * Transform a media file
991 * @param array $params An associative array of handler-specific parameters.
992 * Typical keys are width, height and page.
993 * @param int $flags A bitfield, may contain self::RENDER_NOW to force rendering
994 * @return MediaTransformOutput|bool False on failure
996 function transform( $params, $flags = 0 ) {
997 global $wgThumbnailEpoch;
999 do {
1000 if ( !$this->canRender() ) {
1001 $thumb = $this->iconThumb();
1002 break; // not a bitmap or renderable image, don't try
1005 // Get the descriptionUrl to embed it as comment into the thumbnail. Bug 19791.
1006 $descriptionUrl = $this->getDescriptionUrl();
1007 if ( $descriptionUrl ) {
1008 $params['descriptionUrl'] = wfExpandUrl( $descriptionUrl, PROTO_CANONICAL );
1011 $handler = $this->getHandler();
1012 $script = $this->getTransformScript();
1013 if ( $script && !( $flags & self::RENDER_NOW ) ) {
1014 // Use a script to transform on client request, if possible
1015 $thumb = $handler->getScriptedTransform( $this, $script, $params );
1016 if ( $thumb ) {
1017 break;
1021 $normalisedParams = $params;
1022 $handler->normaliseParams( $this, $normalisedParams );
1024 $thumbName = $this->thumbName( $normalisedParams );
1025 $thumbUrl = $this->getThumbUrl( $thumbName );
1026 $thumbPath = $this->getThumbPath( $thumbName ); // final thumb path
1028 if ( $this->repo ) {
1029 // Defer rendering if a 404 handler is set up...
1030 if ( $this->repo->canTransformVia404() && !( $flags & self::RENDER_NOW ) ) {
1031 wfDebug( __METHOD__ . " transformation deferred.\n" );
1032 // XXX: Pass in the storage path even though we are not rendering anything
1033 // and the path is supposed to be an FS path. This is due to getScalerType()
1034 // getting called on the path and clobbering $thumb->getUrl() if it's false.
1035 $thumb = $handler->getTransform( $this, $thumbPath, $thumbUrl, $params );
1036 break;
1038 // Check if an up-to-date thumbnail already exists...
1039 wfDebug( __METHOD__ . ": Doing stat for $thumbPath\n" );
1040 if ( !( $flags & self::RENDER_FORCE ) && $this->repo->fileExists( $thumbPath ) ) {
1041 $timestamp = $this->repo->getFileTimestamp( $thumbPath );
1042 if ( $timestamp !== false && $timestamp >= $wgThumbnailEpoch ) {
1043 // XXX: Pass in the storage path even though we are not rendering anything
1044 // and the path is supposed to be an FS path. This is due to getScalerType()
1045 // getting called on the path and clobbering $thumb->getUrl() if it's false.
1046 $thumb = $handler->getTransform( $this, $thumbPath, $thumbUrl, $params );
1047 $thumb->setStoragePath( $thumbPath );
1048 break;
1050 } elseif ( $flags & self::RENDER_FORCE ) {
1051 wfDebug( __METHOD__ . " forcing rendering per flag File::RENDER_FORCE\n" );
1054 // If the backend is ready-only, don't keep generating thumbnails
1055 // only to return transformation errors, just return the error now.
1056 if ( $this->repo->getReadOnlyReason() !== false ) {
1057 $thumb = $this->transformErrorOutput( $thumbPath, $thumbUrl, $params, $flags );
1058 break;
1062 $tmpFile = $this->makeTransformTmpFile( $thumbPath );
1064 if ( !$tmpFile ) {
1065 $thumb = $this->transformErrorOutput( $thumbPath, $thumbUrl, $params, $flags );
1066 } else {
1067 $thumb = $this->generateAndSaveThumb( $tmpFile, $params, $flags );
1069 } while ( false );
1071 return is_object( $thumb ) ? $thumb : false;
1075 * Generates a thumbnail according to the given parameters and saves it to storage
1076 * @param TempFSFile $tmpFile Temporary file where the rendered thumbnail will be saved
1077 * @param array $transformParams
1078 * @param int $flags
1079 * @return bool|MediaTransformOutput
1081 public function generateAndSaveThumb( $tmpFile, $transformParams, $flags ) {
1082 global $wgUseSquid, $wgIgnoreImageErrors;
1084 $handler = $this->getHandler();
1086 $normalisedParams = $transformParams;
1087 $handler->normaliseParams( $this, $normalisedParams );
1089 $thumbName = $this->thumbName( $normalisedParams );
1090 $thumbUrl = $this->getThumbUrl( $thumbName );
1091 $thumbPath = $this->getThumbPath( $thumbName ); // final thumb path
1093 $tmpThumbPath = $tmpFile->getPath();
1095 if ( $handler->supportsBucketing() ) {
1096 $this->generateBucketsIfNeeded( $normalisedParams, $flags );
1099 // Actually render the thumbnail...
1100 $thumb = $handler->doTransform( $this, $tmpThumbPath, $thumbUrl, $transformParams );
1101 $tmpFile->bind( $thumb ); // keep alive with $thumb
1103 if ( !$thumb ) { // bad params?
1104 $thumb = false;
1105 } elseif ( $thumb->isError() ) { // transform error
1106 $this->lastError = $thumb->toText();
1107 // Ignore errors if requested
1108 if ( $wgIgnoreImageErrors && !( $flags & self::RENDER_NOW ) ) {
1109 $thumb = $handler->getTransform( $this, $tmpThumbPath, $thumbUrl, $transformParams );
1111 } elseif ( $this->repo && $thumb->hasFile() && !$thumb->fileIsSource() ) {
1112 // Copy the thumbnail from the file system into storage...
1113 $disposition = $this->getThumbDisposition( $thumbName );
1114 $status = $this->repo->quickImport( $tmpThumbPath, $thumbPath, $disposition );
1115 if ( $status->isOK() ) {
1116 $thumb->setStoragePath( $thumbPath );
1117 } else {
1118 $thumb = $this->transformErrorOutput( $thumbPath, $thumbUrl, $transformParams, $flags );
1120 // Give extensions a chance to do something with this thumbnail...
1121 Hooks::run( 'FileTransformed', array( $this, $thumb, $tmpThumbPath, $thumbPath ) );
1124 // Purge. Useful in the event of Core -> Squid connection failure or squid
1125 // purge collisions from elsewhere during failure. Don't keep triggering for
1126 // "thumbs" which have the main image URL though (bug 13776)
1127 if ( $wgUseSquid ) {
1128 if ( !$thumb || $thumb->isError() || $thumb->getUrl() != $this->getURL() ) {
1129 SquidUpdate::purge( array( $thumbUrl ) );
1133 return $thumb;
1137 * Generates chained bucketed thumbnails if needed
1138 * @param array $params
1139 * @param int $flags
1140 * @return bool Whether at least one bucket was generated
1142 protected function generateBucketsIfNeeded( $params, $flags = 0 ) {
1143 if ( !$this->repo
1144 || !isset( $params['physicalWidth'] )
1145 || !isset( $params['physicalHeight'] )
1146 || !( $bucket = $this->getThumbnailBucket( $params['physicalWidth'] ) )
1147 || $bucket == $params['physicalWidth'] ) {
1148 return false;
1151 $bucketPath = $this->getBucketThumbPath( $bucket );
1153 if ( $this->repo->fileExists( $bucketPath ) ) {
1154 return false;
1157 $params['physicalWidth'] = $bucket;
1158 $params['width'] = $bucket;
1160 $params = $this->getHandler()->sanitizeParamsForBucketing( $params );
1162 $bucketName = $this->getBucketThumbName( $bucket );
1164 $tmpFile = $this->makeTransformTmpFile( $bucketPath );
1166 if ( !$tmpFile ) {
1167 return false;
1170 $thumb = $this->generateAndSaveThumb( $tmpFile, $params, $flags );
1172 if ( !$thumb || $thumb->isError() ) {
1173 return false;
1176 $this->tmpBucketedThumbCache[$bucket] = $tmpFile->getPath();
1177 // For the caching to work, we need to make the tmp file survive as long as
1178 // this object exists
1179 $tmpFile->bind( $this );
1181 return true;
1185 * Returns the most appropriate source image for the thumbnail, given a target thumbnail size
1186 * @param array $params
1187 * @return array Source path and width/height of the source
1189 public function getThumbnailSource( $params ) {
1190 if ( $this->repo
1191 && $this->getHandler()->supportsBucketing()
1192 && isset( $params['physicalWidth'] )
1193 && $bucket = $this->getThumbnailBucket( $params['physicalWidth'] )
1195 if ( $this->getWidth() != 0 ) {
1196 $bucketHeight = round( $this->getHeight() * ( $bucket / $this->getWidth() ) );
1197 } else {
1198 $bucketHeight = 0;
1201 // Try to avoid reading from storage if the file was generated by this script
1202 if ( isset( $this->tmpBucketedThumbCache[$bucket] ) ) {
1203 $tmpPath = $this->tmpBucketedThumbCache[$bucket];
1205 if ( file_exists( $tmpPath ) ) {
1206 return array(
1207 'path' => $tmpPath,
1208 'width' => $bucket,
1209 'height' => $bucketHeight
1214 $bucketPath = $this->getBucketThumbPath( $bucket );
1216 if ( $this->repo->fileExists( $bucketPath ) ) {
1217 $fsFile = $this->repo->getLocalReference( $bucketPath );
1219 if ( $fsFile ) {
1220 return array(
1221 'path' => $fsFile->getPath(),
1222 'width' => $bucket,
1223 'height' => $bucketHeight
1229 // Thumbnailing a very large file could result in network saturation if
1230 // everyone does it at once.
1231 if ( $this->getSize() >= 1e7 ) { // 10MB
1232 $that = $this;
1233 $work = new PoolCounterWorkViaCallback( 'GetLocalFileCopy', sha1( $this->getName() ),
1234 array(
1235 'doWork' => function () use ( $that ) {
1236 return $that->getLocalRefPath();
1240 $srcPath = $work->execute();
1241 } else {
1242 $srcPath = $this->getLocalRefPath();
1245 // Original file
1246 return array(
1247 'path' => $srcPath,
1248 'width' => $this->getWidth(),
1249 'height' => $this->getHeight()
1254 * Returns the repo path of the thumb for a given bucket
1255 * @param int $bucket
1256 * @return string
1258 protected function getBucketThumbPath( $bucket ) {
1259 $thumbName = $this->getBucketThumbName( $bucket );
1260 return $this->getThumbPath( $thumbName );
1264 * Returns the name of the thumb for a given bucket
1265 * @param int $bucket
1266 * @return string
1268 protected function getBucketThumbName( $bucket ) {
1269 return $this->thumbName( array( 'physicalWidth' => $bucket ) );
1273 * Creates a temp FS file with the same extension and the thumbnail
1274 * @param string $thumbPath Thumbnail path
1275 * @return TempFSFile
1277 protected function makeTransformTmpFile( $thumbPath ) {
1278 $thumbExt = FileBackend::extensionFromPath( $thumbPath );
1279 return TempFSFile::factory( 'transform_', $thumbExt );
1283 * @param string $thumbName Thumbnail name
1284 * @param string $dispositionType Type of disposition (either "attachment" or "inline")
1285 * @return string Content-Disposition header value
1287 function getThumbDisposition( $thumbName, $dispositionType = 'inline' ) {
1288 $fileName = $this->name; // file name to suggest
1289 $thumbExt = FileBackend::extensionFromPath( $thumbName );
1290 if ( $thumbExt != '' && $thumbExt !== $this->getExtension() ) {
1291 $fileName .= ".$thumbExt";
1294 return FileBackend::makeContentDisposition( $dispositionType, $fileName );
1298 * Hook into transform() to allow migration of thumbnail files
1299 * STUB
1300 * Overridden by LocalFile
1301 * @param string $thumbName
1303 function migrateThumbFile( $thumbName ) {
1307 * Get a MediaHandler instance for this file
1309 * @return MediaHandler|bool Registered MediaHandler for file's MIME type
1310 * or false if none found
1312 function getHandler() {
1313 if ( !isset( $this->handler ) ) {
1314 $this->handler = MediaHandler::getHandler( $this->getMimeType() );
1317 return $this->handler;
1321 * Get a ThumbnailImage representing a file type icon
1323 * @return ThumbnailImage
1325 function iconThumb() {
1326 global $wgResourceBasePath, $IP;
1327 $assetsPath = "$wgResourceBasePath/resources/assets/file-type-icons/";
1328 $assetsDirectory = "$IP/resources/assets/file-type-icons/";
1330 $try = array( 'fileicon-' . $this->getExtension() . '.png', 'fileicon.png' );
1331 foreach ( $try as $icon ) {
1332 if ( file_exists( $assetsDirectory . $icon ) ) { // always FS
1333 $params = array( 'width' => 120, 'height' => 120 );
1335 return new ThumbnailImage( $this, $assetsPath . $icon, false, $params );
1339 return null;
1343 * Get last thumbnailing error.
1344 * Largely obsolete.
1345 * @return string
1347 function getLastError() {
1348 return $this->lastError;
1352 * Get all thumbnail names previously generated for this file
1353 * STUB
1354 * Overridden by LocalFile
1355 * @return array
1357 function getThumbnails() {
1358 return array();
1362 * Purge shared caches such as thumbnails and DB data caching
1363 * STUB
1364 * Overridden by LocalFile
1365 * @param array $options Options, which include:
1366 * 'forThumbRefresh' : The purging is only to refresh thumbnails
1368 function purgeCache( $options = array() ) {
1372 * Purge the file description page, but don't go after
1373 * pages using the file. Use when modifying file history
1374 * but not the current data.
1376 function purgeDescription() {
1377 $title = $this->getTitle();
1378 if ( $title ) {
1379 $title->invalidateCache();
1380 $title->purgeSquid();
1385 * Purge metadata and all affected pages when the file is created,
1386 * deleted, or majorly updated.
1388 function purgeEverything() {
1389 // Delete thumbnails and refresh file metadata cache
1390 $this->purgeCache();
1391 $this->purgeDescription();
1393 // Purge cache of all pages using this file
1394 $title = $this->getTitle();
1395 if ( $title ) {
1396 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
1397 $update->doUpdate();
1402 * Return a fragment of the history of file.
1404 * STUB
1405 * @param int $limit Limit of rows to return
1406 * @param string $start Only revisions older than $start will be returned
1407 * @param string $end Only revisions newer than $end will be returned
1408 * @param bool $inc Include the endpoints of the time range
1410 * @return array
1412 function getHistory( $limit = null, $start = null, $end = null, $inc = true ) {
1413 return array();
1417 * Return the history of this file, line by line. Starts with current version,
1418 * then old versions. Should return an object similar to an image/oldimage
1419 * database row.
1421 * STUB
1422 * Overridden in LocalFile
1423 * @return bool
1425 public function nextHistoryLine() {
1426 return false;
1430 * Reset the history pointer to the first element of the history.
1431 * Always call this function after using nextHistoryLine() to free db resources
1432 * STUB
1433 * Overridden in LocalFile.
1435 public function resetHistory() {
1439 * Get the filename hash component of the directory including trailing slash,
1440 * e.g. f/fa/
1441 * If the repository is not hashed, returns an empty string.
1443 * @return string
1445 function getHashPath() {
1446 if ( !isset( $this->hashPath ) ) {
1447 $this->assertRepoDefined();
1448 $this->hashPath = $this->repo->getHashPath( $this->getName() );
1451 return $this->hashPath;
1455 * Get the path of the file relative to the public zone root.
1456 * This function is overridden in OldLocalFile to be like getArchiveRel().
1458 * @return string
1460 function getRel() {
1461 return $this->getHashPath() . $this->getName();
1465 * Get the path of an archived file relative to the public zone root
1467 * @param bool|string $suffix If not false, the name of an archived thumbnail file
1469 * @return string
1471 function getArchiveRel( $suffix = false ) {
1472 $path = 'archive/' . $this->getHashPath();
1473 if ( $suffix === false ) {
1474 $path = substr( $path, 0, -1 );
1475 } else {
1476 $path .= $suffix;
1479 return $path;
1483 * Get the path, relative to the thumbnail zone root, of the
1484 * thumbnail directory or a particular file if $suffix is specified
1486 * @param bool|string $suffix If not false, the name of a thumbnail file
1487 * @return string
1489 function getThumbRel( $suffix = false ) {
1490 $path = $this->getRel();
1491 if ( $suffix !== false ) {
1492 $path .= '/' . $suffix;
1495 return $path;
1499 * Get urlencoded path of the file relative to the public zone root.
1500 * This function is overridden in OldLocalFile to be like getArchiveUrl().
1502 * @return string
1504 function getUrlRel() {
1505 return $this->getHashPath() . rawurlencode( $this->getName() );
1509 * Get the path, relative to the thumbnail zone root, for an archived file's thumbs directory
1510 * or a specific thumb if the $suffix is given.
1512 * @param string $archiveName The timestamped name of an archived image
1513 * @param bool|string $suffix If not false, the name of a thumbnail file
1514 * @return string
1516 function getArchiveThumbRel( $archiveName, $suffix = false ) {
1517 $path = 'archive/' . $this->getHashPath() . $archiveName . "/";
1518 if ( $suffix === false ) {
1519 $path = substr( $path, 0, -1 );
1520 } else {
1521 $path .= $suffix;
1524 return $path;
1528 * Get the path of the archived file.
1530 * @param bool|string $suffix If not false, the name of an archived file.
1531 * @return string
1533 function getArchivePath( $suffix = false ) {
1534 $this->assertRepoDefined();
1536 return $this->repo->getZonePath( 'public' ) . '/' . $this->getArchiveRel( $suffix );
1540 * Get the path of an archived file's thumbs, or a particular thumb if $suffix is specified
1542 * @param string $archiveName The timestamped name of an archived image
1543 * @param bool|string $suffix If not false, the name of a thumbnail file
1544 * @return string
1546 function getArchiveThumbPath( $archiveName, $suffix = false ) {
1547 $this->assertRepoDefined();
1549 return $this->repo->getZonePath( 'thumb' ) . '/' .
1550 $this->getArchiveThumbRel( $archiveName, $suffix );
1554 * Get the path of the thumbnail directory, or a particular file if $suffix is specified
1556 * @param bool|string $suffix If not false, the name of a thumbnail file
1557 * @return string
1559 function getThumbPath( $suffix = false ) {
1560 $this->assertRepoDefined();
1562 return $this->repo->getZonePath( 'thumb' ) . '/' . $this->getThumbRel( $suffix );
1566 * Get the path of the transcoded directory, or a particular file if $suffix is specified
1568 * @param bool|string $suffix If not false, the name of a media file
1569 * @return string
1571 function getTranscodedPath( $suffix = false ) {
1572 $this->assertRepoDefined();
1574 return $this->repo->getZonePath( 'transcoded' ) . '/' . $this->getThumbRel( $suffix );
1578 * Get the URL of the archive directory, or a particular file if $suffix is specified
1580 * @param bool|string $suffix If not false, the name of an archived file
1581 * @return string
1583 function getArchiveUrl( $suffix = false ) {
1584 $this->assertRepoDefined();
1585 $ext = $this->getExtension();
1586 $path = $this->repo->getZoneUrl( 'public', $ext ) . '/archive/' . $this->getHashPath();
1587 if ( $suffix === false ) {
1588 $path = substr( $path, 0, -1 );
1589 } else {
1590 $path .= rawurlencode( $suffix );
1593 return $path;
1597 * Get the URL of the archived file's thumbs, or a particular thumb if $suffix is specified
1599 * @param string $archiveName The timestamped name of an archived image
1600 * @param bool|string $suffix If not false, the name of a thumbnail file
1601 * @return string
1603 function getArchiveThumbUrl( $archiveName, $suffix = false ) {
1604 $this->assertRepoDefined();
1605 $ext = $this->getExtension();
1606 $path = $this->repo->getZoneUrl( 'thumb', $ext ) . '/archive/' .
1607 $this->getHashPath() . rawurlencode( $archiveName ) . "/";
1608 if ( $suffix === false ) {
1609 $path = substr( $path, 0, -1 );
1610 } else {
1611 $path .= rawurlencode( $suffix );
1614 return $path;
1618 * Get the URL of the zone directory, or a particular file if $suffix is specified
1620 * @param string $zone Name of requested zone
1621 * @param bool|string $suffix If not false, the name of a file in zone
1622 * @return string Path
1624 function getZoneUrl( $zone, $suffix = false ) {
1625 $this->assertRepoDefined();
1626 $ext = $this->getExtension();
1627 $path = $this->repo->getZoneUrl( $zone, $ext ) . '/' . $this->getUrlRel();
1628 if ( $suffix !== false ) {
1629 $path .= '/' . rawurlencode( $suffix );
1632 return $path;
1636 * Get the URL of the thumbnail directory, or a particular file if $suffix is specified
1638 * @param bool|string $suffix If not false, the name of a thumbnail file
1639 * @return string Path
1641 function getThumbUrl( $suffix = false ) {
1642 return $this->getZoneUrl( 'thumb', $suffix );
1646 * Get the URL of the transcoded directory, or a particular file if $suffix is specified
1648 * @param bool|string $suffix If not false, the name of a media file
1649 * @return string Path
1651 function getTranscodedUrl( $suffix = false ) {
1652 return $this->getZoneUrl( 'transcoded', $suffix );
1656 * Get the public zone virtual URL for a current version source file
1658 * @param bool|string $suffix If not false, the name of a thumbnail file
1659 * @return string
1661 function getVirtualUrl( $suffix = false ) {
1662 $this->assertRepoDefined();
1663 $path = $this->repo->getVirtualUrl() . '/public/' . $this->getUrlRel();
1664 if ( $suffix !== false ) {
1665 $path .= '/' . rawurlencode( $suffix );
1668 return $path;
1672 * Get the public zone virtual URL for an archived version source file
1674 * @param bool|string $suffix If not false, the name of a thumbnail file
1675 * @return string
1677 function getArchiveVirtualUrl( $suffix = false ) {
1678 $this->assertRepoDefined();
1679 $path = $this->repo->getVirtualUrl() . '/public/archive/' . $this->getHashPath();
1680 if ( $suffix === false ) {
1681 $path = substr( $path, 0, -1 );
1682 } else {
1683 $path .= rawurlencode( $suffix );
1686 return $path;
1690 * Get the virtual URL for a thumbnail file or directory
1692 * @param bool|string $suffix If not false, the name of a thumbnail file
1693 * @return string
1695 function getThumbVirtualUrl( $suffix = false ) {
1696 $this->assertRepoDefined();
1697 $path = $this->repo->getVirtualUrl() . '/thumb/' . $this->getUrlRel();
1698 if ( $suffix !== false ) {
1699 $path .= '/' . rawurlencode( $suffix );
1702 return $path;
1706 * @return bool
1708 function isHashed() {
1709 $this->assertRepoDefined();
1711 return (bool)$this->repo->getHashLevels();
1715 * @throws MWException
1717 function readOnlyError() {
1718 throw new MWException( get_class( $this ) . ': write operations are not supported' );
1722 * Record a file upload in the upload log and the image table
1723 * STUB
1724 * Overridden by LocalFile
1725 * @param string $oldver
1726 * @param string $desc
1727 * @param string $license
1728 * @param string $copyStatus
1729 * @param string $source
1730 * @param bool $watch
1731 * @param string|bool $timestamp
1732 * @param null|User $user User object or null to use $wgUser
1733 * @return bool
1734 * @throws MWException
1736 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '',
1737 $watch = false, $timestamp = false, User $user = null
1739 $this->readOnlyError();
1743 * Move or copy a file to its public location. If a file exists at the
1744 * destination, move it to an archive. Returns a FileRepoStatus object with
1745 * the archive name in the "value" member on success.
1747 * The archive name should be passed through to recordUpload for database
1748 * registration.
1750 * Options to $options include:
1751 * - headers : name/value map of HTTP headers to use in response to GET/HEAD requests
1753 * @param string $srcPath Local filesystem path to the source image
1754 * @param int $flags A bitwise combination of:
1755 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1756 * @param array $options Optional additional parameters
1757 * @return FileRepoStatus On success, the value member contains the
1758 * archive name, or an empty string if it was a new file.
1760 * STUB
1761 * Overridden by LocalFile
1763 function publish( $srcPath, $flags = 0, array $options = array() ) {
1764 $this->readOnlyError();
1768 * @return bool
1770 function formatMetadata() {
1771 if ( !$this->getHandler() ) {
1772 return false;
1775 return $this->getHandler()->formatMetadata( $this, $this->getMetadata() );
1779 * Returns true if the file comes from the local file repository.
1781 * @return bool
1783 function isLocal() {
1784 return $this->repo && $this->repo->isLocal();
1788 * Returns the name of the repository.
1790 * @return string
1792 function getRepoName() {
1793 return $this->repo ? $this->repo->getName() : 'unknown';
1797 * Returns the repository
1799 * @return FileRepo|LocalRepo|bool
1801 function getRepo() {
1802 return $this->repo;
1806 * Returns true if the image is an old version
1807 * STUB
1809 * @return bool
1811 function isOld() {
1812 return false;
1816 * Is this file a "deleted" file in a private archive?
1817 * STUB
1819 * @param int $field One of DELETED_* bitfield constants
1820 * @return bool
1822 function isDeleted( $field ) {
1823 return false;
1827 * Return the deletion bitfield
1828 * STUB
1829 * @return int
1831 function getVisibility() {
1832 return 0;
1836 * Was this file ever deleted from the wiki?
1838 * @return bool
1840 function wasDeleted() {
1841 $title = $this->getTitle();
1843 return $title && $title->isDeletedQuick();
1847 * Move file to the new title
1849 * Move current, old version and all thumbnails
1850 * to the new filename. Old file is deleted.
1852 * Cache purging is done; checks for validity
1853 * and logging are caller's responsibility
1855 * @param Title $target New file name
1856 * @return FileRepoStatus
1858 function move( $target ) {
1859 $this->readOnlyError();
1863 * Delete all versions of the file.
1865 * Moves the files into an archive directory (or deletes them)
1866 * and removes the database rows.
1868 * Cache purging is done; logging is caller's responsibility.
1870 * @param string $reason
1871 * @param bool $suppress Hide content from sysops?
1872 * @param User|null $user
1873 * @return bool Boolean on success, false on some kind of failure
1874 * STUB
1875 * Overridden by LocalFile
1877 function delete( $reason, $suppress = false, $user = null ) {
1878 $this->readOnlyError();
1882 * Restore all or specified deleted revisions to the given file.
1883 * Permissions and logging are left to the caller.
1885 * May throw database exceptions on error.
1887 * @param array $versions Set of record ids of deleted items to restore,
1888 * or empty to restore all revisions.
1889 * @param bool $unsuppress Remove restrictions on content upon restoration?
1890 * @return int|bool The number of file revisions restored if successful,
1891 * or false on failure
1892 * STUB
1893 * Overridden by LocalFile
1895 function restore( $versions = array(), $unsuppress = false ) {
1896 $this->readOnlyError();
1900 * Returns 'true' if this file is a type which supports multiple pages,
1901 * e.g. DJVU or PDF. Note that this may be true even if the file in
1902 * question only has a single page.
1904 * @return bool
1906 function isMultipage() {
1907 return $this->getHandler() && $this->handler->isMultiPage( $this );
1911 * Returns the number of pages of a multipage document, or false for
1912 * documents which aren't multipage documents
1914 * @return bool|int
1916 function pageCount() {
1917 if ( !isset( $this->pageCount ) ) {
1918 if ( $this->getHandler() && $this->handler->isMultiPage( $this ) ) {
1919 $this->pageCount = $this->handler->pageCount( $this );
1920 } else {
1921 $this->pageCount = false;
1925 return $this->pageCount;
1929 * Calculate the height of a thumbnail using the source and destination width
1931 * @param int $srcWidth
1932 * @param int $srcHeight
1933 * @param int $dstWidth
1935 * @return int
1937 static function scaleHeight( $srcWidth, $srcHeight, $dstWidth ) {
1938 // Exact integer multiply followed by division
1939 if ( $srcWidth == 0 ) {
1940 return 0;
1941 } else {
1942 return round( $srcHeight * $dstWidth / $srcWidth );
1947 * Get an image size array like that returned by getImageSize(), or false if it
1948 * can't be determined. Loads the image size directly from the file ignoring caches.
1950 * @note Use getWidth()/getHeight() instead of this method unless you have a
1951 * a good reason. This method skips all caches.
1953 * @param string $filePath The path to the file (e.g. From getLocalPathRef() )
1954 * @return array The width, followed by height, with optionally more things after
1956 function getImageSize( $filePath ) {
1957 if ( !$this->getHandler() ) {
1958 return false;
1961 return $this->getHandler()->getImageSize( $this, $filePath );
1965 * Get the URL of the image description page. May return false if it is
1966 * unknown or not applicable.
1968 * @return string
1970 function getDescriptionUrl() {
1971 if ( $this->repo ) {
1972 return $this->repo->getDescriptionUrl( $this->getName() );
1973 } else {
1974 return false;
1979 * Get the HTML text of the description page, if available
1981 * @param bool|Language $lang Optional language to fetch description in
1982 * @return string
1984 function getDescriptionText( $lang = false ) {
1985 global $wgMemc, $wgLang;
1986 if ( !$this->repo || !$this->repo->fetchDescription ) {
1987 return false;
1989 if ( !$lang ) {
1990 $lang = $wgLang;
1992 $renderUrl = $this->repo->getDescriptionRenderUrl( $this->getName(), $lang->getCode() );
1993 if ( $renderUrl ) {
1994 if ( $this->repo->descriptionCacheExpiry > 0 ) {
1995 wfDebug( "Attempting to get the description from cache..." );
1996 $key = $this->repo->getLocalCacheKey(
1997 'RemoteFileDescription',
1998 'url',
1999 $lang->getCode(),
2000 $this->getName()
2002 $obj = $wgMemc->get( $key );
2003 if ( $obj ) {
2004 wfDebug( "success!\n" );
2006 return $obj;
2008 wfDebug( "miss\n" );
2010 wfDebug( "Fetching shared description from $renderUrl\n" );
2011 $res = Http::get( $renderUrl, array(), __METHOD__ );
2012 if ( $res && $this->repo->descriptionCacheExpiry > 0 ) {
2013 $wgMemc->set( $key, $res, $this->repo->descriptionCacheExpiry );
2016 return $res;
2017 } else {
2018 return false;
2023 * Get description of file revision
2024 * STUB
2026 * @param int $audience One of:
2027 * File::FOR_PUBLIC to be displayed to all users
2028 * File::FOR_THIS_USER to be displayed to the given user
2029 * File::RAW get the description regardless of permissions
2030 * @param User $user User object to check for, only if FOR_THIS_USER is
2031 * passed to the $audience parameter
2032 * @return string
2034 function getDescription( $audience = self::FOR_PUBLIC, User $user = null ) {
2035 return null;
2039 * Get the 14-character timestamp of the file upload
2041 * @return string|bool TS_MW timestamp or false on failure
2043 function getTimestamp() {
2044 $this->assertRepoDefined();
2046 return $this->repo->getFileTimestamp( $this->getPath() );
2050 * Returns the timestamp (in TS_MW format) of the last change of the description page.
2051 * Returns false if the file does not have a description page, or retrieving the timestamp
2052 * would be expensive.
2053 * @since 1.25
2054 * @return string|bool
2056 public function getDescriptionTouched() {
2057 return false;
2061 * Get the SHA-1 base 36 hash of the file
2063 * @return string
2065 function getSha1() {
2066 $this->assertRepoDefined();
2068 return $this->repo->getFileSha1( $this->getPath() );
2072 * Get the deletion archive key, "<sha1>.<ext>"
2074 * @return string
2076 function getStorageKey() {
2077 $hash = $this->getSha1();
2078 if ( !$hash ) {
2079 return false;
2081 $ext = $this->getExtension();
2082 $dotExt = $ext === '' ? '' : ".$ext";
2084 return $hash . $dotExt;
2088 * Determine if the current user is allowed to view a particular
2089 * field of this file, if it's marked as deleted.
2090 * STUB
2091 * @param int $field
2092 * @param User $user User object to check, or null to use $wgUser
2093 * @return bool
2095 function userCan( $field, User $user = null ) {
2096 return true;
2100 * @return array HTTP header name/value map to use for HEAD/GET request responses
2102 function getStreamHeaders() {
2103 $handler = $this->getHandler();
2104 if ( $handler ) {
2105 return $handler->getStreamHeaders( $this->getMetadata() );
2106 } else {
2107 return array();
2112 * @return string
2114 function getLongDesc() {
2115 $handler = $this->getHandler();
2116 if ( $handler ) {
2117 return $handler->getLongDesc( $this );
2118 } else {
2119 return MediaHandler::getGeneralLongDesc( $this );
2124 * @return string
2126 function getShortDesc() {
2127 $handler = $this->getHandler();
2128 if ( $handler ) {
2129 return $handler->getShortDesc( $this );
2130 } else {
2131 return MediaHandler::getGeneralShortDesc( $this );
2136 * @return string
2138 function getDimensionsString() {
2139 $handler = $this->getHandler();
2140 if ( $handler ) {
2141 return $handler->getDimensionsString( $this );
2142 } else {
2143 return '';
2148 * @return string
2150 function getRedirected() {
2151 return $this->redirected;
2155 * @return Title|null
2157 function getRedirectedTitle() {
2158 if ( $this->redirected ) {
2159 if ( !$this->redirectTitle ) {
2160 $this->redirectTitle = Title::makeTitle( NS_FILE, $this->redirected );
2163 return $this->redirectTitle;
2166 return null;
2170 * @param string $from
2171 * @return void
2173 function redirectedFrom( $from ) {
2174 $this->redirected = $from;
2178 * @return bool
2180 function isMissing() {
2181 return false;
2185 * Check if this file object is small and can be cached
2186 * @return bool
2188 public function isCacheable() {
2189 return true;
2193 * Assert that $this->repo is set to a valid FileRepo instance
2194 * @throws MWException
2196 protected function assertRepoDefined() {
2197 if ( !( $this->repo instanceof $this->repoClass ) ) {
2198 throw new MWException( "A {$this->repoClass} object is not set for this File.\n" );
2203 * Assert that $this->title is set to a Title
2204 * @throws MWException
2206 protected function assertTitleDefined() {
2207 if ( !( $this->title instanceof Title ) ) {
2208 throw new MWException( "A Title object is not set for this File.\n" );
2213 * True if creating thumbnails from the file is large or otherwise resource-intensive.
2214 * @return bool
2216 public function isExpensiveToThumbnail() {
2217 $handler = $this->getHandler();
2218 return $handler ? $handler->isExpensiveToThumbnail( $this ) : false;