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