-
Notifications
You must be signed in to change notification settings - Fork 1
/
NUploadFile.php
98 lines (84 loc) · 2.63 KB
/
NUploadFile.php
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
<?php
/*
* Nupload file behavior
* @author Naser Kholghi <kholghi67@gmail.com>
* @link https://github.com/na3r/NUploadFile
* @version 1.0
*/
class NUploadFile extends CActiveRecordBehavior {
protected $_uploadDirectory;
protected $_fileField;
protected $_tmpFile;
/*
* set true if you want to delete the file on delete record and when user upload new file
*/
protected $_removeFile = true;
public function afterFind() {
$this->_tmpFile = $this->owner->{$this->fileField};
}
public function afterDelete() {
$this->removeFile($this->owner->{$this->fileField});
}
public function uploadFile() {
if(!$this->owner->isNewRecord)
$tmpFile = $this->_tmpFile;
$path = $this->uploadDirectory;
if(!is_dir($path))
mkdir($path);
$fileField = $this->owner->{$this->fileField};
$fileField = CUploadedFile::getInstance($this->owner, $this->fileField);
if($fileField instanceof CUploadedFile) {
//generate unique name for uploaded file
$newName = trim(md5(time().$fileField)).'.'.CFileHelper::getExtension($fileField->name);
$fileField->saveAs($path.$newName);
$this->owner->{$this->fileField} = $this->_getDirName() . $newName;
if(!$this->owner->isNewRecord)
$this->removeFile($path.$tmpFile);
return true;
}
$this->owner->{$this->fileField} = $tmpFile;
}
public function removeFile($fileName) {
$path = $this->uploadDirectory.$fileName;
if(is_file($path) && $this->removeFile)
unlink($path);
}
/*
* return class name as directory name
*/
private function _getDirName() {
return DIRECTORY_SEPARATOR . strtolower(get_class($this->owner)) . DIRECTORY_SEPARATOR;
}
public function setUploadDirectory($dir) {
if(!is_dir($dir))
throw new CException(Yii::t('NUploadFile', '"{dir}" directory is not exists', array('{dir}'=>$dir)));
$this->_uploadDirectory = $dir;
}
/*
* return upload directory path. if null returns runtimePath
*/
public function getUploadDirectory() {
$dirName = $this->_getDirName();
if($this->_uploadDirectory==null)
return Yii::app()->runtimePath.$dirName;
return str_replace('//', '/', $this->_uploadDirectory.$dirName);
}
public function setFileField($fileField) {
$this->_fileField = $fileField;
}
public function getFileField() {
return $this->_fileField;
}
public function setRemoveFile($removeFile) {
$this->_removeFile = $removeFile;
}
public function getRemoveFile() {
return $this->_removeFile;
}
public function getFilePath() {
$filePath = $this->owner->{$this->fileField};
if($this->_uploadDirectory==null)
return Yii::app()->runtimePath.$filePath;
return str_replace('//', '/', $this->_uploadDirectory.$filePath);
}
}