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