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