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