1: <?php
2:
3: 4: 5: 6: 7: 8: 9: 10:
11:
12: namespace Nette\Forms\Controls;
13:
14: use Nette,
15: Nette\Http;
16:
17:
18:
19: 20: 21: 22: 23:
24: class UploadControl extends BaseControl
25: {
26:
27: 28: 29:
30: public function __construct($label = NULL)
31: {
32: parent::__construct($label);
33: $this->control->type = 'file';
34: }
35:
36:
37:
38: 39: 40: 41: 42: 43:
44: protected function attached($form)
45: {
46: if ($form instanceof Nette\Forms\Form) {
47: if ($form->getMethod() !== Nette\Forms\Form::POST) {
48: throw new Nette\InvalidStateException('File upload requires method POST.');
49: }
50: $form->getElementPrototype()->enctype = 'multipart/form-data';
51: }
52: parent::attached($form);
53: }
54:
55:
56:
57: 58: 59: 60: 61:
62: public function setValue($value)
63: {
64: if (is_array($value)) {
65: $this->value = new Http\FileUpload($value);
66:
67: } elseif ($value instanceof Http\FileUpload) {
68: $this->value = $value;
69:
70: } else {
71: $this->value = new Http\FileUpload(NULL);
72: }
73: return $this;
74: }
75:
76:
77:
78: 79: 80: 81:
82: public function isFilled()
83: {
84: return $this->value instanceof Http\FileUpload && $this->value->isOK();
85: }
86:
87:
88:
89: 90: 91: 92: 93: 94:
95: public static function validateFileSize(UploadControl $control, $limit)
96: {
97: $file = $control->getValue();
98: return $file instanceof Http\FileUpload && $file->getSize() <= $limit;
99: }
100:
101:
102:
103: 104: 105: 106: 107: 108:
109: public static function validateMimeType(UploadControl $control, $mimeType)
110: {
111: $file = $control->getValue();
112: if ($file instanceof Http\FileUpload) {
113: $type = strtolower($file->getContentType());
114: $mimeTypes = is_array($mimeType) ? $mimeType : explode(',', $mimeType);
115: if (in_array($type, $mimeTypes, TRUE)) {
116: return TRUE;
117: }
118: if (in_array(preg_replace('#/.*#', '/*', $type), $mimeTypes, TRUE)) {
119: return TRUE;
120: }
121: }
122: return FALSE;
123: }
124:
125:
126:
127: 128: 129: 130:
131: public static function validateImage(UploadControl $control)
132: {
133: $file = $control->getValue();
134: return $file instanceof Http\FileUpload && $file->isImage();
135: }
136:
137: }
138: