merged master
[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 return $this->generateThumbName( $this->getName(), $params );
771 }
772
773 /**
774 * Generate a thumbnail file name from a name and specified parameters
775 *
776 * @param string $name
777 * @param array $params Parameters which will be passed to MediaHandler::makeParamString
778 *
779 * @return string
780 */
781 function generateThumbName( $name, $params ) {
782 if ( !$this->getHandler() ) {
783 return null;
784 }
785 $extension = $this->getExtension();
786 list( $thumbExt, $thumbMime ) = $this->handler->getThumbType(
787 $extension, $this->getMimeType(), $params );
788 $thumbName = $this->handler->makeParamString( $params ) . '-' . $name;
789 if ( $thumbExt != $extension ) {
790 $thumbName .= ".$thumbExt";
791 }
792 return $thumbName;
793 }
794
795 /**
796 * Create a thumbnail of the image having the specified width/height.
797 * The thumbnail will not be created if the width is larger than the
798 * image's width. Let the browser do the scaling in this case.
799 * The thumbnail is stored on disk and is only computed if the thumbnail
800 * file does not exist OR if it is older than the image.
801 * Returns the URL.
802 *
803 * Keeps aspect ratio of original image. If both width and height are
804 * specified, the generated image will be no bigger than width x height,
805 * and will also have correct aspect ratio.
806 *
807 * @param $width Integer: maximum width of the generated thumbnail
808 * @param $height Integer: maximum height of the image (optional)
809 *
810 * @return string
811 */
812 public function createThumb( $width, $height = -1 ) {
813 $params = array( 'width' => $width );
814 if ( $height != -1 ) {
815 $params['height'] = $height;
816 }
817 $thumb = $this->transform( $params );
818 if ( is_null( $thumb ) || $thumb->isError() ) {
819 return '';
820 }
821 return $thumb->getUrl();
822 }
823
824 /**
825 * Return either a MediaTransformError or placeholder thumbnail (if $wgIgnoreImageErrors)
826 *
827 * @param $thumbPath string Thumbnail storage path
828 * @param $thumbUrl string Thumbnail URL
829 * @param $params Array
830 * @param $flags integer
831 * @return MediaTransformOutput
832 */
833 protected function transformErrorOutput( $thumbPath, $thumbUrl, $params, $flags ) {
834 global $wgIgnoreImageErrors;
835
836 if ( $wgIgnoreImageErrors && !( $flags & self::RENDER_NOW ) ) {
837 return $this->handler->getTransform( $this, $thumbPath, $thumbUrl, $params );
838 } else {
839 return new MediaTransformError( 'thumbnail_error',
840 $params['width'], 0, wfMessage( 'thumbnail-dest-create' )->text() );
841 }
842 }
843
844 /**
845 * Transform a media file
846 *
847 * @param $params Array: an associative array of handler-specific parameters.
848 * Typical keys are width, height and page.
849 * @param $flags Integer: a bitfield, may contain self::RENDER_NOW to force rendering
850 * @return MediaTransformOutput|bool False on failure
851 */
852 function transform( $params, $flags = 0 ) {
853 global $wgUseSquid, $wgIgnoreImageErrors, $wgThumbnailEpoch;
854
855 wfProfileIn( __METHOD__ );
856 do {
857 if ( !$this->canRender() ) {
858 $thumb = $this->iconThumb();
859 break; // not a bitmap or renderable image, don't try
860 }
861
862 // Get the descriptionUrl to embed it as comment into the thumbnail. Bug 19791.
863 $descriptionUrl = $this->getDescriptionUrl();
864 if ( $descriptionUrl ) {
865 $params['descriptionUrl'] = wfExpandUrl( $descriptionUrl, PROTO_CANONICAL );
866 }
867
868 $script = $this->getTransformScript();
869 if ( $script && !( $flags & self::RENDER_NOW ) ) {
870 // Use a script to transform on client request, if possible
871 $thumb = $this->handler->getScriptedTransform( $this, $script, $params );
872 if ( $thumb ) {
873 break;
874 }
875 }
876
877 $normalisedParams = $params;
878 $this->handler->normaliseParams( $this, $normalisedParams );
879
880 $thumbName = $this->thumbName( $normalisedParams );
881 $thumbUrl = $this->getThumbUrl( $thumbName );
882 $thumbPath = $this->getThumbPath( $thumbName ); // final thumb path
883
884 if ( $this->repo ) {
885 // Defer rendering if a 404 handler is set up...
886 if ( $this->repo->canTransformVia404() && !( $flags & self::RENDER_NOW ) ) {
887 wfDebug( __METHOD__ . " transformation deferred." );
888 // XXX: Pass in the storage path even though we are not rendering anything
889 // and the path is supposed to be an FS path. This is due to getScalerType()
890 // getting called on the path and clobbering $thumb->getUrl() if it's false.
891 $thumb = $this->handler->getTransform( $this, $thumbPath, $thumbUrl, $params );
892 break;
893 }
894 // Clean up broken thumbnails as needed
895 $this->migrateThumbFile( $thumbName );
896 // Check if an up-to-date thumbnail already exists...
897 wfDebug( __METHOD__.": Doing stat for $thumbPath\n" );
898 if ( $this->repo->fileExists( $thumbPath ) && !( $flags & self::RENDER_FORCE ) ) {
899 $timestamp = $this->repo->getFileTimestamp( $thumbPath );
900 if ( $timestamp !== false && $timestamp >= $wgThumbnailEpoch ) {
901 // XXX: Pass in the storage path even though we are not rendering anything
902 // and the path is supposed to be an FS path. This is due to getScalerType()
903 // getting called on the path and clobbering $thumb->getUrl() if it's false.
904 $thumb = $this->handler->getTransform( $this, $thumbPath, $thumbUrl, $params );
905 $thumb->setStoragePath( $thumbPath );
906 break;
907 }
908 } elseif ( $flags & self::RENDER_FORCE ) {
909 wfDebug( __METHOD__ . " forcing rendering per flag File::RENDER_FORCE\n" );
910 }
911 }
912
913 // If the backend is ready-only, don't keep generating thumbnails
914 // only to return transformation errors, just return the error now.
915 if ( $this->repo->getReadOnlyReason() !== false ) {
916 $thumb = $this->transformErrorOutput( $thumbPath, $thumbUrl, $params, $flags );
917 break;
918 }
919
920 // Create a temp FS file with the same extension and the thumbnail
921 $thumbExt = FileBackend::extensionFromPath( $thumbPath );
922 $tmpFile = TempFSFile::factory( 'transform_', $thumbExt );
923 if ( !$tmpFile ) {
924 $thumb = $this->transformErrorOutput( $thumbPath, $thumbUrl, $params, $flags );
925 break;
926 }
927 $tmpThumbPath = $tmpFile->getPath(); // path of 0-byte temp file
928
929 // Actually render the thumbnail...
930 wfProfileIn( __METHOD__ . '-doTransform' );
931 $thumb = $this->handler->doTransform( $this, $tmpThumbPath, $thumbUrl, $params );
932 wfProfileOut( __METHOD__ . '-doTransform' );
933 $tmpFile->bind( $thumb ); // keep alive with $thumb
934
935 if ( !$thumb ) { // bad params?
936 $thumb = null;
937 } elseif ( $thumb->isError() ) { // transform error
938 $this->lastError = $thumb->toText();
939 // Ignore errors if requested
940 if ( $wgIgnoreImageErrors && !( $flags & self::RENDER_NOW ) ) {
941 $thumb = $this->handler->getTransform( $this, $tmpThumbPath, $thumbUrl, $params );
942 }
943 } elseif ( $this->repo && $thumb->hasFile() && !$thumb->fileIsSource() ) {
944 // Copy the thumbnail from the file system into storage...
945 $status = $this->repo->quickImport( $tmpThumbPath, $thumbPath );
946 if ( $status->isOK() ) {
947 $thumb->setStoragePath( $thumbPath );
948 } else {
949 $thumb = $this->transformErrorOutput( $thumbPath, $thumbUrl, $params, $flags );
950 }
951 // Give extensions a chance to do something with this thumbnail...
952 wfRunHooks( 'FileTransformed', array( $this, $thumb, $tmpThumbPath, $thumbPath ) );
953 }
954
955 // Purge. Useful in the event of Core -> Squid connection failure or squid
956 // purge collisions from elsewhere during failure. Don't keep triggering for
957 // "thumbs" which have the main image URL though (bug 13776)
958 if ( $wgUseSquid ) {
959 if ( !$thumb || $thumb->isError() || $thumb->getUrl() != $this->getURL() ) {
960 SquidUpdate::purge( array( $thumbUrl ) );
961 }
962 }
963 } while ( false );
964
965 wfProfileOut( __METHOD__ );
966 return is_object( $thumb ) ? $thumb : false;
967 }
968
969 /**
970 * Hook into transform() to allow migration of thumbnail files
971 * STUB
972 * Overridden by LocalFile
973 */
974 function migrateThumbFile( $thumbName ) {}
975
976 /**
977 * Get a MediaHandler instance for this file
978 *
979 * @return MediaHandler
980 */
981 function getHandler() {
982 if ( !isset( $this->handler ) ) {
983 $this->handler = MediaHandler::getHandler( $this->getMimeType() );
984 }
985 return $this->handler;
986 }
987
988 /**
989 * Get a ThumbnailImage representing a file type icon
990 *
991 * @return ThumbnailImage
992 */
993 function iconThumb() {
994 global $wgStylePath, $wgStyleDirectory;
995
996 $try = array( 'fileicon-' . $this->getExtension() . '.png', 'fileicon.png' );
997 foreach ( $try as $icon ) {
998 $path = '/common/images/icons/' . $icon;
999 $filepath = $wgStyleDirectory . $path;
1000 if ( file_exists( $filepath ) ) { // always FS
1001 return new ThumbnailImage( $this, $wgStylePath . $path, 120, 120 );
1002 }
1003 }
1004 return null;
1005 }
1006
1007 /**
1008 * Get last thumbnailing error.
1009 * Largely obsolete.
1010 */
1011 function getLastError() {
1012 return $this->lastError;
1013 }
1014
1015 /**
1016 * Get all thumbnail names previously generated for this file
1017 * STUB
1018 * Overridden by LocalFile
1019 * @return array
1020 */
1021 function getThumbnails() {
1022 return array();
1023 }
1024
1025 /**
1026 * Purge shared caches such as thumbnails and DB data caching
1027 * STUB
1028 * Overridden by LocalFile
1029 * @param $options Array Options, which include:
1030 * 'forThumbRefresh' : The purging is only to refresh thumbnails
1031 */
1032 function purgeCache( $options = array() ) {}
1033
1034 /**
1035 * Purge the file description page, but don't go after
1036 * pages using the file. Use when modifying file history
1037 * but not the current data.
1038 */
1039 function purgeDescription() {
1040 $title = $this->getTitle();
1041 if ( $title ) {
1042 $title->invalidateCache();
1043 $title->purgeSquid();
1044 }
1045 }
1046
1047 /**
1048 * Purge metadata and all affected pages when the file is created,
1049 * deleted, or majorly updated.
1050 */
1051 function purgeEverything() {
1052 // Delete thumbnails and refresh file metadata cache
1053 $this->purgeCache();
1054 $this->purgeDescription();
1055
1056 // Purge cache of all pages using this file
1057 $title = $this->getTitle();
1058 if ( $title ) {
1059 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
1060 $update->doUpdate();
1061 }
1062 }
1063
1064 /**
1065 * Return a fragment of the history of file.
1066 *
1067 * STUB
1068 * @param $limit integer Limit of rows to return
1069 * @param $start string timestamp Only revisions older than $start will be returned
1070 * @param $end string timestamp Only revisions newer than $end will be returned
1071 * @param $inc bool Include the endpoints of the time range
1072 *
1073 * @return array
1074 */
1075 function getHistory( $limit = null, $start = null, $end = null, $inc=true ) {
1076 return array();
1077 }
1078
1079 /**
1080 * Return the history of this file, line by line. Starts with current version,
1081 * then old versions. Should return an object similar to an image/oldimage
1082 * database row.
1083 *
1084 * STUB
1085 * Overridden in LocalFile
1086 * @return bool
1087 */
1088 public function nextHistoryLine() {
1089 return false;
1090 }
1091
1092 /**
1093 * Reset the history pointer to the first element of the history.
1094 * Always call this function after using nextHistoryLine() to free db resources
1095 * STUB
1096 * Overridden in LocalFile.
1097 */
1098 public function resetHistory() {}
1099
1100 /**
1101 * Get the filename hash component of the directory including trailing slash,
1102 * e.g. f/fa/
1103 * If the repository is not hashed, returns an empty string.
1104 *
1105 * @return string
1106 */
1107 function getHashPath() {
1108 if ( !isset( $this->hashPath ) ) {
1109 $this->assertRepoDefined();
1110 $this->hashPath = $this->repo->getHashPath( $this->getName() );
1111 }
1112 return $this->hashPath;
1113 }
1114
1115 /**
1116 * Get the path of the file relative to the public zone root.
1117 * This function is overriden in OldLocalFile to be like getArchiveRel().
1118 *
1119 * @return string
1120 */
1121 function getRel() {
1122 return $this->getHashPath() . $this->getName();
1123 }
1124
1125 /**
1126 * Get the path of an archived file relative to the public zone root
1127 *
1128 * @param $suffix bool|string if not false, the name of an archived thumbnail file
1129 *
1130 * @return string
1131 */
1132 function getArchiveRel( $suffix = false ) {
1133 $path = 'archive/' . $this->getHashPath();
1134 if ( $suffix === false ) {
1135 $path = substr( $path, 0, -1 );
1136 } else {
1137 $path .= $suffix;
1138 }
1139 return $path;
1140 }
1141
1142 /**
1143 * Get the path, relative to the thumbnail zone root, of the
1144 * thumbnail directory or a particular file if $suffix is specified
1145 *
1146 * @param $suffix bool|string if not false, the name of a thumbnail file
1147 *
1148 * @return string
1149 */
1150 function getThumbRel( $suffix = false ) {
1151 $path = $this->getRel();
1152 if ( $suffix !== false ) {
1153 $path .= '/' . $suffix;
1154 }
1155 return $path;
1156 }
1157
1158 /**
1159 * Get urlencoded path of the file relative to the public zone root.
1160 * This function is overriden in OldLocalFile to be like getArchiveUrl().
1161 *
1162 * @return string
1163 */
1164 function getUrlRel() {
1165 return $this->getHashPath() . rawurlencode( $this->getName() );
1166 }
1167
1168 /**
1169 * Get the path, relative to the thumbnail zone root, for an archived file's thumbs directory
1170 * or a specific thumb if the $suffix is given.
1171 *
1172 * @param $archiveName string the timestamped name of an archived image
1173 * @param $suffix bool|string if not false, the name of a thumbnail file
1174 *
1175 * @return string
1176 */
1177 function getArchiveThumbRel( $archiveName, $suffix = false ) {
1178 $path = 'archive/' . $this->getHashPath() . $archiveName . "/";
1179 if ( $suffix === false ) {
1180 $path = substr( $path, 0, -1 );
1181 } else {
1182 $path .= $suffix;
1183 }
1184 return $path;
1185 }
1186
1187 /**
1188 * Get the path of the archived file.
1189 *
1190 * @param $suffix bool|string if not false, the name of an archived file.
1191 *
1192 * @return string
1193 */
1194 function getArchivePath( $suffix = false ) {
1195 $this->assertRepoDefined();
1196 return $this->repo->getZonePath( 'public' ) . '/' . $this->getArchiveRel( $suffix );
1197 }
1198
1199 /**
1200 * Get the path of an archived file's thumbs, or a particular thumb if $suffix is specified
1201 *
1202 * @param $archiveName string the timestamped name of an archived image
1203 * @param $suffix bool|string if not false, the name of a thumbnail file
1204 *
1205 * @return string
1206 */
1207 function getArchiveThumbPath( $archiveName, $suffix = false ) {
1208 $this->assertRepoDefined();
1209 return $this->repo->getZonePath( 'thumb' ) . '/' .
1210 $this->getArchiveThumbRel( $archiveName, $suffix );
1211 }
1212
1213 /**
1214 * Get the path of the thumbnail directory, or a particular file if $suffix is specified
1215 *
1216 * @param $suffix bool|string if not false, the name of a thumbnail file
1217 *
1218 * @return string
1219 */
1220 function getThumbPath( $suffix = false ) {
1221 $this->assertRepoDefined();
1222 return $this->repo->getZonePath( 'thumb' ) . '/' . $this->getThumbRel( $suffix );
1223 }
1224
1225 /**
1226 * Get the URL of the archive directory, or a particular file if $suffix is specified
1227 *
1228 * @param $suffix bool|string if not false, the name of an archived file
1229 *
1230 * @return string
1231 */
1232 function getArchiveUrl( $suffix = false ) {
1233 $this->assertRepoDefined();
1234 $path = $this->repo->getZoneUrl( 'public' ) . '/archive/' . $this->getHashPath();
1235 if ( $suffix === false ) {
1236 $path = substr( $path, 0, -1 );
1237 } else {
1238 $path .= rawurlencode( $suffix );
1239 }
1240 return $path;
1241 }
1242
1243 /**
1244 * Get the URL of the archived file's thumbs, or a particular thumb if $suffix is specified
1245 *
1246 * @param $archiveName string the timestamped name of an archived image
1247 * @param $suffix bool|string if not false, the name of a thumbnail file
1248 *
1249 * @return string
1250 */
1251 function getArchiveThumbUrl( $archiveName, $suffix = false ) {
1252 $this->assertRepoDefined();
1253 $path = $this->repo->getZoneUrl( 'thumb' ) . '/archive/' .
1254 $this->getHashPath() . rawurlencode( $archiveName ) . "/";
1255 if ( $suffix === false ) {
1256 $path = substr( $path, 0, -1 );
1257 } else {
1258 $path .= rawurlencode( $suffix );
1259 }
1260 return $path;
1261 }
1262
1263 /**
1264 * Get the URL of the thumbnail directory, or a particular file if $suffix is specified
1265 *
1266 * @param $suffix bool|string if not false, the name of a thumbnail file
1267 *
1268 * @return string path
1269 */
1270 function getThumbUrl( $suffix = false ) {
1271 $this->assertRepoDefined();
1272 $path = $this->repo->getZoneUrl( 'thumb' ) . '/' . $this->getUrlRel();
1273 if ( $suffix !== false ) {
1274 $path .= '/' . rawurlencode( $suffix );
1275 }
1276 return $path;
1277 }
1278
1279 /**
1280 * Get the public zone virtual URL for a current version source file
1281 *
1282 * @param $suffix bool|string if not false, the name of a thumbnail file
1283 *
1284 * @return string
1285 */
1286 function getVirtualUrl( $suffix = false ) {
1287 $this->assertRepoDefined();
1288 $path = $this->repo->getVirtualUrl() . '/public/' . $this->getUrlRel();
1289 if ( $suffix !== false ) {
1290 $path .= '/' . rawurlencode( $suffix );
1291 }
1292 return $path;
1293 }
1294
1295 /**
1296 * Get the public zone virtual URL for an archived version source file
1297 *
1298 * @param $suffix bool|string if not false, the name of a thumbnail file
1299 *
1300 * @return string
1301 */
1302 function getArchiveVirtualUrl( $suffix = false ) {
1303 $this->assertRepoDefined();
1304 $path = $this->repo->getVirtualUrl() . '/public/archive/' . $this->getHashPath();
1305 if ( $suffix === false ) {
1306 $path = substr( $path, 0, -1 );
1307 } else {
1308 $path .= rawurlencode( $suffix );
1309 }
1310 return $path;
1311 }
1312
1313 /**
1314 * Get the virtual URL for a thumbnail file or directory
1315 *
1316 * @param $suffix bool|string if not false, the name of a thumbnail file
1317 *
1318 * @return string
1319 */
1320 function getThumbVirtualUrl( $suffix = false ) {
1321 $this->assertRepoDefined();
1322 $path = $this->repo->getVirtualUrl() . '/thumb/' . $this->getUrlRel();
1323 if ( $suffix !== false ) {
1324 $path .= '/' . rawurlencode( $suffix );
1325 }
1326 return $path;
1327 }
1328
1329 /**
1330 * @return bool
1331 */
1332 function isHashed() {
1333 $this->assertRepoDefined();
1334 return (bool)$this->repo->getHashLevels();
1335 }
1336
1337 /**
1338 * @throws MWException
1339 */
1340 function readOnlyError() {
1341 throw new MWException( get_class($this) . ': write operations are not supported' );
1342 }
1343
1344 /**
1345 * Record a file upload in the upload log and the image table
1346 * STUB
1347 * Overridden by LocalFile
1348 * @param $oldver
1349 * @param $desc
1350 * @param $license string
1351 * @param $copyStatus string
1352 * @param $source string
1353 * @param $watch bool
1354 */
1355 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '', $watch = false ) {
1356 $this->readOnlyError();
1357 }
1358
1359 /**
1360 * Move or copy a file to its public location. If a file exists at the
1361 * destination, move it to an archive. Returns a FileRepoStatus object with
1362 * the archive name in the "value" member on success.
1363 *
1364 * The archive name should be passed through to recordUpload for database
1365 * registration.
1366 *
1367 * @param $srcPath String: local filesystem path to the source image
1368 * @param $flags Integer: a bitwise combination of:
1369 * File::DELETE_SOURCE Delete the source file, i.e. move
1370 * rather than copy
1371 * @return FileRepoStatus object. On success, the value member contains the
1372 * archive name, or an empty string if it was a new file.
1373 *
1374 * STUB
1375 * Overridden by LocalFile
1376 */
1377 function publish( $srcPath, $flags = 0 ) {
1378 $this->readOnlyError();
1379 }
1380
1381 /**
1382 * @return bool
1383 */
1384 function formatMetadata() {
1385 if ( !$this->getHandler() ) {
1386 return false;
1387 }
1388 return $this->getHandler()->formatMetadata( $this, $this->getMetadata() );
1389 }
1390
1391 /**
1392 * Returns true if the file comes from the local file repository.
1393 *
1394 * @return bool
1395 */
1396 function isLocal() {
1397 return $this->repo && $this->repo->isLocal();
1398 }
1399
1400 /**
1401 * Returns the name of the repository.
1402 *
1403 * @return string
1404 */
1405 function getRepoName() {
1406 return $this->repo ? $this->repo->getName() : 'unknown';
1407 }
1408
1409 /**
1410 * Returns the repository
1411 *
1412 * @return FileRepo|bool
1413 */
1414 function getRepo() {
1415 return $this->repo;
1416 }
1417
1418 /**
1419 * Returns true if the image is an old version
1420 * STUB
1421 *
1422 * @return bool
1423 */
1424 function isOld() {
1425 return false;
1426 }
1427
1428 /**
1429 * Is this file a "deleted" file in a private archive?
1430 * STUB
1431 *
1432 * @param $field
1433 *
1434 * @return bool
1435 */
1436 function isDeleted( $field ) {
1437 return false;
1438 }
1439
1440 /**
1441 * Return the deletion bitfield
1442 * STUB
1443 * @return int
1444 */
1445 function getVisibility() {
1446 return 0;
1447 }
1448
1449 /**
1450 * Was this file ever deleted from the wiki?
1451 *
1452 * @return bool
1453 */
1454 function wasDeleted() {
1455 $title = $this->getTitle();
1456 return $title && $title->isDeletedQuick();
1457 }
1458
1459 /**
1460 * Move file to the new title
1461 *
1462 * Move current, old version and all thumbnails
1463 * to the new filename. Old file is deleted.
1464 *
1465 * Cache purging is done; checks for validity
1466 * and logging are caller's responsibility
1467 *
1468 * @param $target Title New file name
1469 * @return FileRepoStatus object.
1470 */
1471 function move( $target ) {
1472 $this->readOnlyError();
1473 }
1474
1475 /**
1476 * Delete all versions of the file.
1477 *
1478 * Moves the files into an archive directory (or deletes them)
1479 * and removes the database rows.
1480 *
1481 * Cache purging is done; logging is caller's responsibility.
1482 *
1483 * @param $reason String
1484 * @param $suppress Boolean: hide content from sysops?
1485 * @return bool on success, false on some kind of failure
1486 * STUB
1487 * Overridden by LocalFile
1488 */
1489 function delete( $reason, $suppress = false ) {
1490 $this->readOnlyError();
1491 }
1492
1493 /**
1494 * Restore all or specified deleted revisions to the given file.
1495 * Permissions and logging are left to the caller.
1496 *
1497 * May throw database exceptions on error.
1498 *
1499 * @param $versions array set of record ids of deleted items to restore,
1500 * or empty to restore all revisions.
1501 * @param $unsuppress bool remove restrictions on content upon restoration?
1502 * @return int|bool the number of file revisions restored if successful,
1503 * or false on failure
1504 * STUB
1505 * Overridden by LocalFile
1506 */
1507 function restore( $versions = array(), $unsuppress = false ) {
1508 $this->readOnlyError();
1509 }
1510
1511 /**
1512 * Returns 'true' if this file is a type which supports multiple pages,
1513 * e.g. DJVU or PDF. Note that this may be true even if the file in
1514 * question only has a single page.
1515 *
1516 * @return Bool
1517 */
1518 function isMultipage() {
1519 return $this->getHandler() && $this->handler->isMultiPage( $this );
1520 }
1521
1522 /**
1523 * Returns the number of pages of a multipage document, or false for
1524 * documents which aren't multipage documents
1525 *
1526 * @return bool|int
1527 */
1528 function pageCount() {
1529 if ( !isset( $this->pageCount ) ) {
1530 if ( $this->getHandler() && $this->handler->isMultiPage( $this ) ) {
1531 $this->pageCount = $this->handler->pageCount( $this );
1532 } else {
1533 $this->pageCount = false;
1534 }
1535 }
1536 return $this->pageCount;
1537 }
1538
1539 /**
1540 * Calculate the height of a thumbnail using the source and destination width
1541 *
1542 * @param $srcWidth
1543 * @param $srcHeight
1544 * @param $dstWidth
1545 *
1546 * @return int
1547 */
1548 static function scaleHeight( $srcWidth, $srcHeight, $dstWidth ) {
1549 // Exact integer multiply followed by division
1550 if ( $srcWidth == 0 ) {
1551 return 0;
1552 } else {
1553 return round( $srcHeight * $dstWidth / $srcWidth );
1554 }
1555 }
1556
1557 /**
1558 * Get an image size array like that returned by getImageSize(), or false if it
1559 * can't be determined.
1560 *
1561 * @param $fileName String: The filename
1562 * @return Array
1563 */
1564 function getImageSize( $fileName ) {
1565 if ( !$this->getHandler() ) {
1566 return false;
1567 }
1568 return $this->handler->getImageSize( $this, $fileName );
1569 }
1570
1571 /**
1572 * Get the URL of the image description page. May return false if it is
1573 * unknown or not applicable.
1574 *
1575 * @return string
1576 */
1577 function getDescriptionUrl() {
1578 if ( $this->repo ) {
1579 return $this->repo->getDescriptionUrl( $this->getName() );
1580 } else {
1581 return false;
1582 }
1583 }
1584
1585 /**
1586 * Get the HTML text of the description page, if available
1587 *
1588 * @return string
1589 */
1590 function getDescriptionText() {
1591 global $wgMemc, $wgLang;
1592 if ( !$this->repo || !$this->repo->fetchDescription ) {
1593 return false;
1594 }
1595 $renderUrl = $this->repo->getDescriptionRenderUrl( $this->getName(), $wgLang->getCode() );
1596 if ( $renderUrl ) {
1597 if ( $this->repo->descriptionCacheExpiry > 0 ) {
1598 wfDebug("Attempting to get the description from cache...");
1599 $key = $this->repo->getLocalCacheKey( 'RemoteFileDescription', 'url', $wgLang->getCode(),
1600 $this->getName() );
1601 $obj = $wgMemc->get($key);
1602 if ($obj) {
1603 wfDebug("success!\n");
1604 return $obj;
1605 }
1606 wfDebug("miss\n");
1607 }
1608 wfDebug( "Fetching shared description from $renderUrl\n" );
1609 $res = Http::get( $renderUrl );
1610 if ( $res && $this->repo->descriptionCacheExpiry > 0 ) {
1611 $wgMemc->set( $key, $res, $this->repo->descriptionCacheExpiry );
1612 }
1613 return $res;
1614 } else {
1615 return false;
1616 }
1617 }
1618
1619 /**
1620 * Get description of file revision
1621 * STUB
1622 *
1623 * @param $audience Integer: one of:
1624 * File::FOR_PUBLIC to be displayed to all users
1625 * File::FOR_THIS_USER to be displayed to the given user
1626 * File::RAW get the description regardless of permissions
1627 * @param $user User object to check for, only if FOR_THIS_USER is passed
1628 * to the $audience parameter
1629 * @return string
1630 */
1631 function getDescription( $audience = self::FOR_PUBLIC, User $user = null ) {
1632 return null;
1633 }
1634
1635 /**
1636 * Get the 14-character timestamp of the file upload
1637 *
1638 * @return string|bool TS_MW timestamp or false on failure
1639 */
1640 function getTimestamp() {
1641 $this->assertRepoDefined();
1642 return $this->repo->getFileTimestamp( $this->getPath() );
1643 }
1644
1645 /**
1646 * Get the SHA-1 base 36 hash of the file
1647 *
1648 * @return string
1649 */
1650 function getSha1() {
1651 $this->assertRepoDefined();
1652 return $this->repo->getFileSha1( $this->getPath() );
1653 }
1654
1655 /**
1656 * Get the deletion archive key, "<sha1>.<ext>"
1657 *
1658 * @return string
1659 */
1660 function getStorageKey() {
1661 $hash = $this->getSha1();
1662 if ( !$hash ) {
1663 return false;
1664 }
1665 $ext = $this->getExtension();
1666 $dotExt = $ext === '' ? '' : ".$ext";
1667 return $hash . $dotExt;
1668 }
1669
1670 /**
1671 * Determine if the current user is allowed to view a particular
1672 * field of this file, if it's marked as deleted.
1673 * STUB
1674 * @param $field Integer
1675 * @param $user User object to check, or null to use $wgUser
1676 * @return Boolean
1677 */
1678 function userCan( $field, User $user = null ) {
1679 return true;
1680 }
1681
1682 /**
1683 * Get an associative array containing information about a file in the local filesystem.
1684 *
1685 * @param $path String: absolute local filesystem path
1686 * @param $ext Mixed: the file extension, or true to extract it from the filename.
1687 * Set it to false to ignore the extension.
1688 *
1689 * @return array
1690 */
1691 static function getPropsFromPath( $path, $ext = true ) {
1692 wfDebug( __METHOD__.": Getting file info for $path\n" );
1693 wfDeprecated( __METHOD__, '1.19' );
1694
1695 $fsFile = new FSFile( $path );
1696 return $fsFile->getProps();
1697 }
1698
1699 /**
1700 * Get a SHA-1 hash of a file in the local filesystem, in base-36 lower case
1701 * encoding, zero padded to 31 digits.
1702 *
1703 * 160 log 2 / log 36 = 30.95, so the 160-bit hash fills 31 digits in base 36
1704 * fairly neatly.
1705 *
1706 * @param $path string
1707 *
1708 * @return bool|string False on failure
1709 */
1710 static function sha1Base36( $path ) {
1711 wfDeprecated( __METHOD__, '1.19' );
1712
1713 $fsFile = new FSFile( $path );
1714 return $fsFile->getSha1Base36();
1715 }
1716
1717 /**
1718 * @return string
1719 */
1720 function getLongDesc() {
1721 $handler = $this->getHandler();
1722 if ( $handler ) {
1723 return $handler->getLongDesc( $this );
1724 } else {
1725 return MediaHandler::getGeneralLongDesc( $this );
1726 }
1727 }
1728
1729 /**
1730 * @return string
1731 */
1732 function getShortDesc() {
1733 $handler = $this->getHandler();
1734 if ( $handler ) {
1735 return $handler->getShortDesc( $this );
1736 } else {
1737 return MediaHandler::getGeneralShortDesc( $this );
1738 }
1739 }
1740
1741 /**
1742 * @return string
1743 */
1744 function getDimensionsString() {
1745 $handler = $this->getHandler();
1746 if ( $handler ) {
1747 return $handler->getDimensionsString( $this );
1748 } else {
1749 return '';
1750 }
1751 }
1752
1753 /**
1754 * @return
1755 */
1756 function getRedirected() {
1757 return $this->redirected;
1758 }
1759
1760 /**
1761 * @return Title
1762 */
1763 function getRedirectedTitle() {
1764 if ( $this->redirected ) {
1765 if ( !$this->redirectTitle ) {
1766 $this->redirectTitle = Title::makeTitle( NS_FILE, $this->redirected );
1767 }
1768 return $this->redirectTitle;
1769 }
1770 }
1771
1772 /**
1773 * @param $from
1774 * @return void
1775 */
1776 function redirectedFrom( $from ) {
1777 $this->redirected = $from;
1778 }
1779
1780 /**
1781 * @return bool
1782 */
1783 function isMissing() {
1784 return false;
1785 }
1786
1787 /**
1788 * Check if this file object is small and can be cached
1789 * @return boolean
1790 */
1791 public function isCacheable() {
1792 return true;
1793 }
1794
1795 /**
1796 * Assert that $this->repo is set to a valid FileRepo instance
1797 * @throws MWException
1798 */
1799 protected function assertRepoDefined() {
1800 if ( !( $this->repo instanceof $this->repoClass ) ) {
1801 throw new MWException( "A {$this->repoClass} object is not set for this File.\n" );
1802 }
1803 }
1804
1805 /**
1806 * Assert that $this->title is set to a Title
1807 * @throws MWException
1808 */
1809 protected function assertTitleDefined() {
1810 if ( !( $this->title instanceof Title ) ) {
1811 throw new MWException( "A Title object is not set for this File.\n" );
1812 }
1813 }
1814 }