891a1e4e7fd1dc2977cfc2140f81cfbf68e039c3
[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 * Transform a media file
672 *
673 * @param $params Array: an associative array of handler-specific parameters.
674 * Typical keys are width, height and page.
675 * @param $flags Integer: a bitfield, may contain self::RENDER_NOW to force rendering
676 * @return MediaTransformOutput | false
677 */
678 function transform( $params, $flags = 0 ) {
679 global $wgUseSquid, $wgIgnoreImageErrors, $wgThumbnailEpoch, $wgServer;
680
681 wfProfileIn( __METHOD__ );
682 do {
683 if ( !$this->canRender() ) {
684 // not a bitmap or renderable image, don't try.
685 $thumb = $this->iconThumb();
686 break;
687 }
688
689 // Get the descriptionUrl to embed it as comment into the thumbnail. Bug 19791.
690 $descriptionUrl = $this->getDescriptionUrl();
691 if ( $descriptionUrl ) {
692 $params['descriptionUrl'] = $wgServer . $descriptionUrl;
693 }
694
695 $script = $this->getTransformScript();
696 if ( $script && !($flags & self::RENDER_NOW) ) {
697 // Use a script to transform on client request, if possible
698 $thumb = $this->handler->getScriptedTransform( $this, $script, $params );
699 if( $thumb ) {
700 break;
701 }
702 }
703
704 $normalisedParams = $params;
705 $this->handler->normaliseParams( $this, $normalisedParams );
706 $thumbName = $this->thumbName( $normalisedParams );
707 $thumbPath = $this->getThumbPath( $thumbName );
708 $thumbUrl = $this->getThumbUrl( $thumbName );
709
710 if ( $this->repo && $this->repo->canTransformVia404() && !($flags & self::RENDER_NOW ) ) {
711 $thumb = $this->handler->getTransform( $this, $thumbPath, $thumbUrl, $params );
712 break;
713 }
714
715 wfDebug( __METHOD__.": Doing stat for $thumbPath\n" );
716 $this->migrateThumbFile( $thumbName );
717 if ( file_exists( $thumbPath )) {
718 $thumbTime = filemtime( $thumbPath );
719 if ( $thumbTime !== FALSE &&
720 gmdate( 'YmdHis', $thumbTime ) >= $wgThumbnailEpoch ) {
721
722 $thumb = $this->handler->getTransform( $this, $thumbPath, $thumbUrl, $params );
723 break;
724 }
725 }
726 $thumb = $this->handler->doTransform( $this, $thumbPath, $thumbUrl, $params );
727
728 // Ignore errors if requested
729 if ( !$thumb ) {
730 $thumb = null;
731 } elseif ( $thumb->isError() ) {
732 $this->lastError = $thumb->toText();
733 if ( $wgIgnoreImageErrors && !($flags & self::RENDER_NOW) ) {
734 $thumb = $this->handler->getTransform( $this, $thumbPath, $thumbUrl, $params );
735 }
736 }
737
738 // Purge. Useful in the event of Core -> Squid connection failure or squid
739 // purge collisions from elsewhere during failure. Don't keep triggering for
740 // "thumbs" which have the main image URL though (bug 13776)
741 if ( $wgUseSquid && ( !$thumb || $thumb->isError() || $thumb->getUrl() != $this->getURL()) ) {
742 SquidUpdate::purge( array( $thumbUrl ) );
743 }
744 } while (false);
745
746 wfProfileOut( __METHOD__ );
747 return is_object( $thumb ) ? $thumb : false;
748 }
749
750 /**
751 * Hook into transform() to allow migration of thumbnail files
752 * STUB
753 * Overridden by LocalFile
754 */
755 function migrateThumbFile( $thumbName ) {}
756
757 /**
758 * Get a MediaHandler instance for this file
759 * @return MediaHandler
760 */
761 function getHandler() {
762 if ( !isset( $this->handler ) ) {
763 $this->handler = MediaHandler::getHandler( $this->getMimeType() );
764 }
765 return $this->handler;
766 }
767
768 /**
769 * Get a ThumbnailImage representing a file type icon
770 * @return ThumbnailImage
771 */
772 function iconThumb() {
773 global $wgStylePath, $wgStyleDirectory;
774
775 $try = array( 'fileicon-' . $this->getExtension() . '.png', 'fileicon.png' );
776 foreach( $try as $icon ) {
777 $path = '/common/images/icons/' . $icon;
778 $filepath = $wgStyleDirectory . $path;
779 if( file_exists( $filepath ) ) {
780 return new ThumbnailImage( $this, $wgStylePath . $path, 120, 120 );
781 }
782 }
783 return null;
784 }
785
786 /**
787 * Get last thumbnailing error.
788 * Largely obsolete.
789 */
790 function getLastError() {
791 return $this->lastError;
792 }
793
794 /**
795 * Get all thumbnail names previously generated for this file
796 * STUB
797 * Overridden by LocalFile
798 */
799 function getThumbnails() {
800 return array();
801 }
802
803 /**
804 * Purge shared caches such as thumbnails and DB data caching
805 * STUB
806 * Overridden by LocalFile
807 */
808 function purgeCache() {}
809
810 /**
811 * Purge the file description page, but don't go after
812 * pages using the file. Use when modifying file history
813 * but not the current data.
814 */
815 function purgeDescription() {
816 $title = $this->getTitle();
817 if ( $title ) {
818 $title->invalidateCache();
819 $title->purgeSquid();
820 }
821 }
822
823 /**
824 * Purge metadata and all affected pages when the file is created,
825 * deleted, or majorly updated.
826 */
827 function purgeEverything() {
828 // Delete thumbnails and refresh file metadata cache
829 $this->purgeCache();
830 $this->purgeDescription();
831
832 // Purge cache of all pages using this file
833 $title = $this->getTitle();
834 if ( $title ) {
835 $update = new HTMLCacheUpdate( $title, 'imagelinks' );
836 $update->doUpdate();
837 }
838 }
839
840 /**
841 * Return a fragment of the history of file.
842 *
843 * STUB
844 * @param $limit integer Limit of rows to return
845 * @param $start timestamp Only revisions older than $start will be returned
846 * @param $end timestamp Only revisions newer than $end will be returned
847 * @param $inc bool Include the endpoints of the time range
848 *
849 * @return array
850 */
851 function getHistory($limit = null, $start = null, $end = null, $inc=true) {
852 return array();
853 }
854
855 /**
856 * Return the history of this file, line by line. Starts with current version,
857 * then old versions. Should return an object similar to an image/oldimage
858 * database row.
859 *
860 * STUB
861 * Overridden in LocalFile
862 */
863 public function nextHistoryLine() {
864 return false;
865 }
866
867 /**
868 * Reset the history pointer to the first element of the history.
869 * Always call this function after using nextHistoryLine() to free db resources
870 * STUB
871 * Overridden in LocalFile.
872 */
873 public function resetHistory() {}
874
875 /**
876 * Get the filename hash component of the directory including trailing slash,
877 * e.g. f/fa/
878 * If the repository is not hashed, returns an empty string.
879 *
880 * @return string
881 */
882 function getHashPath() {
883 if ( !isset( $this->hashPath ) ) {
884 $this->hashPath = $this->repo->getHashPath( $this->getName() );
885 }
886 return $this->hashPath;
887 }
888
889 /**
890 * Get the path of the file relative to the public zone root
891 *
892 * @return string
893 */
894 function getRel() {
895 return $this->getHashPath() . $this->getName();
896 }
897
898 /**
899 * Get urlencoded relative path of the file
900 *
901 * @return string
902 */
903 function getUrlRel() {
904 return $this->getHashPath() . rawurlencode( $this->getName() );
905 }
906
907 /**
908 * Get the relative path for an archived file
909 *
910 * @param $suffix bool|string if not false, the name of an archived thumbnail file
911 *
912 * @return string
913 */
914 function getArchiveRel( $suffix = false ) {
915 $path = 'archive/' . $this->getHashPath();
916 if ( $suffix === false ) {
917 $path = substr( $path, 0, -1 );
918 } else {
919 $path .= $suffix;
920 }
921 return $path;
922 }
923
924 /**
925 * Get the relative path for an archived file's thumbs directory
926 * or a specific thumb if the $suffix is given.
927 *
928 * @param $archiveName string the timestamped name of an archived image
929 * @param $suffix bool|string if not false, the name of a thumbnail file
930 *
931 * @return string
932 */
933 function getArchiveThumbRel( $archiveName, $suffix = false ) {
934 $path = 'archive/' . $this->getHashPath() . $archiveName . "/";
935 if ( $suffix === false ) {
936 $path = substr( $path, 0, -1 );
937 } else {
938 $path .= $suffix;
939 }
940 return $path;
941 }
942
943 /**
944 * Get the path of the archived file.
945 *
946 * @param $suffix bool|string if not false, the name of an archived file.
947 *
948 * @return string
949 */
950 function getArchivePath( $suffix = false ) {
951 return $this->repo->getZonePath( 'public' ) . '/' . $this->getArchiveRel( $suffix );
952 }
953
954 /**
955 * Get the path of the archived file's thumbs, or a particular thumb if $suffix is specified
956 *
957 * @param $archiveName string the timestamped name of an archived image
958 * @param $suffix bool|string if not false, the name of a thumbnail file
959 *
960 * @return string
961 */
962 function getArchiveThumbPath( $archiveName, $suffix = false ) {
963 return $this->repo->getZonePath( 'thumb' ) . '/' . $this->getArchiveThumbRel( $archiveName, $suffix );
964 }
965
966 /**
967 * Get the path of the thumbnail directory, or a particular file if $suffix is specified
968 *
969 * @param $suffix bool|string if not false, the name of a thumbnail file
970 *
971 * @return string
972 */
973 function getThumbPath( $suffix = false ) {
974 $path = $this->repo->getZonePath( 'thumb' ) . '/' . $this->getRel();
975 if ( $suffix !== false ) {
976 $path .= '/' . $suffix;
977 }
978 return $path;
979 }
980
981 /**
982 * Get the URL of the archive directory, or a particular file if $suffix is specified
983 *
984 * @param $suffix bool|string if not false, the name of an archived file
985 *
986 * @return string
987 */
988 function getArchiveUrl( $suffix = false ) {
989 $path = $this->repo->getZoneUrl('public') . '/archive/' . $this->getHashPath();
990 if ( $suffix === false ) {
991 $path = substr( $path, 0, -1 );
992 } else {
993 $path .= rawurlencode( $suffix );
994 }
995 return $path;
996 }
997
998 /**
999 * Get the URL of the archived file's thumbs, or a particular thumb if $suffix is specified
1000 *
1001 * @param $archiveName string the timestamped name of an archived image
1002 * @param $suffix bool|string if not false, the name of a thumbnail file
1003 *
1004 * @return string
1005 */
1006 function getArchiveThumbUrl( $archiveName, $suffix = false ) {
1007 $path = $this->repo->getZoneUrl('thumb') . '/archive/' . $this->getHashPath() . rawurlencode( $archiveName ) . "/";
1008 if ( $suffix === false ) {
1009 $path = substr( $path, 0, -1 );
1010 } else {
1011 $path .= rawurlencode( $suffix );
1012 }
1013 return $path;
1014 }
1015
1016 /**
1017 * Get the URL of the thumbnail directory, or a particular file if $suffix is specified
1018 *
1019 * @param $suffix bool|string if not false, the name of a thumbnail file
1020 *
1021 * @return path
1022 */
1023 function getThumbUrl( $suffix = false ) {
1024 $path = $this->repo->getZoneUrl('thumb') . '/' . $this->getUrlRel();
1025 if ( $suffix !== false ) {
1026 $path .= '/' . rawurlencode( $suffix );
1027 }
1028 return $path;
1029 }
1030
1031 /**
1032 * Get the virtual URL for an archived file's thumbs, or a specific thumb.
1033 *
1034 * @param $suffix bool|string if not false, the name of a thumbnail file
1035 *
1036 * @return string
1037 */
1038 function getArchiveVirtualUrl( $suffix = false ) {
1039 $path = $this->repo->getVirtualUrl() . '/public/archive/' . $this->getHashPath();
1040 if ( $suffix === false ) {
1041 $path = substr( $path, 0, -1 );
1042 } else {
1043 $path .= rawurlencode( $suffix );
1044 }
1045 return $path;
1046 }
1047
1048 /**
1049 * Get the virtual URL for a thumbnail file or directory
1050 *
1051 * @param $suffix bool|string if not false, the name of a thumbnail file
1052 *
1053 * @return string
1054 */
1055 function getThumbVirtualUrl( $suffix = false ) {
1056 $path = $this->repo->getVirtualUrl() . '/thumb/' . $this->getUrlRel();
1057 if ( $suffix !== false ) {
1058 $path .= '/' . rawurlencode( $suffix );
1059 }
1060 return $path;
1061 }
1062
1063 /**
1064 * Get the virtual URL for the file itself
1065 *
1066 * @param $suffix bool|string if not false, the name of a thumbnail file
1067 *
1068 * @return string
1069 */
1070 function getVirtualUrl( $suffix = false ) {
1071 $path = $this->repo->getVirtualUrl() . '/public/' . $this->getUrlRel();
1072 if ( $suffix !== false ) {
1073 $path .= '/' . rawurlencode( $suffix );
1074 }
1075 return $path;
1076 }
1077
1078 /**
1079 * @return bool
1080 */
1081 function isHashed() {
1082 return $this->repo->isHashed();
1083 }
1084
1085 /**
1086 * @throws MWException
1087 */
1088 function readOnlyError() {
1089 throw new MWException( get_class($this) . ': write operations are not supported' );
1090 }
1091
1092 /**
1093 * Record a file upload in the upload log and the image table
1094 * STUB
1095 * Overridden by LocalFile
1096 * @param $oldver
1097 * @param $desc
1098 * @param $license string
1099 * @param $copyStatus string
1100 * @param $source string
1101 * @param $watch bool
1102 */
1103 function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '', $watch = false ) {
1104 $this->readOnlyError();
1105 }
1106
1107 /**
1108 * Move or copy a file to its public location. If a file exists at the
1109 * destination, move it to an archive. Returns a FileRepoStatus object with
1110 * the archive name in the "value" member on success.
1111 *
1112 * The archive name should be passed through to recordUpload for database
1113 * registration.
1114 *
1115 * @param $srcPath String: local filesystem path to the source image
1116 * @param $flags Integer: a bitwise combination of:
1117 * File::DELETE_SOURCE Delete the source file, i.e. move
1118 * rather than copy
1119 * @return FileRepoStatus object. On success, the value member contains the
1120 * archive name, or an empty string if it was a new file.
1121 *
1122 * STUB
1123 * Overridden by LocalFile
1124 */
1125 function publish( $srcPath, $flags = 0 ) {
1126 $this->readOnlyError();
1127 }
1128
1129 /**
1130 * @return bool
1131 */
1132 function formatMetadata() {
1133 if ( !$this->getHandler() ) {
1134 return false;
1135 }
1136 return $this->getHandler()->formatMetadata( $this, $this->getMetadata() );
1137 }
1138
1139 /**
1140 * Returns true if the file comes from the local file repository.
1141 *
1142 * @return bool
1143 */
1144 function isLocal() {
1145 $repo = $this->getRepo();
1146 return $repo && $repo->isLocal();
1147 }
1148
1149 /**
1150 * Returns the name of the repository.
1151 *
1152 * @return string
1153 */
1154 function getRepoName() {
1155 return $this->repo ? $this->repo->getName() : 'unknown';
1156 }
1157
1158 /**
1159 * Returns the repository
1160 *
1161 * @return FileRepo
1162 */
1163 function getRepo() {
1164 return $this->repo;
1165 }
1166
1167 /**
1168 * Returns true if the image is an old version
1169 * STUB
1170 *
1171 * @return bool
1172 */
1173 function isOld() {
1174 return false;
1175 }
1176
1177 /**
1178 * Is this file a "deleted" file in a private archive?
1179 * STUB
1180 *
1181 * @param $field
1182 *
1183 * @return bool
1184 */
1185 function isDeleted( $field ) {
1186 return false;
1187 }
1188
1189 /**
1190 * Return the deletion bitfield
1191 * STUB
1192 */
1193 function getVisibility() {
1194 return 0;
1195 }
1196
1197 /**
1198 * Was this file ever deleted from the wiki?
1199 *
1200 * @return bool
1201 */
1202 function wasDeleted() {
1203 $title = $this->getTitle();
1204 return $title && $title->isDeletedQuick();
1205 }
1206
1207 /**
1208 * Move file to the new title
1209 *
1210 * Move current, old version and all thumbnails
1211 * to the new filename. Old file is deleted.
1212 *
1213 * Cache purging is done; checks for validity
1214 * and logging are caller's responsibility
1215 *
1216 * @param $target Title New file name
1217 * @return FileRepoStatus object.
1218 */
1219 function move( $target ) {
1220 $this->readOnlyError();
1221 }
1222
1223 /**
1224 * Delete all versions of the file.
1225 *
1226 * Moves the files into an archive directory (or deletes them)
1227 * and removes the database rows.
1228 *
1229 * Cache purging is done; logging is caller's responsibility.
1230 *
1231 * @param $reason String
1232 * @param $suppress Boolean: hide content from sysops?
1233 * @return true on success, false on some kind of failure
1234 * STUB
1235 * Overridden by LocalFile
1236 */
1237 function delete( $reason, $suppress = false ) {
1238 $this->readOnlyError();
1239 }
1240
1241 /**
1242 * Restore all or specified deleted revisions to the given file.
1243 * Permissions and logging are left to the caller.
1244 *
1245 * May throw database exceptions on error.
1246 *
1247 * @param $versions array set of record ids of deleted items to restore,
1248 * or empty to restore all revisions.
1249 * @param $unsuppress bool remove restrictions on content upon restoration?
1250 * @return int|false the number of file revisions restored if successful,
1251 * or false on failure
1252 * STUB
1253 * Overridden by LocalFile
1254 */
1255 function restore( $versions = array(), $unsuppress = false ) {
1256 $this->readOnlyError();
1257 }
1258
1259 /**
1260 * Returns 'true' if this file is a type which supports multiple pages,
1261 * e.g. DJVU or PDF. Note that this may be true even if the file in
1262 * question only has a single page.
1263 *
1264 * @return Bool
1265 */
1266 function isMultipage() {
1267 return $this->getHandler() && $this->handler->isMultiPage( $this );
1268 }
1269
1270 /**
1271 * Returns the number of pages of a multipage document, or false for
1272 * documents which aren't multipage documents
1273 *
1274 * @return false|int
1275 */
1276 function pageCount() {
1277 if ( !isset( $this->pageCount ) ) {
1278 if ( $this->getHandler() && $this->handler->isMultiPage( $this ) ) {
1279 $this->pageCount = $this->handler->pageCount( $this );
1280 } else {
1281 $this->pageCount = false;
1282 }
1283 }
1284 return $this->pageCount;
1285 }
1286
1287 /**
1288 * Calculate the height of a thumbnail using the source and destination width
1289 *
1290 * @param $srcWidth
1291 * @param $srcHeight
1292 * @param $dstWidth
1293 *
1294 * @return int
1295 */
1296 static function scaleHeight( $srcWidth, $srcHeight, $dstWidth ) {
1297 // Exact integer multiply followed by division
1298 if ( $srcWidth == 0 ) {
1299 return 0;
1300 } else {
1301 return round( $srcHeight * $dstWidth / $srcWidth );
1302 }
1303 }
1304
1305 /**
1306 * Get an image size array like that returned by getImageSize(), or false if it
1307 * can't be determined.
1308 *
1309 * @param $fileName String: The filename
1310 * @return Array
1311 */
1312 function getImageSize( $fileName ) {
1313 if ( !$this->getHandler() ) {
1314 return false;
1315 }
1316 return $this->handler->getImageSize( $this, $fileName );
1317 }
1318
1319 /**
1320 * Get the URL of the image description page. May return false if it is
1321 * unknown or not applicable.
1322 *
1323 * @return string
1324 */
1325 function getDescriptionUrl() {
1326 return $this->repo->getDescriptionUrl( $this->getName() );
1327 }
1328
1329 /**
1330 * Get the HTML text of the description page, if available
1331 *
1332 * @return string
1333 */
1334 function getDescriptionText() {
1335 global $wgMemc, $wgLang;
1336 if ( !$this->repo->fetchDescription ) {
1337 return false;
1338 }
1339 $renderUrl = $this->repo->getDescriptionRenderUrl( $this->getName(), $wgLang->getCode() );
1340 if ( $renderUrl ) {
1341 if ( $this->repo->descriptionCacheExpiry > 0 ) {
1342 wfDebug("Attempting to get the description from cache...");
1343 $key = $this->repo->getLocalCacheKey( 'RemoteFileDescription', 'url', $wgLang->getCode(),
1344 $this->getName() );
1345 $obj = $wgMemc->get($key);
1346 if ($obj) {
1347 wfDebug("success!\n");
1348 return $obj;
1349 }
1350 wfDebug("miss\n");
1351 }
1352 wfDebug( "Fetching shared description from $renderUrl\n" );
1353 $res = Http::get( $renderUrl );
1354 if ( $res && $this->repo->descriptionCacheExpiry > 0 ) {
1355 $wgMemc->set( $key, $res, $this->repo->descriptionCacheExpiry );
1356 }
1357 return $res;
1358 } else {
1359 return false;
1360 }
1361 }
1362
1363 /**
1364 * Get discription of file revision
1365 * STUB
1366 *
1367 * @return string
1368 */
1369 function getDescription() {
1370 return null;
1371 }
1372
1373 /**
1374 * Get the 14-character timestamp of the file upload, or false if
1375 * it doesn't exist
1376 *
1377 * @return string
1378 */
1379 function getTimestamp() {
1380 $path = $this->getPath();
1381 if ( !file_exists( $path ) ) {
1382 return false;
1383 }
1384 return wfTimestamp( TS_MW, filemtime( $path ) );
1385 }
1386
1387 /**
1388 * Get the SHA-1 base 36 hash of the file
1389 *
1390 * @return string
1391 */
1392 function getSha1() {
1393 return self::sha1Base36( $this->getPath() );
1394 }
1395
1396 /**
1397 * Get the deletion archive key, <sha1>.<ext>
1398 *
1399 * @return string
1400 */
1401 function getStorageKey() {
1402 $hash = $this->getSha1();
1403 if ( !$hash ) {
1404 return false;
1405 }
1406 $ext = $this->getExtension();
1407 $dotExt = $ext === '' ? '' : ".$ext";
1408 return $hash . $dotExt;
1409 }
1410
1411 /**
1412 * Determine if the current user is allowed to view a particular
1413 * field of this file, if it's marked as deleted.
1414 * STUB
1415 * @param $field Integer
1416 * @return Boolean
1417 */
1418 function userCan( $field ) {
1419 return true;
1420 }
1421
1422 /**
1423 * Get an associative array containing information about a file in the local filesystem.
1424 *
1425 * @param $path String: absolute local filesystem path
1426 * @param $ext Mixed: the file extension, or true to extract it from the filename.
1427 * Set it to false to ignore the extension.
1428 *
1429 * @return array
1430 */
1431 static function getPropsFromPath( $path, $ext = true ) {
1432 wfProfileIn( __METHOD__ );
1433 wfDebug( __METHOD__.": Getting file info for $path\n" );
1434 $info = array(
1435 'fileExists' => file_exists( $path ) && !is_dir( $path )
1436 );
1437 $gis = false;
1438 if ( $info['fileExists'] ) {
1439 $magic = MimeMagic::singleton();
1440
1441 if ( $ext === true ) {
1442 $i = strrpos( $path, '.' );
1443 $ext = strtolower( $i ? substr( $path, $i + 1 ) : '' );
1444 }
1445
1446 # mime type according to file contents
1447 $info['file-mime'] = $magic->guessMimeType( $path, false );
1448 # logical mime type
1449 $info['mime'] = $magic->improveTypeFromExtension( $info['file-mime'], $ext );
1450
1451 list( $info['major_mime'], $info['minor_mime'] ) = self::splitMime( $info['mime'] );
1452 $info['media_type'] = $magic->getMediaType( $path, $info['mime'] );
1453
1454 # Get size in bytes
1455 $info['size'] = filesize( $path );
1456
1457 # Height, width and metadata
1458 $handler = MediaHandler::getHandler( $info['mime'] );
1459 if ( $handler ) {
1460 $tempImage = (object)array();
1461 $info['metadata'] = $handler->getMetadata( $tempImage, $path );
1462 $gis = $handler->getImageSize( $tempImage, $path, $info['metadata'] );
1463 } else {
1464 $gis = false;
1465 $info['metadata'] = '';
1466 }
1467 $info['sha1'] = self::sha1Base36( $path );
1468
1469 wfDebug(__METHOD__.": $path loaded, {$info['size']} bytes, {$info['mime']}.\n");
1470 } else {
1471 $info['mime'] = null;
1472 $info['media_type'] = MEDIATYPE_UNKNOWN;
1473 $info['metadata'] = '';
1474 $info['sha1'] = '';
1475 wfDebug(__METHOD__.": $path NOT FOUND!\n");
1476 }
1477 if( $gis ) {
1478 # NOTE: $gis[2] contains a code for the image type. This is no longer used.
1479 $info['width'] = $gis[0];
1480 $info['height'] = $gis[1];
1481 if ( isset( $gis['bits'] ) ) {
1482 $info['bits'] = $gis['bits'];
1483 } else {
1484 $info['bits'] = 0;
1485 }
1486 } else {
1487 $info['width'] = 0;
1488 $info['height'] = 0;
1489 $info['bits'] = 0;
1490 }
1491 wfProfileOut( __METHOD__ );
1492 return $info;
1493 }
1494
1495 /**
1496 * Get a SHA-1 hash of a file in the local filesystem, in base-36 lower case
1497 * encoding, zero padded to 31 digits.
1498 *
1499 * 160 log 2 / log 36 = 30.95, so the 160-bit hash fills 31 digits in base 36
1500 * fairly neatly.
1501 *
1502 * @param $path string
1503 *
1504 * @return false|string False on failure
1505 */
1506 static function sha1Base36( $path ) {
1507 wfSuppressWarnings();
1508 $hash = sha1_file( $path );
1509 wfRestoreWarnings();
1510 if ( $hash === false ) {
1511 return false;
1512 } else {
1513 return wfBaseConvert( $hash, 16, 36, 31 );
1514 }
1515 }
1516
1517 /**
1518 * @return string
1519 */
1520 function getLongDesc() {
1521 $handler = $this->getHandler();
1522 if ( $handler ) {
1523 return $handler->getLongDesc( $this );
1524 } else {
1525 return MediaHandler::getGeneralLongDesc( $this );
1526 }
1527 }
1528
1529 /**
1530 * @return string
1531 */
1532 function getShortDesc() {
1533 $handler = $this->getHandler();
1534 if ( $handler ) {
1535 return $handler->getShortDesc( $this );
1536 } else {
1537 return MediaHandler::getGeneralShortDesc( $this );
1538 }
1539 }
1540
1541 /**
1542 * @return string
1543 */
1544 function getDimensionsString() {
1545 $handler = $this->getHandler();
1546 if ( $handler ) {
1547 return $handler->getDimensionsString( $this );
1548 } else {
1549 return '';
1550 }
1551 }
1552
1553 /**
1554 * @return
1555 */
1556 function getRedirected() {
1557 return $this->redirected;
1558 }
1559
1560 /**
1561 * @return Title
1562 */
1563 function getRedirectedTitle() {
1564 if ( $this->redirected ) {
1565 if ( !$this->redirectTitle ) {
1566 $this->redirectTitle = Title::makeTitle( NS_FILE, $this->redirected );
1567 }
1568 return $this->redirectTitle;
1569 }
1570 }
1571
1572 /**
1573 * @param $from
1574 * @return void
1575 */
1576 function redirectedFrom( $from ) {
1577 $this->redirected = $from;
1578 }
1579
1580 /**
1581 * @return bool
1582 */
1583 function isMissing() {
1584 return false;
1585 }
1586 }
1587 /**
1588 * Aliases for backwards compatibility with 1.6
1589 */
1590 define( 'MW_IMG_DELETED_FILE', File::DELETED_FILE );
1591 define( 'MW_IMG_DELETED_COMMENT', File::DELETED_COMMENT );
1592 define( 'MW_IMG_DELETED_USER', File::DELETED_USER );
1593 define( 'MW_IMG_DELETED_RESTRICTED', File::DELETED_RESTRICTED );