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