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: public static function validateFileSize(UploadControl $control, $limit)
89: {
90: $file = $control->getValue();
91: return $file instanceof Http\FileUpload && $file->getSize() <= $limit;
92: }
93:
94:
95: 96: 97: 98: 99:
100: public static function validateMimeType(UploadControl $control, $mimeType)
101: {
102: $file = $control->getValue();
103: if ($file instanceof Http\FileUpload) {
104: $type = strtolower($file->getContentType());
105: $mimeTypes = is_array($mimeType) ? $mimeType : explode(',', $mimeType);
106: if (in_array($type, $mimeTypes, TRUE)) {
107: return TRUE;
108: }
109: if (in_array(preg_replace('#/.*#', '/*', $type), $mimeTypes, TRUE)) {
110: return TRUE;
111: }
112: }
113: return FALSE;
114: }
115:
116:
117: 118: 119: 120: 121:
122: public static function validateImage(UploadControl $control)
123: {
124: $file = $control->getValue();
125: return $file instanceof Http\FileUpload && $file->isImage();
126: }
127:
128: }
129: