Merge "Made Title cache use MapCacheLRU"
[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 return $handler->getCommonMetaArray( $this );
587 }
588
589 /**
590 * get versioned metadata
591 *
592 * @param array|string $metadata Array or string of (serialized) metadata
593 * @param int $version Version number.
594 * @return array Array containing metadata, or what was passed to it on fail
595 * (unserializing if not array)
596 */
597 public function convertMetadataVersion( $metadata, $version ) {
598 $handler = $this->getHandler();
599 if ( !is_array( $metadata ) ) {
600 // Just to make the return type consistent
601 $metadata = unserialize( $metadata );
602 }
603 if ( $handler ) {
604 return $handler->convertMetadataVersion( $metadata, $version );
605 } else {
606 return $metadata;
607 }
608 }
609
610 /**
611 * Return the bit depth of the file
612 * Overridden by LocalFile
613 * STUB
614 * @return int
615 */
616 public function getBitDepth() {
617 return 0;
618 }
619
620 /**
621 * Return the size of the image file, in bytes
622 * Overridden by LocalFile, UnregisteredLocalFile
623 * STUB
624 * @return bool
625 */
626 public function getSize() {
627 return false;
628 }
629
630 /**
631 * Returns the mime type of the file.
632 * Overridden by LocalFile, UnregisteredLocalFile
633 * STUB
634 *
635 * @return string
636 */
637 function getMimeType() {
638 return 'unknown/unknown';
639 }
640
641 /**
642 * Return the type of the media in the file.
643 * Use the value returned by this function with the MEDIATYPE_xxx constants.
644 * Overridden by LocalFile,
645 * STUB
646 * @return string
647 */
648 function getMediaType() {
649 return MEDIATYPE_UNKNOWN;
650 }
651
652 /**
653 * Checks if the output of transform() for this file is likely
654 * to be valid. If this is false, various user elements will
655 * display a placeholder instead.
656 *
657 * Currently, this checks if the file is an image format
658 * that can be converted to a format
659 * supported by all browsers (namely GIF, PNG and JPEG),
660 * or if it is an SVG image and SVG conversion is enabled.
661 *
662 * @return bool
663 */
664 function canRender() {
665 if ( !isset( $this->canRender ) ) {
666 $this->canRender = $this->getHandler() && $this->handler->canRender( $this );
667 }
668
669 return $this->canRender;
670 }
671
672 /**
673 * Accessor for __get()
674 * @return bool
675 */
676 protected function getCanRender() {
677 return $this->canRender();
678 }
679
680 /**
681 * Return true if the file is of a type that can't be directly
682 * rendered by typical browsers and needs to be re-rasterized.
683 *
684 * This returns true for everything but the bitmap types
685 * supported by all browsers, i.e. JPEG; GIF and PNG. It will
686 * also return true for any non-image formats.
687 *
688 * @return bool
689 */
690 function mustRender() {
691 return $this->getHandler() && $this->handler->mustRender( $this );
692 }
693
694 /**
695 * Alias for canRender()
696 *
697 * @return bool
698 */
699 function allowInlineDisplay() {
700 return $this->canRender();
701 }
702
703 /**
704 * Determines if this media file is in a format that is unlikely to
705 * contain viruses or malicious content. It uses the global
706 * $wgTrustedMediaFormats list to determine if the file is safe.
707 *
708 * This is used to show a warning on the description page of non-safe files.
709 * It may also be used to disallow direct [[media:...]] links to such files.
710 *
711 * Note that this function will always return true if allowInlineDisplay()
712 * or isTrustedFile() is true for this file.
713 *
714 * @return bool
715 */
716 function isSafeFile() {
717 if ( !isset( $this->isSafeFile ) ) {
718 $this->isSafeFile = $this->getIsSafeFileUncached();
719 }
720
721 return $this->isSafeFile;
722 }
723
724 /**
725 * Accessor for __get()
726 *
727 * @return bool
728 */
729 protected function getIsSafeFile() {
730 return $this->isSafeFile();
731 }
732
733 /**
734 * Uncached accessor
735 *
736 * @return bool
737 */
738 protected function getIsSafeFileUncached() {
739 global $wgTrustedMediaFormats;
740
741 if ( $this->allowInlineDisplay() ) {
742 return true;
743 }
744 if ( $this->isTrustedFile() ) {
745 return true;
746 }
747
748 $type = $this->getMediaType();
749 $mime = $this->getMimeType();
750 #wfDebug( "LocalFile::isSafeFile: type= $type, mime= $mime\n" );
751
752 if ( !$type || $type === MEDIATYPE_UNKNOWN ) {
753 return false; #unknown type, not trusted
754 }
755 if ( in_array( $type, $wgTrustedMediaFormats ) ) {
756 return true;
757 }
758
759 if ( $mime === "unknown/unknown" ) {
760 return false; #unknown type, not trusted
761 }
762 if ( in_array( $mime, $wgTrustedMediaFormats ) ) {
763 return true;
764 }
765
766 return false;
767 }
768
769 /**
770 * Returns true if the file is flagged as trusted. Files flagged that way
771 * can be linked to directly, even if that is not allowed for this type of
772 * file normally.
773 *
774 * This is a dummy function right now and always returns false. It could be
775 * implemented to extract a flag from the database. The trusted flag could be
776 * set on upload, if the user has sufficient privileges, to bypass script-
777 * and html-filters. It may even be coupled with cryptographics signatures
778 * or such.
779 *
780 * @return bool
781 */
782 function isTrustedFile() {
783 #this could be implemented to check a flag in the database,
784 #look for signatures, etc
785 return false;
786 }
787
788 /**
789 * Returns true if file exists in the repository.
790 *
791 * Overridden by LocalFile to avoid unnecessary stat calls.
792 *
793 * @return bool Whether file exists in the repository.
794 */
795 public function exists() {
796 return $this->getPath() && $this->repo->fileExists( $this->path );
797 }
798
799 /**
800 * Returns true if file exists in the repository and can be included in a page.
801 * It would be unsafe to include private images, making public thumbnails inadvertently
802 *
803 * @return bool Whether file exists in the repository and is includable.
804 */
805 public function isVisible() {
806 return $this->exists();
807 }
808
809 /**
810 * @return string
811 */
812 function getTransformScript() {
813 if ( !isset( $this->transformScript ) ) {
814 $this->transformScript = false;
815 if ( $this->repo ) {
816 $script = $this->repo->getThumbScriptUrl();
817 if ( $script ) {
818 $this->transformScript = wfAppendQuery( $script, array( 'f' => $this->getName() ) );
819 }
820 }
821 }
822
823 return $this->transformScript;
824 }
825
826 /**
827 * Get a ThumbnailImage which is the same size as the source
828 *
829 * @param array $handlerParams
830 *
831 * @return string
832 */
833 function getUnscaledThumb( $handlerParams = array() ) {
834 $hp =& $handlerParams;
835 $page = isset( $hp['page'] ) ? $hp['page'] : false;
836 $width = $this->getWidth( $page );
837 if ( !$width ) {
838 return $this->iconThumb();
839 }
840 $hp['width'] = $width;
841
842 return $this->transform( $hp );
843 }
844
845 /**
846 * Return the file name of a thumbnail with the specified parameters.
847 * Use File::THUMB_FULL_NAME to always get a name like "<params>-<source>".
848 * Otherwise, the format may be "<params>-<source>" or "<params>-thumbnail.<ext>".
849 *
850 * @param array $params handler-specific parameters
851 * @param int $flags Bitfield that supports THUMB_* constants
852 * @return string
853 */
854 public function thumbName( $params, $flags = 0 ) {
855 $name = ( $this->repo && !( $flags & self::THUMB_FULL_NAME ) )
856 ? $this->repo->nameForThumb( $this->getName() )
857 : $this->getName();
858
859 return $this->generateThumbName( $name, $params );
860 }
861
862 /**
863 * Generate a thumbnail file name from a name and specified parameters
864 *
865 * @param string $name
866 * @param array $params Parameters which will be passed to MediaHandler::makeParamString
867 * @return string
868 */
869 public function generateThumbName( $name, $params ) {
870 if ( !$this->getHandler() ) {
871 return null;
872 }
873 $extension = $this->getExtension();
874 list( $thumbExt, ) = $this->handler->getThumbType(
875 $extension, $this->getMimeType(), $params );
876 $thumbName = $this->handler->makeParamString( $params ) . '-' . $name;
877 if ( $thumbExt != $extension ) {
878 $thumbName .= ".$thumbExt";
879 }
880
881 return $thumbName;
882 }
883
884 /**
885 * Create a thumbnail of the image having the specified width/height.
886 * The thumbnail will not be created if the width is larger than the
887 * image's width. Let the browser do the scaling in this case.
888 * The thumbnail is stored on disk and is only computed if the thumbnail
889 * file does not exist OR if it is older than the image.
890 * Returns the URL.
891 *
892 * Keeps aspect ratio of original image. If both width and height are
893 * specified, the generated image will be no bigger than width x height,
894 * and will also have correct aspect ratio.
895 *
896 * @param int $width Maximum width of the generated thumbnail
897 * @param int $height Maximum height of the image (optional)
898 *
899 * @return string
900 */
901 public function createThumb( $width, $height = -1 ) {
902 $params = array( 'width' => $width );
903 if ( $height != -1 ) {
904 $params['height'] = $height;
905 }
906 $thumb = $this->transform( $params );
907 if ( !$thumb || $thumb->isError() ) {
908 return '';
909 }
910
911 return $thumb->getUrl();
912 }
913
914 /**
915 * Return either a MediaTransformError or placeholder thumbnail (if $wgIgnoreImageErrors)
916 *
917 * @param string $thumbPath Thumbnail storage path
918 * @param string $thumbUrl Thumbnail URL
919 * @param array $params
920 * @param int $flags
921 * @return MediaTransformOutput
922 */
923 protected function transformErrorOutput( $thumbPath, $thumbUrl, $params, $flags ) {
924 global $wgIgnoreImageErrors;
925
926 $handler = $this->getHandler();
927 if ( $handler && $wgIgnoreImageErrors && !( $flags & self::RENDER_NOW ) ) {
928 return $handler->getTransform( $this, $thumbPath, $thumbUrl, $params );
929 } else {
930 return new MediaTransformError( 'thumbnail_error',
931 $params['width'], 0, wfMessage( 'thumbnail-dest-create' )->text() );
932 }
933 }
934
935 /**
936 * Transform a media file
937 *
938 * @param array $params an associative array of handler-specific parameters.
939 * Typical keys are width, height and page.
940 * @param int $flags A bitfield, may contain self::RENDER_NOW to force rendering
941 * @return MediaTransformOutput|bool False on failure
942 */
943 function transform( $params, $flags = 0 ) {
944 global $wgUseSquid, $wgIgnoreImageErrors, $wgThumbnailEpoch;
945
946 wfProfileIn( __METHOD__ );
947 do {
948 if ( !$this->canRender() ) {
949 $thumb = $this->iconThumb();
950 break; // not a bitmap or renderable image, don't try
951 }
952
953 // Get the descriptionUrl to embed it as comment into the thumbnail. Bug 19791.
954 $descriptionUrl = $this->getDescriptionUrl();
955 if ( $descriptionUrl ) {
956 $params['descriptionUrl'] = wfExpandUrl( $descriptionUrl, PROTO_CANONICAL );
957 }
958
959 $handler = $this->getHandler();
960 $script = $this->getTransformScript();
961 if ( $script && !( $flags & self::RENDER_NOW ) ) {
962 // Use a script to transform on client request, if possible
963 $thumb = $handler->getScriptedTransform( $this, $script, $params );
964 if ( $thumb ) {
965 break;
966 }
967 }
968
969 $normalisedParams = $params;
970 $handler->normaliseParams( $this, $normalisedParams );
971
972 $thumbName = $this->thumbName( $normalisedParams );
973 $thumbUrl = $this->getThumbUrl( $thumbName );
974 $thumbPath = $this->getThumbPath( $thumbName ); // final thumb path
975
976 if ( $this->repo ) {
977 // Defer rendering if a 404 handler is set up...
978 if ( $this->repo->canTransformVia404() && !( $flags & self::RENDER_NOW ) ) {
979 wfDebug( __METHOD__ . " transformation deferred." );
980 // XXX: Pass in the storage path even though we are not rendering anything
981 // and the path is supposed to be an FS path. This is due to getScalerType()
982 // getting called on the path and clobbering $thumb->getUrl() if it's false.
983 $thumb = $handler->getTransform( $this, $thumbPath, $thumbUrl, $params );
984 break;
985 }
986 // Clean up broken thumbnails as needed
987 $this->migrateThumbFile( $thumbName );
988 // Check if an up-to-date thumbnail already exists...
989 wfDebug( __METHOD__ . ": Doing stat for $thumbPath\n" );
990 if ( !( $flags & self::RENDER_FORCE ) && $this->repo->fileExists( $thumbPath ) ) {
991 $timestamp = $this->repo->getFileTimestamp( $thumbPath );
992 if ( $timestamp !== false && $timestamp >= $wgThumbnailEpoch ) {
993 // XXX: Pass in the storage path even though we are not rendering anything
994 // and the path is supposed to be an FS path. This is due to getScalerType()
995 // getting called on the path and clobbering $thumb->getUrl() if it's false.
996 $thumb = $handler->getTransform( $this, $thumbPath, $thumbUrl, $params );
997 $thumb->setStoragePath( $thumbPath );
998 break;
999 }
1000 } elseif ( $flags & self::RENDER_FORCE ) {
1001 wfDebug( __METHOD__ . " forcing rendering per flag File::RENDER_FORCE\n" );
1002 }
1003 }
1004
1005 // If the backend is ready-only, don't keep generating thumbnails
1006 // only to return transformation errors, just return the error now.
1007 if ( $this->repo->getReadOnlyReason() !== false ) {
1008 $thumb = $this->transformErrorOutput( $thumbPath, $thumbUrl, $params, $flags );
1009 break;
1010 }
1011
1012 // Create a temp FS file with the same extension and the thumbnail
1013 $thumbExt = FileBackend::extensionFromPath( $thumbPath );
1014 $tmpFile = TempFSFile::factory( 'transform_', $thumbExt );
1015 if ( !$tmpFile ) {
1016 $thumb = $this->transformErrorOutput( $thumbPath, $thumbUrl, $params, $flags );
1017 break;
1018 }
1019 $tmpThumbPath = $tmpFile->getPath(); // path of 0-byte temp file
1020
1021 // Actually render the thumbnail...
1022 wfProfileIn( __METHOD__ . '-doTransform' );
1023 $thumb = $handler->doTransform( $this, $tmpThumbPath, $thumbUrl, $params );
1024 wfProfileOut( __METHOD__ . '-doTransform' );
1025 $tmpFile->bind( $thumb ); // keep alive with $thumb
1026
1027 if ( !$thumb ) { // bad params?
1028 $thumb = null;
1029 } elseif ( $thumb->isError() ) { // transform error
1030 $this->lastError = $thumb->toText();
1031 // Ignore errors if requested
1032 if ( $wgIgnoreImageErrors && !( $flags & self::RENDER_NOW ) ) {
1033 $thumb = $handler->getTransform( $this, $tmpThumbPath, $thumbUrl, $params );
1034 }
1035 } elseif ( $this->repo && $thumb->hasFile() && !$thumb->fileIsSource() ) {
1036 // Copy the thumbnail from the file system into storage...
1037 $disposition = $this->getThumbDisposition( $thumbName );
1038 $status = $this->repo->quickImport( $tmpThumbPath, $thumbPath, $disposition );
1039 if ( $status->isOK() ) {
1040 $thumb->setStoragePath( $thumbPath );
1041 } else {
1042 $thumb = $this->transformErrorOutput( $thumbPath, $thumbUrl, $params, $flags );
1043 }
1044 // Give extensions a chance to do something with this thumbnail...
1045 wfRunHooks( 'FileTransformed', array( $this, $thumb, $tmpThumbPath, $thumbPath ) );
1046 }
1047
1048 // Purge. Useful in the event of Core -> Squid connection failure or squid
1049 // purge collisions from elsewhere during failure. Don't keep triggering for
1050 // "thumbs" which have the main image URL though (bug 13776)
1051 if ( $wgUseSquid ) {
1052 if ( !$thumb || $thumb->isError() || $thumb->getUrl() != $this->getURL() ) {
1053 SquidUpdate::purge( array( $thumbUrl ) );
1054 }
1055 }
1056 } while ( false );
1057
1058 wfProfileOut( __METHOD__ );
1059
1060 return is_object( $thumb ) ? $thumb : false;
1061 }
1062
1063 /**
1064 * @param string $thumbName Thumbnail name
1065 * @return string Content-Disposition header value
1066 */
1067 function getThumbDisposition( $thumbName ) {
1068 $fileName = $this->name; // file name to suggest
1069 $thumbExt = FileBackend::extensionFromPath( $thumbName );
1070 if ( $thumbExt != '' && $thumbExt !== $this->getExtension() ) {
1071 $fileName .= ".$thumbExt";
1072 }
1073
1074 return FileBackend::makeContentDisposition( 'inline', $fileName );
1075 }
1076
1077 /**
1078 * Hook into transform() to allow migration of thumbnail files
1079 * STUB
1080 * Overridden by LocalFile
1081 */
1082 function migrateThumbFile( $thumbName ) {
1083 }
1084
1085 /**
1086 * Get a MediaHandler instance for this file
1087 *
1088 * @return MediaHandler|bool Registered MediaHandler for file's MIME type
1089 * or false if none found
1090 */
1091 function getHandler() {
1092 if ( !isset( $this->handler ) ) {
1093 $this->handler = MediaHandler::getHandler( $this->getMimeType() );
1094 }
1095
1096 return $this->handler;
1097 }
1098
1099 /**
1100 * Get a ThumbnailImage representing a file type icon
1101 *
1102 * @return ThumbnailImage
1103 */
1104 function iconThumb() {
1105 global $wgStylePath, $wgStyleDirectory;
1106
1107 $try = array( 'fileicon-' . $this->getExtension() . '.png', 'fileicon.png' );
1108 foreach ( $try as $icon ) {
1109 $path = '/common/images/icons/' . $icon;
1110 $filepath = $wgStyleDirectory . $path;
1111 if ( file_exists( $filepath ) ) { // always FS
1112 $params = array( 'width' => 120, 'height' => 120 );
1113
1114 return new ThumbnailImage( $this, $wgStylePath . $path, false, $params );
1115 }
1116 }
1117
1118 return null;
1119 }
1120
1121 /**
1122 * Get last thumbnailing error.
1123 * Largely obsolete.
1124 */
1125 function getLastError() {
1126 return $this->lastError;
1127 }
1128
1129 /**
1130 * Get all thumbnail names previously generated for this file
1131 * STUB
1132 * Overridden by LocalFile
1133 * @return array
1134 */
1135 function getThumbnails() {
1136 return array();
1137 }
1138
1139 /**
1140 * Purge shared caches such as thumbnails and DB data caching
1141 * STUB
1142 * Overridden by LocalFile
1143 * @param array $options Options, which include:
1144 * 'forThumbRefresh' : The purging is only to refresh thumbnails
1145 */
1146 function purgeCache( $options = array() ) {
1147 }
1148
1149 /**
1150 * Purge the file description page, but don't go after
1151 * pages using the file. Use when modifying file history
1152 * but not the current data.
1153 */
1154 function purgeDescription() {
1155 $title = $this->getTitle();
1156 if ( $title ) {
1157 $title->invalidateCache();
1158 $title->purgeSquid();
1159 }
1160 }
1161
1162 /**
1163 * Purge metadata and all affected pages when the file is created,
1164 * deleted, or majorly updated.
1165 */
1166 function purgeEverything() {
1167 // Delete thumbnails and refresh file metadata cache
1168 $this->purgeCache();
1169 $this->purgeDescription();
1170
1171 // Purge cache of all pages using this file
1172 $title = $this->getTitle();
1173 if ( $title ) {
1174 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
1175 $update->doUpdate();
1176 }
1177 }
1178
1179 /**
1180 * Return a fragment of the history of file.
1181 *
1182 * STUB
1183 * @param int $limit Limit of rows to return
1184 * @param string $start timestamp Only revisions older than $start will be returned
1185 * @param string $end timestamp Only revisions newer than $end will be returned
1186 * @param bool $inc Include the endpoints of the time range
1187 *
1188 * @return array
1189 */
1190 function getHistory( $limit = null, $start = null, $end = null, $inc = true ) {
1191 return array();
1192 }
1193
1194 /**
1195 * Return the history of this file, line by line. Starts with current version,
1196 * then old versions. Should return an object similar to an image/oldimage
1197 * database row.
1198 *
1199 * STUB
1200 * Overridden in LocalFile
1201 * @return bool
1202 */
1203 public function nextHistoryLine() {
1204 return false;
1205 }
1206
1207 /**
1208 * Reset the history pointer to the first element of the history.
1209 * Always call this function after using nextHistoryLine() to free db resources
1210 * STUB
1211 * Overridden in LocalFile.
1212 */
1213 public function resetHistory() {
1214 }
1215
1216 /**
1217 * Get the filename hash component of the directory including trailing slash,
1218 * e.g. f/fa/
1219 * If the repository is not hashed, returns an empty string.
1220 *
1221 * @return string
1222 */
1223 function getHashPath() {
1224 if ( !isset( $this->hashPath ) ) {
1225 $this->assertRepoDefined();
1226 $this->hashPath = $this->repo->getHashPath( $this->getName() );
1227 }
1228
1229 return $this->hashPath;
1230 }
1231
1232 /**
1233 * Get the path of the file relative to the public zone root.
1234 * This function is overriden in OldLocalFile to be like getArchiveRel().
1235 *
1236 * @return string
1237 */
1238 function getRel() {
1239 return $this->getHashPath() . $this->getName();
1240 }
1241
1242 /**
1243 * Get the path of an archived file relative to the public zone root
1244 *
1245 * @param bool|string $suffix if not false, the name of an archived thumbnail file
1246 *
1247 * @return string
1248 */
1249 function getArchiveRel( $suffix = false ) {
1250 $path = 'archive/' . $this->getHashPath();
1251 if ( $suffix === false ) {
1252 $path = substr( $path, 0, -1 );
1253 } else {
1254 $path .= $suffix;
1255 }
1256
1257 return $path;
1258 }
1259
1260 /**
1261 * Get the path, relative to the thumbnail zone root, of the
1262 * thumbnail directory or a particular file if $suffix is specified
1263 *
1264 * @param bool|string $suffix if not false, the name of a thumbnail file
1265 * @return string
1266 */
1267 function getThumbRel( $suffix = false ) {
1268 $path = $this->getRel();
1269 if ( $suffix !== false ) {
1270 $path .= '/' . $suffix;
1271 }
1272
1273 return $path;
1274 }
1275
1276 /**
1277 * Get urlencoded path of the file relative to the public zone root.
1278 * This function is overriden in OldLocalFile to be like getArchiveUrl().
1279 *
1280 * @return string
1281 */
1282 function getUrlRel() {
1283 return $this->getHashPath() . rawurlencode( $this->getName() );
1284 }
1285
1286 /**
1287 * Get the path, relative to the thumbnail zone root, for an archived file's thumbs directory
1288 * or a specific thumb if the $suffix is given.
1289 *
1290 * @param string $archiveName the timestamped name of an archived image
1291 * @param bool|string $suffix if not false, the name of a thumbnail file
1292 * @return string
1293 */
1294 function getArchiveThumbRel( $archiveName, $suffix = false ) {
1295 $path = 'archive/' . $this->getHashPath() . $archiveName . "/";
1296 if ( $suffix === false ) {
1297 $path = substr( $path, 0, -1 );
1298 } else {
1299 $path .= $suffix;
1300 }
1301
1302 return $path;
1303 }
1304
1305 /**
1306 * Get the path of the archived file.
1307 *
1308 * @param bool|string $suffix if not false, the name of an archived file.
1309 * @return string
1310 */
1311 function getArchivePath( $suffix = false ) {
1312 $this->assertRepoDefined();
1313
1314 return $this->repo->getZonePath( 'public' ) . '/' . $this->getArchiveRel( $suffix );
1315 }
1316
1317 /**
1318 * Get the path of an archived file's thumbs, or a particular thumb if $suffix is specified
1319 *
1320 * @param string $archiveName the timestamped name of an archived image
1321 * @param bool|string $suffix if not false, the name of a thumbnail file
1322 * @return string
1323 */
1324 function getArchiveThumbPath( $archiveName, $suffix = false ) {
1325 $this->assertRepoDefined();
1326
1327 return $this->repo->getZonePath( 'thumb' ) . '/' .
1328 $this->getArchiveThumbRel( $archiveName, $suffix );
1329 }
1330
1331 /**
1332 * Get the path of the thumbnail directory, or a particular file if $suffix is specified
1333 *
1334 * @param bool|string $suffix If not false, the name of a thumbnail file
1335 * @return string
1336 */
1337 function getThumbPath( $suffix = false ) {
1338 $this->assertRepoDefined();
1339
1340 return $this->repo->getZonePath( 'thumb' ) . '/' . $this->getThumbRel( $suffix );
1341 }
1342
1343 /**
1344 * Get the path of the transcoded directory, or a particular file if $suffix is specified
1345 *
1346 * @param bool|string $suffix If not false, the name of a media file
1347 * @return string
1348 */
1349 function getTranscodedPath( $suffix = false ) {
1350 $this->assertRepoDefined();
1351
1352 return $this->repo->getZonePath( 'transcoded' ) . '/' . $this->getThumbRel( $suffix );
1353 }
1354
1355 /**
1356 * Get the URL of the archive directory, or a particular file if $suffix is specified
1357 *
1358 * @param bool|string $suffix If not false, the name of an archived file
1359 * @return string
1360 */
1361 function getArchiveUrl( $suffix = false ) {
1362 $this->assertRepoDefined();
1363 $ext = $this->getExtension();
1364 $path = $this->repo->getZoneUrl( 'public', $ext ) . '/archive/' . $this->getHashPath();
1365 if ( $suffix === false ) {
1366 $path = substr( $path, 0, -1 );
1367 } else {
1368 $path .= rawurlencode( $suffix );
1369 }
1370
1371 return $path;
1372 }
1373
1374 /**
1375 * Get the URL of the archived file's thumbs, or a particular thumb if $suffix is specified
1376 *
1377 * @param string $archiveName the timestamped name of an archived image
1378 * @param bool|string $suffix If not false, the name of a thumbnail file
1379 * @return string
1380 */
1381 function getArchiveThumbUrl( $archiveName, $suffix = false ) {
1382 $this->assertRepoDefined();
1383 $ext = $this->getExtension();
1384 $path = $this->repo->getZoneUrl( 'thumb', $ext ) . '/archive/' .
1385 $this->getHashPath() . rawurlencode( $archiveName ) . "/";
1386 if ( $suffix === false ) {
1387 $path = substr( $path, 0, -1 );
1388 } else {
1389 $path .= rawurlencode( $suffix );
1390 }
1391
1392 return $path;
1393 }
1394
1395 /**
1396 * Get the URL of the zone directory, or a particular file if $suffix is specified
1397 *
1398 * @param string $zone name of requested zone
1399 * @param bool|string $suffix If not false, the name of a file in zone
1400 * @return string path
1401 */
1402 function getZoneUrl( $zone, $suffix = false ) {
1403 $this->assertRepoDefined();
1404 $ext = $this->getExtension();
1405 $path = $this->repo->getZoneUrl( $zone, $ext ) . '/' . $this->getUrlRel();
1406 if ( $suffix !== false ) {
1407 $path .= '/' . rawurlencode( $suffix );
1408 }
1409
1410 return $path;
1411 }
1412
1413 /**
1414 * Get the URL of the thumbnail directory, or a particular file if $suffix is specified
1415 *
1416 * @param bool|string $suffix if not false, the name of a thumbnail file
1417 * @return string path
1418 */
1419 function getThumbUrl( $suffix = false ) {
1420 return $this->getZoneUrl( 'thumb', $suffix );
1421 }
1422
1423 /**
1424 * Get the URL of the transcoded directory, or a particular file if $suffix is specified
1425 *
1426 * @param bool|string $suffix If not false, the name of a media file
1427 * @return string path
1428 */
1429 function getTranscodedUrl( $suffix = false ) {
1430 return $this->getZoneUrl( 'transcoded', $suffix );
1431 }
1432
1433 /**
1434 * Get the public zone virtual URL for a current version source file
1435 *
1436 * @param bool|string $suffix If not false, the name of a thumbnail file
1437 * @return string
1438 */
1439 function getVirtualUrl( $suffix = false ) {
1440 $this->assertRepoDefined();
1441 $path = $this->repo->getVirtualUrl() . '/public/' . $this->getUrlRel();
1442 if ( $suffix !== false ) {
1443 $path .= '/' . rawurlencode( $suffix );
1444 }
1445
1446 return $path;
1447 }
1448
1449 /**
1450 * Get the public zone virtual URL for an archived version source file
1451 *
1452 * @param bool|string $suffix If not false, the name of a thumbnail file
1453 * @return string
1454 */
1455 function getArchiveVirtualUrl( $suffix = false ) {
1456 $this->assertRepoDefined();
1457 $path = $this->repo->getVirtualUrl() . '/public/archive/' . $this->getHashPath();
1458 if ( $suffix === false ) {
1459 $path = substr( $path, 0, -1 );
1460 } else {
1461 $path .= rawurlencode( $suffix );
1462 }
1463
1464 return $path;
1465 }
1466
1467 /**
1468 * Get the virtual URL for a thumbnail file or directory
1469 *
1470 * @param bool|string $suffix If not false, the name of a thumbnail file
1471 * @return string
1472 */
1473 function getThumbVirtualUrl( $suffix = false ) {
1474 $this->assertRepoDefined();
1475 $path = $this->repo->getVirtualUrl() . '/thumb/' . $this->getUrlRel();
1476 if ( $suffix !== false ) {
1477 $path .= '/' . rawurlencode( $suffix );
1478 }
1479
1480 return $path;
1481 }
1482
1483 /**
1484 * @return bool
1485 */
1486 function isHashed() {
1487 $this->assertRepoDefined();
1488
1489 return (bool)$this->repo->getHashLevels();
1490 }
1491
1492 /**
1493 * @throws MWException
1494 */
1495 function readOnlyError() {
1496 throw new MWException( get_class( $this ) . ': write operations are not supported' );
1497 }
1498
1499 /**
1500 * Record a file upload in the upload log and the image table
1501 * STUB
1502 * Overridden by LocalFile
1503 * @param $oldver
1504 * @param $desc
1505 * @param string $license
1506 * @param string $copyStatus
1507 * @param string $source
1508 * @param bool $watch
1509 * @param string|bool $timestamp
1510 * @param null|User $user User object or null to use $wgUser
1511 * @return bool
1512 * @throws MWException
1513 */
1514 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '',
1515 $watch = false, $timestamp = false, User $user = null
1516 ) {
1517 $this->readOnlyError();
1518 }
1519
1520 /**
1521 * Move or copy a file to its public location. If a file exists at the
1522 * destination, move it to an archive. Returns a FileRepoStatus object with
1523 * the archive name in the "value" member on success.
1524 *
1525 * The archive name should be passed through to recordUpload for database
1526 * registration.
1527 *
1528 * Options to $options include:
1529 * - headers : name/value map of HTTP headers to use in response to GET/HEAD requests
1530 *
1531 * @param string $srcPath local filesystem path to the source image
1532 * @param int $flags A bitwise combination of:
1533 * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy
1534 * @param array $options Optional additional parameters
1535 * @return FileRepoStatus object. On success, the value member contains the
1536 * archive name, or an empty string if it was a new file.
1537 *
1538 * STUB
1539 * Overridden by LocalFile
1540 */
1541 function publish( $srcPath, $flags = 0, array $options = array() ) {
1542 $this->readOnlyError();
1543 }
1544
1545 /**
1546 * @return bool
1547 */
1548 function formatMetadata() {
1549 if ( !$this->getHandler() ) {
1550 return false;
1551 }
1552
1553 return $this->getHandler()->formatMetadata( $this, $this->getMetadata() );
1554 }
1555
1556 /**
1557 * Returns true if the file comes from the local file repository.
1558 *
1559 * @return bool
1560 */
1561 function isLocal() {
1562 return $this->repo && $this->repo->isLocal();
1563 }
1564
1565 /**
1566 * Returns the name of the repository.
1567 *
1568 * @return string
1569 */
1570 function getRepoName() {
1571 return $this->repo ? $this->repo->getName() : 'unknown';
1572 }
1573
1574 /**
1575 * Returns the repository
1576 *
1577 * @return FileRepo|LocalRepo|bool
1578 */
1579 function getRepo() {
1580 return $this->repo;
1581 }
1582
1583 /**
1584 * Returns true if the image is an old version
1585 * STUB
1586 *
1587 * @return bool
1588 */
1589 function isOld() {
1590 return false;
1591 }
1592
1593 /**
1594 * Is this file a "deleted" file in a private archive?
1595 * STUB
1596 *
1597 * @param int $field one of DELETED_* bitfield constants
1598 * @return bool
1599 */
1600 function isDeleted( $field ) {
1601 return false;
1602 }
1603
1604 /**
1605 * Return the deletion bitfield
1606 * STUB
1607 * @return int
1608 */
1609 function getVisibility() {
1610 return 0;
1611 }
1612
1613 /**
1614 * Was this file ever deleted from the wiki?
1615 *
1616 * @return bool
1617 */
1618 function wasDeleted() {
1619 $title = $this->getTitle();
1620
1621 return $title && $title->isDeletedQuick();
1622 }
1623
1624 /**
1625 * Move file to the new title
1626 *
1627 * Move current, old version and all thumbnails
1628 * to the new filename. Old file is deleted.
1629 *
1630 * Cache purging is done; checks for validity
1631 * and logging are caller's responsibility
1632 *
1633 * @param Title $target New file name
1634 * @return FileRepoStatus object.
1635 */
1636 function move( $target ) {
1637 $this->readOnlyError();
1638 }
1639
1640 /**
1641 * Delete all versions of the file.
1642 *
1643 * Moves the files into an archive directory (or deletes them)
1644 * and removes the database rows.
1645 *
1646 * Cache purging is done; logging is caller's responsibility.
1647 *
1648 * @param string $reason
1649 * @param bool $suppress Hide content from sysops?
1650 * @return bool on success, false on some kind of failure
1651 * STUB
1652 * Overridden by LocalFile
1653 */
1654 function delete( $reason, $suppress = false ) {
1655 $this->readOnlyError();
1656 }
1657
1658 /**
1659 * Restore all or specified deleted revisions to the given file.
1660 * Permissions and logging are left to the caller.
1661 *
1662 * May throw database exceptions on error.
1663 *
1664 * @param array $versions set of record ids of deleted items to restore,
1665 * or empty to restore all revisions.
1666 * @param bool $unsuppress remove restrictions on content upon restoration?
1667 * @return int|bool the number of file revisions restored if successful,
1668 * or false on failure
1669 * STUB
1670 * Overridden by LocalFile
1671 */
1672 function restore( $versions = array(), $unsuppress = false ) {
1673 $this->readOnlyError();
1674 }
1675
1676 /**
1677 * Returns 'true' if this file is a type which supports multiple pages,
1678 * e.g. DJVU or PDF. Note that this may be true even if the file in
1679 * question only has a single page.
1680 *
1681 * @return bool
1682 */
1683 function isMultipage() {
1684 return $this->getHandler() && $this->handler->isMultiPage( $this );
1685 }
1686
1687 /**
1688 * Returns the number of pages of a multipage document, or false for
1689 * documents which aren't multipage documents
1690 *
1691 * @return bool|int
1692 */
1693 function pageCount() {
1694 if ( !isset( $this->pageCount ) ) {
1695 if ( $this->getHandler() && $this->handler->isMultiPage( $this ) ) {
1696 $this->pageCount = $this->handler->pageCount( $this );
1697 } else {
1698 $this->pageCount = false;
1699 }
1700 }
1701
1702 return $this->pageCount;
1703 }
1704
1705 /**
1706 * Calculate the height of a thumbnail using the source and destination width
1707 *
1708 * @param int $srcWidth
1709 * @param int $srcHeight
1710 * @param int $dstWidth
1711 *
1712 * @return int
1713 */
1714 static function scaleHeight( $srcWidth, $srcHeight, $dstWidth ) {
1715 // Exact integer multiply followed by division
1716 if ( $srcWidth == 0 ) {
1717 return 0;
1718 } else {
1719 return round( $srcHeight * $dstWidth / $srcWidth );
1720 }
1721 }
1722
1723 /**
1724 * Get an image size array like that returned by getImageSize(), or false if it
1725 * can't be determined.
1726 *
1727 * @param string $fileName The filename
1728 * @return array
1729 */
1730 function getImageSize( $fileName ) {
1731 if ( !$this->getHandler() ) {
1732 return false;
1733 }
1734
1735 return $this->handler->getImageSize( $this, $fileName );
1736 }
1737
1738 /**
1739 * Get the URL of the image description page. May return false if it is
1740 * unknown or not applicable.
1741 *
1742 * @return string
1743 */
1744 function getDescriptionUrl() {
1745 if ( $this->repo ) {
1746 return $this->repo->getDescriptionUrl( $this->getName() );
1747 } else {
1748 return false;
1749 }
1750 }
1751
1752 /**
1753 * Get the HTML text of the description page, if available
1754 *
1755 * @param bool|Language $lang Optional language to fetch description in
1756 * @return string
1757 */
1758 function getDescriptionText( $lang = false ) {
1759 global $wgMemc, $wgLang;
1760 if ( !$this->repo || !$this->repo->fetchDescription ) {
1761 return false;
1762 }
1763 if ( !$lang ) {
1764 $lang = $wgLang;
1765 }
1766 $renderUrl = $this->repo->getDescriptionRenderUrl( $this->getName(), $lang->getCode() );
1767 if ( $renderUrl ) {
1768 if ( $this->repo->descriptionCacheExpiry > 0 ) {
1769 wfDebug( "Attempting to get the description from cache..." );
1770 $key = $this->repo->getLocalCacheKey(
1771 'RemoteFileDescription',
1772 'url',
1773 $lang->getCode(),
1774 $this->getName()
1775 );
1776 $obj = $wgMemc->get( $key );
1777 if ( $obj ) {
1778 wfDebug( "success!\n" );
1779
1780 return $obj;
1781 }
1782 wfDebug( "miss\n" );
1783 }
1784 wfDebug( "Fetching shared description from $renderUrl\n" );
1785 $res = Http::get( $renderUrl );
1786 if ( $res && $this->repo->descriptionCacheExpiry > 0 ) {
1787 $wgMemc->set( $key, $res, $this->repo->descriptionCacheExpiry );
1788 }
1789
1790 return $res;
1791 } else {
1792 return false;
1793 }
1794 }
1795
1796 /**
1797 * Get description of file revision
1798 * STUB
1799 *
1800 * @param int $audience One of:
1801 * File::FOR_PUBLIC to be displayed to all users
1802 * File::FOR_THIS_USER to be displayed to the given user
1803 * File::RAW get the description regardless of permissions
1804 * @param User $user User object to check for, only if FOR_THIS_USER is
1805 * passed to the $audience parameter
1806 * @return string
1807 */
1808 function getDescription( $audience = self::FOR_PUBLIC, User $user = null ) {
1809 return null;
1810 }
1811
1812 /**
1813 * Get the 14-character timestamp of the file upload
1814 *
1815 * @return string|bool TS_MW timestamp or false on failure
1816 */
1817 function getTimestamp() {
1818 $this->assertRepoDefined();
1819
1820 return $this->repo->getFileTimestamp( $this->getPath() );
1821 }
1822
1823 /**
1824 * Get the SHA-1 base 36 hash of the file
1825 *
1826 * @return string
1827 */
1828 function getSha1() {
1829 $this->assertRepoDefined();
1830
1831 return $this->repo->getFileSha1( $this->getPath() );
1832 }
1833
1834 /**
1835 * Get the deletion archive key, "<sha1>.<ext>"
1836 *
1837 * @return string
1838 */
1839 function getStorageKey() {
1840 $hash = $this->getSha1();
1841 if ( !$hash ) {
1842 return false;
1843 }
1844 $ext = $this->getExtension();
1845 $dotExt = $ext === '' ? '' : ".$ext";
1846
1847 return $hash . $dotExt;
1848 }
1849
1850 /**
1851 * Determine if the current user is allowed to view a particular
1852 * field of this file, if it's marked as deleted.
1853 * STUB
1854 * @param int $field
1855 * @param User $user User object to check, or null to use $wgUser
1856 * @return bool
1857 */
1858 function userCan( $field, User $user = null ) {
1859 return true;
1860 }
1861
1862 /**
1863 * Get an associative array containing information about a file in the local filesystem.
1864 *
1865 * @param string $path absolute local filesystem path
1866 * @param string|bool $ext The file extension, or true to extract it from
1867 * the filename. Set it to false to ignore the extension.
1868 *
1869 * @return array
1870 * @deprecated since 1.19
1871 */
1872 static function getPropsFromPath( $path, $ext = true ) {
1873 wfDebug( __METHOD__ . ": Getting file info for $path\n" );
1874 wfDeprecated( __METHOD__, '1.19' );
1875
1876 $fsFile = new FSFile( $path );
1877
1878 return $fsFile->getProps();
1879 }
1880
1881 /**
1882 * Get a SHA-1 hash of a file in the local filesystem, in base-36 lower case
1883 * encoding, zero padded to 31 digits.
1884 *
1885 * 160 log 2 / log 36 = 30.95, so the 160-bit hash fills 31 digits in base 36
1886 * fairly neatly.
1887 *
1888 * @param $path string
1889 * @return bool|string False on failure
1890 * @deprecated since 1.19
1891 */
1892 static function sha1Base36( $path ) {
1893 wfDeprecated( __METHOD__, '1.19' );
1894
1895 $fsFile = new FSFile( $path );
1896
1897 return $fsFile->getSha1Base36();
1898 }
1899
1900 /**
1901 * @return array HTTP header name/value map to use for HEAD/GET request responses
1902 */
1903 function getStreamHeaders() {
1904 $handler = $this->getHandler();
1905 if ( $handler ) {
1906 return $handler->getStreamHeaders( $this->getMetadata() );
1907 } else {
1908 return array();
1909 }
1910 }
1911
1912 /**
1913 * @return string
1914 */
1915 function getLongDesc() {
1916 $handler = $this->getHandler();
1917 if ( $handler ) {
1918 return $handler->getLongDesc( $this );
1919 } else {
1920 return MediaHandler::getGeneralLongDesc( $this );
1921 }
1922 }
1923
1924 /**
1925 * @return string
1926 */
1927 function getShortDesc() {
1928 $handler = $this->getHandler();
1929 if ( $handler ) {
1930 return $handler->getShortDesc( $this );
1931 } else {
1932 return MediaHandler::getGeneralShortDesc( $this );
1933 }
1934 }
1935
1936 /**
1937 * @return string
1938 */
1939 function getDimensionsString() {
1940 $handler = $this->getHandler();
1941 if ( $handler ) {
1942 return $handler->getDimensionsString( $this );
1943 } else {
1944 return '';
1945 }
1946 }
1947
1948 /**
1949 * @return string
1950 */
1951 function getRedirected() {
1952 return $this->redirected;
1953 }
1954
1955 /**
1956 * @return Title|null
1957 */
1958 function getRedirectedTitle() {
1959 if ( $this->redirected ) {
1960 if ( !$this->redirectTitle ) {
1961 $this->redirectTitle = Title::makeTitle( NS_FILE, $this->redirected );
1962 }
1963
1964 return $this->redirectTitle;
1965 }
1966
1967 return null;
1968 }
1969
1970 /**
1971 * @param string $from
1972 * @return void
1973 */
1974 function redirectedFrom( $from ) {
1975 $this->redirected = $from;
1976 }
1977
1978 /**
1979 * @return bool
1980 */
1981 function isMissing() {
1982 return false;
1983 }
1984
1985 /**
1986 * Check if this file object is small and can be cached
1987 * @return bool
1988 */
1989 public function isCacheable() {
1990 return true;
1991 }
1992
1993 /**
1994 * Assert that $this->repo is set to a valid FileRepo instance
1995 * @throws MWException
1996 */
1997 protected function assertRepoDefined() {
1998 if ( !( $this->repo instanceof $this->repoClass ) ) {
1999 throw new MWException( "A {$this->repoClass} object is not set for this File.\n" );
2000 }
2001 }
2002
2003 /**
2004 * Assert that $this->title is set to a Title
2005 * @throws MWException
2006 */
2007 protected function assertTitleDefined() {
2008 if ( !( $this->title instanceof Title ) ) {
2009 throw new MWException( "A Title object is not set for this File.\n" );
2010 }
2011 }
2012 }