Completed
Push — dev5 ( d45a54...be76cd )
by Ron
09:51
created

FileLinksController::disableLink()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 5
c 0
b 0
f 0
nc 1
nop 1
dl 0
loc 10
rs 10
1
<?php
2
3
namespace App\Http\Controllers\FileLinks;
4
5
use App\Files;
6
use Carbon\Carbon;
7
use App\FileLinks;
8
use App\FileLinkFiles;
9
use App\CustomerFileTypes;
10
use Illuminate\Support\Str;
11
use Illuminate\Http\Request;
12
use Illuminate\Http\UploadedFile;
13
use Illuminate\Support\Facades\Log;
14
use Illuminate\Support\Facades\Auth;
15
use App\Http\Controllers\Controller;
16
use Illuminate\Support\Facades\Route;
17
use Illuminate\Support\Facades\Storage;
18
use Pion\Laravel\ChunkUpload\Receiver\FileReceiver;
19
use Pion\Laravel\ChunkUpload\Handler\HandlerFactory;
20
use Pion\Laravel\ChunkUpload\Handler\AbstractHandler;
21
use Pion\Laravel\ChunkUpload\Exceptions\UploadMissingFileException;
22
use App\Http\Resources\FileLinksCollection;
23
24
class FileLinksController extends Controller
25
{
26
    //  Only authorized users have access
27
    public function __construct(\Gate $gate)
0 ignored issues
show
Unused Code introduced by
The parameter $gate is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

27
    public function __construct(/** @scrutinizer ignore-unused */ \Gate $gate)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
28
    {
29
        //  Verify the user is logged in and has permissions for this page
30
        $this->middleware('auth');
31
        $this->middleware(function ($request, $next) {
32
            $this->user = auth()->user();
0 ignored issues
show
Bug Best Practice introduced by
The property user does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
33
            $this->authorize('hasAccess', 'use_file_links');
34
            return $next($request);
35
        });
36
    }
37
38
    //  Landing page shows all links that the user owns
39
    public function index()
40
    {
41
        Log::debug('Route ' . Route::currentRouteName() . ' visited by User ID-' . Auth::user()->user_id);
42
        return view('links.index');
43
    }
44
45
    //  Ajax call to show the links for a specific user
46
    public function find($id)
47
    {
48
        if($id == 0)
49
        {
50
            $id = Auth::user()->user_id;
51
        }
52
53
        Log::debug('Route '.Route::currentRouteName().' visited by User ID-'.Auth::user()->user_id);
54
        return $links = new FileLinksCollection(
0 ignored issues
show
Unused Code introduced by
The assignment to $links is dead and can be removed.
Loading history...
55
            FileLinks::where('user_id', $id)
56
                ->withCount('FileLinkFiles')
57
                ->orderBy('expire', 'desc')->get()
58
        );
59
    }
60
61
62
63
64
65
66
67
68
69
70
    //  Create a new file link form
71
    public function create()
72
    {
73
        Log::debug('Route '.Route::currentRouteName().' visited by User ID-'.Auth::user()->user_id);
74
        return view('links.form.newLink');
75
    }
76
77
    //  Submit the new file link form
78
    public function store(Request $request)
79
    {
80
        $request->validate([
81
            'name'   => 'required',
82
            'expire' => 'required'
83
        ]);
84
85
        if(!empty($request->file))
86
        {
87
            $receiver = new FileReceiver('file', $request, HandlerFactory::classFromRequest($request));
88
89
            //  Verify that the upload is valid and being processed
90
            if($receiver->isUploaded() === false)
91
            {
92
                Log::error('Upload File Missing - '.$request->toArray());
93
                throw new UploadMissingFileException();
94
            }
95
96
            //  Recieve and process the file
97
            $save = $receiver->receive();
98
99
            //  See if the uploade has finished
100
            if($save->isFinished())
101
            {
102
                $this->saveFile($save->getFile());
103
104
                return 'uploaded successfully';
105
            }
106
107
            //  Get the current progress
108
            $handler = $save->handler();
109
110
            Log::debug('Route '.Route::currentRouteName().' visited by User ID-'.Auth::user()->user_id);
111
            Log::debug('File being uploaded.  Percentage done - '.$handler->getPercentageDone());
112
            return response()->json([
113
                'done'   => $handler->getPercentageDone(),
114
                'status' => true
115
            ]);
116
        }
117
118
        //  If there are no files being uploaded or the file uploade process is done
119
        if(isset($request->_completed) && $request->_completed)
120
        {
121
            Log::debug('Route '.Route::currentRouteName().' visited by User ID-'.Auth::user()->user_id);
122
            Log::debug('Link data submitted.  Data - ', $request->toArray());
123
            $linkID = $this->createLink($request);
124
            if($request->session()->has('newLinkFile'))
125
            {
126
                //  If there were files uploaded to the link, process them
127
                $files = session('newLinkFile');
128
                $path = config('filesystems.paths.links').DIRECTORY_SEPARATOR.$linkID;
129
130
                foreach($files as $file)
131
                {
132
                    $data = Files::find($file);
133
                    //  Move the file to the proper folder
134
                    Storage::move($data->file_link.$data->file_name, $path.DIRECTORY_SEPARATOR.$data->file_name);
135
                    //  Update file link in DB
136
                    $data->update([
137
                        'file_link' => $path.DIRECTORY_SEPARATOR
138
                    ]);
139
                    //  Attach file to the link
140
                    FileLinkFiles::create([
141
                        'link_id' => $linkID,
142
                        'file_id' => $data->file_id,
143
                        'user_id' => Auth::user()->user_id,
144
                        'upload' => 0
145
                    ]);
146
147
                    Log::debug('File Added for link ID-'.$linkID.'.  File ID-'.$data->file_id);
148
                }
149
150
                $request->session()->forget('newLinkFile');
151
            }
152
153
            return response()->json(['link' => $linkID, 'name' => urlencode($request->name)]);
154
        }
155
156
        return response()->json(['complete' => false]);
157
    }
158
159
    //  Create the new file link
160
    private function createLink($data)
161
    {
162
        //  Generate a random hash to use as the file link and make sure it is not already in use
163
        do
164
        {
165
            $hash = strtolower(Str::random(15));
166
            $dup  = FileLinks::where('link_hash', $hash)->get()->count();
167
        } while($dup != 0);
168
169
        //  If the "customer id" field is populated, separate the ID from the name and prepare for insertion.
170
        if($data->customer_tag != null)
171
        {
172
            $custID = explode(' ', $data->customer_tag);
173
            $custID = $custID[0];
174
        }
175
        else
176
        {
177
            $custID = null;
178
        }
179
180
        //  Create the new file link
181
        $link = FileLinks::create([
182
            'user_id'      => Auth::user()->user_id,
183
            'cust_id'      => $custID,
184
            'link_hash'    => $hash,
185
            'link_name'    => $data->name,
186
            'expire'       => $data->expire,
187
            'allow_upload' => isset($data->allowUp) && $data->allowUp ? true : false
188
        ]);
189
190
        Log::info('File Link Created for User ID-'.Auth::user()->user_id.'.  Link ID-'.$link->link_id);
191
192
        return $link->link_id;
193
    }
194
195
    //  Save a file attached to the link
196
    private function saveFile(UploadedFile $file)
197
    {
198
        $filePath = config('filesystems.paths.links').DIRECTORY_SEPARATOR.'_tmp';
199
200
        //  Clean the file and store it
201
        $fileName = Files::cleanFilename($filePath, $file->getClientOriginalName());
202
        $file->storeAs($filePath, $fileName);
203
204
        //  Place file in Files table of DB
205
        $newFile = Files::create([
206
            'file_name' => $fileName,
207
            'file_link' => $filePath.DIRECTORY_SEPARATOR
208
        ]);
209
        $fileID = $newFile->file_id;
210
211
        //  Save the file ID in the session array
212
        $fileArr = session('newLinkFile') != null ? session('newLinkFile') : [];
213
        $fileArr[] = $fileID;
214
        session(['newLinkFile' => $fileArr]);
215
216
        //  Log stored file
217
        Log::info('File Stored', ['file_id' => $fileID, 'file_path' => $filePath.DIRECTORY_SEPARATOR.$fileName]);
218
219
        return $fileID;
220
    }
221
222
    //  Show details about a file link
223
    public function details($id, $name)
0 ignored issues
show
Unused Code introduced by
The parameter $name is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

223
    public function details($id, /** @scrutinizer ignore-unused */ $name)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
224
    {
225
        //  Verify that the link is a valid link
226
        $linkData = FileLinks::find($id);
227
228
        //  If the link is invalid, return an error page
229
        if(empty($linkData))
230
        {
231
            Log::warning('User tried to view bad file link', ['user_id' => Auth::user()->user_id, 'link_id' => $id]);
232
            return view('links.badLink');
233
        }
234
235
        //  Determine if the link has a customer attached or not
236
        $hasCust = $linkData->cust_id != null ? true : false;
237
238
        //  Get the possible file types for attaching a file to a customer
239
        $fileTypes = CustomerFileTypes::all();
240
241
        Log::debug('Route '.Route::currentRouteName().' visited by User ID-'.Auth::user()->user_id);
242
        Log::debug('Link Detials - ', $linkData->toArray());
243
        return view('links.details', [
244
            'link_id'    => $id,
245
            'has_cust'   => $hasCust,
246
            'file_types' => $fileTypes
247
        ]);
248
    }
249
250
    //  Ajax call te get JSON details of the link
251
    public function show($id)
252
    {
253
        $linkData = FileLinks::where('link_id', $id)->leftJoin('customers', 'file_links.cust_id', '=', 'customers.cust_id')->first();
254
255
        //  Format the expiration date to be readable
256
        $linkData->timestamp = $linkData->expire;
257
        $linkData->expire    = date('M d, Y', strtotime($linkData->expire));
258
259
        Log::debug('Route '.Route::currentRouteName().' visited by User ID-'.Auth::user()->user_id);
260
        Log::debug('Link Details - ', $linkData->toArray());
261
        return response()->json($linkData);
262
    }
263
264
    //  Update the link's details
265
    public function update(Request $request, $id)
266
    {
267
        $request->validate([
268
            'name'   => 'required',
269
            'expire' => 'required'
270
        ]);
271
272
        FileLinks::find($id)->update([
273
            'link_name'    => $request->name,
274
            'expire'       => $request->expire,
275
            'allow_upload' => isset($request->allowUp) && $request->allowUp ? true : false
276
        ]);
277
278
        Log::debug('Route '.Route::currentRouteName().' visited by User ID-'.Auth::user()->user_id);
279
        Log::debug('Updated Link Data for link ID-'.$id, $request->toArray());
280
        Log::info('File Link Updated', ['link_id' => $id]);
281
282
        return response()->json(['success' => true]);
283
    }
284
285
    //  Update the customer that is attached to the customer
286
    public function updateCustomer(Request $request, $id)
287
    {
288
        //  If the "customer id" field is populated, separate the ID from the name and prepare for insertion.
289
        if($request->customer_tag != null && $request->customer_tag != 'NULL')
290
        {
291
            $custID = explode(' ', $request->customer_tag);
292
            $custID = $custID[0];
293
        }
294
        else
295
        {
296
            $custID = null;
297
        }
298
299
        FileLinks::find($id)->update([
300
            'cust_id' => $custID
301
        ]);
302
303
        Log::debug('Route '.Route::currentRouteName().' visited by User ID-'.Auth::user()->user_id);
304
        Log::debug('Submitted Data -', $request->toArray());
305
        return response()->json(['success' => true]);
306
    }
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
    //  Disable a file linke, but do not remove it (set the expire date to a previous date)
328
    public function disableLink($id)
329
    {
330
        //  update the expire date for the link
331
        FileLinks::find($id)->update([
332
            'expire' => Carbon::yesterday()
333
        ]);
334
335
        Log::info('User ID '.Auth::user()->user_id.' disabled link ID - '.$id);
336
        Log::debug('Route ' . Route::currentRouteName() . ' visited by User ID-' . Auth::user()->user_id);
337
        return response()->json(['success' => true]);
338
    }
339
340
    //  Delete a file link
341
    public function destroy($id)
342
    {
343
        //  Remove the file from database
344
        $data = FileLinkFiles::where('link_id', $id)->get();
345
        if(!$data->isEmpty())
346
        {
347
            foreach($data as $file)
348
            {
349
                $fileID = $file->file_id;
350
                $file->delete();
351
352
                //  Delete the file if it is no longer in use
353
                Files::deleteFile($fileID);
354
            }
355
        }
356
357
        FileLinks::find($id)->delete();
358
359
        Log::debug('Route '.Route::currentRouteName().' visited by User ID-'.Auth::user()->user_id);
360
        Log::info('File link deleted', ['link_id' => $id, 'user_id' => Auth::user()->user_id]);
361
362
        return response()->json([
363
            'success' => true
364
        ]);
365
    }
366
}
367