response.php 8.5 KB

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