1: <?php
2:
3: 4: 5: 6: 7:
8:
9:
10:
11: 12: 13: 14: 15: 16: 17: 18: 19: 20:
21: class NFileResponse extends NObject implements IPresenterResponse
22: {
23:
24: private $file;
25:
26:
27: private $contentType;
28:
29:
30: private $name;
31:
32:
33: public $resuming = TRUE;
34:
35:
36: 37: 38: 39: 40:
41: public function __construct($file, $name = NULL, $contentType = NULL)
42: {
43: if (!is_file($file)) {
44: throw new NBadRequestException("File '$file' doesn't exist.");
45: }
46:
47: $this->file = $file;
48: $this->name = $name ? $name : basename($file);
49: $this->contentType = $contentType ? $contentType : 'application/octet-stream';
50: }
51:
52:
53: 54: 55: 56:
57: public function getFile()
58: {
59: return $this->file;
60: }
61:
62:
63: 64: 65: 66:
67: public function getName()
68: {
69: return $this->name;
70: }
71:
72:
73: 74: 75: 76:
77: public function getContentType()
78: {
79: return $this->contentType;
80: }
81:
82:
83: 84: 85: 86:
87: public function send(IHttpRequest $httpRequest, IHttpResponse $httpResponse)
88: {
89: $httpResponse->setContentType($this->contentType);
90: $httpResponse->setHeader('Content-Disposition', 'attachment; filename="' . $this->name . '"');
91:
92: $filesize = $length = filesize($this->file);
93: $handle = fopen($this->file, 'r');
94:
95: if ($this->resuming) {
96: $httpResponse->setHeader('Accept-Ranges', 'bytes');
97: if (preg_match('#^bytes=(\d*)-(\d*)\z#', $httpRequest->getHeader('Range'), $matches)) {
98: list(, $start, $end) = $matches;
99: if ($start === '') {
100: $start = max(0, $filesize - $end);
101: $end = $filesize - 1;
102:
103: } elseif ($end === '' || $end > $filesize - 1) {
104: $end = $filesize - 1;
105: }
106: if ($end < $start) {
107: $httpResponse->setCode(416);
108: return;
109: }
110:
111: $httpResponse->setCode(206);
112: $httpResponse->setHeader('Content-Range', 'bytes ' . $start . '-' . $end . '/' . $filesize);
113: $length = $end - $start + 1;
114: fseek($handle, $start);
115:
116: } else {
117: $httpResponse->setHeader('Content-Range', 'bytes 0-' . ($filesize - 1) . '/' . $filesize);
118: }
119: }
120:
121: $httpResponse->setHeader('Content-Length', $length);
122: while (!feof($handle) && $length > 0) {
123: echo $s = fread($handle, min(4e6, $length));
124: $length -= strlen($s);
125: }
126: fclose($handle);
127: }
128:
129: }
130: