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