forked from pgyf/yii2-upload-behavior
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathUploadBehavior.php
725 lines (682 loc) · 23.3 KB
/
UploadBehavior.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
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
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
<?php
namespace haohetao\file;
use Closure;
use Yii;
use yii\base\ErrorException;
use yii\base\InvalidConfigException;
use yii\base\InvalidArgumentException;
use yii\db\BaseActiveRecord;
use yii\helpers\ArrayHelper;
use yii\helpers\FileHelper;
/**
* UploadBehavior automatically uploads file and fills the specified attribute
* with a value of the name of the uploaded file.
*
* To use UploadBehavior, insert the following code to your ActiveRecord class:
*
* ```php
* use liyunfang\file\UploadBehavior;
*
* function behaviors()
* {
* return [
* [
* 'class' => UploadBehavior::class,
* 'attributes' => [
* [
* 'attribute' => 'file1',
* 'path' => '@webroot/upload/file/file1/{id}',
* 'url' => '@web/upload/file/file1/{id}',
* //'scenarios' => ['insert', 'update'],
* //'multiple' => true,
* //'multipleSeparator' => '|',
* //'nullValue' => '',
* //'instanceByName' => false;
* //'generateNewName' => true,
* //'unlinkOnSave' => true,
* //'deleteTempFile' => true,
* ]
* [
* ...
* ]
* ]
* 'scenarios' => ['insert', 'update'],
* //'multipleSeparator' => '|',
* //'nullValue' => '',
* //'instanceByName' => false;
* //'generateNewName' => true,
* //'unlinkOnSave' => true,
* //'deleteTempFile' => true,
* ],
* ];
* }
* ```
*
* @author liyunfang <[email protected]>
*/
class UploadBehavior extends \yii\base\Behavior
{
/**
* @event Event an event that is triggered after a file is uploaded.
*/
const EVENT_AFTER_UPLOAD = 'afterUpload';
/**
* @var string the attribute which holds the attachment.
*/
public $attributes;
/**
* @var array the scenarios in which the behavior will be triggered
* Scenarios configuration for each attribute
*/
public $scenarios = [];
/**
* @var bool Getting file instance by name
*/
public $instanceByName = false;
/**
* @var string 当设置$instanceByName时使用的InputName,null时自动生成
*/
public $instanceInputName = null;
/**
* @var boolean|callable generate a new unique name for the file
* set true or anonymous function takes the old filename and returns a new name.
* @see self::generateFileName()
*/
public $generateNewName = true;
/**
* @var boolean If `true` current attribute file will be deleted
*/
public $unlinkOnSave = true;
/**
* @var boolean If `true` current attribute file will be deleted after model deletion.
*/
public $unlinkOnDelete = true;
/**
* @var boolean $deleteTempFile whether to delete the temporary file after saving.
*/
public $deleteTempFile = true;
/**
* multiple File name separator
*/
public $multipleSeparator = '|';
/**
* When the value of null
*/
public $nullValue = '';
/**
* @var UploadedFile the uploaded file instance.
*/
protected $files;
/**
* Delete fileName
*/
protected $deleteFileName = [];
/**
* @inheritdoc
*/
public function init()
{
parent::init();
if ($this->attributes === null) {
throw new InvalidConfigException('The "attribute" property must be set.');
}
if (!is_array($this->attributes)) {
throw new InvalidConfigException('"attribute" expects the array');
}
$this->configInit();
}
/**
* Initialization configuration
* @throws InvalidConfigException
*/
private function configInit()
{
$attributes = [];
foreach ($this->attributes as $k => $v) {
$path = ArrayHelper::getValue($v, 'path');
if ($path === null) {
throw new InvalidConfigException('The "path" property must be set.');
}
$url = ArrayHelper::getValue($v, 'url');
if ($url === null) {
throw new InvalidConfigException('The "url" property must be set.');
}
$attribute = ArrayHelper::remove($v, 'attribute');
if ($attribute) {
$attributes[$attribute] = $v;
} else {
throw new InvalidConfigException('Array must contain the key : attribute .');
}
}
$this->attributes = $attributes;
}
/**
* @inheritdoc
*/
public function events()
{
return [
BaseActiveRecord::EVENT_BEFORE_VALIDATE => 'beforeValidate',
BaseActiveRecord::EVENT_BEFORE_INSERT => 'beforeSave',
BaseActiveRecord::EVENT_BEFORE_UPDATE => 'beforeSave',
BaseActiveRecord::EVENT_AFTER_INSERT => 'afterSave',
BaseActiveRecord::EVENT_AFTER_UPDATE => 'afterSave',
BaseActiveRecord::EVENT_AFTER_DELETE => 'afterDelete',
];
}
/**
* Gets the attribute configuration, does not exist then gets the global configuration
* @param string $attribute
* @param string $key
* @return mixed
*/
protected function getAttributeConfig($attribute, $key)
{
if (is_array($attribute)) {
$attributeConfig = $attribute;
} else {
if (isset($this->attributes[$attribute])) {
$attributeConfig = $this->attributes[$attribute];
} else {
throw new ErrorException("属性 $attribute 的配置不存在或指定了错误的属性名");
}
}
if ($key) {
if (isset($attributeConfig[$key])) {
return $attributeConfig[$key];
} else {
if (property_exists(static::class, $key)) {
return $this->$key;
}
}
}
return null;
}
/**
* Whether there has current scenario
* @param string $attribute
* @return boolean
*/
protected function hasScenario($attribute)
{
if (is_array($attribute)) {
$attributeConfig = $attribute;
} else {
$attributeConfig = $this->attributes[$attribute];
}
$model = $this->owner;
$scenario = $this->getAttributeConfig($attributeConfig, 'scenarios');
if (in_array($model->scenario, $scenario)) {
return true;
}
return false;
}
/**
* Returns attribute value
* @param string $attribute
* @param boolean $old
* @return string
*/
protected function getAttributeValue($attribute, $old = false)
{
/** @var BaseActiveRecord $model */
$model = $this->owner;
return ($old === true) ? $model->getOldAttribute($attribute) : $model->$attribute;
}
/**
* This method is invoked before validation starts.
*/
public function beforeValidate()
{
/** @var BaseActiveRecord $model */
$model = $this->owner;
foreach ($this->attributes as $attribute => $attributeConfig) {
if ($this->hasScenario($attributeConfig)) {
$file = $this->getAttributeValue($attribute);
if (!$this->validateFile($file)) {
$file = $this->getUploadInstance($attribute);
}
if (!isset($this->files[$attribute]) && $this->validateFile($file)) {
$model->$attribute = $file;
$this->files[$attribute] = $file;
} else {
if ($model->$attribute == null) {
$nullValue = $this->getAttributeConfig($attribute, 'nullValue');
$model->$attribute = $nullValue;
}
}
}
}
}
/**
* This method is called at the beginning of inserting or updating a record.
*/
public function beforeSave()
{
/** @var BaseActiveRecord $model */
$model = $this->owner;
foreach ($this->attributes as $attribute => $attributeConfig) {
if ($this->hasScenario($attributeConfig)) {
if (isset($this->files[$attribute]) && $this->validateFile($this->files[$attribute])) {
if (!$model->getIsNewRecord() && $model->isAttributeChanged($attribute)) {
if ($this->getAttributeConfig($attributeConfig, 'unlinkOnSave') === true) {
$this->deleteFileName[$attribute] = $this->resolveFileName($attribute, true);
}
}
} else {
// Protect attribute
$model->$attribute = $model->getOldAttribute($attribute);
}
} else {
if (!$model->getIsNewRecord() && $model->isAttributeChanged($attribute)) {
if ($this->getAttributeConfig($attributeConfig, 'unlinkOnSave')) {
$this->deleteFileName[$attribute] = $this->resolveFileName($attribute, true);
}
}
}
}
$this->fileSave();
}
/**
* This method is called at the end of inserting or updating a record.
* @throws \yii\base\InvalidArgumentException
*/
public function afterSave()
{
$this->unlinkOnSave();
}
/**
* Save file
* @throws InvalidArgumentException
*/
public function fileSave()
{
if ($this->files) {
$model = $this->owner;
foreach ($this->files as $attribute => $file) {
if ($this->hasScenario($attribute) && $model->isAttributeChanged($attribute) && $this->validateFile($file)) {
$basePath = $this->getUploaddirectory($attribute);
if (is_string($basePath) && FileHelper::createDirectory($basePath)) {
$this->save($attribute, $file, $basePath);
$this->afterUpload();
} else {
throw new InvalidArgumentException("Directory specified in 'path' attribute doesn't exist or cannot be created.");
}
}
}
}
}
/**
* After delete file
* @param string $attribute
* @param string $singleFileName
*/
public function afterUnlink($attribute, $singleFileName)
{
}
/**
* Delete file
*/
public function unlinkOnSave()
{
if ($this->deleteFileName) {
foreach ($this->deleteFileName as $attribute => $fileName) {
if ($fileName) {
$fileNames = [];
if (is_array($fileName)) {
$fileNames = $fileName;
} else {
$fileNames[] = $fileName;
}
$basePath = $this->getUploaddirectory($attribute);
foreach ($fileNames as $fn) {
$path = $basePath . '/' . $fn;
if (is_file($path)) {
@unlink($path);
}
$this->afterUnlink($attribute, $fn);
}
}
}
}
}
/**
* This method is invoked before deleting a record.
*/
public function afterDelete()
{
foreach ($this->attributes as $attribute => $attributeConfig) {
$unlinkOnDelete = $this->getAttributeConfig($attributeConfig, 'unlinkOnDelete');
if ($unlinkOnDelete) {
$this->delete($attribute);
}
}
}
/**
* Returns file path for the attribute.
* @param string $attribute
* @param boolean $old
* @return string|array|null the file path.
*/
public function getUploadPath($attribute, $old = false)
{
$fileName = $this->resolveFileName($attribute, $old);
if (!$fileName) {
return $fileName;
}
$basePath = $this->getUploaddirectory($attribute);
if (is_array($fileName)) {
foreach ($fileName as $k => $fn) {
$fileName[$k] = $basePath . '/' . $fn;
}
return $fileName ? $fileName : null;;
}
return $fileName ? $basePath . '/' . $fileName : "";
}
/**
* Returns file url for the attribute.
* @param string $attribute
* @return string|array|null the file url.
*/
public function getUploadUrl($attribute)
{
$fileName = $this->resolveFileName($attribute, true);
if (!$fileName) {
return $fileName;
}
$multiple = $this->getAttributeConfig($attribute, 'multiple');
$url = $this->getAttributeConfig($attribute, 'url');
$url = Yii::getAlias($this->resolvePath($url));
if (is_array($fileName)) {
foreach ($fileName as $k => $fn) {
if ($fn) {
$fileName[$k] = $url . '/' . $fn;
}
}
return $fileName ? $fileName : null;
}
if ($fileName) {
$fileName = $url . '/' . $fileName;
if ($multiple) {
return [$fileName];
} else {
return $fileName;
}
}
return null;
}
/**
* Replaces all placeholders in path variable with corresponding values.
*/
protected function resolvePath($path)
{
/** @var BaseActiveRecord $model */
$model = $this->owner;
return preg_replace_callback('/{([^}]+)}/', function ($matches) use ($model) {
$name = $matches[1];
$attribute = ArrayHelper::getValue($model, $name);
if (is_string($attribute) || is_numeric($attribute)) {
return $attribute;
} else {
return $matches[0];
}
}, $path);
}
/**
* Saves the uploaded file.
* @param UploadedFile $file the uploaded file instance
* @param string $path the file path used to save the uploaded file
* @return boolean true whether the file is saved successfully
*/
protected function save($attribute, $file, $path)
{
$model = $this->owner;
$model->$attribute = '';
try {
$deleteTempFile = $this->getAttributeConfig($attribute, 'deleteTempFile');
$multipleSeparator = $this->getAttributeConfig($attribute, 'multipleSeparator');
if (is_array($file)) {
foreach ($file as $f) {
$fileName = $this->getFileName($attribute, $f);
if (!$f->saveAs($path . '/' . $fileName, $deleteTempFile)) {
throw new ErrorException('save file failed:' . $fileName);
}
$model->$attribute .= $fileName . $multipleSeparator;
}
$model->$attribute = trim($model->$attribute, $multipleSeparator);
} else {
$fileName = $this->getFileName($attribute, $file);
if (!$file->saveAs($path . '/' . $fileName, $deleteTempFile)) {
throw new ErrorException('save file failed:' . $fileName);
}
$model->$attribute = $fileName;
}
} catch (\Exception $exc) {
throw $exc;//new \Exception('File save exception');
}
return true;
}
/**
* Deletes old file.
* @param string $attribute
* @param boolean $old
*/
protected function delete($attribute, $old = false)
{
$fileName = $this->resolveFileName($attribute, $old);
if ($fileName) {
$fileNames = [];
if (is_array($fileName)) {
$fileNames = $fileName;
} else {
$fileNames[] = $fileName;
}
$basePath = $this->getUploaddirectory($attribute);
foreach ($fileNames as $fn) {
$filePath = $basePath . '/' . $fn;
if (is_file($filePath)) {
@unlink($filePath);
$this->afterUnlink($attribute, $fn);
}
}
}
}
/**
* Get the UploadedFile
* @param string $attribute
* @return UploadedFile|array
*/
protected function getUploadInstance($attribute)
{
$model = $this->owner;
$multiple = $this->getAttributeConfig($attribute, 'multiple');
$instanceByName = $this->getAttributeConfig($attribute, 'instanceByName');
$instanceInputName = $this->getAttributeConfig($attribute, 'instanceInputName');
if ($multiple) {
if (UploadBehavior::isBase64()) {
$file = UploadedFile::getInstancesByBase64($model, $attribute);
} else {
if ($instanceByName) {
$file = UploadedFile::getInstancesByInputName($model, $attribute, $instanceInputName);
} else {
$file = UploadedFile::getInstances($model, $attribute);
}
}
} else {
if (UploadBehavior::isBase64()) {
$file = UploadedFile::getInstanceByBase64($model, $attribute);
} else {
if ($instanceByName) {
$file = UploadedFile::getInstanceByInputName($model, $attribute, $instanceInputName);
} else {
$file = UploadedFile::getInstance($model, $attribute);
}
}
}
$files = null;
if (isset($file) && is_object($file)) {
$files = [$file];
} else if (isset($file) && is_array($file)) {
$files = $file;
}
if (isset($files) && is_array($files)) {
foreach ($files as $one) {
if ($one && $one->hasError) {
switch ($one->error) {
case UPLOAD_ERR_INI_SIZE:
$message = "The uploaded file exceeds the upload_max_filesize directive in php.ini";
break;
case UPLOAD_ERR_FORM_SIZE:
$message = "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form";
break;
case UPLOAD_ERR_PARTIAL:
$message = "The uploaded file was only partially uploaded";
break;
case UPLOAD_ERR_NO_FILE:
$message = "No file was uploaded";
break;
case UPLOAD_ERR_NO_TMP_DIR:
$message = "Missing a temporary folder";
break;
case UPLOAD_ERR_CANT_WRITE:
$message = "Failed to write file to disk";
break;
case UPLOAD_ERR_EXTENSION:
$message = "File upload stopped by extension";
break;
default:
$message = "Unknown upload error";
break;
}
throw new ErrorException($message);
}
}
}
return $file;
}
/**
* Verification file
* @param UploadedFile|array $file
* @return boolean
*/
protected function validateFile($file)
{
$files = [];
if (is_array($file)) {
$files = $file;
} else {
$files[] = $file;
}
if (!$files) {
return false;
}
foreach ($files as $f) {
if (!($f instanceof UploadedFile)) {
return false;
}
}
return true;
}
/**
* Get upload directory
* @return string
*/
protected function getUploaddirectory($attribute)
{
$path = $this->getAttributeConfig($attribute, 'path');
$path = $this->resolvePath($path);
return Yii::getAlias($path);
}
/**
* resolve file name
* @param string $attribute
* @param boolean $old
* @return string|array
*/
protected function resolveFileName($attribute, $old = false)
{
$multiple = $this->getAttributeConfig($attribute, 'multiple');
$multipleSeparator = $this->getAttributeConfig($attribute, 'multipleSeparator');
$fileName = $this->getAttributeValue($attribute, $old);
$fileName = trim($fileName, $multipleSeparator);
if ($fileName) {
if ($multiple) {
if (false !== strpos($fileName, $multipleSeparator)) {
return explode($multipleSeparator, $fileName);
} else {
return [$fileName];
}
} else {
return $fileName;
}
}
return null;
}
/**
* @param UploadedFile $file
* @return string
*/
protected function getFileName($attribute, $file)
{
$generateNewName = $this->getAttributeConfig($attribute, 'generateNewName');
if ($generateNewName) {
return $generateNewName instanceof Closure || is_array($generateNewName)
? call_user_func($generateNewName, $file)
: $this->generateFileName($file);
} else {
return $this->sanitize($file->name);
}
}
/**
* Replaces characters in strings that are illegal/unsafe for filename.
*
* #my* unsaf<e>&file:name?".png
*
* @param string $filename the source filename to be "sanitized"
* @return boolean string the sanitized filename
*/
public static function sanitize($filename)
{
return str_replace([' ', '"', '\'', '&', '/', '\\', '?', '#'], '-', $filename);
}
/**
* Generates random filename.
* @param UploadedFile $file
* @return string
*/
protected function generateFileName($file)
{
return uniqid() . '.' . $file->extension;
}
/**
* This method is invoked after uploading a file.
* The default implementation raises the [[EVENT_AFTER_UPLOAD]] event.
* You may override this method to do postprocessing after the file is uploaded.
* Make sure you call the parent implementation so that the event is raised properly.
*/
protected function afterUpload()
{
$this->owner->trigger(self::EVENT_AFTER_UPLOAD);
}
/**
* 是否base64上传
* @return bool
*/
public static function isBase64()
{
$mime = Yii::$app->request->getContentType();
if (strncasecmp($mime, 'application/json', 16) === 0) {
return true;
}
if (strncasecmp($mime, 'text/json', 9) === 0) {
return true;
}
if (strncasecmp($mime, 'application/javascript', 22) === 0) {
return true;
}
if (strncasecmp($mime, 'text/javascript', 15) === 0) {
return true;
}
return false;
}
}