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