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