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