1<?php 2 3declare(strict_types=1); 4 5namespace Sabre\DAV\Browser; 6 7use Sabre\DAV; 8use Sabre\DAV\INode; 9use Sabre\DAV\PropFind; 10use Sabre\Uri; 11 12/** 13 * GuessContentType plugin. 14 * 15 * A lot of the built-in File objects just return application/octet-stream 16 * as a content-type by default. This is a problem for some clients, because 17 * they expect a correct contenttype. 18 * 19 * There's really no accurate, fast and portable way to determine the contenttype 20 * so this extension does what the rest of the world does, and guesses it based 21 * on the file extension. 22 * 23 * @copyright Copyright (C) fruux GmbH (https://fruux.com/) 24 * @author Evert Pot (http://evertpot.com/) 25 * @license http://sabre.io/license/ Modified BSD License 26 */ 27class GuessContentType extends DAV\ServerPlugin 28{ 29 /** 30 * List of recognized file extensions. 31 * 32 * Feel free to add more 33 * 34 * @var array 35 */ 36 public $extensionMap = [ 37 // images 38 'jpg' => 'image/jpeg', 39 'gif' => 'image/gif', 40 'png' => 'image/png', 41 42 // groupware 43 'ics' => 'text/calendar', 44 'vcf' => 'text/vcard', 45 46 // text 47 'txt' => 'text/plain', 48 ]; 49 50 /** 51 * Initializes the plugin. 52 */ 53 public function initialize(DAV\Server $server) 54 { 55 // Using a relatively low priority (200) to allow other extensions 56 // to set the content-type first. 57 $server->on('propFind', [$this, 'propFind'], 200); 58 } 59 60 /** 61 * Our PROPFIND handler. 62 * 63 * Here we set a contenttype, if the node didn't already have one. 64 */ 65 public function propFind(PropFind $propFind, INode $node) 66 { 67 $propFind->handle('{DAV:}getcontenttype', function () use ($propFind) { 68 list(, $fileName) = Uri\split($propFind->getPath()); 69 70 return $this->getContentType($fileName); 71 }); 72 } 73 74 /** 75 * Simple method to return the contenttype. 76 * 77 * @param string $fileName 78 * 79 * @return string 80 */ 81 protected function getContentType($fileName) 82 { 83 if (null !== $fileName) { 84 // Just grabbing the extension 85 $extension = strtolower(substr($fileName, strrpos($fileName, '.') + 1)); 86 if (isset($this->extensionMap[$extension])) { 87 return $this->extensionMap[$extension]; 88 } 89 } 90 91 return 'application/octet-stream'; 92 } 93} 94