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