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