1 <?php
2 3 4 5 6 7 8 9
10
11 12 13 14 15 16 17 18 19 20
21 class P3FileUploadBehavior extends CActiveRecordBehavior {
22 const TRASH_FOLDER = 'trash';
23
24 public $uploadInstance;
25 26 27 28
29 public $dataAlias;
30 31 32 33
34 public $dataSubdirectory;
35 36 37 38
39 public $trashAlias;
40
41 private $_baseDataPath;
42 private $_fullDataPath;
43 private $_relativeDataPath;
44 private $_trashPath;
45 private $_fileToDelete;
46
47 48 49 50 51 52
53 public function afterValidate($event) {
54
55 $this->prepareDataDirectory();
56 $file = CUploadedFile::getInstanceByName($this->uploadInstance);
57
58 if ($file instanceof CUploadedFile && $file->getError() == UPLOAD_ERR_OK && !$this->Owner->hasErrors()) {
59
60 $uniqueFilename = P3StringHelper::generateUniqueFilename($file->getName());
61 $fullFilePath = $this->_fullDataPath . DIRECTORY_SEPARATOR . $uniqueFilename;
62 $relativeFilePath = $this->_relativeDataPath . DIRECTORY_SEPARATOR . $uniqueFilename;
63
64 if ($file->saveAs($fullFilePath)) {
65
66 if (!$this->Owner->isNewRecord) {
67 $this->deleteFile($this->Owner->path);
68 }
69 if (!$this->Owner->title) {
70 $this->Owner->title = P3StringHelper::cleanName($file->name,32);
71 }
72 $this->Owner->path = $relativeFilePath;
73 $this->Owner->mimeType = $file->type;
74 $this->Owner->size = $file->size;
75 $this->Owner->originalName = $file->name;
76 $this->Owner->md5 = md5_file($fullFilePath);
77 } else {
78 $this->Owner->addError('filePath', 'File uploaded failed!');
79 }
80 } else {
81 if ($this->Owner->isNewRecord) {
82
83 Yii::trace('No file uploaded!');
84 }
85 }
86 }
87
88 public function beforeDelete($event) {
89 $this->_fileToDelete = $this->Owner->path;
90 }
91
92 public function afterDelete($event) {
93 $this->prepareDataDirectory();
94 $this->deleteFile($this->_fileToDelete);
95 }
96
97
98 private function deleteFile($path) {
99 $fileToDelete = $this->_baseDataPath . DIRECTORY_SEPARATOR . $path;
100 if (is_file($fileToDelete)) {
101 if (!rename($fileToDelete, $this->_trashPath . DIRECTORY_SEPARATOR . basename($path))) {
102 Yii::log("Error while moving file '" . $path . "' to trash.", CLogger::LEVEL_WARNING);
103 } else {
104 Yii::log("Moved file '" . $path . "' to trash.", CLogger::LEVEL_INFO);
105 }
106 } else {
107 Yii::log("Error file '" . $path . "' could not be deleted. File not found.", CLogger::LEVEL_WARNING);
108 }
109 }
110
111 private function prepareDataDirectory() {
112 $this->_baseDataPath = Yii::getPathOfAlias($this->dataAlias);
113 $this->_fullDataPath = Yii::getPathOfAlias($this->dataAlias) . DIRECTORY_SEPARATOR . $this->dataSubdirectory;
114 $this->_relativeDataPath = $this->dataSubdirectory;
115 if (!is_dir($this->_fullDataPath)) {
116 mkdir($this->_fullDataPath);
117 chmod($this->_fullDataPath, 0777);
118 }
119
120 $this->_trashPath = Yii::getPathOfAlias($this->trashAlias);
121 if (!is_dir($this->_trashPath)) {
122 mkdir($this->_trashPath);
123 chmod($this->_trashPath, 0777);
124 }
125 }
126
127 }
128
129 ?>
130