This repository was archived by the owner on Mar 30, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAttachableBehavior.php
More file actions
359 lines (311 loc) · 11.8 KB
/
AttachableBehavior.php
File metadata and controls
359 lines (311 loc) · 11.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
<?php
// The behavior uses the Folder and File Utility classes
App::uses('Folder', 'Utility');
App::uses('File', 'Utility');
class AttachableBehavior extends ModelBehavior {
private $_defaults = array(
'attachments' => array(
'file' => array(
'dir' => 'files', // location of the folder in webroot folder, can specify subfolders also
'types' => '*', // use '*' for all file types, or put an array of mime types
'extensions' => '*',
'maxSize' => 5242880, // 5 MB (in bytes)
'physicalName' => '{ID}-{FILENAME}', // name for the file to save, filename will be converted to lowercase and any special characters and spaces will be removed
'errorMessages' => array(
'DIRECTORY_NOT_WRITABLE' => 'Directory not writable.',
'INVALID_FILE_TYPE' => 'This file type is not supported.',
'INVALID_FILE_SIZE' => 'The file is too large to upload.',
),
'createDir' => true,
),
),
'baseDir' => 'uploads',
'dir' => 'files',
'types' => '*',
'extensions' => '*',
'maxSize' => 5242880,
'physicalName' => '{ID}-{FILENAME}',
'errorMessages' => array(
'DIRECTORY_NOT_WRITABLE' => 'Directory not writable.',
'DIRECTORY_DOES_NOT_EXIST' => "The target directory doesn't exist",
'INVALID_FILE_TYPE' => 'This file type is not supported.',
'INVALID_FILE_EXTENSION' => 'This file type is not supported.',
'INVALID_FILE_SIZE' => 'The file is too large to upload.',
'ERROR_UPLOADING_FILE' => 'There was an error uploading the file.',
'FILE_NOT_UPLOADED' => 'The file was not properly uploaded.',
'PARENT_DIRECTORY_NOT_WRITABLE' => 'The parent directory is now writable.',
),
'createDir' => true,
);
public function setup(Model $Model, $options = array()) {
$this->settings[$Model->alias] = array_merge($this->_defaults, $options);
}
public function beforeSave(Model $Model) {
$attachments = $this->settings[$Model->alias]['attachments'];
foreach ($attachments as $label => $options) {
if (isset($Model->data[$Model->alias][$label])) {
$attachment = $Model->data[$Model->alias][$label];
if (!empty($attachment['tmp_name']) && empty($Model->validationErrors)) {
$this->uploadAttachment($Model, $label, $attachment, $options);
} else {
unset($Model->data[$Model->alias][$label]);
}
}
}
if (!empty($Model->validationErrors)) {
$this->removeUploadedImages($Model, $attachments);
return false;
}
return true;
}
public function beforeDelete(Model $Model, $cascade) {
// remove the existing files for the record
$attachments = $this->settings[$Model->alias]['attachments'];
$data = $Model->findById($Model->id);
foreach ($attachments as $label => $options) {
$attachment = $data[$Model->alias][$label];
if (!empty($attachment)) {
// get the real path for the attachment
$targetDirectoryPath = $this->getTargetDirectoryPath($Model, $label);
$filePath = $targetDirectoryPath . DS . $attachment;
$file = new File($filePath);
$file->delete();
}
}
return true;
}
private function uploadAttachment(Model $Model, $label = "", $attachment = array(), $options = array()) {
$createDir = $this->getSetting($Model, $label, 'createDir');
if ( !$this->isValidFileType($Model, $label, $attachment) ) return;
if ( !$this->isValidFileExtension($Model, $label, $attachment) ) return;
if ( !$this->isValidFileSize($Model, $label, $attachment) ) return;
if ( !$this->isFileUploaded($Model, $label, $attachment) ) return;
if ( !($createDir || $this->isTargetDirectoryAvailable($Model, $label) ) ) return;
if ( !( $this->isTargetDirectoryWritable($Model, $label) || ( $createDir && $this->isTargetParentDirectoryWritable($Model, $label) ) ) ) return;
if ($this->uploadFile($Model, $label, $attachment, $options)) {
$this->removePreviousImage($Model, $label);
}
}
private function removePreviousImage(Model $Model, $label = "") {
// check if the record is being edited
if (property_exists($Model, 'id')) {
$data = $Model->findById($Model->id);
$fileName = $data[$Model->alias][$label];
$currentFileName = $Model->data[$Model->alias][$label];
// check if the uploaded file is of same name as previous file
if ($currentFileName !== $fileName && !empty($fileName)) {
$targetDirectoryPath = $this->getTargetDirectoryPath($Model, $label);
$targetFilePath = $targetDirectoryPath . DS . $fileName;
//debug($targetFilePath);
$file = new File($targetFilePath);
$file->delete();
}
}
}
/**
* Removes the uploaded images in case of error in any of the field
*/
private function removeUploadedImages(Model $Model, $attachments) {
foreach ($attachments as $label => $options) {
if (isset($Model->data[$Model->alias][$label])) {
$attachment = $Model->data[$Model->alias][$label];
if ( ( !is_array($attachment) && !empty($attachment) ) || ( is_array($attachment) && !empty($attachment['tmp_name']) ) ) {
if (is_array($attachment)) {
$physicalFileName = $this->getPhysicalFileName($Model, $label, $attachment);
} else {
$physicalFileName = $attachment;
}
$targetDirectoryPath = $this->getTargetDirectoryPath($Model, $label);
$targetFileFullPath = $targetDirectoryPath . DS . $physicalFileName;
$file = new File($targetFileFullPath);
$file->delete();
}
}
}
}
private function isFileUploaded(Model $Model, $label = "", $attachment = array()) {
$result = false;
if (!empty($attachment['tmp_name'])) {
$result = is_uploaded_file($attachment['tmp_name']);
}
if (!$result) {
$Model->validationErrors[$label] = $this->getSetting($Model, $label, 'errorMessages.FILE_NOT_UPLOADED');
}
return $result;
}
private function isValidFileType(Model $Model, $label = "", $attachment = array()) {
$validFileTypes = $this->getSetting($Model, $label, 'types');
if (is_array($validFileTypes)) {
if (in_array(strtolower($attachment['type']), $validFileTypes) || in_array('*', $validFileTypes)) {
return true;
}
} else if ($validFileTypes = '*') {
return true;
}
$Model->validationErrors[$label] = $this->getSetting($Model, $label, 'errorMessages.INVALID_FILE_TYPE');
return false;
}
private function isValidFileExtension(Model $Model, $label = "", $attachment = array()) {
$validFileExtensions = $this->getSetting($Model, $label, 'extensions');
if (is_array($validFileExtensions)) {
$extension = $this->getFileExtension($attachment);
if (in_array(strtolower($extension), $validFileExtensions) || in_array('*', $validFileExtensions)) {
return true;
}
} else if ($validFileTypes = '*') {
return true;
}
$Model->validationErrors[$label] = $this->getSetting($Model, $label, 'errorMessages.INVALID_FILE_EXTENSION');
return false;
}
private function isValidFileSize(Model $Model, $label = "", $attachment = array()) {
$validFileSize = $this->getSetting($Model, $label, 'maxSize');
if ($validFileSize > $attachment['size'] || $validFileSize == 0) {
return true;
}
$Model->validationErrors[$label] = $this->getSetting($Model, $label, 'errorMessages.INVALID_FILE_SIZE');
return false;
}
private function isTargetDirectoryAvailable(Model $Model, $label = "") {
$targetDirectoryPath = $this->getTargetDirectoryPath($Model, $label);
if ($this->folderExists($targetDirectoryPath)) {
return true;
}
$Model->validationErrors[$label] = $this->getSetting($Model, $label, 'errorMessages.DIRECTORY_DOES_NOT_EXIST');
return false;
}
private function isTargetDirectoryWritable(Model $Model, $label = "") {
$targetDirectory = $this->getTargetDirectoryPath($Model, $label);
if (is_dir($targetDirectory) && is_writable($targetDirectory)) {
return true;
}
$Model->validationErrors[$label] = $this->getSetting($Model, $label, 'errorMessages.DIRECTORY_NOT_WRITABLE');
return false;
}
private function isTargetParentDirectoryWritable(Model $Model, $label = "") {
$targetDirectory = $this->getTargetDirectoryPath($Model, $label);
$targetParent = dirname($targetDirectory);
if (is_dir($targetParent) && is_writable($targetParent)) {
return true;
}
$Model->validationErrors[$label] = $this->getSetting($Model, $label, 'errorMessages.PARENT_DIRECTORY_NOT_WRITABLE');
return false;
}
private function getPhysicalFileName(Model $Model, $label = "", $attachment = array()) {
$fileNameFormat = $this->getSetting($Model, $label, 'physicalName');
$id = null;
if(isset($Model->data[$Model->alias]['id']) && !empty($Model->data[$Model->alias]['id'])){
$id = $Model->data[$Model->name]['id'];
} else {
$query = $Model->query("SHOW TABLE STATUS LIKE '" . $Model->table . "'");
$id = $query[0]['TABLES']['Auto_increment'];
}
$replacement_array = array(
'{ID}' => $id,
'{FILENAME}' => Inflector::slug($this->getFileName($attachment)),
'{TIMESTAMP}' => time(),
);
$physicalNameFormat = $this->getSetting($Model, $label, 'physicalName');
return strtolower(strtr($physicalNameFormat, $replacement_array) . '.' .$this->getFileExtension($attachment));
}
private function getSetting(Model $Model, $label, $name) {
$names = explode('.', $name);
$key = $names[0];
unset($names[0]);
$modelSettings = $this->settings[$Model->alias];
if (isset($modelSettings['attachments'][$label][$key])) {
$returnValue = $this->getKeyValue($modelSettings['attachments'][$label][$key], $names);
if ($returnValue !== null) {
return $returnValue;
}
}
if (isset($modelSettings[$key])) {
$returnValue = $this->getKeyValue($modelSettings[$key], $names);
if ($returnValue !== null) {
return $returnValue;
}
}
return null;
}
private function getKeyValue($array = null, $keys = null) {
if (!empty($array) && !empty($keys)) {
foreach ($keys as $key) {
if (isset($array[$key])) {
$array = $array[$key];
} else {
$array = null;
}
}
}
return $array;
}
/**
* Get the normalized name of the file
*/
private function getFileName($attachment = null) {
if ($attachment) {
// get the filename and return
$file = new File($attachment['name']);
return $file->name();
}
return null;
}
/**
* Get the file extension
*/
private function getFileExtension($attachment = null) {
if ($attachment) {
$file = new File($attachment['name']);
return $file->ext();
}
return null;
}
/**
* Returns the destination path of the file to be uploaded
*/
private function getTargetDirectoryPath(Model $Model, $label = "") {
$dir = $this->getSetting($Model, $label, 'dir');
$baseDir = $this->getSetting($Model, $label, 'baseDir');
$path = WWW_ROOT . $baseDir . DS . $dir;
return $path;
}
/**
* Create the directory
*/
private function createTargetDirectory($targetDirectory = "") {
if ($targetDirectory) {
if (!$this->folderExists($targetDirectory)) {
$folder = new Folder($targetDirectory, true, 0755);
return $folder->path;
} else {
return $targetDirectory;
}
}
return false;
}
private function folderExists($folder = "") {
if ($folder) {
if (is_dir($folder)) {
return true;
}
}
return false;
}
/**
* Uploads the file and returns the uploaded file name
*/
private function uploadFile(Model $Model, $label = "", $attachment = array()) {
$physicalFileName = $this->getPhysicalFileName($Model, $label, $attachment);
$targetDirectoryPath = $this->getTargetDirectoryPath($Model, $label);
$createDir = $this->getSetting($Model, $label, 'createDir');
if ( $this->createTargetDirectory($targetDirectoryPath) ) {
$targetFileFullPath = $targetDirectoryPath . DS . $physicalFileName;
if (move_uploaded_file($attachment['tmp_name'], $targetFileFullPath)) {
$Model->data[$Model->alias][$label] = $physicalFileName;
return true;
}
}
$Model->validationErrors[$label] = $this->getSetting($Model, $label, 'errorMessages.ERROR_UPLOADING_FILE');
return false;
}
}