-
Notifications
You must be signed in to change notification settings - Fork 93
Expand file tree
/
Copy pathDocumentController.php
More file actions
365 lines (306 loc) · 11.3 KB
/
DocumentController.php
File metadata and controls
365 lines (306 loc) · 11.3 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
<?php
namespace App\Http\Controllers;
// Models
use App\Models\Control;
use App\Models\Document;
// Framework
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
class DocumentController extends Controller
{
public function getTemplate(Request $request)
{
// Get document teample id
$id = (int) $request->get('id');
if ($id === 1) {
// return default model
return response()->download(storage_path('app/models/control_'. Auth::user()->language .'.docx'));
}
if ($id === 2) {
// check exists new model
if (file_exists(storage_path('app/models/control_.docx'))) {
// return new model
return response()->download(storage_path('app/models/control_.docx'));
}
}
if ($id === 3) {
// return default model
return response()->download(storage_path('app/models/pilotage_'. Auth::user()->language .'.docx'));
}
if ($id === 4) {
// check exists new model
if (file_exists(storage_path('app/models/pilotage_.docx'))) {
// return new model
return response()->download(storage_path('app/models/pilotage_.docx'));
}
}
return null;
}
public function saveTemplate(Request $request)
{
// Only for administrator
abort_if(
(Auth::User()->role !== 1),
Response::HTTP_FORBIDDEN,
'403 Forbidden'
);
$messages = Collect();
if ($request->has('template1')) {
// Get image file
$template = $request->file('template1');
// Upload image
$template->storeAs('models', 'control_.docx');
$messages->push('Template updated !');
}
if ($request->has('template2')) {
// Get image file
$template = $request->file('template2');
// Upload image
$template->storeAs('models', 'pilotage_.docx');
$messages->push('Template updated !');
}
return redirect()
->back()
->with('messages', $messages);
}
public function get(int $id)
{
// Not for API
abort_if(
(Auth::User()->role === 4),
Response::HTTP_FORBIDDEN,
'403 Forbidden'
);
$document = Document::Find($id);
// Document not found
abort_if($document === null, Response::HTTP_NOT_FOUND, '404 Not Found');
// Auditee may get documents from assigned controls only
abort_if(
(Auth::User()->role === 5) &&
! DB::table('control_user')
->where('user_id', Auth::User()->id)
->where('control_id', $document->control_id)
->exists(),
Response::HTTP_FORBIDDEN,
'403 Forbidden'
);
// get path
$path = storage_path('docs/' . $id);
// check file exists
abort_if(! file_exists($path), Response::HTTP_NOT_FOUND, '404 Not Found');
// get file content
$file_contents = file_get_contents($path);
return response($file_contents)
->header('Cache-Control', 'no-cache private')
->header('Content-Description', 'File Transfer')
->header('Content-Type', $document->mimetype)
->header('Content-length', (string) strlen($file_contents))
->header('Content-Disposition', 'attachment; filename="' . $document->filename .'"')
->header('Content-Transfer-Encoding', 'binary');
}
public function store(Request $request)
{
// Not for API
abort_if((Auth::User()->isAPI()), Response::HTTP_FORBIDDEN, '403 Forbidden');
// Get file
$file = $request->file('file');
// Get Control
$control_id = $request->get('control');
// Auditee may save document to assigned control only
abort_if(
Auth::User()->role === 5 &&
! (DB::table('control_user')
->where('control_id', $control_id)
->where('user_id', Auth::User()->id)
->exists()
||
DB::table('control_user_group')
->join('user_user_group', 'control_user_group.user_group_id', '=', 'user_user_group.user_group_id')
->where('control_user_group.control_id', $control_id)
->where('user_user_group.user_id', Auth::User()->id)
->exists()),
Response::HTTP_FORBIDDEN,
'403 Forbidden'
);
// Calculate file hash
$hash = hash_file('sha256', $file->path());
// Check if a document with this hash already exists
$existingDocument = Document::where('hash', $hash)->first();
// Create new document record
$doc = new Document();
$doc->control_id = $control_id;
$doc->filename = $file->getClientOriginalName();
$doc->mimetype = $file->getClientMimeType();
$doc->size = $file->getSize();
$doc->hash = $hash;
$doc->save();
$newPath = storage_path('docs/' . $doc->id);
$deduplicated = false;
if ($existingDocument !== null) {
// Reuse existing file - create hard link
$existingPath = storage_path('docs/' . $existingDocument->id);
if (file_exists($existingPath)) {
if (link($existingPath, $newPath)) {
$deduplicated = true;
} else {
// Fallback: hard-link failed (e.g., different filesystem)
$file->move(storage_path('docs'), (string) $doc->id);
}
} else {
// Fallback: if existing file is missing, store the uploaded file
$file->move(storage_path('docs'), (string) $doc->id);
}
} else {
// New file - store it
$file->move(storage_path('docs'), (string) $doc->id);
}
// response
return response()->json(
[
'success' => $doc->filename,
'id' => $doc->id,
'deduplicated' => $deduplicated,
]
);
}
public function delete(int $id)
{
// Not for API and Auditor
abort_if(
(Auth::User()->role === 3) ||
(Auth::User()->role === 4),
Response::HTTP_FORBIDDEN,
'403 Forbidden'
);
// Find the document
$document = Document::Find($id);
if ($document === null) {
return response()
->json(
['errorMessage' => 'File not found !']
);
}
// Auditee may delete documents from assigned controls
// when control has not been made
abort_if(
(Auth::User()->role === 5) &&
! DB::table('control_user')
->where('user_id', Auth::User()->id)
->where('control_id', $document->control_id)
->leftjoin('controls', 'controls.id', '=', 'control_user.control_id')
->whereNull('controls.realisation_date')
->exists(),
Response::HTTP_FORBIDDEN,
'403 Forbidden'
);
$path = storage_path('docs/'.$document->id);
if (file_exists($path)) {
unlink($path);
}
$document->delete();
return null;
}
public function index()
{
// Only for administrator
abort_if(
(Auth::User()->role !== 1),
Response::HTTP_FORBIDDEN,
'403 Forbidden'
);
$count = Document::count();
$sum = Document::sum('size');
$duration = config('deming.cleanup-duration');
return view('/documents/index')
->with('count', $count)
->with('sum', $sum)
->with('duration', $duration);
}
public function check()
{
// Only for administrator
abort_if(
(Auth::User()->role !== 1),
Response::HTTP_FORBIDDEN,
'403 Forbidden'
);
// Get all documents with computed metadata
$documents = Document::all()->map(function ($doc) {
$filePath = storage_path('docs/' . $doc->id);
$fileExists = file_exists($filePath);
// Add computed attributes to document object
$doc->file_exists = $fileExists;
$doc->link_count = 0;
$doc->hash_valid = false;
if ($fileExists) {
$stats = stat($filePath);
if ($stats !== false) {
$doc->link_count = $stats['nlink'] ?? 0;
}
$computedHash = hash_file('sha256', $filePath);
$doc->hash_valid = $computedHash !== false && hash_equals($doc->hash, $computedHash);
}
return $doc;
});
// Show view with pre-computed metadata
return view('/documents/check')
->with('documents', $documents);
}
public function saveConfig(Request $request)
{
// Only for administrator
abort_if(
(Auth::User()->role !== 1),
Response::HTTP_FORBIDDEN,
'403 Forbidden'
);
// Get duration from request
$duration = $request->get('duration');
// Get action
$action = $request->input('action');
// Act
if ($action === 'save') {
// Set duration
config(['deming.cleanup-duration' => $duration]);
// Save configuration
$text = '<?php return ' . var_export(config('deming'), true) . ';';
file_put_contents(config_path('deming.php'), $text);
// Message
$messages = Collect(['Configuration saved !']);
} elseif (($action === 'test') && ($duration > 0)) {
$dateLimit = Carbon::now()->subMonths($duration)->toDateString();
$result = Control::cleanup($dateLimit, true);
$messages = Collect(
[
"{$result['logCount']} log(s) will be deleted.",
"{$result['documentCount']} document(s) will be deleted.",
"{$result['controlCount']} control(s) will be deleted.",
]
);
} elseif (($action === 'delete') && ($duration > 0)) {
$dateLimit = Carbon::now()->subMonths($duration)->toDateString();
$result = Control::cleanup($dateLimit, false);
$messages = Collect(
[
"{$result['logCount']} log(s) deleted.",
"{$result['documentCount']} document(s) deleted.",
"{$result['controlCount']} control(s) deleted.",
]
);
} else {
$messages = null;
}
// get previous fields
$count = Document::count();
$sum = Document::sum('size');
// Redirect
return view('/documents/index')
->with('count', $count)
->with('sum', $sum)
->with('duration', $duration)
->with('messages', $messages);
}
}