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