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