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