StreamResponse.php 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Bernhard Posselt <dev@bernhard-posselt.com>
  6. * @author Lukas Reschke <lukas@statuscode.ch>
  7. * @author Morris Jobke <hey@morrisjobke.de>
  8. * @author Robin Appelman <robin@icewind.nl>
  9. *
  10. * @license AGPL-3.0
  11. *
  12. * This code is free software: you can redistribute it and/or modify
  13. * it under the terms of the GNU Affero General Public License, version 3,
  14. * as published by the Free Software Foundation.
  15. *
  16. * This program is distributed in the hope that it will be useful,
  17. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  18. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  19. * GNU Affero General Public License for more details.
  20. *
  21. * You should have received a copy of the GNU Affero General Public License, version 3,
  22. * along with this program. If not, see <http://www.gnu.org/licenses/>
  23. *
  24. */
  25. namespace OCP\AppFramework\Http;
  26. use OCP\AppFramework\Http;
  27. /**
  28. * Class StreamResponse
  29. *
  30. * @package OCP\AppFramework\Http
  31. * @since 8.1.0
  32. */
  33. class StreamResponse extends Response implements ICallbackResponse {
  34. /** @var string */
  35. private $filePath;
  36. /**
  37. * @param string|resource $filePath the path to the file or a file handle which should be streamed
  38. * @since 8.1.0
  39. */
  40. public function __construct ($filePath) {
  41. parent::__construct();
  42. $this->filePath = $filePath;
  43. }
  44. /**
  45. * Streams the file using readfile
  46. *
  47. * @param IOutput $output a small wrapper that handles output
  48. * @since 8.1.0
  49. */
  50. public function callback (IOutput $output) {
  51. // handle caching
  52. if ($output->getHttpResponseCode() !== Http::STATUS_NOT_MODIFIED) {
  53. if (!(is_resource($this->filePath) || file_exists($this->filePath))) {
  54. $output->setHttpResponseCode(Http::STATUS_NOT_FOUND);
  55. } elseif ($output->setReadfile($this->filePath) === false) {
  56. $output->setHttpResponseCode(Http::STATUS_BAD_REQUEST);
  57. }
  58. }
  59. }
  60. }