ZipResponse.php 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * @copyright Copyright (c) 2018 Roeland Jago Douma <roeland@famdouma.nl>
  5. *
  6. * @author Jakob Sack <mail@jakobsack.de>
  7. * @author Roeland Jago Douma <roeland@famdouma.nl>
  8. *
  9. * @license AGPL-3.0
  10. *
  11. * This code is free software: you can redistribute it and/or modify
  12. * it under the terms of the GNU Affero General Public License, version 3,
  13. * as published by the Free Software Foundation.
  14. *
  15. * This program is distributed in the hope that it will be useful,
  16. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. * GNU Affero General Public License for more details.
  19. *
  20. * You should have received a copy of the GNU Affero General Public License, version 3,
  21. * along with this program. If not, see <http://www.gnu.org/licenses/>
  22. *
  23. */
  24. namespace OCP\AppFramework\Http;
  25. use OCP\IRequest;
  26. use OC\Streamer;
  27. /**
  28. * Public library to send several files in one zip archive.
  29. *
  30. * @since 15.0.0
  31. */
  32. class ZipResponse extends Response implements ICallbackResponse {
  33. /** @var resource[] Files to be added to the zip response */
  34. private $resources;
  35. /** @var string Filename that the zip file should have */
  36. private $name;
  37. private $request;
  38. /**
  39. * @since 15.0.0
  40. */
  41. public function __construct(IRequest $request, string $name = 'output') {
  42. parent::__construct();
  43. $this->name = $name;
  44. $this->request = $request;
  45. }
  46. /**
  47. * @since 15.0.0
  48. */
  49. public function addResource($r, string $internalName, int $size, int $time = -1) {
  50. if (!\is_resource($r)) {
  51. throw new \InvalidArgumentException('No resource provided');
  52. }
  53. $this->resources[] = [
  54. 'resource' => $r,
  55. 'internalName' => $internalName,
  56. 'size' => $size,
  57. 'time' => $time,
  58. ];
  59. }
  60. /**
  61. * @since 15.0.0
  62. */
  63. public function callback(IOutput $output) {
  64. $size = 0;
  65. $files = count($this->resources);
  66. foreach ($this->resources as $resource) {
  67. $size += $resource['size'];
  68. }
  69. $zip = new Streamer($this->request, $size, $files);
  70. $zip->sendHeaders($this->name);
  71. foreach ($this->resources as $resource) {
  72. $zip->addFileFromStream($resource['resource'], $resource['internalName'], $resource['size'], $resource['time']);
  73. }
  74. $zip->finalize();
  75. }
  76. }