1
0

StreamResponse.php 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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. * @author Kate Döen <kate.doeen@nextcloud.com>
  12. *
  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. namespace OCP\AppFramework\Http;
  29. use OCP\AppFramework\Http;
  30. /**
  31. * Class StreamResponse
  32. *
  33. * @since 8.1.0
  34. * @template S of int
  35. * @template H of array<string, mixed>
  36. * @template-extends Response<int, array<string, mixed>>
  37. */
  38. class StreamResponse extends Response implements ICallbackResponse {
  39. /** @var string */
  40. private $filePath;
  41. /**
  42. * @param string|resource $filePath the path to the file or a file handle which should be streamed
  43. * @param S $status
  44. * @param H $headers
  45. * @since 8.1.0
  46. */
  47. public function __construct(mixed $filePath, int $status = Http::STATUS_OK, array $headers = []) {
  48. parent::__construct($status, $headers);
  49. $this->filePath = $filePath;
  50. }
  51. /**
  52. * Streams the file using readfile
  53. *
  54. * @param IOutput $output a small wrapper that handles output
  55. * @since 8.1.0
  56. */
  57. public function callback(IOutput $output) {
  58. // handle caching
  59. if ($output->getHttpResponseCode() !== Http::STATUS_NOT_MODIFIED) {
  60. if (!(is_resource($this->filePath) || file_exists($this->filePath))) {
  61. $output->setHttpResponseCode(Http::STATUS_NOT_FOUND);
  62. } elseif ($output->setReadfile($this->filePath) === false) {
  63. $output->setHttpResponseCode(Http::STATUS_BAD_REQUEST);
  64. }
  65. }
  66. }
  67. }