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