Passed
Push — dev5 ( 1f3b64...3a6272 )
by Ron
06:33
created

FileLinksController::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 5
c 1
b 0
f 0
nc 1
nop 0
dl 0
loc 8
rs 10
ccs 5
cts 5
cp 1
crap 1
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 App\Http\Resources\FileLinksCollection;
19
use App\Http\Resources\CustomerFileTypesCollection;
20
use Pion\Laravel\ChunkUpload\Receiver\FileReceiver;
21
use Pion\Laravel\ChunkUpload\Handler\HandlerFactory;
22
// use Pion\Laravel\ChunkUpload\Handler\AbstractHandler;
23
use App\Http\Resources\FileLinks as FileLinksResource;
24
use Pion\Laravel\ChunkUpload\Exceptions\UploadMissingFileException;
25
26
class FileLinksController extends Controller
27
{
28
    private $user;
29
30
    //  Only authorized users have access
31 18
    public function __construct()
32
    {
33
        //  Verify the user is logged in and has permissions for this page
34 18
        $this->middleware('auth');
35
        $this->middleware(function($request, $next) {
36 14
            $this->user = auth()->user();
37 14
            $this->authorize('hasAccess', 'use_file_links');
38 10
            return $next($request);
39 18
        });
40 18
    }
41
42
    //  Landing page shows all links that the user owns
43 2
    public function index()
44
    {
45 2
        Log::debug('Route '.Route::currentRouteName().' visited by User ID-'.Auth::user()->user_id);
46 2
        return view('links.index');
47
    }
48
49
    //  Ajax call to show the links for a specific user
50 8
    public function find($id)
51
    {
52
        //  Verify if the user is trying to pull their own links
53 8
        if($id == 0)
54
        {
55 2
            $id = Auth::user()->user_id;
56
        }
57
        //  If the user is trying to pull someone elses links, they must be able to manage users
58 6
        else if ($id != Auth::user()->user_id && !$this->authorize('hasAccess', 'manage_users'))
59
        {
60
            return abort(403);
0 ignored issues
show
Bug introduced by
Are you sure the usage of abort(403) is correct as it seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
61
        }
62
63 6
        Log::debug('Route '.Route::currentRouteName().' visited by User ID-'.Auth::user()->user_id);
64 6
        $links = new FileLinksCollection(
65 6
            FileLinks::where('user_id', $id)
66 6
                ->withCount('FileLinkFiles')
67 6
                ->orderBy('expire', 'desc')->get()
68
        );
69
70 6
        return $links;
71
    }
72
73
    //  Create a new file link form
74
    public function create()
75
    {
76
        Log::debug('Route '.Route::currentRouteName().' visited by User ID-'.Auth::user()->user_id);
77
        return view('links.newLink');
78
    }
79
80
    //  Submit the new file link form
81
    public function store(Request $request)
82
    {
83
        $request->validate([
84
            'name'       => 'required',
85
            'expire'     => 'required',
86
            'customerID' => 'exists:customers,cust_id|nullable'
87
        ]);
88
89
        if(!empty($request->file))
90
        {
91
            $receiver = new FileReceiver('file', $request, HandlerFactory::classFromRequest($request));
92
93
            //  Verify that the upload is valid and being processed
94
            if($receiver->isUploaded() === false)
95
            {
96
                Log::error('Upload File Missing - ' .
97
                /** @scrutinizer ignore-type */
98
                $request->toArray());
99
                throw new UploadMissingFileException();
100
            }
101
102
            //  Recieve and process the file
103
            $save = $receiver->receive();
104
105
            //  See if the uploade has finished
106
            if($save->isFinished())
107
            {
108
                $this->saveFile($save->getFile());
109
110
                return 'uploaded successfully';
111
            }
112
113
            //  Get the current progress
114
            $handler = $save->handler();
115
116
            Log::debug('Route '.Route::currentRouteName().' visited by User ID-'.Auth::user()->user_id);
117
            Log::debug('File being uploaded.  Percentage done - '.$handler->getPercentageDone());
118
            return response()->json([
119
                'done'   => $handler->getPercentageDone(),
120
                'status' => true
121
            ]);
122
        }
123
124
        //  If there are no files being uploaded or the file uploade process is done
125
        if(isset($request->_completed) && $request->_completed)
126
        {
127
            Log::debug('Route '.Route::currentRouteName().' visited by User ID-'.Auth::user()->user_id);
128
            Log::debug('Link data submitted.  Data - ',
129
            /** @scrutinizer ignore-type */
130
            $request->toArray());
131
            $linkID = $this->createLink($request);
132
            if($request->session()->has('newLinkFile'))
133
            {
134
                //  If there were files uploaded to the link, process them
135
                $files = session('newLinkFile');
136
                $path = config('filesystems.paths.links').DIRECTORY_SEPARATOR.$linkID;
137
138
                foreach($files as $file)
139
                {
140
                    $data = Files::find($file);
141
                    //  Move the file to the proper folder
142
                    Storage::move($data->file_link.$data->file_name, $path.DIRECTORY_SEPARATOR.$data->file_name);
2 ignored issues
show
Bug introduced by
The property file_link does not seem to exist on App\Files. Are you sure there is no database migration missing?

Checks if undeclared accessed properties appear in database migrations and if the creating migration is correct.

Loading history...
Bug introduced by
The property file_name does not seem to exist on App\Files. Are you sure there is no database migration missing?

Checks if undeclared accessed properties appear in database migrations and if the creating migration is correct.

Loading history...
143
                    //  Update file link in DB
144
                    $data->update([
145
                        'file_link' => $path.DIRECTORY_SEPARATOR
146
                    ]);
147
                    //  Attach file to the link
148
                    FileLinkFiles::create([
149
                        'link_id' => $linkID,
150
                        'file_id' => $data->file_id,
1 ignored issue
show
Bug introduced by
The property file_id does not seem to exist on App\Files. Are you sure there is no database migration missing?

Checks if undeclared accessed properties appear in database migrations and if the creating migration is correct.

Loading history...
151
                        'user_id' => Auth::user()->user_id,
152
                        'upload' => 0
153
                    ]);
154
155
                    Log::debug('File Added for link ID-'.$linkID.'.  File ID-'.$data->file_id);
156
                }
157
158
                $request->session()->forget('newLinkFile');
159
            }
160
161
            return response()->json(['link' => $linkID, 'name' => Str::slug($request->name)]);
162
        }
163
164
        return response()->json(['complete' => false]);
165
    }
166
167
    //  Create the new file link
168
    private function createLink($data)
169
    {
170
        //  Generate a random hash to use as the file link and make sure it is not already in use
171
        do
172
        {
173
            $hash = strtolower(Str::random(15));
174
            $dup  = FileLinks::where('link_hash', $hash)->get()->count();
175
        } while($dup != 0);
176
177
        //  Create the new file link
178
        $link = FileLinks::create([
179
            'user_id'      => Auth::user()->user_id,
180
            'cust_id'      => $data->customerID,
181
            'link_hash'    => $hash,
182
            'link_name'    => $data->name,
183
            'expire'       => $data->expire,
184
            'allow_upload' => isset($data->allowUp) && $data->allowUp ? true : false,
185
            'note'         => $data->note
186
        ]);
187
188
        Log::info('File Link Created for User ID-'.Auth::user()->user_id.'.  Link ID-'.$link->link_id);
1 ignored issue
show
Bug introduced by
The property link_id does not seem to exist on App\FileLinks. Are you sure there is no database migration missing?

Checks if undeclared accessed properties appear in database migrations and if the creating migration is correct.

Loading history...
189
190
        return $link->link_id;
191
    }
192
193
    //  Save a file attached to the link
194
    private function saveFile(UploadedFile $file)
195
    {
196
        $filePath = config('filesystems.paths.links').DIRECTORY_SEPARATOR.'_tmp';
197
198
        //  Clean the file and store it
199
        $fileName = Files::cleanFilename($filePath, $file->getClientOriginalName());
200
        $file->storeAs($filePath, $fileName);
201
202
        //  Place file in Files table of DB
203
        $newFile = Files::create([
204
            'file_name' => $fileName,
205
            'file_link' => $filePath.DIRECTORY_SEPARATOR
206
        ]);
207
        $fileID = $newFile->file_id;
1 ignored issue
show
Bug introduced by
The property file_id does not seem to exist on App\Files. Are you sure there is no database migration missing?

Checks if undeclared accessed properties appear in database migrations and if the creating migration is correct.

Loading history...
208
209
        //  Save the file ID in the session array
210
        $fileArr = session('newLinkFile') != null ? session('newLinkFile') : [];
211
        $fileArr[] = $fileID;
212
        session(['newLinkFile' => $fileArr]);
213
214
        //  Log stored file
215
        Log::info('File Stored', ['file_id' => $fileID, 'file_path' => $filePath.DIRECTORY_SEPARATOR.$fileName]);
216
        return $fileID;
217
    }
218
219
    //  Show details about a file link
220
    public function details($id, /** @scrutinizer ignore-unused */ $name)
221
    {
222
        //  Verify that the link is a valid link
223
        $linkData = FileLinks::find($id);
224
        $fileTypes = new CustomerFileTypesCollection(CustomerFileTypes::all());
225
226
        //  If the link is invalid, return an error page
227
        if(empty($linkData))
228
        {
229
            Log::warning('User tried to view bad file link', ['user_id' => Auth::user()->user_id, 'link_id' => $id]);
230
            return view('links.badLink');
231
        }
232
233
        Log::debug('Route '.Route::currentRouteName().' visited by User ID-'.Auth::user()->user_id);
234
        Log::debug('Link Detials - ',
235
        /** @scrutinizer ignore-type */
236
        $linkData->toArray());
237
        return view('links.details', [
238
            'link_id'    => $linkData->link_id,
1 ignored issue
show
Bug introduced by
The property link_id does not seem to exist on App\FileLinks. Are you sure there is no database migration missing?

Checks if undeclared accessed properties appear in database migrations and if the creating migration is correct.

Loading history...
239
            'cust_id'    => $linkData->cust_id,
1 ignored issue
show
Bug introduced by
The property cust_id does not seem to exist on App\FileLinks. Are you sure there is no database migration missing?

Checks if undeclared accessed properties appear in database migrations and if the creating migration is correct.

Loading history...
240
            'file_types' => $fileTypes
241
        ]);
242
    }
243
244
    //  Ajax call te get JSON details of the link
245
    public function show($id)
246
    {
247
        $linkData = new FileLinksResource(FileLinks::find($id));
248
249
        Log::debug('Route '.Route::currentRouteName().' visited by User ID-'.Auth::user()->user_id);
250
        return $linkData;
251
    }
252
253
    //  Update the link's details
254
    public function update(Request $request, $id)
255
    {
256
        $request->validate([
257
            'name'       => 'required',
258
            'expire'     => 'required',
259
            'customerTag' => 'exists:customers,cust_id|nullable'
260
        ]);
261
262
        FileLinks::find($id)->update([
263
            'link_name'    => $request->name,
264
            'expire'       => $request->expire,
265
            'allow_upload' => isset($request->allowUpload) && $request->allowUpload ? true : false,
266
            'cust_id'      => $request->customerTag,
267
            'note'         => $request->hasInstructions ? $request->instructions : null
268
        ]);
269
270
        Log::debug('Route '.Route::currentRouteName().' visited by User ID-'.Auth::user()->user_id);
271
        Log::debug('Updated Link Data for link ID-'.$id,
272
        /** @scrutinizer ignore-type */
273
        $request->toArray());
274
        Log::info('File Link Updated', ['link_id' => $id]);
275
276
        return response()->json(['success' => true]);
277
    }
278
279
    //  Disable a file linke, but do not remove it (set the expire date to a previous date)
280
    public function disableLink($id)
281
    {
282
        //  update the expire date for the link
283
        FileLinks::find($id)->update([
284
            'expire' => Carbon::yesterday()
285
        ]);
286
287
        Log::info('User ID '.Auth::user()->user_id.' disabled link ID - '.$id);
288
        Log::debug('Route '.Route::currentRouteName().' visited by User ID-'.Auth::user()->user_id);
289
        return response()->json(['success' => true]);
290
    }
291
292
    //  Delete a file link
293
    public function destroy($id)
294
    {
295
        //  Remove the file from database
296
        $data = FileLinkFiles::where('link_id', $id)->get();
297
        if(!$data->isEmpty())
298
        {
299
            foreach($data as $file)
300
            {
301
                $fileID = $file->file_id;
1 ignored issue
show
Bug introduced by
The property file_id does not seem to exist on App\FileLinkFiles. Are you sure there is no database migration missing?

Checks if undeclared accessed properties appear in database migrations and if the creating migration is correct.

Loading history...
302
                $file->delete();
303
304
                //  Delete the file if it is no longer in use
305
                Files::deleteFile($fileID);
306
            }
307
        }
308
309
        FileLinks::find($id)->delete();
310
311
        Log::debug('Route '.Route::currentRouteName().' visited by User ID-'.Auth::user()->user_id);
312
        Log::info('File link deleted', ['link_id' => $id, 'user_id' => Auth::user()->user_id]);
313
314
        return response()->json([
315
            'success' => true
316
        ]);
317
    }
318
}
319