response.php 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  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_NOT_FOUND = 404;
  36. const STATUS_INTERNAL_SERVER_ERROR = 500;
  37. const STATUS_SERVICE_UNAVAILABLE = 503;
  38. /**
  39. * Enable response caching by sending correct HTTP headers
  40. * @param integer $cache_time time to cache the response
  41. * >0 cache time in seconds
  42. * 0 and <0 enable default browser caching
  43. * null cache indefinitely
  44. */
  45. static public function enableCaching($cache_time = null) {
  46. if (is_numeric($cache_time)) {
  47. header('Pragma: public');// enable caching in IE
  48. if ($cache_time > 0) {
  49. self::setExpiresHeader('PT'.$cache_time.'S');
  50. header('Cache-Control: max-age='.$cache_time.', must-revalidate');
  51. }
  52. else {
  53. self::setExpiresHeader(0);
  54. header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
  55. }
  56. }
  57. else {
  58. header('Cache-Control: cache');
  59. header('Pragma: cache');
  60. }
  61. }
  62. /**
  63. * disable browser caching
  64. * @see enableCaching with cache_time = 0
  65. */
  66. static public function disableCaching() {
  67. self::enableCaching(0);
  68. }
  69. /**
  70. * Set response status
  71. * @param int $status a HTTP status code, see also the STATUS constants
  72. */
  73. static public function setStatus($status) {
  74. $protocol = \OC::$server->getRequest()->getHttpProtocol();
  75. switch($status) {
  76. case self::STATUS_NOT_MODIFIED:
  77. $status = $status . ' Not Modified';
  78. break;
  79. case self::STATUS_TEMPORARY_REDIRECT:
  80. if ($protocol == 'HTTP/1.1') {
  81. $status = $status . ' Temporary Redirect';
  82. break;
  83. } else {
  84. $status = self::STATUS_FOUND;
  85. // fallthrough
  86. }
  87. case self::STATUS_FOUND;
  88. $status = $status . ' Found';
  89. break;
  90. case self::STATUS_NOT_FOUND;
  91. $status = $status . ' Not Found';
  92. break;
  93. case self::STATUS_INTERNAL_SERVER_ERROR;
  94. $status = $status . ' Internal Server Error';
  95. break;
  96. case self::STATUS_SERVICE_UNAVAILABLE;
  97. $status = $status . ' Service Unavailable';
  98. break;
  99. }
  100. header($protocol.' '.$status);
  101. }
  102. /**
  103. * Send redirect response
  104. * @param string $location to redirect to
  105. */
  106. static public function redirect($location) {
  107. self::setStatus(self::STATUS_TEMPORARY_REDIRECT);
  108. header('Location: '.$location);
  109. }
  110. /**
  111. * Set response expire time
  112. * @param string|DateTime $expires date-time when the response expires
  113. * string for DateInterval from now
  114. * DateTime object when to expire response
  115. */
  116. static public function setExpiresHeader($expires) {
  117. if (is_string($expires) && $expires[0] == 'P') {
  118. $interval = $expires;
  119. $expires = new DateTime('now');
  120. $expires->add(new DateInterval($interval));
  121. }
  122. if ($expires instanceof DateTime) {
  123. $expires->setTimezone(new DateTimeZone('GMT'));
  124. $expires = $expires->format(DateTime::RFC2822);
  125. }
  126. header('Expires: '.$expires);
  127. }
  128. /**
  129. * Checks and set ETag header, when the request matches sends a
  130. * 'not modified' response
  131. * @param string $etag token to use for modification check
  132. */
  133. static public function setETagHeader($etag) {
  134. if (empty($etag)) {
  135. return;
  136. }
  137. $etag = '"'.$etag.'"';
  138. if (isset($_SERVER['HTTP_IF_NONE_MATCH']) &&
  139. trim($_SERVER['HTTP_IF_NONE_MATCH']) == $etag) {
  140. self::setStatus(self::STATUS_NOT_MODIFIED);
  141. exit;
  142. }
  143. header('ETag: '.$etag);
  144. }
  145. /**
  146. * Checks and set Last-Modified header, when the request matches sends a
  147. * 'not modified' response
  148. * @param int|DateTime|string $lastModified time when the response was last modified
  149. */
  150. static public function setLastModifiedHeader($lastModified) {
  151. if (empty($lastModified)) {
  152. return;
  153. }
  154. if (is_int($lastModified)) {
  155. $lastModified = gmdate(DateTime::RFC2822, $lastModified);
  156. }
  157. if ($lastModified instanceof DateTime) {
  158. $lastModified = $lastModified->format(DateTime::RFC2822);
  159. }
  160. if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) &&
  161. trim($_SERVER['HTTP_IF_MODIFIED_SINCE']) == $lastModified) {
  162. self::setStatus(self::STATUS_NOT_MODIFIED);
  163. exit;
  164. }
  165. header('Last-Modified: '.$lastModified);
  166. }
  167. /**
  168. * Sets the content disposition header (with possible workarounds)
  169. * @param string $filename file name
  170. * @param string $type disposition type, either 'attachment' or 'inline'
  171. */
  172. static public function setContentDispositionHeader( $filename, $type = 'attachment' ) {
  173. if (\OC::$server->getRequest()->isUserAgent(
  174. [
  175. \OC\AppFramework\Http\Request::USER_AGENT_IE,
  176. \OC\AppFramework\Http\Request::USER_AGENT_ANDROID_MOBILE_CHROME,
  177. \OC\AppFramework\Http\Request::USER_AGENT_FREEBOX,
  178. ])) {
  179. header( 'Content-Disposition: ' . rawurlencode($type) . '; filename="' . rawurlencode( $filename ) . '"' );
  180. } else {
  181. header( 'Content-Disposition: ' . rawurlencode($type) . '; filename*=UTF-8\'\'' . rawurlencode( $filename )
  182. . '; filename="' . rawurlencode( $filename ) . '"' );
  183. }
  184. }
  185. /**
  186. * Sets the content length header (with possible workarounds)
  187. * @param string|int|float $length Length to be sent
  188. */
  189. static public function setContentLengthHeader($length) {
  190. if (PHP_INT_SIZE === 4) {
  191. if ($length > PHP_INT_MAX && stripos(PHP_SAPI, 'apache') === 0) {
  192. // Apache PHP SAPI casts Content-Length headers to PHP integers.
  193. // This enforces a limit of PHP_INT_MAX (2147483647 on 32-bit
  194. // platforms). So, if the length is greater than PHP_INT_MAX,
  195. // we just do not send a Content-Length header to prevent
  196. // bodies from being received incompletely.
  197. return;
  198. }
  199. // Convert signed integer or float to unsigned base-10 string.
  200. $lfh = new \OC\LargeFileHelper;
  201. $length = $lfh->formatUnsignedInteger($length);
  202. }
  203. header('Content-Length: '.$length);
  204. }
  205. /**
  206. * Send file as response, checking and setting caching headers
  207. * @param string $filepath of file to send
  208. * @deprecated 8.1.0 - Use \OCP\AppFramework\Http\StreamResponse or another AppFramework controller instead
  209. */
  210. static public function sendFile($filepath) {
  211. $fp = fopen($filepath, 'rb');
  212. if ($fp) {
  213. self::setLastModifiedHeader(filemtime($filepath));
  214. self::setETagHeader(md5_file($filepath));
  215. self::setContentLengthHeader(filesize($filepath));
  216. fpassthru($fp);
  217. }
  218. else {
  219. self::setStatus(self::STATUS_NOT_FOUND);
  220. }
  221. }
  222. /**
  223. * This function adds some security related headers to all requests served via base.php
  224. * The implementation of this function has to happen here to ensure that all third-party
  225. * components (e.g. SabreDAV) also benefit from this headers.
  226. */
  227. public static function addSecurityHeaders() {
  228. /**
  229. * FIXME: Content Security Policy for legacy ownCloud components. This
  230. * can be removed once \OCP\AppFramework\Http\Response from the AppFramework
  231. * is used everywhere.
  232. * @see \OCP\AppFramework\Http\Response::getHeaders
  233. */
  234. $policy = 'default-src \'self\'; '
  235. . 'script-src \'self\' \'unsafe-eval\'; '
  236. . 'style-src \'self\' \'unsafe-inline\'; '
  237. . 'frame-src *; '
  238. . 'img-src * data: blob:; '
  239. . 'font-src \'self\' data:; '
  240. . 'media-src *; '
  241. . 'connect-src *';
  242. header('Content-Security-Policy:' . $policy);
  243. // Send fallback headers for installations that don't have the possibility to send
  244. // custom headers on the webserver side
  245. if(getenv('modHeadersAvailable') !== 'true') {
  246. header('X-XSS-Protection: 1; mode=block'); // Enforce browser based XSS filters
  247. header('X-Content-Type-Options: nosniff'); // Disable sniffing the content type for IE
  248. header('X-Frame-Options: Sameorigin'); // Disallow iFraming from other domains
  249. header('X-Robots-Tag: none'); // https://developers.google.com/webmasters/control-crawl-index/docs/robots_meta_tag
  250. header('X-Download-Options: noopen'); // https://msdn.microsoft.com/en-us/library/jj542450(v=vs.85).aspx
  251. header('X-Permitted-Cross-Domain-Policies: none'); // https://www.adobe.com/devnet/adobe-media-server/articles/cross-domain-xml-for-streaming.html
  252. }
  253. }
  254. }