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