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