-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathUploadFile.php
More file actions
530 lines (491 loc) · 15.6 KB
/
UploadFile.php
File metadata and controls
530 lines (491 loc) · 15.6 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
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
<?php
/**
* Attachment
*
* @author Ryuji AMANO <ryuji@ryus.co.jp>
* @link http://www.netcommons.org NetCommons Project
* @license http://www.netcommons.org/license.txt NetCommons License
*/
App::uses('FilesAppModel', 'Files.Model');
App::uses('Folder', 'Utility');
//app/webroot/index.phpでセットするため、不要だが、念のため入れておく。
if (!defined('UPLOADS_ROOT')) {
if (file_exists(dirname(WWW_ROOT) . DS . 'Uploads' . DS)) {
define('UPLOADS_ROOT', dirname(WWW_ROOT) . DS . 'Uploads' . DS);
} else {
define('UPLOADS_ROOT', WWW_ROOT);
}
}
/**
* Summary for File Model
*
* @SuppressWarnings(PHPMD.TooManyPublicMethods)
*/
class UploadFile extends FilesAppModel {
/**
* @var string UploadFileでアップロードする基準パス
*/
public $uploadBasePath = UPLOADS_ROOT;
/**
* アップロードファイルを登録する際、
* アップロードディレクトリのパスがWEB_ROOTパス配下になるのでUPLOADS_ROOTにchdirする必要があるため、
* 処理が終わったら元に戻すように現在のパスを保持しておく用の変数
*
* @var string UploadFileでアップロードする基準パス
*/
private $__currentDir = null;
/**
* @var int recursiveはデフォルトアソシエーションなしに
*/
public $recursive = -1;
/**
* ビヘイビア
*
* @var array
*/
public $actsAs = [
'Files.UploadFileDisableThumbnail',
'Upload.Upload' => [
'real_file_name' => array(
'thumbnailSizes' => array(
// NC2 800 , 640, 480だった
'big' => '800ml',
'medium' => '400ml',
'small' => '200ml',
'thumb' => '80x80',
),
'nameCallback' => 'nameCallback',
'fields' => [
//'dir' => 'path',
'type' => 'mimetype',
'size' => 'size'
],
'deleteFolderOnDelete' => true,
),
],
'Files.UploadFileValidate',
];
/**
* hasMany
*
* @var array
*/
public $hasMany = [
'UploadFilesContent' => array(
'className' => 'Files.UploadFilesContent',
),
];
/**
* beforeValidate
*
* @param array $options options
* @return bool
*/
public function beforeValidate($options = array()) {
// 拡張子チェック
$uploadAllowExtension = $this->getAllowExtension();
$this->validate['real_file_name']['extension'] = [
'rule' => ['isValidExtension', $uploadAllowExtension, false],
'message' => __d('files', 'It is upload disabled file format')
];
$this->validate['real_file_name']['size'] = 'validateRoomFileSizeLimit';
return parent::beforeValidate($options);
}
/**
* ビヘイビア設定
*
* @param array $options オプション
* @return void
*/
public function setOptions($options) {
$this->uploadSettings('real_file_name', $options);
}
/**
* アップロードファイルとコンテンツとの関連づけ削除
*
* @param int $contentId コンテンツID
* @param int $fileId アップロードファイルID
* @throws InternalErrorException
* @return void
*/
public function removeFile($contentId, $fileId) {
if (! $contentId || ! $fileId) {
return;
}
$UploadFilesContent = ClassRegistry::init('Files.UploadFilesContent');
$link = $UploadFilesContent->findByContentIdAndUploadFileId($contentId, $fileId);
if ($link) {
// 関連レコードみつかったら削除する
if ($UploadFilesContent->delete($link['UploadFilesContent']['id'], false) === false) {
throw new InternalErrorException('Failed UploadFile::removeFile()');
}
// ファイルIDの関連テーブルが他に見つからなかったらファイルも削除する
$count = $UploadFilesContent->find('count', ['conditions' => ['upload_file_id' => $fileId]]);
if ($count == 0) {
// 他に関連レコード無ければファイル削除
if ($this->deleteUploadFile($fileId) === false) {
throw new InternalErrorException('Failed UploadFile::removeFile()');
}
}
}
}
/**
* Delete uploadFile
*
* @param int $fileId UploadFile.id
* @return bool
*/
public function deleteUploadFile($fileId) {
// Uploadビヘイビアにpathを渡す
$uploadFile = $this->findById($fileId);
if (! $uploadFile) {
//データがない場合、既に削除済みとしてtrueを返す。
return true;
}
if (file_exists($this->getRealFilePath($uploadFile))) {
$path = $this->uploadBasePath . $uploadFile['UploadFile']['path'];
$this->uploadSettings('real_file_name', 'path', $path);
$this->uploadSettings('real_file_name', 'thumbnailPath', $path);
$result = $this->delete($fileId, false);
} else {
$this->Behaviors->disable('Upload.Upload');
$result = $this->delete($fileId, false);
$this->Behaviors->enable('Upload.Upload');
}
return $result;
}
/**
* nameCallback method
*
* @param string $field Name of field being modified
* @param string $currentName current filename
* @param array $data Array of data being manipulated in the current request
* @param array $options Array of options for the current rename
* @return string file name
*/
public function nameCallback($field, $currentName, $data, $options) {
//return Security::hash(mt_rand() . microtime(), 'md5')
return Security::hash($currentName, 'md5') . '.' . pathinfo($currentName, PATHINFO_EXTENSION);
}
/**
* beforeSave
*
* ファイルの保存先を設定
* トータルダウンロード数を設定
*
* @param array $options オプション
* @return void
*/
public function beforeSave($options = array()) {
$this->__currentDir = getcwd();
chdir($this->uploadBasePath);
// imagickクラスがなかったらサムネイル生成はGDを利用
if (class_exists('imagick') === false) {
// @codeCoverageIgnoreStart
$this->uploadSettings('real_file_name', 'thumbnailMethod', '_resizePhp');
// @codeCoverageIgnoreEnd
}
$path = $this->__makePathField();
$this->data['UploadFile']['path'] = $path;
$this->uploadSettings('real_file_name', 'path', $path);
$this->uploadSettings('real_file_name', 'thumbnailPath', $path);
// トータルダウンロード数設定
if ($this->data['UploadFile']['content_key']) {
$this->virtualFields['total'] = 'sum(download_count)';
$options = [
'fields' => ['total'],
'conditions' => [
'plugin_key' => $this->data['UploadFile']['plugin_key'],
'content_key' => $this->data['UploadFile']['content_key'],
'field_name' => $this->data['UploadFile']['field_name'],
]
];
if (Hash::get($this->data, 'UploadFile.id', false) === false) {
// 新規の時だけトータルをセット
$result = $this->find('first', $options);
$total = ($result['UploadFile']['total'] !== null) ? $result['UploadFile']['total'] : 0;
$this->data['UploadFile']['total_download_count'] = $total;
}
unset($this->virtualFields['total']);
}
return true;
}
/**
* upload_files.pathを生成する
*
* @return string
*/
private function __makePathField() {
$path = 'files' . DS . 'upload_file' . DS;
if (!empty($this->data['UploadFile']['room_id'])) {
$roomId = $this->data['UploadFile']['room_id'];
} else {
$roomId = Current::read('Room.id');
}
if ($roomId) {
$path .= 'real_file_name' . DS . $roomId . DS;
if (!empty($this->data['UploadFile']['id']) &&
!empty($this->data['UploadFile']['path']) &&
$this->data['UploadFile']['path'] !== $path) {
$path = $this->data['UploadFile']['path'];
}
} else {
$path .= $this->data['UploadFile']['field_name'] . DS;
}
return $path;
}
/**
* save()実行後に呼ばれるメソッド
*
* @param bool $created 新しいレコードが作成された場合はTrue
* @param array $options Model::save()のオプション
* @return void
* @link http://book.cakephp.org/2.0/ja/models/callback-methods.html#aftersave
* @see Model::save()
*/
public function afterSave($created, $options = array()) {
chdir($this->__currentDir);
parent::afterSave($created, $options);
}
/**
* ファイル情報取得
*
* @param string $pluginKey プラグインキー
* @param int $contentId コンテンツID
* @param string $fieldName フィールド名
* @return array|false
*/
public function getFile($pluginKey, $contentId, $fieldName) {
$options = [
'fields' => [
'UploadFilesContent.id',
'UploadFilesContent.plugin_key',
'UploadFilesContent.content_id',
'UploadFilesContent.upload_file_id',
'UploadFilesContent.content_is_active',
'UploadFilesContent.content_is_latest',
'UploadFile.id',
'UploadFile.plugin_key',
'UploadFile.content_key',
'UploadFile.field_name',
'UploadFile.original_name',
'UploadFile.path',
'UploadFile.real_file_name',
'UploadFile.extension',
'UploadFile.mimetype',
'UploadFile.size',
'UploadFile.download_count',
'UploadFile.total_download_count',
'UploadFile.room_id',
'UploadFile.block_key'
],
'conditions' => [
'UploadFilesContent.plugin_key' => $pluginKey,
'UploadFilesContent.content_id' => $contentId,
'UploadFile.field_name' => $fieldName
],
'order' => ['UploadFile.id' => 'desc']
];
$UploadFilesContent = ClassRegistry::init('Files.UploadFilesContent');
$file = $UploadFilesContent->find('first', $options);
return $file;
}
/**
* ファイル情報取得
*
* アバターなどは、UploadFilesContentを見る必要がないので、ContentKeyでファイル情報を取得できるようにする
*
* @param string $pluginKey プラグインキー
* @param string $contentKey コンテンツキー
* @param string $fieldName フィールド名
* @return array|false
*/
public function getFileByContentKey($pluginKey, $contentKey, $fieldName) {
$options = [
'fields' => [
'UploadFile.id',
'UploadFile.plugin_key',
'UploadFile.content_key',
'UploadFile.field_name',
'UploadFile.original_name',
'UploadFile.path',
'UploadFile.real_file_name',
'UploadFile.extension',
'UploadFile.mimetype',
'UploadFile.size',
'UploadFile.download_count',
'UploadFile.total_download_count',
'UploadFile.room_id',
'UploadFile.block_key'
],
'conditions' => [
'UploadFile.plugin_key' => $pluginKey,
'UploadFile.content_key' => $contentKey,
'UploadFile.field_name' => $fieldName
],
'order' => ['UploadFile.id' => 'desc']
];
$file = $this->find('first', $options);
return $file;
}
/**
* ダウンロードカウントアップ
*
* @param array $data UploadFileデータ
* @throws InternalErrorException
* @return void
*/
public function countUp($data) {
$data[$this->alias]['download_count'] = $data[$this->alias]['download_count'] + 1;
$data[$this->alias]['total_download_count'] = $data[$this->alias]['total_download_count'] + 1;
// plugin_key, content_key, field_nameが同じだったら
$this->create();
$this->begin();
$result = $this->save($data, ['callbacks' => false, 'validate' => false]);
if ($result === false) {
throw new InternalErrorException('Failed UploadFile::countUp()');
}
$this->commit();
return $result;
}
/**
* FileインスタンスのファイルをUplodFileに登録する
*
* @param File|string $file 登録するファイルのFileインスタンス OR ファイルパス
* @param string $pluginKey プラグインキー
* @param string $contentKey コンテンツキー
* @param string $fieldName フィールド名
* @param array $data データ登録時に上書きしたいデータを渡す
* @return array
* @throws InternalErrorException
*/
public function registByFile(File $file, $pluginKey, $contentKey, $fieldName, $data = array()) {
if (is_string($file)) {
$file = new File($file);
}
// データの登録
$_tmpData = $this->create();
// $dataにアサイン
$_tmpData['UploadFile']['plugin_key'] = $pluginKey;
$_tmpData['UploadFile']['content_key'] = $contentKey;
$_tmpData['UploadFile']['field_name'] = $fieldName;
$originalName = property_exists($file, 'originalName') ? $file->originalName : $file->name;
$_tmpData['UploadFile']['original_name'] = $originalName;
$_tmpData['UploadFile']['extension'] = pathinfo($file->name, PATHINFO_EXTENSION);
$_tmpData['UploadFile']['real_file_name'] = [
'name' => $file->name,
'type' => $file->mime(),
'tmp_name' => $file->path,
'error' => 0,
'size' => $file->size(),
];
$data = Hash::merge($_tmpData, $data);
$data = $this->save($data);
if ($data === false) {
throw new InternalErrorException('Failed UploadFile::registByFile()');
}
return $data;
}
/**
* 関連テーブルにコンテンツとUploadFileとの関連データを作成
*
* @param string $pluginKey プラグインキー
* @param int $contentId コンテンツID
* @param int $uploadFileId アップロードファイルID
* @throws InternalErrorException
* @return void
*/
public function makeLink($pluginKey, $contentId, $uploadFileId) {
$data = [
'content_id' => $contentId,
'upload_file_id' => $uploadFileId,
'plugin_key' => $pluginKey,
];
$UploadFilesContent = ClassRegistry::init('Files.UploadFilesContent');
$data = $UploadFilesContent->create($data);
if ($UploadFilesContent->save($data) === false) {
throw new InternalErrorException('Failed UploadFile::makeLink()');
}
}
/**
* 関連テーブルデータの削除
*
* @param string $pluginKey プラグインキー
* @param int $contentId コンテンツID
* @param string $fieldName フィールド名
* @return void
*/
public function deleteLink($pluginKey, $contentId, $fieldName = null) {
if (! $pluginKey || ! $contentId) {
return;
}
$conditions = [
'UploadFilesContent.plugin_key' => $pluginKey,
'UploadFilesContent.content_id' => $contentId,
];
if ($fieldName !== null) {
$conditions['UploadFile.field_name'] = $fieldName;
}
$result = $this->UploadFilesContent->find('all', ['conditions' => $conditions]);
foreach ($result as $link) {
$this->_deleteNoRelationUploadFile($link);
}
}
/**
* 関連テーブルデータがひとつもないUploadFileレコードを削除する
*
* @param array $link UploadFilesContent関連レコードのデータ
* @throws InternalErrorException
* @return void
*/
protected function _deleteNoRelationUploadFile($link) {
$this->UploadFilesContent->delete($link['UploadFilesContent']['id']);
// このリンク以外にリンクがなければUploadFileレコードを削除する
$conditions = [
'UploadFilesContent.upload_file_id' => $link['UploadFile']['id'],
];
$count = $this->UploadFilesContent->find('count', ['conditions' => $conditions]);
if ($count == 0) {
if ($this->deleteUploadFile($link['UploadFile']['id']) === false) {
throw new InternalErrorException('Failed UploadFile::_deleteNoRelationUploadFile');
};
}
}
/**
* 添付ファイルをDBに登録する
*
* @param string $pluginKey 登録するプラグイン名
* @param string $contentKey コンテンツキー
* @param int $contentId コンテンツID
* @param string $fieldName フィールド名
* @param File $file 登録するファイルのFileインスタンス
*
* @return void
*/
public function attach($pluginKey, $contentKey, $contentId, $fieldName, $file) {
// UploadFileへ登録
$uploadFile = $this->registByFile(
$file,
$pluginKey,
$contentKey,
$fieldName
);
// 以前の添付ファイルとの関連を切る。
$this->deleteLink($pluginKey, $contentId, $fieldName);
// 関連テーブル登録
$this->makeLink($pluginKey, $contentId, $uploadFile['UploadFile']['id']);
}
/**
* UploadFileに登録済みの実ファイルのパスを返す
*
* @param array $uploadFileData UploadFile
* @return string 実ファイルパス
*/
public function getRealFilePath($uploadFileData) {
$filePath = $this->uploadBasePath .
$uploadFileData['UploadFile']['path'] .
$uploadFileData['UploadFile']['id'] .
DS . $uploadFileData['UploadFile']['real_file_name'];
return $filePath;
}
}