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