Merge "mw.Feedback: If the message is posted remotely, link the title correctly"
[lhc/web/wiklou.git] / includes / filerepo / file / File.php
1 <?php
2 /**
3 * @defgroup FileAbstraction File abstraction
4 * @ingroup FileRepo
5 *
6 * Represents files in a repository.
7 */
8 use MediaWiki\MediaWikiServices;
9
10 /**
11 * Base code for files.
12 *
13 * This program is free software; you can redistribute it and/or modify
14 * it under the terms of the GNU General Public License as published by
15 * the Free Software Foundation; either version 2 of the License, or
16 * (at your option) any later version.
17 *
18 * This program is distributed in the hope that it will be useful,
19 * but WITHOUT ANY WARRANTY; without even the implied warranty of
20 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 * GNU General Public License for more details.
22 *
23 * You should have received a copy of the GNU General Public License along
24 * with this program; if not, write to the Free Software Foundation, Inc.,
25 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
26 * http://www.gnu.org/copyleft/gpl.html
27 *
28 * @file
29 * @ingroup FileAbstraction
30 */
31
32 /**
33 * Implements some public methods and some protected utility functions which
34 * are required by multiple child classes. Contains stub functionality for
35 * unimplemented public methods.
36 *
37 * Stub functions which should be overridden are marked with STUB. Some more
38 * concrete functions are also typically overridden by child classes.
39 *
40 * Note that only the repo object knows what its file class is called. You should
41 * never name a file class explictly outside of the repo class. Instead use the
42 * repo's factory functions to generate file objects, for example:
43 *
44 * RepoGroup::singleton()->getLocalRepo()->newFile( $title );
45 *
46 * The convenience functions wfLocalFile() and wfFindFile() should be sufficient
47 * in most cases.
48 *
49 * @ingroup FileAbstraction
50 */
51 abstract class File implements IDBAccessObject {
52 // Bitfield values akin to the Revision deletion constants
53 const DELETED_FILE = 1;
54 const DELETED_COMMENT = 2;
55 const DELETED_USER = 4;
56 const DELETED_RESTRICTED = 8;
57
58 /** Force rendering in the current process */
59 const RENDER_NOW = 1;
60 /**
61 * Force rendering even if thumbnail already exist and using RENDER_NOW
62 * I.e. you have to pass both flags: File::RENDER_NOW | File::RENDER_FORCE
63 */
64 const RENDER_FORCE = 2;
65
66 const DELETE_SOURCE = 1;
67
68 // Audience options for File::getDescription()
69 const FOR_PUBLIC = 1;
70 const FOR_THIS_USER = 2;
71 const RAW = 3;
72
73 // Options for File::thumbName()
74 const THUMB_FULL_NAME = 1;
75
76 /**
77 * Some member variables can be lazy-initialised using __get(). The
78 * initialisation function for these variables is always a function named
79 * like getVar(), where Var is the variable name with upper-case first
80 * letter.
81 *
82 * The following variables are initialised in this way in this base class:
83 * name, extension, handler, path, canRender, isSafeFile,
84 * transformScript, hashPath, pageCount, url
85 *
86 * Code within this class should generally use the accessor function
87 * directly, since __get() isn't re-entrant and therefore causes bugs that
88 * depend on initialisation order.
89 */
90
91 /**
92 * The following member variables are not lazy-initialised
93 */
94
95 /** @var FileRepo|LocalRepo|ForeignAPIRepo|bool */
96 public $repo;
97
98 /** @var Title|string|bool */
99 protected $title;
100
101 /** @var string Text of last error */
102 protected $lastError;
103
104 /** @var string Main part of the title, with underscores (Title::getDBkey) */
105 protected $redirected;
106
107 /** @var Title */
108 protected $redirectedTitle;
109
110 /** @var FSFile|bool False if undefined */
111 protected $fsFile;
112
113 /** @var MediaHandler */
114 protected $handler;
115
116 /** @var string The URL corresponding to one of the four basic zones */
117 protected $url;
118
119 /** @var string File extension */
120 protected $extension;
121
122 /** @var string The name of a file from its title object */
123 protected $name;
124
125 /** @var string The storage path corresponding to one of the zones */
126 protected $path;
127
128 /** @var string Relative path including trailing slash */
129 protected $hashPath;
130
131 /** @var string|false Number of pages of a multipage document, or false for
132 * documents which aren't multipage documents
133 */
134 protected $pageCount;
135
136 /** @var string URL of transformscript (for example thumb.php) */
137 protected $transformScript;
138
139 /** @var Title */
140 protected $redirectTitle;
141
142 /** @var bool Whether the output of transform() for this file is likely to be valid. */
143 protected $canRender;
144
145 /** @var bool Whether this media file is in a format that is unlikely to
146 * contain viruses or malicious content
147 */
148 protected $isSafeFile;
149
150 /** @var string Required Repository class type */
151 protected $repoClass = FileRepo::class;
152
153 /** @var array Cache of tmp filepaths pointing to generated bucket thumbnails, keyed by width */
154 protected $tmpBucketedThumbCache = [];
155
156 /**
157 * Call this constructor from child classes.
158 *
159 * Both $title and $repo are optional, though some functions
160 * may return false or throw exceptions if they are not set.
161 * Most subclasses will want to call assertRepoDefined() here.
162 *
163 * @param Title|string|bool $title
164 * @param FileRepo|bool $repo
165 */
166 function __construct( $title, $repo ) {
167 // Some subclasses do not use $title, but set name/title some other way
168 if ( $title !== false ) {
169 $title = self::normalizeTitle( $title, 'exception' );
170 }
171 $this->title = $title;
172 $this->repo = $repo;
173 }
174
175 /**
176 * Given a string or Title object return either a
177 * valid Title object with namespace NS_FILE or null
178 *
179 * @param Title|string $title
180 * @param string|bool $exception Use 'exception' to throw an error on bad titles
181 * @throws MWException
182 * @return Title|null
183 */
184 static function normalizeTitle( $title, $exception = false ) {
185 $ret = $title;
186 if ( $ret instanceof Title ) {
187 # Normalize NS_MEDIA -> NS_FILE
188 if ( $ret->getNamespace() == NS_MEDIA ) {
189 $ret = Title::makeTitleSafe( NS_FILE, $ret->getDBkey() );
190 # Sanity check the title namespace
191 } elseif ( $ret->getNamespace() !== NS_FILE ) {
192 $ret = null;
193 }
194 } else {
195 # Convert strings to Title objects
196 $ret = Title::makeTitleSafe( NS_FILE, (string)$ret );
197 }
198 if ( !$ret && $exception !== false ) {
199 throw new MWException( "`$title` is not a valid file title." );
200 }
201
202 return $ret;
203 }
204
205 function __get( $name ) {
206 $function = [ $this, 'get' . ucfirst( $name ) ];
207 if ( !is_callable( $function ) ) {
208 return null;
209 } else {
210 $this->$name = call_user_func( $function );
211
212 return $this->$name;
213 }
214 }
215
216 /**
217 * Normalize a file extension to the common form, making it lowercase and checking some synonyms,
218 * and ensure it's clean. Extensions with non-alphanumeric characters will be discarded.
219 * Keep in sync with mw.Title.normalizeExtension() in JS.
220 *
221 * @param string $extension File extension (without the leading dot)
222 * @return string File extension in canonical form
223 */
224 static function normalizeExtension( $extension ) {
225 $lower = strtolower( $extension );
226 $squish = [
227 'htm' => 'html',
228 'jpeg' => 'jpg',
229 'mpeg' => 'mpg',
230 'tiff' => 'tif',
231 'ogv' => 'ogg' ];
232 if ( isset( $squish[$lower] ) ) {
233 return $squish[$lower];
234 } elseif ( preg_match( '/^[0-9a-z]+$/', $lower ) ) {
235 return $lower;
236 } else {
237 return '';
238 }
239 }
240
241 /**
242 * Checks if file extensions are compatible
243 *
244 * @param File $old Old file
245 * @param string $new New name
246 *
247 * @return bool|null
248 */
249 static function checkExtensionCompatibility( File $old, $new ) {
250 $oldMime = $old->getMimeType();
251 $n = strrpos( $new, '.' );
252 $newExt = self::normalizeExtension( $n ? substr( $new, $n + 1 ) : '' );
253 $mimeMagic = MediaWiki\MediaWikiServices::getInstance()->getMimeAnalyzer();
254
255 return $mimeMagic->isMatchingExtension( $newExt, $oldMime );
256 }
257
258 /**
259 * Upgrade the database row if there is one
260 * Called by ImagePage
261 * STUB
262 */
263 function upgradeRow() {
264 }
265
266 /**
267 * Split an internet media type into its two components; if not
268 * a two-part name, set the minor type to 'unknown'.
269 *
270 * @param string $mime "text/html" etc
271 * @return array ("text", "html") etc
272 */
273 public static function splitMime( $mime ) {
274 if ( strpos( $mime, '/' ) !== false ) {
275 return explode( '/', $mime, 2 );
276 } else {
277 return [ $mime, 'unknown' ];
278 }
279 }
280
281 /**
282 * Callback for usort() to do file sorts by name
283 *
284 * @param File $a
285 * @param File $b
286 * @return int Result of name comparison
287 */
288 public static function compare( File $a, File $b ) {
289 return strcmp( $a->getName(), $b->getName() );
290 }
291
292 /**
293 * Return the name of this file
294 *
295 * @return string
296 */
297 public function getName() {
298 if ( !isset( $this->name ) ) {
299 $this->assertRepoDefined();
300 $this->name = $this->repo->getNameFromTitle( $this->title );
301 }
302
303 return $this->name;
304 }
305
306 /**
307 * Get the file extension, e.g. "svg"
308 *
309 * @return string
310 */
311 function getExtension() {
312 if ( !isset( $this->extension ) ) {
313 $n = strrpos( $this->getName(), '.' );
314 $this->extension = self::normalizeExtension(
315 $n ? substr( $this->getName(), $n + 1 ) : '' );
316 }
317
318 return $this->extension;
319 }
320
321 /**
322 * Return the associated title object
323 *
324 * @return Title
325 */
326 public function getTitle() {
327 return $this->title;
328 }
329
330 /**
331 * Return the title used to find this file
332 *
333 * @return Title
334 */
335 public function getOriginalTitle() {
336 if ( $this->redirected ) {
337 return $this->getRedirectedTitle();
338 }
339
340 return $this->title;
341 }
342
343 /**
344 * Return the URL of the file
345 *
346 * @return string
347 */
348 public function getUrl() {
349 if ( !isset( $this->url ) ) {
350 $this->assertRepoDefined();
351 $ext = $this->getExtension();
352 $this->url = $this->repo->getZoneUrl( 'public', $ext ) . '/' . $this->getUrlRel();
353 }
354
355 return $this->url;
356 }
357
358 /**
359 * Get short description URL for a files based on the page ID
360 *
361 * @return string|null
362 * @since 1.27
363 */
364 public function getDescriptionShortUrl() {
365 return null;
366 }
367
368 /**
369 * Return a fully-qualified URL to the file.
370 * Upload URL paths _may or may not_ be fully qualified, so
371 * we check. Local paths are assumed to belong on $wgServer.
372 *
373 * @return string
374 */
375 public function getFullUrl() {
376 return wfExpandUrl( $this->getUrl(), PROTO_RELATIVE );
377 }
378
379 /**
380 * @return string
381 */
382 public function getCanonicalUrl() {
383 return wfExpandUrl( $this->getUrl(), PROTO_CANONICAL );
384 }
385
386 /**
387 * @return string
388 */
389 function getViewURL() {
390 if ( $this->mustRender() ) {
391 if ( $this->canRender() ) {
392 return $this->createThumb( $this->getWidth() );
393 } else {
394 wfDebug( __METHOD__ . ': supposed to render ' . $this->getName() .
395 ' (' . $this->getMimeType() . "), but can't!\n" );
396
397 return $this->getUrl(); # hm... return NULL?
398 }
399 } else {
400 return $this->getUrl();
401 }
402 }
403
404 /**
405 * Return the storage path to the file. Note that this does
406 * not mean that a file actually exists under that location.
407 *
408 * This path depends on whether directory hashing is active or not,
409 * i.e. whether the files are all found in the same directory,
410 * or in hashed paths like /images/3/3c.
411 *
412 * Most callers don't check the return value, but ForeignAPIFile::getPath
413 * returns false.
414 *
415 * @return string|bool ForeignAPIFile::getPath can return false
416 */
417 public function getPath() {
418 if ( !isset( $this->path ) ) {
419 $this->assertRepoDefined();
420 $this->path = $this->repo->getZonePath( 'public' ) . '/' . $this->getRel();
421 }
422
423 return $this->path;
424 }
425
426 /**
427 * Get an FS copy or original of this file and return the path.
428 * Returns false on failure. Callers must not alter the file.
429 * Temporary files are cleared automatically.
430 *
431 * @return string|bool False on failure
432 */
433 public function getLocalRefPath() {
434 $this->assertRepoDefined();
435 if ( !isset( $this->fsFile ) ) {
436 $starttime = microtime( true );
437 $this->fsFile = $this->repo->getLocalReference( $this->getPath() );
438
439 $statTiming = microtime( true ) - $starttime;
440 MediaWikiServices::getInstance()->getStatsdDataFactory()->timing(
441 'media.thumbnail.generate.fetchoriginal', 1000 * $statTiming );
442
443 if ( !$this->fsFile ) {
444 $this->fsFile = false; // null => false; cache negative hits
445 }
446 }
447
448 return ( $this->fsFile )
449 ? $this->fsFile->getPath()
450 : false;
451 }
452
453 /**
454 * Return the width of the image. Returns false if the width is unknown
455 * or undefined.
456 *
457 * STUB
458 * Overridden by LocalFile, UnregisteredLocalFile
459 *
460 * @param int $page
461 * @return int|bool
462 */
463 public function getWidth( $page = 1 ) {
464 return false;
465 }
466
467 /**
468 * Return the height of the image. Returns false if the height is unknown
469 * or undefined
470 *
471 * STUB
472 * Overridden by LocalFile, UnregisteredLocalFile
473 *
474 * @param int $page
475 * @return bool|int False on failure
476 */
477 public function getHeight( $page = 1 ) {
478 return false;
479 }
480
481 /**
482 * Return the smallest bucket from $wgThumbnailBuckets which is at least
483 * $wgThumbnailMinimumBucketDistance larger than $desiredWidth. The returned bucket, if any,
484 * will always be bigger than $desiredWidth.
485 *
486 * @param int $desiredWidth
487 * @param int $page
488 * @return bool|int
489 */
490 public function getThumbnailBucket( $desiredWidth, $page = 1 ) {
491 global $wgThumbnailBuckets, $wgThumbnailMinimumBucketDistance;
492
493 $imageWidth = $this->getWidth( $page );
494
495 if ( $imageWidth === false ) {
496 return false;
497 }
498
499 if ( $desiredWidth > $imageWidth ) {
500 return false;
501 }
502
503 if ( !$wgThumbnailBuckets ) {
504 return false;
505 }
506
507 $sortedBuckets = $wgThumbnailBuckets;
508
509 sort( $sortedBuckets );
510
511 foreach ( $sortedBuckets as $bucket ) {
512 if ( $bucket >= $imageWidth ) {
513 return false;
514 }
515
516 if ( $bucket - $wgThumbnailMinimumBucketDistance > $desiredWidth ) {
517 return $bucket;
518 }
519 }
520
521 // Image is bigger than any available bucket
522 return false;
523 }
524
525 /**
526 * Returns ID or name of user who uploaded the file
527 * STUB
528 *
529 * @param string $type 'text' or 'id'
530 * @return string|int
531 */
532 public function getUser( $type = 'text' ) {
533 return null;
534 }
535
536 /**
537 * Get the duration of a media file in seconds
538 *
539 * @return float|int
540 */
541 public function getLength() {
542 $handler = $this->getHandler();
543 if ( $handler ) {
544 return $handler->getLength( $this );
545 } else {
546 return 0;
547 }
548 }
549
550 /**
551 * Return true if the file is vectorized
552 *
553 * @return bool
554 */
555 public function isVectorized() {
556 $handler = $this->getHandler();
557 if ( $handler ) {
558 return $handler->isVectorized( $this );
559 } else {
560 return false;
561 }
562 }
563
564 /**
565 * Gives a (possibly empty) list of languages to render
566 * the file in.
567 *
568 * If the file doesn't have translations, or if the file
569 * format does not support that sort of thing, returns
570 * an empty array.
571 *
572 * @return array
573 * @since 1.23
574 */
575 public function getAvailableLanguages() {
576 $handler = $this->getHandler();
577 if ( $handler ) {
578 return $handler->getAvailableLanguages( $this );
579 } else {
580 return [];
581 }
582 }
583
584 /**
585 * Get the language code from the available languages for this file that matches the language
586 * requested by the user
587 *
588 * @param string $userPreferredLanguage
589 * @return string|null
590 */
591 public function getMatchedLanguage( $userPreferredLanguage ) {
592 $handler = $this->getHandler();
593 if ( $handler && method_exists( $handler, 'getMatchedLanguage' ) ) {
594 return $handler->getMatchedLanguage(
595 $userPreferredLanguage,
596 $handler->getAvailableLanguages( $this )
597 );
598 } else {
599 return null;
600 }
601 }
602
603 /**
604 * In files that support multiple language, what is the default language
605 * to use if none specified.
606 *
607 * @return string|null Lang code, or null if filetype doesn't support multiple languages.
608 * @since 1.23
609 */
610 public function getDefaultRenderLanguage() {
611 $handler = $this->getHandler();
612 if ( $handler ) {
613 return $handler->getDefaultRenderLanguage( $this );
614 } else {
615 return null;
616 }
617 }
618
619 /**
620 * Will the thumbnail be animated if one would expect it to be.
621 *
622 * Currently used to add a warning to the image description page
623 *
624 * @return bool False if the main image is both animated
625 * and the thumbnail is not. In all other cases must return
626 * true. If image is not renderable whatsoever, should
627 * return true.
628 */
629 public function canAnimateThumbIfAppropriate() {
630 $handler = $this->getHandler();
631 if ( !$handler ) {
632 // We cannot handle image whatsoever, thus
633 // one would not expect it to be animated
634 // so true.
635 return true;
636 } else {
637 if ( $this->allowInlineDisplay()
638 && $handler->isAnimatedImage( $this )
639 && !$handler->canAnimateThumbnail( $this )
640 ) {
641 // Image is animated, but thumbnail isn't.
642 // This is unexpected to the user.
643 return false;
644 } else {
645 // Image is not animated, so one would
646 // not expect thumb to be
647 return true;
648 }
649 }
650 }
651
652 /**
653 * Get handler-specific metadata
654 * Overridden by LocalFile, UnregisteredLocalFile
655 * STUB
656 * @return bool|array
657 */
658 public function getMetadata() {
659 return false;
660 }
661
662 /**
663 * Like getMetadata but returns a handler independent array of common values.
664 * @see MediaHandler::getCommonMetaArray()
665 * @return array|bool Array or false if not supported
666 * @since 1.23
667 */
668 public function getCommonMetaArray() {
669 $handler = $this->getHandler();
670
671 if ( !$handler ) {
672 return false;
673 }
674
675 return $handler->getCommonMetaArray( $this );
676 }
677
678 /**
679 * get versioned metadata
680 *
681 * @param array|string $metadata Array or string of (serialized) metadata
682 * @param int $version Version number.
683 * @return array Array containing metadata, or what was passed to it on fail
684 * (unserializing if not array)
685 */
686 public function convertMetadataVersion( $metadata, $version ) {
687 $handler = $this->getHandler();
688 if ( !is_array( $metadata ) ) {
689 // Just to make the return type consistent
690 $metadata = unserialize( $metadata );
691 }
692 if ( $handler ) {
693 return $handler->convertMetadataVersion( $metadata, $version );
694 } else {
695 return $metadata;
696 }
697 }
698
699 /**
700 * Return the bit depth of the file
701 * Overridden by LocalFile
702 * STUB
703 * @return int
704 */
705 public function getBitDepth() {
706 return 0;
707 }
708
709 /**
710 * Return the size of the image file, in bytes
711 * Overridden by LocalFile, UnregisteredLocalFile
712 * STUB
713 * @return bool
714 */
715 public function getSize() {
716 return false;
717 }
718
719 /**
720 * Returns the MIME type of the file.
721 * Overridden by LocalFile, UnregisteredLocalFile
722 * STUB
723 *
724 * @return string
725 */
726 function getMimeType() {
727 return 'unknown/unknown';
728 }
729
730 /**
731 * Return the type of the media in the file.
732 * Use the value returned by this function with the MEDIATYPE_xxx constants.
733 * Overridden by LocalFile,
734 * STUB
735 * @return string
736 */
737 function getMediaType() {
738 return MEDIATYPE_UNKNOWN;
739 }
740
741 /**
742 * Checks if the output of transform() for this file is likely
743 * to be valid. If this is false, various user elements will
744 * display a placeholder instead.
745 *
746 * Currently, this checks if the file is an image format
747 * that can be converted to a format
748 * supported by all browsers (namely GIF, PNG and JPEG),
749 * or if it is an SVG image and SVG conversion is enabled.
750 *
751 * @return bool
752 */
753 function canRender() {
754 if ( !isset( $this->canRender ) ) {
755 $this->canRender = $this->getHandler() && $this->handler->canRender( $this ) && $this->exists();
756 }
757
758 return $this->canRender;
759 }
760
761 /**
762 * Accessor for __get()
763 * @return bool
764 */
765 protected function getCanRender() {
766 return $this->canRender();
767 }
768
769 /**
770 * Return true if the file is of a type that can't be directly
771 * rendered by typical browsers and needs to be re-rasterized.
772 *
773 * This returns true for everything but the bitmap types
774 * supported by all browsers, i.e. JPEG; GIF and PNG. It will
775 * also return true for any non-image formats.
776 *
777 * @return bool
778 */
779 function mustRender() {
780 return $this->getHandler() && $this->handler->mustRender( $this );
781 }
782
783 /**
784 * Alias for canRender()
785 *
786 * @return bool
787 */
788 function allowInlineDisplay() {
789 return $this->canRender();
790 }
791
792 /**
793 * Determines if this media file is in a format that is unlikely to
794 * contain viruses or malicious content. It uses the global
795 * $wgTrustedMediaFormats list to determine if the file is safe.
796 *
797 * This is used to show a warning on the description page of non-safe files.
798 * It may also be used to disallow direct [[media:...]] links to such files.
799 *
800 * Note that this function will always return true if allowInlineDisplay()
801 * or isTrustedFile() is true for this file.
802 *
803 * @return bool
804 */
805 function isSafeFile() {
806 if ( !isset( $this->isSafeFile ) ) {
807 $this->isSafeFile = $this->getIsSafeFileUncached();
808 }
809
810 return $this->isSafeFile;
811 }
812
813 /**
814 * Accessor for __get()
815 *
816 * @return bool
817 */
818 protected function getIsSafeFile() {
819 return $this->isSafeFile();
820 }
821
822 /**
823 * Uncached accessor
824 *
825 * @return bool
826 */
827 protected function getIsSafeFileUncached() {
828 global $wgTrustedMediaFormats;
829
830 if ( $this->allowInlineDisplay() ) {
831 return true;
832 }
833 if ( $this->isTrustedFile() ) {
834 return true;
835 }
836
837 $type = $this->getMediaType();
838 $mime = $this->getMimeType();
839 # wfDebug( "LocalFile::isSafeFile: type= $type, mime= $mime\n" );
840
841 if ( !$type || $type === MEDIATYPE_UNKNOWN ) {
842 return false; # unknown type, not trusted
843 }
844 if ( in_array( $type, $wgTrustedMediaFormats ) ) {
845 return true;
846 }
847
848 if ( $mime === "unknown/unknown" ) {
849 return false; # unknown type, not trusted
850 }
851 if ( in_array( $mime, $wgTrustedMediaFormats ) ) {
852 return true;
853 }
854
855 return false;
856 }
857
858 /**
859 * Returns true if the file is flagged as trusted. Files flagged that way
860 * can be linked to directly, even if that is not allowed for this type of
861 * file normally.
862 *
863 * This is a dummy function right now and always returns false. It could be
864 * implemented to extract a flag from the database. The trusted flag could be
865 * set on upload, if the user has sufficient privileges, to bypass script-
866 * and html-filters. It may even be coupled with cryptographics signatures
867 * or such.
868 *
869 * @return bool
870 */
871 function isTrustedFile() {
872 # this could be implemented to check a flag in the database,
873 # look for signatures, etc
874 return false;
875 }
876
877 /**
878 * Load any lazy-loaded file object fields from source
879 *
880 * This is only useful when setting $flags
881 *
882 * Overridden by LocalFile to actually query the DB
883 *
884 * @param int $flags Bitfield of File::READ_* constants
885 */
886 public function load( $flags = 0 ) {
887 }
888
889 /**
890 * Returns true if file exists in the repository.
891 *
892 * Overridden by LocalFile to avoid unnecessary stat calls.
893 *
894 * @return bool Whether file exists in the repository.
895 */
896 public function exists() {
897 return $this->getPath() && $this->repo->fileExists( $this->path );
898 }
899
900 /**
901 * Returns true if file exists in the repository and can be included in a page.
902 * It would be unsafe to include private images, making public thumbnails inadvertently
903 *
904 * @return bool Whether file exists in the repository and is includable.
905 */
906 public function isVisible() {
907 return $this->exists();
908 }
909
910 /**
911 * @return string
912 */
913 function getTransformScript() {
914 if ( !isset( $this->transformScript ) ) {
915 $this->transformScript = false;
916 if ( $this->repo ) {
917 $script = $this->repo->getThumbScriptUrl();
918 if ( $script ) {
919 $this->transformScript = wfAppendQuery( $script, [ 'f' => $this->getName() ] );
920 }
921 }
922 }
923
924 return $this->transformScript;
925 }
926
927 /**
928 * Get a ThumbnailImage which is the same size as the source
929 *
930 * @param array $handlerParams
931 *
932 * @return ThumbnailImage|MediaTransformOutput|bool False on failure
933 */
934 function getUnscaledThumb( $handlerParams = [] ) {
935 $hp =& $handlerParams;
936 $page = isset( $hp['page'] ) ? $hp['page'] : false;
937 $width = $this->getWidth( $page );
938 if ( !$width ) {
939 return $this->iconThumb();
940 }
941 $hp['width'] = $width;
942 // be sure to ignore any height specification as well (T64258)
943 unset( $hp['height'] );
944
945 return $this->transform( $hp );
946 }
947
948 /**
949 * Return the file name of a thumbnail with the specified parameters.
950 * Use File::THUMB_FULL_NAME to always get a name like "<params>-<source>".
951 * Otherwise, the format may be "<params>-<source>" or "<params>-thumbnail.<ext>".
952 *
953 * @param array $params Handler-specific parameters
954 * @param int $flags Bitfield that supports THUMB_* constants
955 * @return string|null
956 */
957 public function thumbName( $params, $flags = 0 ) {
958 $name = ( $this->repo && !( $flags & self::THUMB_FULL_NAME ) )
959 ? $this->repo->nameForThumb( $this->getName() )
960 : $this->getName();
961
962 return $this->generateThumbName( $name, $params );
963 }
964
965 /**
966 * Generate a thumbnail file name from a name and specified parameters
967 *
968 * @param string $name
969 * @param array $params Parameters which will be passed to MediaHandler::makeParamString
970 * @return string|null
971 */
972 public function generateThumbName( $name, $params ) {
973 if ( !$this->getHandler() ) {
974 return null;
975 }
976 $extension = $this->getExtension();
977 list( $thumbExt, ) = $this->getHandler()->getThumbType(
978 $extension, $this->getMimeType(), $params );
979 $thumbName = $this->getHandler()->makeParamString( $params );
980
981 if ( $this->repo->supportsSha1URLs() ) {
982 $thumbName .= '-' . $this->getSha1() . '.' . $thumbExt;
983 } else {
984 $thumbName .= '-' . $name;
985
986 if ( $thumbExt != $extension ) {
987 $thumbName .= ".$thumbExt";
988 }
989 }
990
991 return $thumbName;
992 }
993
994 /**
995 * Create a thumbnail of the image having the specified width/height.
996 * The thumbnail will not be created if the width is larger than the
997 * image's width. Let the browser do the scaling in this case.
998 * The thumbnail is stored on disk and is only computed if the thumbnail
999 * file does not exist OR if it is older than the image.
1000 * Returns the URL.
1001 *
1002 * Keeps aspect ratio of original image. If both width and height are
1003 * specified, the generated image will be no bigger than width x height,
1004 * and will also have correct aspect ratio.
1005 *
1006 * @param int $width Maximum width of the generated thumbnail
1007 * @param int $height Maximum height of the image (optional)
1008 *
1009 * @return string
1010 */
1011 public function createThumb( $width, $height = -1 ) {
1012 $params = [ 'width' => $width ];
1013 if ( $height != -1 ) {
1014 $params['height'] = $height;
1015 }
1016 $thumb = $this->transform( $params );
1017 if ( !$thumb || $thumb->isError() ) {
1018 return '';
1019 }
1020
1021 return $thumb->getUrl();
1022 }
1023
1024 /**
1025 * Return either a MediaTransformError or placeholder thumbnail (if $wgIgnoreImageErrors)
1026 *
1027 * @param string $thumbPath Thumbnail storage path
1028 * @param string $thumbUrl Thumbnail URL
1029 * @param array $params
1030 * @param int $flags
1031 * @return MediaTransformOutput
1032 */
1033 protected function transformErrorOutput( $thumbPath, $thumbUrl, $params, $flags ) {
1034 global $wgIgnoreImageErrors;
1035
1036 $handler = $this->getHandler();
1037 if ( $handler && $wgIgnoreImageErrors && !( $flags & self::RENDER_NOW ) ) {
1038 return $handler->getTransform( $this, $thumbPath, $thumbUrl, $params );
1039 } else {
1040 return new MediaTransformError( 'thumbnail_error',
1041 $params['width'], 0, wfMessage( 'thumbnail-dest-create' ) );
1042 }
1043 }
1044
1045 /**
1046 * Transform a media file
1047 *
1048 * @param array $params An associative array of handler-specific parameters.
1049 * Typical keys are width, height and page.
1050 * @param int $flags A bitfield, may contain self::RENDER_NOW to force rendering
1051 * @return ThumbnailImage|MediaTransformOutput|bool False on failure
1052 */
1053 function transform( $params, $flags = 0 ) {
1054 global $wgThumbnailEpoch;
1055
1056 do {
1057 if ( !$this->canRender() ) {
1058 $thumb = $this->iconThumb();
1059 break; // not a bitmap or renderable image, don't try
1060 }
1061
1062 // Get the descriptionUrl to embed it as comment into the thumbnail. T21791.
1063 $descriptionUrl = $this->getDescriptionUrl();
1064 if ( $descriptionUrl ) {
1065 $params['descriptionUrl'] = wfExpandUrl( $descriptionUrl, PROTO_CANONICAL );
1066 }
1067
1068 $handler = $this->getHandler();
1069 $script = $this->getTransformScript();
1070 if ( $script && !( $flags & self::RENDER_NOW ) ) {
1071 // Use a script to transform on client request, if possible
1072 $thumb = $handler->getScriptedTransform( $this, $script, $params );
1073 if ( $thumb ) {
1074 break;
1075 }
1076 }
1077
1078 $normalisedParams = $params;
1079 $handler->normaliseParams( $this, $normalisedParams );
1080
1081 $thumbName = $this->thumbName( $normalisedParams );
1082 $thumbUrl = $this->getThumbUrl( $thumbName );
1083 $thumbPath = $this->getThumbPath( $thumbName ); // final thumb path
1084
1085 if ( $this->repo ) {
1086 // Defer rendering if a 404 handler is set up...
1087 if ( $this->repo->canTransformVia404() && !( $flags & self::RENDER_NOW ) ) {
1088 // XXX: Pass in the storage path even though we are not rendering anything
1089 // and the path is supposed to be an FS path. This is due to getScalerType()
1090 // getting called on the path and clobbering $thumb->getUrl() if it's false.
1091 $thumb = $handler->getTransform( $this, $thumbPath, $thumbUrl, $params );
1092 break;
1093 }
1094 // Check if an up-to-date thumbnail already exists...
1095 wfDebug( __METHOD__ . ": Doing stat for $thumbPath\n" );
1096 if ( !( $flags & self::RENDER_FORCE ) && $this->repo->fileExists( $thumbPath ) ) {
1097 $timestamp = $this->repo->getFileTimestamp( $thumbPath );
1098 if ( $timestamp !== false && $timestamp >= $wgThumbnailEpoch ) {
1099 // XXX: Pass in the storage path even though we are not rendering anything
1100 // and the path is supposed to be an FS path. This is due to getScalerType()
1101 // getting called on the path and clobbering $thumb->getUrl() if it's false.
1102 $thumb = $handler->getTransform( $this, $thumbPath, $thumbUrl, $params );
1103 $thumb->setStoragePath( $thumbPath );
1104 break;
1105 }
1106 } elseif ( $flags & self::RENDER_FORCE ) {
1107 wfDebug( __METHOD__ . " forcing rendering per flag File::RENDER_FORCE\n" );
1108 }
1109
1110 // If the backend is ready-only, don't keep generating thumbnails
1111 // only to return transformation errors, just return the error now.
1112 if ( $this->repo->getReadOnlyReason() !== false ) {
1113 $thumb = $this->transformErrorOutput( $thumbPath, $thumbUrl, $params, $flags );
1114 break;
1115 }
1116 }
1117
1118 $tmpFile = $this->makeTransformTmpFile( $thumbPath );
1119
1120 if ( !$tmpFile ) {
1121 $thumb = $this->transformErrorOutput( $thumbPath, $thumbUrl, $params, $flags );
1122 } else {
1123 $thumb = $this->generateAndSaveThumb( $tmpFile, $params, $flags );
1124 }
1125 } while ( false );
1126
1127 return is_object( $thumb ) ? $thumb : false;
1128 }
1129
1130 /**
1131 * Generates a thumbnail according to the given parameters and saves it to storage
1132 * @param TempFSFile $tmpFile Temporary file where the rendered thumbnail will be saved
1133 * @param array $transformParams
1134 * @param int $flags
1135 * @return bool|MediaTransformOutput
1136 */
1137 public function generateAndSaveThumb( $tmpFile, $transformParams, $flags ) {
1138 global $wgIgnoreImageErrors;
1139
1140 $stats = MediaWikiServices::getInstance()->getStatsdDataFactory();
1141
1142 $handler = $this->getHandler();
1143
1144 $normalisedParams = $transformParams;
1145 $handler->normaliseParams( $this, $normalisedParams );
1146
1147 $thumbName = $this->thumbName( $normalisedParams );
1148 $thumbUrl = $this->getThumbUrl( $thumbName );
1149 $thumbPath = $this->getThumbPath( $thumbName ); // final thumb path
1150
1151 $tmpThumbPath = $tmpFile->getPath();
1152
1153 if ( $handler->supportsBucketing() ) {
1154 $this->generateBucketsIfNeeded( $normalisedParams, $flags );
1155 }
1156
1157 $starttime = microtime( true );
1158
1159 // Actually render the thumbnail...
1160 $thumb = $handler->doTransform( $this, $tmpThumbPath, $thumbUrl, $transformParams );
1161 $tmpFile->bind( $thumb ); // keep alive with $thumb
1162
1163 $statTiming = microtime( true ) - $starttime;
1164 $stats->timing( 'media.thumbnail.generate.transform', 1000 * $statTiming );
1165
1166 if ( !$thumb ) { // bad params?
1167 $thumb = false;
1168 } elseif ( $thumb->isError() ) { // transform error
1169 /** @var MediaTransformError $thumb */
1170 $this->lastError = $thumb->toText();
1171 // Ignore errors if requested
1172 if ( $wgIgnoreImageErrors && !( $flags & self::RENDER_NOW ) ) {
1173 $thumb = $handler->getTransform( $this, $tmpThumbPath, $thumbUrl, $transformParams );
1174 }
1175 } elseif ( $this->repo && $thumb->hasFile() && !$thumb->fileIsSource() ) {
1176 // Copy the thumbnail from the file system into storage...
1177
1178 $starttime = microtime( true );
1179
1180 $disposition = $this->getThumbDisposition( $thumbName );
1181 $status = $this->repo->quickImport( $tmpThumbPath, $thumbPath, $disposition );
1182 if ( $status->isOK() ) {
1183 $thumb->setStoragePath( $thumbPath );
1184 } else {
1185 $thumb = $this->transformErrorOutput( $thumbPath, $thumbUrl, $transformParams, $flags );
1186 }
1187
1188 $statTiming = microtime( true ) - $starttime;
1189 $stats->timing( 'media.thumbnail.generate.store', 1000 * $statTiming );
1190
1191 // Give extensions a chance to do something with this thumbnail...
1192 Hooks::run( 'FileTransformed', [ $this, $thumb, $tmpThumbPath, $thumbPath ] );
1193 }
1194
1195 return $thumb;
1196 }
1197
1198 /**
1199 * Generates chained bucketed thumbnails if needed
1200 * @param array $params
1201 * @param int $flags
1202 * @return bool Whether at least one bucket was generated
1203 */
1204 protected function generateBucketsIfNeeded( $params, $flags = 0 ) {
1205 if ( !$this->repo
1206 || !isset( $params['physicalWidth'] )
1207 || !isset( $params['physicalHeight'] )
1208 ) {
1209 return false;
1210 }
1211
1212 $bucket = $this->getThumbnailBucket( $params['physicalWidth'] );
1213
1214 if ( !$bucket || $bucket == $params['physicalWidth'] ) {
1215 return false;
1216 }
1217
1218 $bucketPath = $this->getBucketThumbPath( $bucket );
1219
1220 if ( $this->repo->fileExists( $bucketPath ) ) {
1221 return false;
1222 }
1223
1224 $starttime = microtime( true );
1225
1226 $params['physicalWidth'] = $bucket;
1227 $params['width'] = $bucket;
1228
1229 $params = $this->getHandler()->sanitizeParamsForBucketing( $params );
1230
1231 $tmpFile = $this->makeTransformTmpFile( $bucketPath );
1232
1233 if ( !$tmpFile ) {
1234 return false;
1235 }
1236
1237 $thumb = $this->generateAndSaveThumb( $tmpFile, $params, $flags );
1238
1239 $buckettime = microtime( true ) - $starttime;
1240
1241 if ( !$thumb || $thumb->isError() ) {
1242 return false;
1243 }
1244
1245 $this->tmpBucketedThumbCache[$bucket] = $tmpFile->getPath();
1246 // For the caching to work, we need to make the tmp file survive as long as
1247 // this object exists
1248 $tmpFile->bind( $this );
1249
1250 MediaWikiServices::getInstance()->getStatsdDataFactory()->timing(
1251 'media.thumbnail.generate.bucket', 1000 * $buckettime );
1252
1253 return true;
1254 }
1255
1256 /**
1257 * Returns the most appropriate source image for the thumbnail, given a target thumbnail size
1258 * @param array $params
1259 * @return array Source path and width/height of the source
1260 */
1261 public function getThumbnailSource( $params ) {
1262 if ( $this->repo
1263 && $this->getHandler()->supportsBucketing()
1264 && isset( $params['physicalWidth'] )
1265 && $bucket = $this->getThumbnailBucket( $params['physicalWidth'] )
1266 ) {
1267 if ( $this->getWidth() != 0 ) {
1268 $bucketHeight = round( $this->getHeight() * ( $bucket / $this->getWidth() ) );
1269 } else {
1270 $bucketHeight = 0;
1271 }
1272
1273 // Try to avoid reading from storage if the file was generated by this script
1274 if ( isset( $this->tmpBucketedThumbCache[$bucket] ) ) {
1275 $tmpPath = $this->tmpBucketedThumbCache[$bucket];
1276
1277 if ( file_exists( $tmpPath ) ) {
1278 return [
1279 'path' => $tmpPath,
1280 'width' => $bucket,
1281 'height' => $bucketHeight
1282 ];
1283 }
1284 }
1285
1286 $bucketPath = $this->getBucketThumbPath( $bucket );
1287
1288 if ( $this->repo->fileExists( $bucketPath ) ) {
1289 $fsFile = $this->repo->getLocalReference( $bucketPath );
1290
1291 if ( $fsFile ) {
1292 return [
1293 'path' => $fsFile->getPath(),
1294 'width' => $bucket,
1295 'height' => $bucketHeight
1296 ];
1297 }
1298 }
1299 }
1300
1301 // Thumbnailing a very large file could result in network saturation if
1302 // everyone does it at once.
1303 if ( $this->getSize() >= 1e7 ) { // 10MB
1304 $work = new PoolCounterWorkViaCallback( 'GetLocalFileCopy', sha1( $this->getName() ),
1305 [
1306 'doWork' => function () {
1307 return $this->getLocalRefPath();
1308 }
1309 ]
1310 );
1311 $srcPath = $work->execute();
1312 } else {
1313 $srcPath = $this->getLocalRefPath();
1314 }
1315
1316 // Original file
1317 return [
1318 'path' => $srcPath,
1319 'width' => $this->getWidth(),
1320 'height' => $this->getHeight()
1321 ];
1322 }
1323
1324 /**
1325 * Returns the repo path of the thumb for a given bucket
1326 * @param int $bucket
1327 * @return string
1328 */
1329 protected function getBucketThumbPath( $bucket ) {
1330 $thumbName = $this->getBucketThumbName( $bucket );
1331 return $this->getThumbPath( $thumbName );
1332 }
1333
1334 /**
1335 * Returns the name of the thumb for a given bucket
1336 * @param int $bucket
1337 * @return string
1338 */
1339 protected function getBucketThumbName( $bucket ) {
1340 return $this->thumbName( [ 'physicalWidth' => $bucket ] );
1341 }
1342
1343 /**
1344 * Creates a temp FS file with the same extension and the thumbnail
1345 * @param string $thumbPath Thumbnail path
1346 * @return TempFSFile|null
1347 */
1348 protected function makeTransformTmpFile( $thumbPath ) {
1349 $thumbExt = FileBackend::extensionFromPath( $thumbPath );
1350 return TempFSFile::factory( 'transform_', $thumbExt, wfTempDir() );
1351 }
1352
1353 /**
1354 * @param string $thumbName Thumbnail name
1355 * @param string $dispositionType Type of disposition (either "attachment" or "inline")
1356 * @return string Content-Disposition header value
1357 */
1358 function getThumbDisposition( $thumbName, $dispositionType = 'inline' ) {
1359 $fileName = $this->name; // file name to suggest
1360 $thumbExt = FileBackend::extensionFromPath( $thumbName );
1361 if ( $thumbExt != '' && $thumbExt !== $this->getExtension() ) {
1362 $fileName .= ".$thumbExt";
1363 }
1364
1365 return FileBackend::makeContentDisposition( $dispositionType, $fileName );
1366 }
1367
1368 /**
1369 * Hook into transform() to allow migration of thumbnail files
1370 * STUB
1371 * Overridden by LocalFile
1372 * @param string $thumbName
1373 */
1374 function migrateThumbFile( $thumbName ) {
1375 }
1376
1377 /**
1378 * Get a MediaHandler instance for this file
1379 *
1380 * @return MediaHandler|bool Registered MediaHandler for file's MIME type
1381 * or false if none found
1382 */
1383 function getHandler() {
1384 if ( !isset( $this->handler ) ) {
1385 $this->handler = MediaHandler::getHandler( $this->getMimeType() );
1386 }
1387
1388 return $this->handler;
1389 }
1390
1391 /**
1392 * Get a ThumbnailImage representing a file type icon
1393 *
1394 * @return ThumbnailImage
1395 */
1396 function iconThumb() {
1397 global $wgResourceBasePath, $IP;
1398 $assetsPath = "$wgResourceBasePath/resources/assets/file-type-icons/";
1399 $assetsDirectory = "$IP/resources/assets/file-type-icons/";
1400
1401 $try = [ 'fileicon-' . $this->getExtension() . '.png', 'fileicon.png' ];
1402 foreach ( $try as $icon ) {
1403 if ( file_exists( $assetsDirectory . $icon ) ) { // always FS
1404 $params = [ 'width' => 120, 'height' => 120 ];
1405
1406 return new ThumbnailImage( $this, $assetsPath . $icon, false, $params );
1407 }
1408 }
1409
1410 return null;
1411 }
1412
1413 /**
1414 * Get last thumbnailing error.
1415 * Largely obsolete.
1416 * @return string
1417 */
1418 function getLastError() {
1419 return $this->lastError;
1420 }
1421
1422 /**
1423 * Get all thumbnail names previously generated for this file
1424 * STUB
1425 * Overridden by LocalFile
1426 * @return array
1427 */
1428 function getThumbnails() {
1429 return [];
1430 }
1431
1432 /**
1433 * Purge shared caches such as thumbnails and DB data caching
1434 * STUB
1435 * Overridden by LocalFile
1436 * @param array $options Options, which include:
1437 * 'forThumbRefresh' : The purging is only to refresh thumbnails
1438 */
1439 function purgeCache( $options = [] ) {
1440 }
1441
1442 /**
1443 * Purge the file description page, but don't go after
1444 * pages using the file. Use when modifying file history
1445 * but not the current data.
1446 */
1447 function purgeDescription() {
1448 $title = $this->getTitle();
1449 if ( $title ) {
1450 $title->invalidateCache();
1451 $title->purgeSquid();
1452 }
1453 }
1454
1455 /**
1456 * Purge metadata and all affected pages when the file is created,
1457 * deleted, or majorly updated.
1458 */
1459 function purgeEverything() {
1460 // Delete thumbnails and refresh file metadata cache
1461 $this->purgeCache();
1462 $this->purgeDescription();
1463
1464 // Purge cache of all pages using this file
1465 $title = $this->getTitle();
1466 if ( $title ) {
1467 DeferredUpdates::addUpdate(
1468 new HTMLCacheUpdate( $title, 'imagelinks', 'file-purge' )
1469 );
1470 }
1471 }
1472
1473 /**
1474 * Return a fragment of the history of file.
1475 *
1476 * STUB
1477 * @param int $limit Limit of rows to return
1478 * @param string $start Only revisions older than $start will be returned
1479 * @param string $end Only revisions newer than $end will be returned
1480 * @param bool $inc Include the endpoints of the time range
1481 *
1482 * @return File[]
1483 */
1484 function getHistory( $limit = null, $start = null, $end = null, $inc = true ) {
1485 return [];
1486 }
1487
1488 /**
1489 * Return the history of this file, line by line. Starts with current version,
1490 * then old versions. Should return an object similar to an image/oldimage
1491 * database row.
1492 *
1493 * STUB
1494 * Overridden in LocalFile
1495 * @return bool
1496 */
1497 public function nextHistoryLine() {
1498 return false;
1499 }
1500
1501 /**
1502 * Reset the history pointer to the first element of the history.
1503 * Always call this function after using nextHistoryLine() to free db resources
1504 * STUB
1505 * Overridden in LocalFile.
1506 */
1507 public function resetHistory() {
1508 }
1509
1510 /**
1511 * Get the filename hash component of the directory including trailing slash,
1512 * e.g. f/fa/
1513 * If the repository is not hashed, returns an empty string.
1514 *
1515 * @return string
1516 */
1517 function getHashPath() {
1518 if ( !isset( $this->hashPath ) ) {
1519 $this->assertRepoDefined();
1520 $this->hashPath = $this->repo->getHashPath( $this->getName() );
1521 }
1522
1523 return $this->hashPath;
1524 }
1525
1526 /**
1527 * Get the path of the file relative to the public zone root.
1528 * This function is overridden in OldLocalFile to be like getArchiveRel().
1529 *
1530 * @return string
1531 */
1532 function getRel() {
1533 return $this->getHashPath() . $this->getName();
1534 }
1535
1536 /**
1537 * Get the path of an archived file relative to the public zone root
1538 *
1539 * @param bool|string $suffix If not false, the name of an archived thumbnail file
1540 *
1541 * @return string
1542 */
1543 function getArchiveRel( $suffix = false ) {
1544 $path = 'archive/' . $this->getHashPath();
1545 if ( $suffix === false ) {
1546 $path = substr( $path, 0, -1 );
1547 } else {
1548 $path .= $suffix;
1549 }
1550
1551 return $path;
1552 }
1553
1554 /**
1555 * Get the path, relative to the thumbnail zone root, of the
1556 * thumbnail directory or a particular file if $suffix is specified
1557 *
1558 * @param bool|string $suffix If not false, the name of a thumbnail file
1559 * @return string
1560 */
1561 function getThumbRel( $suffix = false ) {
1562 $path = $this->getRel();
1563 if ( $suffix !== false ) {
1564 $path .= '/' . $suffix;
1565 }
1566
1567 return $path;
1568 }
1569
1570 /**
1571 * Get urlencoded path of the file relative to the public zone root.
1572 * This function is overridden in OldLocalFile to be like getArchiveUrl().
1573 *
1574 * @return string
1575 */
1576 function getUrlRel() {
1577 return $this->getHashPath() . rawurlencode( $this->getName() );
1578 }
1579
1580 /**
1581 * Get the path, relative to the thumbnail zone root, for an archived file's thumbs directory
1582 * or a specific thumb if the $suffix is given.
1583 *
1584 * @param string $archiveName The timestamped name of an archived image
1585 * @param bool|string $suffix If not false, the name of a thumbnail file
1586 * @return string
1587 */
1588 function getArchiveThumbRel( $archiveName, $suffix = false ) {
1589 $path = 'archive/' . $this->getHashPath() . $archiveName . "/";
1590 if ( $suffix === false ) {
1591 $path = substr( $path, 0, -1 );
1592 } else {
1593 $path .= $suffix;
1594 }
1595
1596 return $path;
1597 }
1598
1599 /**
1600 * Get the path of the archived file.
1601 *
1602 * @param bool|string $suffix If not false, the name of an archived file.
1603 * @return string
1604 */
1605 function getArchivePath( $suffix = false ) {
1606 $this->assertRepoDefined();
1607
1608 return $this->repo->getZonePath( 'public' ) . '/' . $this->getArchiveRel( $suffix );
1609 }
1610
1611 /**
1612 * Get the path of an archived file's thumbs, or a particular thumb if $suffix is specified
1613 *
1614 * @param string $archiveName The timestamped name of an archived image
1615 * @param bool|string $suffix If not false, the name of a thumbnail file
1616 * @return string
1617 */
1618 function getArchiveThumbPath( $archiveName, $suffix = false ) {
1619 $this->assertRepoDefined();
1620
1621 return $this->repo->getZonePath( 'thumb' ) . '/' .
1622 $this->getArchiveThumbRel( $archiveName, $suffix );
1623 }
1624
1625 /**
1626 * Get the path of the thumbnail directory, or a particular file if $suffix is specified
1627 *
1628 * @param bool|string $suffix If not false, the name of a thumbnail file
1629 * @return string
1630 */
1631 function getThumbPath( $suffix = false ) {
1632 $this->assertRepoDefined();
1633
1634 return $this->repo->getZonePath( 'thumb' ) . '/' . $this->getThumbRel( $suffix );
1635 }
1636
1637 /**
1638 * Get the path of the transcoded directory, or a particular file if $suffix is specified
1639 *
1640 * @param bool|string $suffix If not false, the name of a media file
1641 * @return string
1642 */
1643 function getTranscodedPath( $suffix = false ) {
1644 $this->assertRepoDefined();
1645
1646 return $this->repo->getZonePath( 'transcoded' ) . '/' . $this->getThumbRel( $suffix );
1647 }
1648
1649 /**
1650 * Get the URL of the archive directory, or a particular file if $suffix is specified
1651 *
1652 * @param bool|string $suffix If not false, the name of an archived file
1653 * @return string
1654 */
1655 function getArchiveUrl( $suffix = false ) {
1656 $this->assertRepoDefined();
1657 $ext = $this->getExtension();
1658 $path = $this->repo->getZoneUrl( 'public', $ext ) . '/archive/' . $this->getHashPath();
1659 if ( $suffix === false ) {
1660 $path = substr( $path, 0, -1 );
1661 } else {
1662 $path .= rawurlencode( $suffix );
1663 }
1664
1665 return $path;
1666 }
1667
1668 /**
1669 * Get the URL of the archived file's thumbs, or a particular thumb if $suffix is specified
1670 *
1671 * @param string $archiveName The timestamped name of an archived image
1672 * @param bool|string $suffix If not false, the name of a thumbnail file
1673 * @return string
1674 */
1675 function getArchiveThumbUrl( $archiveName, $suffix = false ) {
1676 $this->assertRepoDefined();
1677 $ext = $this->getExtension();
1678 $path = $this->repo->getZoneUrl( 'thumb', $ext ) . '/archive/' .
1679 $this->getHashPath() . rawurlencode( $archiveName ) . "/";
1680 if ( $suffix === false ) {
1681 $path = substr( $path, 0, -1 );
1682 } else {
1683 $path .= rawurlencode( $suffix );
1684 }
1685
1686 return $path;
1687 }
1688
1689 /**
1690 * Get the URL of the zone directory, or a particular file if $suffix is specified
1691 *
1692 * @param string $zone Name of requested zone
1693 * @param bool|string $suffix If not false, the name of a file in zone
1694 * @return string Path
1695 */
1696 function getZoneUrl( $zone, $suffix = false ) {
1697 $this->assertRepoDefined();
1698 $ext = $this->getExtension();
1699 $path = $this->repo->getZoneUrl( $zone, $ext ) . '/' . $this->getUrlRel();
1700 if ( $suffix !== false ) {
1701 $path .= '/' . rawurlencode( $suffix );
1702 }
1703
1704 return $path;
1705 }
1706
1707 /**
1708 * Get the URL of the thumbnail directory, or a particular file if $suffix is specified
1709 *
1710 * @param bool|string $suffix If not false, the name of a thumbnail file
1711 * @return string Path
1712 */
1713 function getThumbUrl( $suffix = false ) {
1714 return $this->getZoneUrl( 'thumb', $suffix );
1715 }
1716
1717 /**
1718 * Get the URL of the transcoded directory, or a particular file if $suffix is specified
1719 *
1720 * @param bool|string $suffix If not false, the name of a media file
1721 * @return string Path
1722 */
1723 function getTranscodedUrl( $suffix = false ) {
1724 return $this->getZoneUrl( 'transcoded', $suffix );
1725 }
1726
1727 /**
1728 * Get the public zone virtual URL for a current version source file
1729 *
1730 * @param bool|string $suffix If not false, the name of a thumbnail file
1731 * @return string
1732 */
1733 function getVirtualUrl( $suffix = false ) {
1734 $this->assertRepoDefined();
1735 $path = $this->repo->getVirtualUrl() . '/public/' . $this->getUrlRel();
1736 if ( $suffix !== false ) {
1737 $path .= '/' . rawurlencode( $suffix );
1738 }
1739
1740 return $path;
1741 }
1742
1743 /**
1744 * Get the public zone virtual URL for an archived version source file
1745 *
1746 * @param bool|string $suffix If not false, the name of a thumbnail file
1747 * @return string
1748 */
1749 function getArchiveVirtualUrl( $suffix = false ) {
1750 $this->assertRepoDefined();
1751 $path = $this->repo->getVirtualUrl() . '/public/archive/' . $this->getHashPath();
1752 if ( $suffix === false ) {
1753 $path = substr( $path, 0, -1 );
1754 } else {
1755 $path .= rawurlencode( $suffix );
1756 }
1757
1758 return $path;
1759 }
1760
1761 /**
1762 * Get the virtual URL for a thumbnail file or directory
1763 *
1764 * @param bool|string $suffix If not false, the name of a thumbnail file
1765 * @return string
1766 */
1767 function getThumbVirtualUrl( $suffix = false ) {
1768 $this->assertRepoDefined();
1769 $path = $this->repo->getVirtualUrl() . '/thumb/' . $this->getUrlRel();
1770 if ( $suffix !== false ) {
1771 $path .= '/' . rawurlencode( $suffix );
1772 }
1773
1774 return $path;
1775 }
1776
1777 /**
1778 * @return bool
1779 */
1780 function isHashed() {
1781 $this->assertRepoDefined();
1782
1783 return (bool)$this->repo->getHashLevels();
1784 }
1785
1786 /**
1787 * @throws MWException
1788 */
1789 function readOnlyError() {
1790 throw new MWException( static::class . ': write operations are not supported' );
1791 }
1792
1793 /**
1794 * Record a file upload in the upload log and the image table
1795 * STUB
1796 * Overridden by LocalFile
1797 * @param string $oldver
1798 * @param string $desc
1799 * @param string $license
1800 * @param string $copyStatus
1801 * @param string $source
1802 * @param bool $watch
1803 * @param string|bool $timestamp
1804 * @param null|User $user User object or null to use $wgUser
1805 * @return bool
1806 * @throws MWException
1807 */
1808 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '',
1809 $watch = false, $timestamp = false, User $user = null
1810 ) {
1811 $this->readOnlyError();
1812 }
1813
1814 /**
1815 * Move or copy a file to its public location. If a file exists at the
1816 * destination, move it to an archive. Returns a Status object with
1817 * the archive name in the "value" member on success.
1818 *
1819 * The archive name should be passed through to recordUpload for database
1820 * registration.
1821 *
1822 * Options to $options include:
1823 * - headers : name/value map of HTTP headers to use in response to GET/HEAD requests
1824 *
1825 * @param string|FSFile $src Local filesystem path to the source image
1826 * @param int $flags A bitwise combination of:
1827 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1828 * @param array $options Optional additional parameters
1829 * @return Status On success, the value member contains the
1830 * archive name, or an empty string if it was a new file.
1831 *
1832 * STUB
1833 * Overridden by LocalFile
1834 */
1835 function publish( $src, $flags = 0, array $options = [] ) {
1836 $this->readOnlyError();
1837 }
1838
1839 /**
1840 * @param bool|IContextSource $context Context to use (optional)
1841 * @return bool
1842 */
1843 function formatMetadata( $context = false ) {
1844 if ( !$this->getHandler() ) {
1845 return false;
1846 }
1847
1848 return $this->getHandler()->formatMetadata( $this, $context );
1849 }
1850
1851 /**
1852 * Returns true if the file comes from the local file repository.
1853 *
1854 * @return bool
1855 */
1856 function isLocal() {
1857 return $this->repo && $this->repo->isLocal();
1858 }
1859
1860 /**
1861 * Returns the name of the repository.
1862 *
1863 * @return string
1864 */
1865 function getRepoName() {
1866 return $this->repo ? $this->repo->getName() : 'unknown';
1867 }
1868
1869 /**
1870 * Returns the repository
1871 *
1872 * @return FileRepo|LocalRepo|bool
1873 */
1874 function getRepo() {
1875 return $this->repo;
1876 }
1877
1878 /**
1879 * Returns true if the image is an old version
1880 * STUB
1881 *
1882 * @return bool
1883 */
1884 function isOld() {
1885 return false;
1886 }
1887
1888 /**
1889 * Is this file a "deleted" file in a private archive?
1890 * STUB
1891 *
1892 * @param int $field One of DELETED_* bitfield constants
1893 * @return bool
1894 */
1895 function isDeleted( $field ) {
1896 return false;
1897 }
1898
1899 /**
1900 * Return the deletion bitfield
1901 * STUB
1902 * @return int
1903 */
1904 function getVisibility() {
1905 return 0;
1906 }
1907
1908 /**
1909 * Was this file ever deleted from the wiki?
1910 *
1911 * @return bool
1912 */
1913 function wasDeleted() {
1914 $title = $this->getTitle();
1915
1916 return $title && $title->isDeletedQuick();
1917 }
1918
1919 /**
1920 * Move file to the new title
1921 *
1922 * Move current, old version and all thumbnails
1923 * to the new filename. Old file is deleted.
1924 *
1925 * Cache purging is done; checks for validity
1926 * and logging are caller's responsibility
1927 *
1928 * @param Title $target New file name
1929 * @return Status
1930 */
1931 function move( $target ) {
1932 $this->readOnlyError();
1933 }
1934
1935 /**
1936 * Delete all versions of the file.
1937 *
1938 * Moves the files into an archive directory (or deletes them)
1939 * and removes the database rows.
1940 *
1941 * Cache purging is done; logging is caller's responsibility.
1942 *
1943 * @param string $reason
1944 * @param bool $suppress Hide content from sysops?
1945 * @param User|null $user
1946 * @return Status
1947 * STUB
1948 * Overridden by LocalFile
1949 */
1950 function delete( $reason, $suppress = false, $user = null ) {
1951 $this->readOnlyError();
1952 }
1953
1954 /**
1955 * Restore all or specified deleted revisions to the given file.
1956 * Permissions and logging are left to the caller.
1957 *
1958 * May throw database exceptions on error.
1959 *
1960 * @param array $versions Set of record ids of deleted items to restore,
1961 * or empty to restore all revisions.
1962 * @param bool $unsuppress Remove restrictions on content upon restoration?
1963 * @return int|bool The number of file revisions restored if successful,
1964 * or false on failure
1965 * STUB
1966 * Overridden by LocalFile
1967 */
1968 function restore( $versions = [], $unsuppress = false ) {
1969 $this->readOnlyError();
1970 }
1971
1972 /**
1973 * Returns 'true' if this file is a type which supports multiple pages,
1974 * e.g. DJVU or PDF. Note that this may be true even if the file in
1975 * question only has a single page.
1976 *
1977 * @return bool
1978 */
1979 function isMultipage() {
1980 return $this->getHandler() && $this->handler->isMultiPage( $this );
1981 }
1982
1983 /**
1984 * Returns the number of pages of a multipage document, or false for
1985 * documents which aren't multipage documents
1986 *
1987 * @return string|bool|int
1988 */
1989 function pageCount() {
1990 if ( !isset( $this->pageCount ) ) {
1991 if ( $this->getHandler() && $this->handler->isMultiPage( $this ) ) {
1992 $this->pageCount = $this->handler->pageCount( $this );
1993 } else {
1994 $this->pageCount = false;
1995 }
1996 }
1997
1998 return $this->pageCount;
1999 }
2000
2001 /**
2002 * Calculate the height of a thumbnail using the source and destination width
2003 *
2004 * @param int $srcWidth
2005 * @param int $srcHeight
2006 * @param int $dstWidth
2007 *
2008 * @return int
2009 */
2010 static function scaleHeight( $srcWidth, $srcHeight, $dstWidth ) {
2011 // Exact integer multiply followed by division
2012 if ( $srcWidth == 0 ) {
2013 return 0;
2014 } else {
2015 return (int)round( $srcHeight * $dstWidth / $srcWidth );
2016 }
2017 }
2018
2019 /**
2020 * Get an image size array like that returned by getImageSize(), or false if it
2021 * can't be determined. Loads the image size directly from the file ignoring caches.
2022 *
2023 * @note Use getWidth()/getHeight() instead of this method unless you have a
2024 * a good reason. This method skips all caches.
2025 *
2026 * @param string $filePath The path to the file (e.g. From getLocalPathRef() )
2027 * @return array|false The width, followed by height, with optionally more things after
2028 */
2029 function getImageSize( $filePath ) {
2030 if ( !$this->getHandler() ) {
2031 return false;
2032 }
2033
2034 return $this->getHandler()->getImageSize( $this, $filePath );
2035 }
2036
2037 /**
2038 * Get the URL of the image description page. May return false if it is
2039 * unknown or not applicable.
2040 *
2041 * @return string
2042 */
2043 function getDescriptionUrl() {
2044 if ( $this->repo ) {
2045 return $this->repo->getDescriptionUrl( $this->getName() );
2046 } else {
2047 return false;
2048 }
2049 }
2050
2051 /**
2052 * Get the HTML text of the description page, if available
2053 *
2054 * @param bool|Language $lang Optional language to fetch description in
2055 * @return string|false
2056 */
2057 function getDescriptionText( $lang = false ) {
2058 global $wgLang;
2059
2060 if ( !$this->repo || !$this->repo->fetchDescription ) {
2061 return false;
2062 }
2063
2064 $lang = $lang ?: $wgLang;
2065
2066 $renderUrl = $this->repo->getDescriptionRenderUrl( $this->getName(), $lang->getCode() );
2067 if ( $renderUrl ) {
2068 $cache = ObjectCache::getMainWANInstance();
2069 $key = $this->repo->getLocalCacheKey(
2070 'RemoteFileDescription',
2071 'url',
2072 $lang->getCode(),
2073 $this->getName()
2074 );
2075
2076 return $cache->getWithSetCallback(
2077 $key,
2078 $this->repo->descriptionCacheExpiry ?: $cache::TTL_UNCACHEABLE,
2079 function ( $oldValue, &$ttl, array &$setOpts ) use ( $renderUrl ) {
2080 wfDebug( "Fetching shared description from $renderUrl\n" );
2081 $res = Http::get( $renderUrl, [], __METHOD__ );
2082 if ( !$res ) {
2083 $ttl = WANObjectCache::TTL_UNCACHEABLE;
2084 }
2085
2086 return $res;
2087 }
2088 );
2089 }
2090
2091 return false;
2092 }
2093
2094 /**
2095 * Get description of file revision
2096 * STUB
2097 *
2098 * @param int $audience One of:
2099 * File::FOR_PUBLIC to be displayed to all users
2100 * File::FOR_THIS_USER to be displayed to the given user
2101 * File::RAW get the description regardless of permissions
2102 * @param User $user User object to check for, only if FOR_THIS_USER is
2103 * passed to the $audience parameter
2104 * @return string
2105 */
2106 function getDescription( $audience = self::FOR_PUBLIC, User $user = null ) {
2107 return null;
2108 }
2109
2110 /**
2111 * Get the 14-character timestamp of the file upload
2112 *
2113 * @return string|bool TS_MW timestamp or false on failure
2114 */
2115 function getTimestamp() {
2116 $this->assertRepoDefined();
2117
2118 return $this->repo->getFileTimestamp( $this->getPath() );
2119 }
2120
2121 /**
2122 * Returns the timestamp (in TS_MW format) of the last change of the description page.
2123 * Returns false if the file does not have a description page, or retrieving the timestamp
2124 * would be expensive.
2125 * @since 1.25
2126 * @return string|bool
2127 */
2128 public function getDescriptionTouched() {
2129 return false;
2130 }
2131
2132 /**
2133 * Get the SHA-1 base 36 hash of the file
2134 *
2135 * @return string
2136 */
2137 function getSha1() {
2138 $this->assertRepoDefined();
2139
2140 return $this->repo->getFileSha1( $this->getPath() );
2141 }
2142
2143 /**
2144 * Get the deletion archive key, "<sha1>.<ext>"
2145 *
2146 * @return string|false
2147 */
2148 function getStorageKey() {
2149 $hash = $this->getSha1();
2150 if ( !$hash ) {
2151 return false;
2152 }
2153 $ext = $this->getExtension();
2154 $dotExt = $ext === '' ? '' : ".$ext";
2155
2156 return $hash . $dotExt;
2157 }
2158
2159 /**
2160 * Determine if the current user is allowed to view a particular
2161 * field of this file, if it's marked as deleted.
2162 * STUB
2163 * @param int $field
2164 * @param User $user User object to check, or null to use $wgUser
2165 * @return bool
2166 */
2167 function userCan( $field, User $user = null ) {
2168 return true;
2169 }
2170
2171 /**
2172 * @deprecated since 1.30, use File::getContentHeaders instead
2173 */
2174 function getStreamHeaders() {
2175 wfDeprecated( __METHOD__, '1.30' );
2176 return $this->getContentHeaders();
2177 }
2178
2179 /**
2180 * @return array HTTP header name/value map to use for HEAD/GET request responses
2181 * @since 1.30
2182 */
2183 function getContentHeaders() {
2184 $handler = $this->getHandler();
2185 if ( $handler ) {
2186 $metadata = $this->getMetadata();
2187
2188 if ( is_string( $metadata ) ) {
2189 $metadata = MediaWiki\quietCall( 'unserialize', $metadata );
2190 }
2191
2192 if ( !is_array( $metadata ) ) {
2193 $metadata = [];
2194 }
2195
2196 return $handler->getContentHeaders( $metadata );
2197 }
2198
2199 return [];
2200 }
2201
2202 /**
2203 * @return string
2204 */
2205 function getLongDesc() {
2206 $handler = $this->getHandler();
2207 if ( $handler ) {
2208 return $handler->getLongDesc( $this );
2209 } else {
2210 return MediaHandler::getGeneralLongDesc( $this );
2211 }
2212 }
2213
2214 /**
2215 * @return string
2216 */
2217 function getShortDesc() {
2218 $handler = $this->getHandler();
2219 if ( $handler ) {
2220 return $handler->getShortDesc( $this );
2221 } else {
2222 return MediaHandler::getGeneralShortDesc( $this );
2223 }
2224 }
2225
2226 /**
2227 * @return string
2228 */
2229 function getDimensionsString() {
2230 $handler = $this->getHandler();
2231 if ( $handler ) {
2232 return $handler->getDimensionsString( $this );
2233 } else {
2234 return '';
2235 }
2236 }
2237
2238 /**
2239 * @return string
2240 */
2241 function getRedirected() {
2242 return $this->redirected;
2243 }
2244
2245 /**
2246 * @return Title|null
2247 */
2248 function getRedirectedTitle() {
2249 if ( $this->redirected ) {
2250 if ( !$this->redirectTitle ) {
2251 $this->redirectTitle = Title::makeTitle( NS_FILE, $this->redirected );
2252 }
2253
2254 return $this->redirectTitle;
2255 }
2256
2257 return null;
2258 }
2259
2260 /**
2261 * @param string $from
2262 * @return void
2263 */
2264 function redirectedFrom( $from ) {
2265 $this->redirected = $from;
2266 }
2267
2268 /**
2269 * @return bool
2270 */
2271 function isMissing() {
2272 return false;
2273 }
2274
2275 /**
2276 * Check if this file object is small and can be cached
2277 * @return bool
2278 */
2279 public function isCacheable() {
2280 return true;
2281 }
2282
2283 /**
2284 * Assert that $this->repo is set to a valid FileRepo instance
2285 * @throws MWException
2286 */
2287 protected function assertRepoDefined() {
2288 if ( !( $this->repo instanceof $this->repoClass ) ) {
2289 throw new MWException( "A {$this->repoClass} object is not set for this File.\n" );
2290 }
2291 }
2292
2293 /**
2294 * Assert that $this->title is set to a Title
2295 * @throws MWException
2296 */
2297 protected function assertTitleDefined() {
2298 if ( !( $this->title instanceof Title ) ) {
2299 throw new MWException( "A Title object is not set for this File.\n" );
2300 }
2301 }
2302
2303 /**
2304 * True if creating thumbnails from the file is large or otherwise resource-intensive.
2305 * @return bool
2306 */
2307 public function isExpensiveToThumbnail() {
2308 $handler = $this->getHandler();
2309 return $handler ? $handler->isExpensiveToThumbnail( $this ) : false;
2310 }
2311
2312 /**
2313 * Whether the thumbnails created on the same server as this code is running.
2314 * @since 1.25
2315 * @return bool
2316 */
2317 public function isTransformedLocally() {
2318 return true;
2319 }
2320 }