1: <?php
2:
3: 4: 5: 6: 7: 8: 9: 10:
11:
12: namespace Nette\Forms;
13:
14: use Nette,
15: Nette\Web\HttpUploadedFile;
16:
17:
18:
19: 20: 21: 22: 23:
24: class FileUpload extends FormControl
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 Form) {
47: if ($form->getMethod() !== Form::POST) {
48: throw new \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 HttpUploadedFile($value);
66:
67: } elseif ($value instanceof HttpUploadedFile) {
68: $this->value = $value;
69:
70: } else {
71: $this->value = new HttpUploadedFile(NULL);
72: }
73: return $this;
74: }
75:
76:
77:
78: 79: 80: 81: 82:
83: public static function validateFilled(IFormControl $control)
84: {
85: $file = $control->getValue();
86: return $file instanceof HttpUploadedFile && $file->isOK();
87: }
88:
89:
90:
91: 92: 93: 94: 95: 96:
97: public static function validateFileSize(FileUpload $control, $limit)
98: {
99: $file = $control->getValue();
100: return $file instanceof HttpUploadedFile && $file->getSize() <= $limit;
101: }
102:
103:
104:
105: 106: 107: 108: 109: 110:
111: public static function validateMimeType(FileUpload $control, $mimeType)
112: {
113: $file = $control->getValue();
114: if ($file instanceof HttpUploadedFile) {
115: $type = strtolower($file->getContentType());
116: $mimeTypes = is_array($mimeType) ? $mimeType : explode(',', $mimeType);
117: if (in_array($type, $mimeTypes, TRUE)) {
118: return TRUE;
119: }
120: if (in_array(preg_replace('#/.*#', '/*', $type), $mimeTypes, TRUE)) {
121: return TRUE;
122: }
123: }
124: return FALSE;
125: }
126:
127: }
128: