response.php 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Andreas Fischer <bantu@owncloud.com>
  6. * @author Bart Visscher <bartv@thisnet.nl>
  7. * @author Jörn Friedrich Dreyer <jfd@butonic.de>
  8. * @author Lukas Reschke <lukas@statuscode.ch>
  9. * @author Morris Jobke <hey@morrisjobke.de>
  10. * @author Robin McCorkell <robin@mccorkell.me.uk>
  11. * @author Stefan Weil <sw@weilnetz.de>
  12. * @author Thomas Müller <thomas.mueller@tmit.eu>
  13. * @author Vincent Petry <pvince81@owncloud.com>
  14. *
  15. * @license AGPL-3.0
  16. *
  17. * This code is free software: you can redistribute it and/or modify
  18. * it under the terms of the GNU Affero General Public License, version 3,
  19. * as published by the Free Software Foundation.
  20. *
  21. * This program is distributed in the hope that it will be useful,
  22. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  23. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  24. * GNU Affero General Public License for more details.
  25. *
  26. * You should have received a copy of the GNU Affero General Public License, version 3,
  27. * along with this program. If not, see <http://www.gnu.org/licenses/>
  28. *
  29. */
  30. class OC_Response {
  31. const STATUS_FOUND = 304;
  32. const STATUS_NOT_MODIFIED = 304;
  33. const STATUS_TEMPORARY_REDIRECT = 307;
  34. const STATUS_BAD_REQUEST = 400;
  35. const STATUS_FORBIDDEN = 403;
  36. const STATUS_NOT_FOUND = 404;
  37. const STATUS_INTERNAL_SERVER_ERROR = 500;
  38. const STATUS_SERVICE_UNAVAILABLE = 503;
  39. /**
  40. * Enable response caching by sending correct HTTP headers
  41. * @param integer $cache_time time to cache the response
  42. * >0 cache time in seconds
  43. * 0 and <0 enable default browser caching
  44. * null cache indefinitely
  45. */
  46. static public function enableCaching($cache_time = null) {
  47. if (is_numeric($cache_time)) {
  48. header('Pragma: public');// enable caching in IE
  49. if ($cache_time > 0) {
  50. self::setExpiresHeader('PT'.$cache_time.'S');
  51. header('Cache-Control: max-age='.$cache_time.', must-revalidate');
  52. }
  53. else {
  54. self::setExpiresHeader(0);
  55. header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
  56. }
  57. }
  58. else {
  59. header('Cache-Control: cache');
  60. header('Pragma: cache');
  61. }
  62. }
  63. /**
  64. * disable browser caching
  65. * @see enableCaching with cache_time = 0
  66. */
  67. static public function disableCaching() {
  68. self::enableCaching(0);
  69. }
  70. /**
  71. * Set response status
  72. * @param int $status a HTTP status code, see also the STATUS constants
  73. */
  74. static public function setStatus($status) {
  75. $protocol = \OC::$server->getRequest()->getHttpProtocol();
  76. switch($status) {
  77. case self::STATUS_NOT_MODIFIED:
  78. $status = $status . ' Not Modified';
  79. break;
  80. case self::STATUS_TEMPORARY_REDIRECT:
  81. if ($protocol == 'HTTP/1.1') {
  82. $status = $status . ' Temporary Redirect';
  83. break;
  84. } else {
  85. $status = self::STATUS_FOUND;
  86. // fallthrough
  87. }
  88. case self::STATUS_FOUND;
  89. $status = $status . ' Found';
  90. break;
  91. case self::STATUS_NOT_FOUND;
  92. $status = $status . ' Not Found';
  93. break;
  94. case self::STATUS_INTERNAL_SERVER_ERROR;
  95. $status = $status . ' Internal Server Error';
  96. break;
  97. case self::STATUS_SERVICE_UNAVAILABLE;
  98. $status = $status . ' Service Unavailable';
  99. break;
  100. }
  101. header($protocol.' '.$status);
  102. }
  103. /**
  104. * Send redirect response
  105. * @param string $location to redirect to
  106. */
  107. static public function redirect($location) {
  108. self::setStatus(self::STATUS_TEMPORARY_REDIRECT);
  109. header('Location: '.$location);
  110. }
  111. /**
  112. * Set response expire time
  113. * @param string|DateTime $expires date-time when the response expires
  114. * string for DateInterval from now
  115. * DateTime object when to expire response
  116. */
  117. static public function setExpiresHeader($expires) {
  118. if (is_string($expires) && $expires[0] == 'P') {
  119. $interval = $expires;
  120. $expires = new DateTime('now');
  121. $expires->add(new DateInterval($interval));
  122. }
  123. if ($expires instanceof DateTime) {
  124. $expires->setTimezone(new DateTimeZone('GMT'));
  125. $expires = $expires->format(DateTime::RFC2822);
  126. }
  127. header('Expires: '.$expires);
  128. }
  129. /**
  130. * Checks and set ETag header, when the request matches sends a
  131. * 'not modified' response
  132. * @param string $etag token to use for modification check
  133. */
  134. static public function setETagHeader($etag) {
  135. if (empty($etag)) {
  136. return;
  137. }
  138. $etag = '"'.$etag.'"';
  139. if (isset($_SERVER['HTTP_IF_NONE_MATCH']) &&
  140. trim($_SERVER['HTTP_IF_NONE_MATCH']) == $etag) {
  141. self::setStatus(self::STATUS_NOT_MODIFIED);
  142. exit;
  143. }
  144. header('ETag: '.$etag);
  145. }
  146. /**
  147. * Checks and set Last-Modified header, when the request matches sends a
  148. * 'not modified' response
  149. * @param int|DateTime|string $lastModified time when the response was last modified
  150. */
  151. static public function setLastModifiedHeader($lastModified) {
  152. if (empty($lastModified)) {
  153. return;
  154. }
  155. if (is_int($lastModified)) {
  156. $lastModified = gmdate(DateTime::RFC2822, $lastModified);
  157. }
  158. if ($lastModified instanceof DateTime) {
  159. $lastModified = $lastModified->format(DateTime::RFC2822);
  160. }
  161. if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) &&
  162. trim($_SERVER['HTTP_IF_MODIFIED_SINCE']) == $lastModified) {
  163. self::setStatus(self::STATUS_NOT_MODIFIED);
  164. exit;
  165. }
  166. header('Last-Modified: '.$lastModified);
  167. }
  168. /**
  169. * Sets the content disposition header (with possible workarounds)
  170. * @param string $filename file name
  171. * @param string $type disposition type, either 'attachment' or 'inline'
  172. */
  173. static public function setContentDispositionHeader( $filename, $type = 'attachment' ) {
  174. if (\OC::$server->getRequest()->isUserAgent(
  175. [
  176. \OC\AppFramework\Http\Request::USER_AGENT_IE,
  177. \OC\AppFramework\Http\Request::USER_AGENT_ANDROID_MOBILE_CHROME,
  178. \OC\AppFramework\Http\Request::USER_AGENT_FREEBOX,
  179. ])) {
  180. header( 'Content-Disposition: ' . rawurlencode($type) . '; filename="' . rawurlencode( $filename ) . '"' );
  181. } else {
  182. header( 'Content-Disposition: ' . rawurlencode($type) . '; filename*=UTF-8\'\'' . rawurlencode( $filename )
  183. . '; filename="' . rawurlencode( $filename ) . '"' );
  184. }
  185. }
  186. /**
  187. * Sets the content length header (with possible workarounds)
  188. * @param string|int|float $length Length to be sent
  189. */
  190. static public function setContentLengthHeader($length) {
  191. if (PHP_INT_SIZE === 4) {
  192. if ($length > PHP_INT_MAX && stripos(PHP_SAPI, 'apache') === 0) {
  193. // Apache PHP SAPI casts Content-Length headers to PHP integers.
  194. // This enforces a limit of PHP_INT_MAX (2147483647 on 32-bit
  195. // platforms). So, if the length is greater than PHP_INT_MAX,
  196. // we just do not send a Content-Length header to prevent
  197. // bodies from being received incompletely.
  198. return;
  199. }
  200. // Convert signed integer or float to unsigned base-10 string.
  201. $lfh = new \OC\LargeFileHelper;
  202. $length = $lfh->formatUnsignedInteger($length);
  203. }
  204. header('Content-Length: '.$length);
  205. }
  206. /**
  207. * Send file as response, checking and setting caching headers
  208. * @param string $filepath of file to send
  209. * @deprecated 8.1.0 - Use \OCP\AppFramework\Http\StreamResponse or another AppFramework controller instead
  210. */
  211. static public function sendFile($filepath) {
  212. $fp = fopen($filepath, 'rb');
  213. if ($fp) {
  214. self::setLastModifiedHeader(filemtime($filepath));
  215. self::setETagHeader(md5_file($filepath));
  216. self::setContentLengthHeader(filesize($filepath));
  217. fpassthru($fp);
  218. }
  219. else {
  220. self::setStatus(self::STATUS_NOT_FOUND);
  221. }
  222. }
  223. /**
  224. * This function adds some security related headers to all requests served via base.php
  225. * The implementation of this function has to happen here to ensure that all third-party
  226. * components (e.g. SabreDAV) also benefit from this headers.
  227. */
  228. public static function addSecurityHeaders() {
  229. /**
  230. * FIXME: Content Security Policy for legacy ownCloud components. This
  231. * can be removed once \OCP\AppFramework\Http\Response from the AppFramework
  232. * is used everywhere.
  233. * @see \OCP\AppFramework\Http\Response::getHeaders
  234. */
  235. $policy = 'default-src \'self\'; '
  236. . 'script-src \'self\' \'unsafe-eval\' \'nonce-'.\OC::$server->getContentSecurityPolicyNonceManager()->getNonce().'\'; '
  237. . 'style-src \'self\' \'unsafe-inline\'; '
  238. . 'frame-src *; '
  239. . 'img-src * data: blob:; '
  240. . 'font-src \'self\' data:; '
  241. . 'media-src *; '
  242. . 'connect-src *; '
  243. . 'object-src \'none\'; '
  244. . 'base-uri \'self\'; ';
  245. header('Content-Security-Policy:' . $policy);
  246. header('X-Frame-Options: Sameorigin'); // Disallow iFraming from other domains
  247. // Send fallback headers for installations that don't have the possibility to send
  248. // custom headers on the webserver side
  249. if(getenv('modHeadersAvailable') !== 'true') {
  250. header('X-XSS-Protection: 1; mode=block'); // Enforce browser based XSS filters
  251. header('X-Content-Type-Options: nosniff'); // Disable sniffing the content type for IE
  252. header('X-Robots-Tag: none'); // https://developers.google.com/webmasters/control-crawl-index/docs/robots_meta_tag
  253. header('X-Download-Options: noopen'); // https://msdn.microsoft.com/en-us/library/jj542450(v=vs.85).aspx
  254. header('X-Permitted-Cross-Domain-Policies: none'); // https://www.adobe.com/devnet/adobe-media-server/articles/cross-domain-xml-for-streaming.html
  255. }
  256. }
  257. }