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