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