StreamResponse.php 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Bernhard Posselt <dev@bernhard-posselt.com>
  6. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  7. * @author Lukas Reschke <lukas@statuscode.ch>
  8. * @author Morris Jobke <hey@morrisjobke.de>
  9. * @author Robin Appelman <robin@icewind.nl>
  10. * @author Roeland Jago Douma <roeland@famdouma.nl>
  11. *
  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. namespace OCP\AppFramework\Http;
  28. use OCP\AppFramework\Http;
  29. /**
  30. * Class StreamResponse
  31. *
  32. * @since 8.1.0
  33. */
  34. class StreamResponse extends Response implements ICallbackResponse {
  35. /** @var string */
  36. private $filePath;
  37. /**
  38. * @param string|resource $filePath the path to the file or a file handle which should be streamed
  39. * @since 8.1.0
  40. */
  41. public function __construct($filePath) {
  42. parent::__construct();
  43. $this->filePath = $filePath;
  44. }
  45. /**
  46. * Streams the file using readfile
  47. *
  48. * @param IOutput $output a small wrapper that handles output
  49. * @since 8.1.0
  50. */
  51. public function callback(IOutput $output) {
  52. // handle caching
  53. if ($output->getHttpResponseCode() !== Http::STATUS_NOT_MODIFIED) {
  54. if (!(is_resource($this->filePath) || file_exists($this->filePath))) {
  55. $output->setHttpResponseCode(Http::STATUS_NOT_FOUND);
  56. } elseif ($output->setReadfile($this->filePath) === false) {
  57. $output->setHttpResponseCode(Http::STATUS_BAD_REQUEST);
  58. }
  59. }
  60. }
  61. }