response.php 8.8 KB

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