response.php 8.5 KB

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