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