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