1: <?php
2:
3: 4: 5: 6: 7: 8: 9: 10:
11:
12: namespace Nette\Http;
13:
14: use Nette;
15:
16:
17:
18: 19: 20: 21: 22: 23: 24: 25: 26: 27: 28: 29: 30: 31:
32: class FileUpload extends Nette\Object
33: {
34:
35: private $name;
36:
37:
38: private $type;
39:
40:
41: private $size;
42:
43:
44: private $tmpName;
45:
46:
47: private $error;
48:
49:
50:
51: public function __construct($value)
52: {
53: foreach (array('name', 'type', 'size', 'tmp_name', 'error') as $key) {
54: if (!isset($value[$key]) || !is_scalar($value[$key])) {
55: $this->error = UPLOAD_ERR_NO_FILE;
56: return;
57: }
58: }
59: $this->name = $value['name'];
60: $this->size = $value['size'];
61: $this->tmpName = $value['tmp_name'];
62: $this->error = $value['error'];
63: }
64:
65:
66:
67: 68: 69: 70:
71: public function getName()
72: {
73: return $this->name;
74: }
75:
76:
77:
78: 79: 80: 81:
82: public function getSanitizedName()
83: {
84: return trim(Nette\Utils\Strings::webalize($this->name, '.', FALSE), '.-');
85: }
86:
87:
88:
89: 90: 91: 92:
93: public function getContentType()
94: {
95: if ($this->isOk() && $this->type === NULL) {
96: $this->type = Nette\Utils\MimeTypeDetector::fromFile($this->tmpName);
97: }
98: return $this->type;
99: }
100:
101:
102:
103: 104: 105: 106:
107: public function getSize()
108: {
109: return $this->size;
110: }
111:
112:
113:
114: 115: 116: 117:
118: public function getTemporaryFile()
119: {
120: return $this->tmpName;
121: }
122:
123:
124:
125: 126: 127: 128:
129: public function __toString()
130: {
131: return $this->tmpName;
132: }
133:
134:
135:
136: 137: 138: 139:
140: public function getError()
141: {
142: return $this->error;
143: }
144:
145:
146:
147: 148: 149: 150:
151: public function isOk()
152: {
153: return $this->error === UPLOAD_ERR_OK;
154: }
155:
156:
157:
158: 159: 160: 161: 162:
163: public function move($dest)
164: {
165: $dir = dirname($dest);
166: if (@mkdir($dir, 0755, TRUE)) {
167: chmod($dir, 0755);
168: }
169: $func = is_uploaded_file($this->tmpName) ? 'move_uploaded_file' : 'rename';
170: if (!$func($this->tmpName, $dest)) {
171: throw new Nette\InvalidStateException("Unable to move uploaded file '$this->tmpName' to '$dest'.");
172: }
173: chmod($dest, 0644);
174: $this->tmpName = $dest;
175: return $this;
176: }
177:
178:
179:
180: 181: 182: 183:
184: public function isImage()
185: {
186: return in_array($this->getContentType(), array('image/gif', 'image/png', 'image/jpeg'), TRUE);
187: }
188:
189:
190:
191: 192: 193: 194:
195: public function toImage()
196: {
197: return Nette\Image::fromFile($this->tmpName);
198: }
199:
200:
201:
202: 203: 204: 205:
206: public function getImageSize()
207: {
208: return $this->isOk() ? @getimagesize($this->tmpName) : NULL;
209: }
210:
211:
212:
213: 214: 215: 216:
217: public function getContents()
218: {
219:
220: return $this->isOk() ? file_get_contents($this->tmpName) : NULL;
221: }
222:
223: }
224: