yii2-file-uploader 1.5.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2017 Fabrizio Caldarelli
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/Module.php ADDED
@@ -0,0 +1,53 @@
1
+ <?php
2
+
3
+ /**
4
+ * @copyright Copyright &copy; Fabrizio Caldarelli, sfmobile.it, 2017
5
+ * @package yii2-file-uploader
6
+ * @version 1.0.2
7
+ */
8
+
9
+ namespace sfmobile\ext\fileUploader;
10
+
11
+ /**
12
+ * Yii2FileUploader module definition class
13
+ */
14
+ class Module extends \yii\base\Module
15
+ {
16
+ /**
17
+ * Base path for file uploaded
18
+ */
19
+ public $fileUploadBasePath;
20
+
21
+ /**
22
+ * Base url for file uploaded
23
+ */
24
+ public $fileUploadBaseUrl;
25
+
26
+ /**
27
+ * Db table name
28
+ * @since 1.0.1
29
+ */
30
+ public $dbTableName = 'tbl_file_upload';
31
+
32
+ /**
33
+ * Specify if file upload base url is absolute or not
34
+ * @since 1.0.2
35
+ */
36
+ public $isFileUploadBaseUrlAbsolute = false;
37
+
38
+
39
+ /**
40
+ * @inheritdoc
41
+ */
42
+ public $controllerNamespace = 'sfmobile\ext\fileUploader\controllers';
43
+
44
+ /**
45
+ * @inheritdoc
46
+ */
47
+ public function init()
48
+ {
49
+ parent::init();
50
+
51
+ // custom initialization code goes here
52
+ }
53
+ }
package/README.md ADDED
@@ -0,0 +1,3 @@
1
+ # THIS REPOSITORY IS ABANDONED
2
+
3
+ Go to https://github.com/FabrizioCaldarelli/yii2-file-upload
@@ -0,0 +1,67 @@
1
+ <?php
2
+ namespace sfmobile\ext\fileUploader\components\kartikFileInput;
3
+
4
+ use yii\widgets\InputWidget;
5
+
6
+ /**
7
+ * Kartik File Input Widget Wrapper
8
+ * @package sfmobile\ext\fileUploader\components\kartikFileInput
9
+ * @version 1.0.3
10
+ */
11
+ class KartikFileInput extends InputWidget {
12
+
13
+ /**
14
+ * @var accepted file types for upload
15
+ * @since 1.0.0
16
+ */
17
+ public $acceptedTypes = 'image/*';
18
+
19
+ /**
20
+ * @var max files to uploader. Default (null) is infinite
21
+ * @since 1.0.0
22
+ */
23
+ public $maxFileCount = null;
24
+
25
+ /**
26
+ * @var auto detect file preview type
27
+ * @since 1.0.1
28
+ */
29
+ public $detectPreviewType = true;
30
+
31
+ /**
32
+ * @var string define form model prefixSessionKey attribute name
33
+ * @since 1.0.2
34
+ */
35
+ public $prefixSessionKeyAttribute = null;
36
+
37
+ /**
38
+ * @var string define validateInitialCount option
39
+ * @since 1.0.3
40
+ */
41
+ public $validateInitialCount = true;
42
+
43
+ /**
44
+ * @var string define minFileCount option
45
+ * @since 1.0.3
46
+ */
47
+ public $minFileCount = 0;
48
+
49
+ public function init(){
50
+ parent::init();
51
+ }
52
+
53
+ public function run(){
54
+
55
+ return $this->render('kartikFileInput', [
56
+ 'model' => $this->model,
57
+ 'attribute' => $this->attribute,
58
+ 'acceptedTypes' => $this->acceptedTypes,
59
+ 'maxFileCount' => $this->maxFileCount,
60
+ 'detectPreviewType' => $this->detectPreviewType,
61
+ 'prefixSessionKeyAttribute' => $this->prefixSessionKeyAttribute,
62
+ 'validateInitialCount' => $this->validateInitialCount,
63
+ 'minFileCount' => $this->minFileCount,
64
+ ]);
65
+ }
66
+ }
67
+ ?>
@@ -0,0 +1,90 @@
1
+ <?php
2
+
3
+ use yii\helpers\ArrayHelper;
4
+ use yii\helpers\Html;
5
+
6
+
7
+ $modelName = \yii\helpers\StringHelper::basename(get_class($model));
8
+
9
+ $moduleId = (\sfmobile\ext\fileUploader\Module::getInstance()->id);
10
+
11
+ $prefixSessionKey = null;
12
+ if($prefixSessionKeyAttribute!=null)
13
+ {
14
+ $prefixSessionKeyAttributeNameParts = \sfmobile\ext\fileUploader\models\FileInSession::getAttributeNameParts($prefixSessionKeyAttribute);
15
+ if(count($prefixSessionKeyAttributeNameParts)>=3)
16
+ {
17
+ $prefixSessionKeyAttributeName = $prefixSessionKeyAttributeNameParts[2];
18
+ if (property_exists($model,$prefixSessionKeyAttributeName)) {
19
+ $prefixSessionKey = $model->$prefixSessionKeyAttributeName;
20
+ }
21
+ }
22
+ }
23
+
24
+ $initialPreview = [];
25
+ $initialPreviewConfig = [];
26
+ $filesInSession = \sfmobile\ext\fileUploader\models\FileInSession::listItems($modelName, $attribute, [ 'prefixSessionKey' => $prefixSessionKey ]);
27
+
28
+
29
+ foreach($filesInSession as $fis)
30
+ {
31
+ $mimeType = $fis->fileMimeType;
32
+
33
+ $initialPreview[] = \yii\helpers\Url::to([$moduleId.'/file-in-session/get', 'model' => $fis->modelName, 'attr' => $fis->attributeName, 'name' => $fis->fileName, 'psk' => $prefixSessionKey], true);
34
+
35
+ $previewType = 'image';
36
+
37
+ // If enabled detect preview type, use it
38
+ if($detectPreviewType)
39
+ {
40
+ if(strpos($mimeType, 'image/') === 0) $previewType = 'image';
41
+ if(strpos($mimeType, 'video/') === 0) $previewType = 'video';
42
+ if(strpos($mimeType, 'audio/') === 0) $previewType = 'audio';
43
+ if(strpos($mimeType, 'text/html') === 0) $previewType = 'html';
44
+ if(strpos($mimeType, 'application/pdf') === 0) $previewType = 'pdf';
45
+ }
46
+
47
+ $initialPreviewConfig[] = [
48
+ 'type' => $previewType,
49
+ 'caption' => $fis->fileName,
50
+ 'size' => $fis->fileSize,
51
+ 'url' => \yii\helpers\Url::to([$moduleId.'/file-in-session/delete'], true),
52
+ 'extra' => ['model' => $fis->modelName, 'attr' => $fis->attributeName, 'name' => $fis->fileName, 'psk' => $prefixSessionKey]
53
+ ];
54
+ }
55
+ ?>
56
+ <?php
57
+
58
+ if($prefixSessionKeyAttribute!=null)
59
+ {
60
+ echo Html::activeHiddenInput($model, $prefixSessionKeyAttribute);
61
+ }
62
+
63
+ echo \kartik\file\FileInput::widget([
64
+ 'model' => $model,
65
+ 'attribute' => $attribute.'[]',
66
+ 'options' => [
67
+ 'accept' => $acceptedTypes,
68
+ 'multiple' => true,
69
+ ],
70
+ 'pluginOptions' => [
71
+ 'maxFileCount' => $maxFileCount,
72
+ 'minFileCount' => $minFileCount,
73
+
74
+ 'previewFileType' => 'any',
75
+ 'showPreview' => true,
76
+ 'showCaption' => true,
77
+ 'showRemove' => true,
78
+ 'showUpload' => false,
79
+ 'overwriteInitial' => false,
80
+ 'validateInitialCount' => true,
81
+
82
+ 'initialPreview'=> $initialPreview,
83
+ 'initialPreviewAsData'=>true,
84
+ 'initialPreviewConfig' => $initialPreviewConfig,
85
+ 'ajaxDeleteSettings' => [
86
+ 'type' => 'GET', // Overrides the default POST method
87
+ ],
88
+ ],
89
+ ]);
90
+ ?>
package/composer.json ADDED
@@ -0,0 +1,23 @@
1
+ {
2
+ "name": "fabriziocaldarelli/yii2-file-uploader",
3
+ "description": "File uploader for Yii2",
4
+ "type": "yii2-extension",
5
+ "keywords": ["yii2","extension", "file", "upload"],
6
+ "license": "MIT",
7
+ "authors": [
8
+ {
9
+ "name": "Fabrizio Caldarelli",
10
+ "email": "fabriziocaldarelli@negusweb.it",
11
+ "homepage": "http://www.negusweb.it"
12
+ }
13
+ ],
14
+ "require": {
15
+ "yiisoft/yii2": "*",
16
+ "kartik-v/yii2-widget-fileinput": "@dev"
17
+ },
18
+ "autoload": {
19
+ "psr-4": {
20
+ "sfmobile\\ext\\fileUploader\\": ""
21
+ }
22
+ }
23
+ }
@@ -0,0 +1,42 @@
1
+ <?php
2
+
3
+ namespace sfmobile\ext\fileUploader\controllers;
4
+
5
+ use Yii;
6
+ use yii\web\Controller;
7
+ use yii\web\NotFoundHttpException;
8
+ use yii\filters\VerbFilter;
9
+
10
+ /**
11
+ * FileInSessionController
12
+ */
13
+ class FileInSessionController extends Controller
14
+ {
15
+ public function actionGet($model, $attr, $name, $psk = null)
16
+ {
17
+ $obj = \sfmobile\ext\fileUploader\models\FileInSession::getItem($model, $attr, $name, ['prefixSessionKey' => $psk] );
18
+
19
+ \Yii::$app->response->format = \yii\web\Response::FORMAT_RAW;
20
+ \Yii::$app->response->headers->add('Content-Type', $obj->fileMimeType);
21
+ \Yii::$app->response->data = $obj->data;
22
+ \Yii::$app->response->send();
23
+ }
24
+
25
+ public function actionDelete($model, $attr, $name, $psk = null)
26
+ {
27
+ $obj = \sfmobile\ext\fileUploader\models\FileInSession::deleteItem($model, $attr, $name, ['prefixSessionKey' => $psk] );
28
+
29
+ $out = ['action' => 'none'];
30
+
31
+ if($obj!=null)
32
+ {
33
+ $out = [
34
+ 'action' => 'delete'
35
+ ];
36
+ }
37
+
38
+ \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
39
+ return $out;
40
+ }
41
+
42
+ }
@@ -0,0 +1,40 @@
1
+ <?php
2
+
3
+ use yii\db\Migration;
4
+
5
+ /**
6
+ * Handles the creation of table `tbl_file_upload`.
7
+ */
8
+ class m171120_201016_create_tbl_file_upload_table extends Migration
9
+ {
10
+ /**
11
+ * @inheritdoc
12
+ */
13
+ public function up()
14
+ {
15
+ $this->createTable('tbl_file_upload', [
16
+ 'id' => $this->primaryKey(),
17
+ 'user_id' => $this->integer()->notNull(),
18
+ 'section' => $this->string(150)->notNull(),
19
+ 'category' => $this->string(150)->notNull(),
20
+ 'refer_table' => $this->string(150)->notNull(),
21
+ 'refer_id' => $this->integer()->notNull(),
22
+ 'file_name' => $this->string(150)->notNull(),
23
+ 'file_name_original' => $this->string(150)->notNull(),
24
+ 'description' => $this->string(500),
25
+ 'mime_type' => $this->string(100)->notNull(),
26
+ 'file_size' => $this->bigInteger()->notNull(),
27
+ 'approved' => 'ENUM("yes", "no", "pending") NOT NULL',
28
+ 'relative_path' => $this->string(1000)->notNull(),
29
+ 'create_time' => $this->timestamp()->notNull(),
30
+ ]);
31
+ }
32
+
33
+ /**
34
+ * @inheritdoc
35
+ */
36
+ public function down()
37
+ {
38
+ $this->dropTable('tbl_file_upload');
39
+ }
40
+ }
@@ -0,0 +1,287 @@
1
+ <?php
2
+
3
+ namespace sfmobile\ext\fileUploader\models;
4
+
5
+ use Yii;
6
+ use yii\helpers\ArrayHelper;
7
+
8
+ /**
9
+ * Handle files in SESSION
10
+ * Options can contain: prefixSessionKey to add a prefix to session key (to distinguish different page using same browser)
11
+ * @package sfmobile\ext\fileUploader\models
12
+ * @version 1.0.5
13
+ */
14
+ class FileInSession extends \yii\base\Model
15
+ {
16
+ public $formInputInfo;
17
+ public $fileUploadAttributes;
18
+
19
+ public $modelName;
20
+ public $attributeName;
21
+ public $data;
22
+
23
+ /**
24
+ * Catch all attributes name parts, splitting tabular index from name
25
+ * @since 1.0.3
26
+ */
27
+ public static function getAttributeNameParts($attributeName)
28
+ {
29
+ $matches = [];
30
+ if (!preg_match(\yii\helpers\BaseHtml::$attributeRegex, $attributeName, $matches)) {
31
+ throw new InvalidArgumentException('Attribute name must contain word characters only.');
32
+ }
33
+ /*
34
+ $prefix = $matches[1];
35
+ $attribute = $matches[2];
36
+ $suffix = $matches[3];
37
+ */
38
+ return $matches;
39
+ }
40
+
41
+ public function getFileName()
42
+ {
43
+ $retVal = null;
44
+ if(($this->formInputInfo!=null)&&(isset($this->formInputInfo['name']))&&($this->formInputInfo['name']!=''))
45
+ {
46
+ $retVal = $this->formInputInfo['name'];
47
+ }
48
+ else if(($this->fileUploadAttributes!=null)&&(isset($this->fileUploadAttributes['file_name_original']))&&($this->fileUploadAttributes['file_name_original']!=null))
49
+ {
50
+ $retVal = $this->fileUploadAttributes['file_name_original'];
51
+ }
52
+ return $retVal;
53
+ }
54
+
55
+ public function getFileSize()
56
+ {
57
+ $retVal = null;
58
+ if(($this->formInputInfo!=null)&&(isset($this->formInputInfo['size']))&&($this->formInputInfo['size']!=''))
59
+ {
60
+ $retVal = $this->formInputInfo['size'];
61
+ }
62
+ else if(($this->fileUploadAttributes!=null)&&(isset($this->fileUploadAttributes['file_size']))&&($this->fileUploadAttributes['file_size']!=null))
63
+ {
64
+ $retVal = $this->fileUploadAttributes['file_size'];
65
+ }
66
+ return $retVal;
67
+ }
68
+
69
+ public function getFileMimeType()
70
+ {
71
+ $retVal = null;
72
+ if(($this->formInputInfo!=null)&&(isset($this->formInputInfo['type']))&&($this->formInputInfo['type']!=''))
73
+ {
74
+ $retVal = $this->formInputInfo['type'];
75
+ }
76
+ else if(($this->fileUploadAttributes!=null)&&(isset($this->fileUploadAttributes['mime_type']))&&($this->fileUploadAttributes['mime_type']!=null))
77
+ {
78
+ $retVal = $this->fileUploadAttributes['mime_type'];
79
+ }
80
+ return $retVal;
81
+ }
82
+
83
+ /**
84
+ * @param $options Contains : prefixSessionKey
85
+ */
86
+ public static function createListFromModel($lstFilesUpload, $modelName, $attributeName, $options = null)
87
+ {
88
+ $arrObj = [];
89
+
90
+ foreach($lstFilesUpload as $fu)
91
+ {
92
+ if(file_exists($fu->absolutePathFile) == false) continue;
93
+
94
+ $data = file_get_contents($fu->absolutePathFile);
95
+
96
+ $fis = new self();
97
+ $fis->modelName = $modelName;
98
+ $fis->attributeName = $attributeName;
99
+ $fis->fileUploadAttributes = $fu->attributes;
100
+ $fis->data = $data;
101
+
102
+ $arrObj[$fu->file_name_original] = $fis;
103
+ }
104
+
105
+ $prefixSessionKey = ArrayHelper::getValue($options, 'prefixSessionKey', '');
106
+
107
+ // Salva in sessione
108
+ $key = $prefixSessionKey.$modelName.'.'.$attributeName;
109
+ $session = \Yii::$app->session;
110
+ $session->set($key, $arrObj);
111
+
112
+ return $arrObj;
113
+ }
114
+
115
+ public static function createListFromForm($modelName, $attributeName, $options = null)
116
+ {
117
+ $attributeNamePartTabularIndex = null;
118
+
119
+ $attributeNameParts = self::getAttributeNameParts($attributeName);
120
+ if($attributeNameParts[1]!='') $attributeNamePartTabularIndex = substr($attributeNameParts[1], 1, strlen($attributeNameParts[1])-2);
121
+ if($attributeNameParts[2]!='') $attributeNamePartName = $attributeNameParts[2];
122
+
123
+ $arrOut = [];
124
+ if(isset($_FILES[$modelName]))
125
+ {
126
+ $lstFuName = ($attributeNamePartTabularIndex == null)?$_FILES[$modelName]['name']:$_FILES[$modelName]['name'][$attributeNamePartTabularIndex];
127
+ $lstFuType = ($attributeNamePartTabularIndex == null)?$_FILES[$modelName]['type']:$_FILES[$modelName]['type'][$attributeNamePartTabularIndex];
128
+ $lstFuTmpName = ($attributeNamePartTabularIndex == null)?$_FILES[$modelName]['tmp_name']:$_FILES[$modelName]['tmp_name'][$attributeNamePartTabularIndex];
129
+ $lstFuError = ($attributeNamePartTabularIndex == null)?$_FILES[$modelName]['error']:$_FILES[$modelName]['error'][$attributeNamePartTabularIndex];
130
+ $lstFuSize = ($attributeNamePartTabularIndex == null)?$_FILES[$modelName]['size']:$_FILES[$modelName]['size'][$attributeNamePartTabularIndex];
131
+
132
+ for($k=0;$k<count($lstFuTmpName);$k++)
133
+ {
134
+ foreach($lstFuTmpName as $key=>$temp)
135
+ {
136
+ if(is_array($temp) == false) continue;
137
+
138
+ if($key != $attributeNamePartName) continue;
139
+
140
+ for($j=0;$j<count($lstFuTmpName[$key]);$j++)
141
+ {
142
+ $fuName = $lstFuName[$key][$j];
143
+ $fuType = $lstFuType[$key][$j];
144
+ $fuError = $lstFuError[$key][$j];
145
+ $fuTmpName = $lstFuTmpName[$key][$j];
146
+ $fuSize = $lstFuSize[$key][$j];
147
+ if(($fuError == 0)&&($fuSize>0)&&file_exists($fuTmpName))
148
+ {
149
+ $formInputInfo = [ 'name' => $fuName, 'type' => $fuType, 'error' => $fuError, 'tmpName' => $fuTmpName, 'size' => $fuSize ];
150
+
151
+ $fuData = file_get_contents($fuTmpName);
152
+ $fileInSession = self::create($modelName, $attributeName, $formInputInfo, null, $fuData, $options);
153
+
154
+ $arrOut[] = $fileInSession;
155
+ }
156
+ }
157
+ }
158
+ }
159
+ }
160
+
161
+ return $arrOut;
162
+ }
163
+
164
+ public static function initFromModelOrCreateFromForm($modelOrModelName, $attributeName, $lstModelFiles, $options = null)
165
+ {
166
+ $modelName = null;
167
+ if(is_string($modelOrModelName))
168
+ {
169
+ $modelName = $modelOrModelName;
170
+ }
171
+ else if(is_object($modelOrModelName))
172
+ {
173
+ $modelName = (new \ReflectionClass($modelOrModelName))->getShortName();
174
+
175
+ $prefixSessionKeyAttribute = ArrayHelper::getValue($options, 'prefixSessionKeyAttribute');
176
+ if($prefixSessionKeyAttribute!=null)
177
+ {
178
+ if (property_exists($modelOrModelName,$prefixSessionKeyAttribute)) {
179
+
180
+ $indexFormModel = ArrayHelper::getValue($options, 'indexFormModel');
181
+
182
+ if($indexFormModel !== null)
183
+ {
184
+ $options['prefixSessionKey'] = ArrayHelper::getValue($_REQUEST, [ $modelName, $indexFormModel, $prefixSessionKeyAttribute ], Yii::$app->getSecurity()->generateRandomString());
185
+ }
186
+ else
187
+ {
188
+ $options['prefixSessionKey'] = ArrayHelper::getValue($_REQUEST, [ $modelName, $prefixSessionKeyAttribute ], Yii::$app->getSecurity()->generateRandomString());
189
+ }
190
+
191
+ $modelOrModelName->$prefixSessionKeyAttribute = $options['prefixSessionKey'];
192
+ }
193
+ }
194
+ }
195
+
196
+ $arrFilesInSessionPerAttributeName = FileInSession::createListFromForm($modelName, $attributeName, $options);
197
+
198
+ if((count($arrFilesInSessionPerAttributeName) == 0)&&(isset($_POST[$modelName]) == false))
199
+ {
200
+ // Inizializza i files
201
+ FileInSession::createListFromModel($lstModelFiles, $modelName, $attributeName, $options);
202
+ }
203
+ }
204
+
205
+ public static function create($modelName, $attributeName, $formInputInfo, $fileUploadAttributes, $data, $options = null)
206
+ {
207
+ $obj = new self();
208
+ $obj->modelName = $modelName;
209
+ $obj->attributeName = $attributeName;
210
+ $obj->formInputInfo = $formInputInfo;
211
+ $obj->fileUploadAttributes = $fileUploadAttributes;
212
+ $obj->data = $data;
213
+
214
+ $filename = $formInputInfo['name'];
215
+
216
+ $prefixSessionKey = ArrayHelper::getValue($options, 'prefixSessionKey', '');
217
+
218
+ // Salva in sessione
219
+ $key = $prefixSessionKey.$modelName.'.'.$attributeName;
220
+ $session = \Yii::$app->session;
221
+ $arrObj = [];
222
+ if($session->has($key)) $arrObj = $session->get($key);
223
+ $arrObj[$filename] = $obj;
224
+ $session->set($key, $arrObj);
225
+
226
+ return $obj;
227
+ }
228
+
229
+ public static function listItems($modelName, $attributeName, $options = null)
230
+ {
231
+ $prefixSessionKey = ArrayHelper::getValue($options, 'prefixSessionKey', '');
232
+
233
+ // Recupera dalla sessione
234
+ $key = $prefixSessionKey.$modelName.'.'.$attributeName;
235
+ $session = \Yii::$app->session;
236
+ $arrObj = [];
237
+ if($session->has($key)) $arrObj = $session->get($key);
238
+ return $arrObj;
239
+ }
240
+
241
+ public static function getItem($modelName, $attributeName, $filename, $options = null)
242
+ {
243
+ $prefixSessionKey = ArrayHelper::getValue($options, 'prefixSessionKey', '');
244
+
245
+ // Recupera dalla sessione
246
+ $key = $prefixSessionKey.$modelName.'.'.$attributeName;
247
+ $session = \Yii::$app->session;
248
+ $arrObj = [];
249
+ if($session->has($key)) $arrObj = $session->get($key);
250
+
251
+ $obj = (isset($arrObj[$filename]))?$arrObj[$filename]:null;
252
+
253
+ return $obj;
254
+ }
255
+
256
+ public static function deleteListItems($modelName, $attributeName, $options = null)
257
+ {
258
+ $prefixSessionKey = ArrayHelper::getValue($options, 'prefixSessionKey', '');
259
+
260
+ $key = $prefixSessionKey.$modelName.'.'.$attributeName;
261
+ $session = \Yii::$app->session;
262
+ $session->remove($key);
263
+ }
264
+
265
+ public static function deleteItem($modelName, $attributeName, $filename, $options = null)
266
+ {
267
+ $prefixSessionKey = ArrayHelper::getValue($options, 'prefixSessionKey', '');
268
+
269
+ $key = $prefixSessionKey.$modelName.'.'.$attributeName;
270
+ $session = \Yii::$app->session;
271
+ $arrObj = [];
272
+ if($session->has($key)) $arrObj = $session->get($key);
273
+
274
+ $obj = (isset($arrObj[$filename]))?$arrObj[$filename]:null;
275
+
276
+ if($obj!=null)
277
+ {
278
+ unset($arrObj[$filename]);
279
+ $session->set($key, $arrObj);
280
+ }
281
+
282
+ return $obj;
283
+ }
284
+
285
+ }
286
+
287
+ ?>
@@ -0,0 +1,300 @@
1
+ <?php
2
+
3
+ namespace sfmobile\ext\fileUploader\models;
4
+
5
+ use Yii;
6
+ use yii\helpers\ArrayHelper;
7
+
8
+ /**
9
+ * This is the model class for table "tbl_file_upload".
10
+ *
11
+ * @property integer $id
12
+ * @property integer $user_id
13
+ * @property string $section
14
+ * @property string $category
15
+ * @property integer $refer_id
16
+ * @property string $file_name
17
+ * @property string $file_name_original
18
+ * @property string $description
19
+ * @property string $mime_type
20
+ * @property integer $file_size
21
+ * @property string $approved
22
+ * @property string $relative_path
23
+ * @property string $refer_table
24
+ * @property string $create_time
25
+ * @version 1.0.5.1
26
+ */
27
+ class FileUpload extends \yii\db\ActiveRecord
28
+ {
29
+ public function afterDelete()
30
+ {
31
+ parent::afterDelete();
32
+
33
+ // Cancella tutti i files relativi a quel filename (le varie versioni a risoluzioni diverse)
34
+ $path_parts = pathinfo($this->absolutePathFile);
35
+ $ppDirname = $path_parts['dirname'];
36
+ $ppFilename =$path_parts['filename'];
37
+ if(file_exists($ppDirname))
38
+ {
39
+ $arrFiles =scandir($ppDirname);
40
+ foreach($arrFiles as $f)
41
+ {
42
+ $pf = $ppDirname.'/'.$f;
43
+ if(is_file($pf))
44
+ {
45
+ if(strpos($f, $ppFilename) === 0)
46
+ {
47
+ @unlink($pf);
48
+ }
49
+ }
50
+ }
51
+ }
52
+ }
53
+
54
+ /**
55
+ **************************************
56
+ * Sync data with and from database
57
+ **************************************
58
+ */
59
+ public static function syncDatabaseFromListFilesSession($lstFilesInSession, $section, $category, $userId, $referOptions, $options = null)
60
+ {
61
+ $arrOut = [];
62
+
63
+ $conditions = array_merge(['section' => $section, 'category' => $category], $referOptions);
64
+
65
+ $lstFilesUpload = self::find()->where($conditions)->all();
66
+
67
+ foreach($lstFilesInSession as $fis)
68
+ {
69
+ $fu = new self();
70
+ $fu->section = $section;
71
+ $fu->category = $category;
72
+ $fu->user_id = $userId;
73
+ $fu->file_name = sha1(basename($fis->fileName)).'.'.strtolower(pathinfo( $fis->fileName, PATHINFO_EXTENSION));
74
+ $fu->file_name_original = $fis->fileName;
75
+ $fu->mime_type = $fis->fileMimeType;
76
+ $fu->file_size = $fis->fileSize;
77
+ $fu->refer_table = $section;
78
+ $fu->approved = 'yes';
79
+ $fu->create_time = date('Y-m-d H:i:s');
80
+
81
+ // Fill refer_id and other refers
82
+ foreach($referOptions as $rk=>$rv)
83
+ {
84
+ $fu->setAttribute($rk, $rv);
85
+ }
86
+
87
+ $fu->relative_path = $fu->relativePathFromDbRecord();
88
+
89
+ // Controlla se il file già esiste
90
+ $keyTrovatoTestFU = -1;
91
+ $arrKeysFilesUpload = array_keys($lstFilesUpload);
92
+ for($k=0;$k<count($lstFilesUpload);$k++)
93
+ {
94
+ $tempKey = $arrKeysFilesUpload[$k];
95
+ $testFU = $lstFilesUpload[ $tempKey ];
96
+ if(($testFU->file_name_original == $fu->file_name_original)&&($testFU->file_size == $fu->file_size)) $keyTrovatoTestFU = $tempKey;
97
+ }
98
+
99
+ // Il file esiste già
100
+ if($keyTrovatoTestFU!=-1)
101
+ {
102
+ $arrOut[] = $testFU;
103
+ unset($lstFilesUpload[$keyTrovatoTestFU]);
104
+ }
105
+ else {
106
+
107
+ $retSave = $fu->save();
108
+
109
+ if($retSave)
110
+ {
111
+ $fuPathFile = $fu->absolutePathFile;
112
+
113
+ $basepath = dirname($fuPathFile);
114
+ if(file_exists($basepath) == false) mkdir($basepath, 0777, true);
115
+
116
+ file_put_contents($fuPathFile, $fis->data);
117
+
118
+ $arrOut[] = $fu;
119
+ }
120
+ }
121
+
122
+ }
123
+
124
+ // Elimina gli ultimi file rimasti precedentemente
125
+ foreach($lstFilesUpload as $fu)
126
+ {
127
+ $fu->delete();
128
+ }
129
+
130
+ return $arrOut;
131
+ }
132
+
133
+ /**
134
+ * Sync files from session and remove them from session at the end
135
+ * @return FileUpload[] saved uploaded files
136
+ * @since 1.0.5.1
137
+ */
138
+ public static function syncFilesFromSessiondAndRemoveFromSession($modelOrModelName, $attributeName, $section, $category, $userId, $referOptions, $options = null)
139
+ {
140
+ $modelName = null;
141
+ if(is_string($modelOrModelName))
142
+ {
143
+ $modelName = $modelOrModelName;
144
+ }
145
+ else if(is_object($modelOrModelName))
146
+ {
147
+ $modelName = (new \ReflectionClass($modelOrModelName))->getShortName();
148
+
149
+ $prefixSessionKeyAttribute = ArrayHelper::getValue($options, 'prefixSessionKeyAttribute');
150
+ if($prefixSessionKeyAttribute!=null)
151
+ {
152
+ if (property_exists($modelOrModelName,$prefixSessionKeyAttribute)) {
153
+
154
+ $indexFormModel = ArrayHelper::getValue($options, 'indexFormModel');
155
+
156
+ if($indexFormModel !== null)
157
+ {
158
+ $options['prefixSessionKey'] = ArrayHelper::getValue($_REQUEST, [ $modelName, $indexFormModel, $prefixSessionKeyAttribute ], Yii::$app->getSecurity()->generateRandomString());
159
+ }
160
+ else
161
+ {
162
+ $options['prefixSessionKey'] = ArrayHelper::getValue($_REQUEST, [ $modelName, $prefixSessionKeyAttribute ], Yii::$app->getSecurity()->generateRandomString());
163
+ }
164
+
165
+ $modelOrModelName->$prefixSessionKeyAttribute = $options['prefixSessionKey'];
166
+ }
167
+ }
168
+ }
169
+
170
+ $lstFileInSession = FileInSession::listItems($modelName, $attributeName, $options);
171
+ $arrSyncedFiles = self::syncDatabaseFromListFilesSession($lstFileInSession, $section, $category, $userId, $referOptions, $options);
172
+ FileInSession::deleteListItems($modelName, $attributeName, $options);
173
+
174
+ return $arrSyncedFiles;
175
+ }
176
+
177
+ /**
178
+ **************************************
179
+ * Path and Url
180
+ **************************************
181
+ */
182
+ public function relativePathFromDbRecord()
183
+ {
184
+ //if(($fu->section == 'sec')&&($fu->category == 'cat')) $rel = self::relativePath_recordDb($fu);
185
+
186
+ $rel = sprintf('/%s/%s/%d/%s', $this->section, $this->category, $this->refer_id, $this->file_name);
187
+
188
+ return $rel;
189
+ }
190
+
191
+ public function getRelativePathFile()
192
+ {
193
+ return $this->relativePathFromDbRecord();
194
+ }
195
+
196
+ public function getAbsolutePathFile()
197
+ {
198
+ $out = null;
199
+ $rel = $this->relativePathFile;
200
+
201
+ if($rel != null)
202
+ {
203
+ $basePath = \sfmobile\ext\fileUploader\Module::getInstance()->fileUploadBasePath;
204
+ $out = $basePath.$rel;
205
+ }
206
+ return $out;
207
+ }
208
+
209
+ /**
210
+ * Return full file url, absolute or relative, based on isRequiredAbsolute parameter
211
+ * @param $isAbsoluteUrl boolean Specify if it needed baseUrl
212
+ */
213
+ public function getUrlFile($options=null, $isAbsoluteUrl=false)
214
+ {
215
+ $out = null;
216
+ $rel = $this->relativePathFromDbRecord();
217
+
218
+ if($rel != null)
219
+ {
220
+ $baseUrl = \sfmobile\ext\fileUploader\Module::getInstance()->fileUploadBaseUrl;
221
+ $out = $baseUrl.$rel;
222
+
223
+ // If it is requested an absolute url, it checks that fileUploadbaseUrl is already in absolute form.
224
+ // If it is already absolute, it does nothing, otherwise apply baseUrl.
225
+ if($isAbsoluteUrl)
226
+ {
227
+ if(\sfmobile\ext\fileUploader\Module::getInstance()->isFileUploadBaseUrlAbsolute)
228
+ {
229
+ // do nothing because fileUploadBaseUrl is already absolute
230
+ }
231
+ else
232
+ {
233
+ // it apply host base url
234
+ $out = \yii\helpers\Url::to($out, true);
235
+ }
236
+ }
237
+
238
+ }
239
+ return $out;
240
+ }
241
+
242
+
243
+
244
+ /**
245
+ * @inheritdoc
246
+ */
247
+ public static function tableName()
248
+ {
249
+ return \sfmobile\ext\fileUploader\Module::getInstance()->dbTableName;
250
+ }
251
+
252
+ /**
253
+ * @inheritdoc
254
+ */
255
+ public function rules()
256
+ {
257
+ return [
258
+ [['user_id', 'section', 'category', 'refer_id', 'file_name', 'file_name_original', 'mime_type', 'file_size', 'approved', 'relative_path', 'refer_table'], 'required'],
259
+ [['user_id', 'refer_id', 'file_size'], 'integer'],
260
+ [['approved'], 'string'],
261
+ [['create_time'], 'safe'],
262
+ [['section', 'category', 'file_name', 'file_name_original', 'refer_table'], 'string', 'max' => 150],
263
+ [['description'], 'string', 'max' => 500],
264
+ [['mime_type'], 'string', 'max' => 100],
265
+ [['relative_path'], 'string', 'max' => 1000],
266
+ ];
267
+ }
268
+
269
+ /**
270
+ * @inheritdoc
271
+ */
272
+ public function attributeLabels()
273
+ {
274
+ return [
275
+ 'id' => Yii::t('app', 'ID'),
276
+ 'user_id' => Yii::t('app', 'User ID'),
277
+ 'section' => Yii::t('app', 'Section'),
278
+ 'category' => Yii::t('app', 'Category'),
279
+ 'refer_id' => Yii::t('app', 'Refer ID'),
280
+ 'file_name' => Yii::t('app', 'File Name'),
281
+ 'file_name_original' => Yii::t('app', 'File Name Original'),
282
+ 'description' => Yii::t('app', 'Description'),
283
+ 'mime_type' => Yii::t('app', 'Mime Type'),
284
+ 'file_size' => Yii::t('app', 'File Size'),
285
+ 'approved' => Yii::t('app', 'Approved'),
286
+ 'relative_path' => Yii::t('app', 'Relative Path'),
287
+ 'refer_table' => Yii::t('app', 'Refer Table'),
288
+ 'create_time' => Yii::t('app', 'Create Time'),
289
+ ];
290
+ }
291
+
292
+ /**
293
+ * @inheritdoc
294
+ * @return \backend\modules\yii2_file_uploader\models\query\FileUploadQuery the active query used by this AR class.
295
+ */
296
+ public static function find()
297
+ {
298
+ return new \sfmobile\ext\fileUploader\models\query\FileUploadQuery(get_called_class());
299
+ }
300
+ }
@@ -0,0 +1,33 @@
1
+ <?php
2
+
3
+ namespace sfmobile\ext\fileUploader\models\query;
4
+
5
+ /**
6
+ * This is the ActiveQuery class for FileUpload class.
7
+ *
8
+ */
9
+ class FileUploadQuery extends \yii\db\ActiveQuery
10
+ {
11
+ /*public function active()
12
+ {
13
+ return $this->andWhere('[[status]]=1');
14
+ }*/
15
+
16
+ /**
17
+ * @inheritdoc
18
+ * @return \backend\modules\yii2_file_uploader\models\FileUpload[]|array
19
+ */
20
+ public function all($db = null)
21
+ {
22
+ return parent::all($db);
23
+ }
24
+
25
+ /**
26
+ * @inheritdoc
27
+ * @return \backend\modules\yii2_file_uploader\models\FileUpload|array|null
28
+ */
29
+ public function one($db = null)
30
+ {
31
+ return parent::one($db);
32
+ }
33
+ }
package/package.json ADDED
@@ -0,0 +1,19 @@
1
+ {
2
+ "name": "yii2-file-uploader",
3
+ "version": "1.5.4",
4
+ "description": "Go to https://github.com/FabrizioCaldarelli/yii2-file-upload",
5
+ "main": "index.js",
6
+ "scripts": {
7
+ "test": "echo \"Error: no test specified\" && exit 1"
8
+ },
9
+ "repository": {
10
+ "type": "git",
11
+ "url": "git+https://github.com/fcaldarelli/yii2-file-uploader.git"
12
+ },
13
+ "author": "Fabrizio Caldarelli",
14
+ "license": "ISC",
15
+ "bugs": {
16
+ "url": "https://github.com/fcaldarelli/yii2-file-uploader/issues"
17
+ },
18
+ "homepage": "https://github.com/fcaldarelli/yii2-file-uploader#readme"
19
+ }