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