Completed
Push — dev5 ( 096a7b...37965d )
by Ron
09:47
created

FileLinksController::update()   A

Complexity

Conditions 3
Paths 1

Size

Total Lines 16
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 9
nc 1
nop 2
dl 0
loc 16
rs 9.9666
c 0
b 0
f 0
1
<?php
2
3
namespace App\Http\Controllers\FileLinks;
4
5
use App\Files;
6
use App\FileLinks;
7
use App\FileLinkFiles;
8
use Illuminate\Support\Str;
9
use Illuminate\Http\Request;
10
use Illuminate\Http\UploadedFile;
11
use Illuminate\Support\Facades\Log;
12
use Illuminate\Support\Facades\Auth;
13
use App\Http\Controllers\Controller;
14
use Illuminate\Support\Facades\Storage;
15
use Pion\Laravel\ChunkUpload\Receiver\FileReceiver;
16
use Pion\Laravel\ChunkUpload\Handler\HandlerFactory;
17
use Pion\Laravel\ChunkUpload\Handler\AbstractHandler;
18
use Pion\Laravel\ChunkUpload\Exceptions\UploadMissingFileException;
19
20
class FileLinksController extends Controller
21
{
22
    //  Only authorized users have access
23
    public function __construct()
24
    {
25
        $this->middleware('auth');
26
    }
27
    
28
    //  Ajax call to show the links for a specific user
29
    public function find($id)
30
    {
31
        $links = FileLinks::where('user_id', $id)
32
            ->withCount('FileLinkFiles')
33
            ->orderBy('expire', 'desc')
34
            ->get();
35
                
36
        //  Reformat the expire field to be a readable date
37
        foreach($links as $link)
38
        {
39
            $link->url        = route('links.details', [$link->link_id, urlencode($link->link_name)]);
40
            $link->showClass  = $link->expire < date('Y-m-d') ? 'table-danger' : '';
41
            $link->expire     = date('M d, Y', strtotime($link->expire));
42
        }
43
        
44
        return response()->json($links);
45
    }
46
    
47
    //  Landing page shows all links that the user owns
48
    public function index()
49
    {
50
        return view('links.index');
51
    }
52
53
    //  Create a new file link form
54
    public function create()
55
    {
56
        return view('links.form.newLink');
57
    }
58
59
    //  Submit the new file link form
60
    public function store(Request $request)
61
    {
62
        $request->validate([
63
            'name'   => 'required', 
64
            'expire' => 'required'
65
        ]);
66
        
67
        if(!empty($request->file))
68
        {            
69
            $receiver = new FileReceiver('file', $request, HandlerFactory::classFromRequest($request));
70
            
71
            //  Verify that the upload is valid and being processed
72
            if($receiver->isUploaded() === false)
73
            {
74
                throw new UploadMissingFileException();
75
            }
76
            
77
            //  Recieve and process the file
78
            $save = $receiver->receive();
79
            
80
            //  See if the uploade has finished
81
            if($save->isFinished())
82
            {
83
                $fileID = $this->saveFile($save->getFile());
0 ignored issues
show
Unused Code introduced by
The assignment to $fileID is dead and can be removed.
Loading history...
84
                
85
                return 'uploaded successfully';
86
            }
87
            
88
            //  Get the current progress
89
            $handler = $save->handler();
90
            
91
            return response()->json([
92
                'done'   => $handler->getPercentageDone(),
93
                'status' => true
94
            ]);
95
        }
96
97
        //  If there are no files being uploaded or the file uploade process is done
98
        if(isset($request->_completed) && $request->_completed)
99
        {            
100
            $linkID = $this->createLink($request);
101
            if($request->session()->has('newLinkFile'))
102
            {
103
                //  If there were files uploaded to the link, process them
104
                $files = session('newLinkFile');
105
                $path = config('filesystems.paths.links').DIRECTORY_SEPARATOR.$linkID;
106
107
                foreach($files as $file)
108
                {
109
                    $data = Files::find($file);
110
                    //  Move the file to the proper folder
111
                    Storage::move($data->file_link.$data->file_name, $path.DIRECTORY_SEPARATOR.$data->file_name);
112
                    //  Update file link in DB
113
                    $data->update([
114
                        'file_link' => $path.DIRECTORY_SEPARATOR
115
                    ]);
116
                    //  Attach file to the link
117
                    FileLinkFiles::create([
118
                        'link_id' => $linkID,
119
                        'file_id' => $data->file_id,
120
                        'user_id' => Auth::user()->user_id,
121
                        'upload' => 0
122
                    ]);
123
                }
124
125
                $request->session()->forget('newLinkFile');
126
            }
127
128
            return response()->json(['link' => $linkID, 'name' => urlencode($request->name)]);
129
        }
130
        
131
        return response()->json(['complete' => false]);
132
    }
133
    
134
    //  Create the new file link
135
    private function createLink($data)
136
    {
137
        //  Generate a random hash to use as the file link and make sure it is not already in use
138
        do
139
        {
140
            $hash = strtolower(Str::random(15));
141
            $dup  = FileLinks::where('link_hash', $hash)->get()->count();
142
        }while($dup != 0);
143
        
144
        //  If the "customer id" field is populated, separate the ID from the name and prepare for insertion.
145
        if($data->customer_tag != null)
146
        {
147
            $custID = explode(' ', $data->customer_tag);
148
            $custID = $custID[0];
149
        }
150
        else
151
        {
152
            $custID = null;
153
        }
154
                
155
        //  Create the new file link
156
        $link = FileLinks::create([
157
            'user_id'      => Auth::user()->user_id,
158
            'cust_id'      => $custID,
159
            'link_hash'    => $hash,
160
            'link_name'    => $data->name,
161
            'expire'       => $data->expire,
162
            'allow_upload' => isset($data->allowUp) && $data->allowUp ? true : false
163
        ]);
164
        
165
        Log::info('File Link Created', ['link_id' => $link->link_id, 'user_id' => Auth::user()->user_id]);
166
        
167
        return $link->link_id;
168
    }
169
    
170
    //  Save a file attached to the link
171
    private function saveFile(UploadedFile $file)
172
    {
173
        $filePath = config('filesystems.paths.links').DIRECTORY_SEPARATOR.'_tmp';
174
        
175
        //  Clean the file and store it
176
        $fileName = Files::cleanFilename($filePath, $file->getClientOriginalName());
177
        $file->storeAs($filePath, $fileName);
178
        
179
        //  Place file in Files table of DB
180
        $newFile = Files::create([
181
            'file_name' => $fileName,
182
            'file_link' => $filePath.DIRECTORY_SEPARATOR
183
        ]);
184
        $fileID = $newFile->file_id;
185
        
186
        //  Save the file ID in the session array
187
        $fileArr = session('newLinkFile') != null ? session('newLinkFile') : [];
188
        $fileArr[] = $fileID;
189
        session(['newLinkFile' => $fileArr]);
190
        
191
        //  Log stored file
192
        Log::info('File Stored', ['file_id' => $fileID, 'file_path' => $filePath.DIRECTORY_SEPARATOR.$fileName]);
193
        
194
        return $fileID;
195
    }
196
197
    //  Show details about a file link
198
    public function details($id, $name)
199
    {
200
        //  Verify that the link is a valid link
201
        $linkData = FileLinks::find($id);
202
        
203
        //  If the link is invalid, return an error page
204
        if(empty($linkData))
205
        {
206
            Log::notice('User tried to view bad file link', ['user_id' => Auth::user()->user_id, 'link_id' => $id]);
207
            return view('links.badLink');
208
        }
209
        
210
        $hasCust = $linkData->cust_id != null ? true : false;
211
        
212
        return view('links.details', [
213
            'link_id' => $id,
214
            'has_cust' => $hasCust
215
        ]);
216
    }
217
    
218
    //  Ajax call te get JSON details of the link
219
    public function show($id)
220
    {
221
        $linkData = FileLinks::where('link_id', $id)->leftJoin('customers', 'file_links.cust_id', '=', 'customers.cust_id')->first();
222
        
223
        //  Format the expiration date to be readable
224
        $linkData->timestamp = $linkData->expire;
0 ignored issues
show
Bug introduced by
The property timestamp does not exist on App\FileLinks. Did you mean timestamps?
Loading history...
225
        $linkData->expire    = date('M d, Y', strtotime($linkData->expire));
226
        
227
        return response()->json($linkData);
228
    }
229
230
    //  Update the link's details
231
    public function update(Request $request, $id)
232
    {
233
        $request->validate([
234
            'name'   => 'required',
235
            'expire' => 'required'
236
        ]);
237
        
238
        FileLinks::find($id)->update([
239
            'link_name'    => $request->name,
240
            'expire'       => $request->expire,
241
            'allow_upload' => isset($request->allowUp) && $request->allowUp ? true : false
242
        ]);
243
        
244
        Log::info('File Link Updated', ['link_id' => $id]);
245
        
246
        return response()->json(['success' => true]);
247
    }
248
    
249
    //  Update the customer that is attached to the customer
250
    public function updateCustomer(Request $request, $id)
251
    {
252
        //  If the "customer id" field is populated, separate the ID from the name and prepare for insertion.
253
        if($request->customer_tag != null && $request->customer_tag != 'NULL')
254
        {
255
            $custID = explode(' ', $request->customer_tag);
256
            $custID = $custID[0];
257
        }
258
        else
259
        {
260
            $custID = null;
261
        }
262
        
263
        FileLinks::find($id)->update([
264
            'cust_id' => $custID
265
        ]);
266
        
267
        return response()->json(['success' => true]);
268
    }
269
270
    //  Delete a file link
271
    public function destroy($id)
272
    {
273
        //  Remove the file from database
274
        $data = FileLinkFiles::where('link_id', $id)->get();
275
        if(!$data->isEmpty())
276
        {
277
            foreach($data as $file)
278
            {
279
                $fileID = $file->file_id;
280
                $file->delete();
281
282
                //  Delete the file if it is no longer in use
283
                Files::deleteFile($fileID);
284
            }
285
        }
286
        
287
        FileLinks::find($id)->delete();
288
        
289
        Log::info('File link deleted', ['link_id' => $id, 'user_id' => Auth::user()->user_id]);
290
        
291
        return response()->json([
292
            'success' => true
293
        ]);
294
    }
295
}
296