Passed
Push — master ( 836696...7e7f2a )
by Ron
01:43 queued 11s
created

FileLinksController::newLinkFile()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 19
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 9
nc 1
nop 2
dl 0
loc 19
rs 9.9666
c 0
b 0
f 0
1
<?php
2
3
namespace App\Http\Controllers;
4
5
use Illuminate\Http\Response;
6
use Illuminate\Http\Request;
7
use Illuminate\Support\Facades\Auth;
8
use Illuminate\Support\Facades\Log;
9
use Zip;
10
use App\Files;
11
use App\FileLinks;
12
use App\FileLinkFiles;
13
use App\FileLinkNotes;
14
15
use Pion\Laravel\ChunkUpload\Exceptions\UploadMissingFileException;
16
use Pion\Laravel\ChunkUpload\Handler\AbstractHandler;
17
use Pion\Laravel\ChunkUpload\Handler\HandlerFactory;
18
use Pion\Laravel\ChunkUpload\Receiver\FileReceiver;
19
use Illuminate\Http\UploadedFile;
20
21
class FileLinksController extends Controller
22
{
23
    //  Only authorized users have access
24
    public function __construct()
25
    {
26
        $this->middleware('auth');
27
    }
28
    
29
    //  Landing page
30
    public function index()
31
    {
32
        return view('links.index');
33
    }
34
35
    //  Create a new File Link
36
    public function create()
37
    {
38
        return view('links.form.newLink');
39
    }
40
41
    //  Store the new file link
42
    public function store(Request $request)
43
    {
44
        $request->validate(['name' => 'required', 'expire' => 'required']);
45
        
46
        if(!empty($request->file))
47
        {
48
            // create the file receiver
49
            $receiver = new FileReceiver("file", $request, HandlerFactory::classFromRequest($request));
50
51
            // check if the upload is success, throw exception or return response you need
52
            if ($receiver->isUploaded() === false) {
53
                throw new UploadMissingFileException();
54
            }
55
56
            // receive the file
57
            $save = $receiver->receive();
58
            // check if the upload has finished (in chunk mode it will send smaller files)
59
            if ($save->isFinished()) {
60
                do
61
                {
62
                    $hash = strtolower(str_random(15));
63
                    $dup = FileLinks::where('link_hash', $hash)->get()->count();
64
                }while($dup != 0);
65
66
                //  Create the new file link
67
                $link = FileLinks::create([
68
                    'user_id'      => Auth::user()->user_id,
69
                    'link_hash'    => $hash,
70
                    'link_name'    => $request->name,
71
                    'expire'       => $request->expire,
72
                    'allow_upload' => isset($request->allowUp) && $request->allowUp ? true : false
73
                ]);
74
                $linkID = $link->link_id;
75
76
                $fileID =  $this->newLinkFile($save->getFile(), $linkID);
77
78
                //  Place the file in the file link files table of DB
79
                FileLinkFiles::create([
80
                    'link_id'  => $linkID,
81
                    'file_id'  => $fileID,
82
                    'user_id'  => Auth::user()->user_id,
83
                    'upload'   => 0
84
                ]);
85
86
                return 'this is the link id'.$linkID;
87
            }
88
            // we are in chunk mode, lets send the current progress
89
            /** @var AbstractHandler $handler */
90
            $handler = $save->handler();
91
92
            return response()->json([
93
                "done" => $handler->getPercentageDone(),
94
                'status' => true
95
            ]);
96
        }
97
        else
98
        {
99
            do
100
            {
101
                $hash = strtolower(str_random(15));
102
                $dup = FileLinks::where('link_hash', $hash)->get()->count();
103
            }while($dup != 0);
104
105
            //  Create the new file link
106
            $link = FileLinks::create([
107
                'user_id'      => Auth::user()->user_id,
108
                'link_hash'    => $hash,
109
                'link_name'    => $request->name,
110
                'expire'       => $request->expire,
111
                'allow_upload' => isset($request->allowUp) && $request->allowUp ? true : false
112
            ]);
113
            $linkID = $link->link_id;
114
            
115
            return $linkID;
116
        }
117
    }
118
    
119
    public function newLinkFile(UploadedFile $file, $linkID)
120
    {
121
        $filePath = config('filesystems.paths.links').DIRECTORY_SEPARATOR.$linkID;
122
        
123
        //  Clean the file and store it
124
        $fileName = Files::cleanFilename($filePath, $file->getClientOriginalName());
125
        $file->storeAs($filePath, $fileName);
126
127
        //  Place file in Files table of DB
128
        $newFile = Files::create([
129
            'file_name' => $fileName,
130
            'file_link' => $filePath.DIRECTORY_SEPARATOR
131
        ]);
132
        $fileID = $newFile->file_id;
133
134
        //  Log stored file
135
        Log::info('File Stored', ['file_id' => $fileID, 'file_path' => $filePath.DIRECTORY_SEPARATOR.$fileName]);
136
        
137
        return $fileID;
138
    }
139
140
    //  Show file links for a specific user
141
    public function show($id)
142
    {
143
        $links = FileLinks::where('user_id', $id)
144
            ->withCount('FileLinkFiles')
145
            ->orderBy('expire', 'desc')
146
            ->get();
147
        
148
        return view('links.loadLinks', [
149
            'links' => $links
150
        ]);
151
    }
152
    
153
    //  Show a links information
154
    public function details($id, $name, Request $request)
155
    {
156
        $linkData = FileLinks::find($id);
157
        if(!$request->session()->has('newLinkId'))
158
        {
159
            $request->session()->forget('newLinkId');
160
        }
161
        
162
        if(empty($linkData))
163
        {
164
            return view('links.badLink');
165
        }
166
        
167
        $emailMsg = "mailto:?subject=A File Link Has Been Created For You&body=View the link details here:  ".route('userLink.details', ['link' => $linkData->link_hash]);
168
        
169
        return view('links.details', [
170
            'data' => $linkData,
171
            'emMsg' => $emailMsg
172
        ]);
173
    }
174
    
175
    //  Get the files for the link
176
    public function getFiles($type, $linkID)
177
    {
178
        $files = null;
179
        switch($type)
180
        {
181
            case 'down':
182
                $files = FileLInkFiles::where('link_id', $linkID)
183
                    ->where('upload', false)
184
                    ->join('files', 'file_link_files.file_id', '=', 'files.file_id')
185
                    ->get();
186
                break;
187
            case 'up':
188
                $files = Files::where('file_link_files.link_id', $linkID)
189
                    ->where('file_link_files.upload', true)
190
                    ->join('file_link_files', 'files.file_id', '=', 'file_link_files.file_id')
191
                    ->with('FileLinkNotes')
192
                    ->get();
193
                break;
194
        }
195
        
196
        return view('links.fileList', [
197
            'files'  => $files,
198
            'type'   => $type,
199
            'linkID' => $linkID
200
        ]);
201
    }
202
    
203
    //  Add a new file
204
    public function addFileForm($id)
205
    {
206
        return view('links.form.addFile', [
207
            'id' => $id
208
        ]);
209
    }
210
    
211
    //  Submit the additional files
212
    public function submitAddFile($id, Request $request)
213
    {
214
        // create the file receiver
215
        $receiver = new FileReceiver("file", $request, HandlerFactory::classFromRequest($request));
216
        
217
        // check if the upload is success, throw exception or return response you need
218
        if ($receiver->isUploaded() === false) {
219
            throw new UploadMissingFileException();
220
        }
221
        
222
        // receive the file
223
        $save = $receiver->receive();
224
        // check if the upload has finished (in chunk mode it will send smaller files)
225
        if ($save->isFinished()) {
226
            return $this->saveFile($save->getFile(), $id);
227
        }
228
        // we are in chunk mode, lets send the current progress
229
        /** @var AbstractHandler $handler */
230
        $handler = $save->handler();
231
        
232
        return response()->json([
233
            "done" => $handler->getPercentageDone(),
234
            'status' => true
235
        ]);
236
    }
237
    
238
    public function saveFile(UploadedFile $file, $id)
239
    {
240
        $filePath = config('filesystems.paths.links').DIRECTORY_SEPARATOR.$id;
241
        
242
        //  Clean the file and store it
243
        $fileName = Files::cleanFilename($filePath, $file->getClientOriginalName());
244
        $file->storeAs($filePath, $fileName);
245
246
        //  Place file in Files table of DB
247
        $newFile = Files::create([
248
            'file_name' => $fileName,
249
            'file_link' => $filePath.DIRECTORY_SEPARATOR
250
        ]);
251
        $fileID = $newFile->file_id;
252
        
253
        //  Place the file in the file link files table of DB
254
        FileLinkFiles::create([
255
            'link_id'  => $id,
256
            'file_id'  => $fileID,
257
            'user_id'  => Auth::user()->user_id,
258
            'upload'   => 0
259
        ]);
260
261
        //  Log stored file
262
        Log::info('File Stored', ['file_id' => $fileID, 'file_path' => $filePath.DIRECTORY_SEPARATOR.$fileName]);
263
        
264
        return $fileID;
265
    }
266
    
267
    protected function createFilename(UploadedFile $file)
268
    {
269
        $extension = $file->getClientOriginalExtension();
270
        $filename = str_replace('.'.$extension, '', $file->getClientOriginalName());
271
        
272
        $filename .= '_'.md5(time()).'.'.$extension;
273
        
274
        return $filename;
275
    }
276
    
277
    //  Get a note that is attached to a file
278
    public function getNote($id)
279
    {
280
        $note = FileLinkNotes::find($id);
281
        
282
        return $note->note;
283
    }
284
285
    //  Edit a links basic informaiton
286
    public function edit($id)
287
    {
288
        $linkData = FileLinks::find($id);
289
        
290
        return view('links.form.editLink', [
291
            'data' => $linkData
292
        ]);
293
    }
294
    
295
    //  Download all files uploaded to a link
296
    public function downloadAllFiles($linkID)
297
    {
298
        $files = Files::where('file_link_files.link_id', $linkID)
299
            ->where('file_link_files.upload', true)
300
            ->join('file_link_files', 'files.file_id', '=', 'file_link_files.file_id')
301
            ->with('FileLinkNotes')
302
            ->get();
303
        $path = config('filesystems.disks.local.root').DIRECTORY_SEPARATOR;
304
        
305
        $zip = Zip::create($path.'download.zip');
306
        foreach($files as $file)
307
        {
308
            $zip->add($path.$file->file_link.$file->file_name);
309
        }
310
        
311
        $zip->close();
312
        
313
        return response()->download($path.'download.zip')->deleteFileAfterSend(true);        
314
    }
315
316
    //  Submit the edit link form
317
    public function update(Request $request, $id)
318
    {
319
        $request->validate([
320
            'link_name' => 'required', 
321
            'expire'    => 'required'
322
        ]);
323
        
324
        FileLinks::find($id)->update([
325
            'link_name'    => $request->link_name,
326
            'expire'       => $request->expire,
327
            'allow_upload' => isset($request->allowUp) && $request->allowUp ? true : false
328
        ]);
329
        
330
        Log::info('File Link Updated', ['link_id' => $id]);
331
    }
332
    
333
    //  Delete a file attached to a link
334
    public function deleteLinkFile($linkFileID)
335
    {
336
        $fileData = FileLinkFiles::find($linkFileID);
337
        $fileID = $fileData->file_id;
338
        $fileData->delete();
339
        
340
        Files::deleteFile($fileID);
341
    }
342
343
    //  Delete a file link
344
    public function destroy($id)
345
    {
346
        //  Remove the file from database
347
        $data = FileLinkFiles::where('link_id', $id)->get();
348
        if(!$data->isEmpty())
349
        {
350
            foreach($data as $file)
351
            {
352
                $fileID = $file->file_id;
353
                $file->delete();
354
355
                //  Delete the file if it is no longer in use
356
                Files::deleteFile($fileID);
357
            }
358
        }
359
        
360
        FileLinks::find($id)->delete();
361
        
362
        Log::info('File link deleted', ['link_id' => $id, 'user_id' => Auth::user()->user_id]);
363
    }
364
}
365