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