Passed
Push — main ( 6aad9e...75935a )
by Julian
03:54
created

searchIcon()   A

Complexity

Conditions 2

Size

Total Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
c 0
b 0
f 0
dl 0
loc 12
rs 9.8666
1
<?php
2
3
namespace App\Http\Controllers;
4
5
use Illuminate\Http\Request;
6
use Illuminate\Support\Facades\Hash;
7
use Cohensive\OEmbed\Facades\OEmbed;
8
use Illuminate\Support\Facades\Schema;
9
use Illuminate\Support\Facades\Route;
10
use Illuminate\Support\Facades\Response;
11
use JeroenDesloovere\VCard\VCard;
12
use Illuminate\Validation\Rule;
13
use Illuminate\Support\Facades\Validator;
14
use Illuminate\Support\Facades\Mail;
15
use App\Mail\ReportSubmissionMail;
16
use GeoSot\EnvEditor\Facades\EnvEditor;
17
18
use Auth;
19
use DB;
20
use ZipArchive;
21
use File;
22
23
use App\Models\User;
24
use App\Models\Button;
25
use App\Models\Link;
26
use App\Models\LinkType;
27
use App\Models\UserData;
28
29
30
//Function tests if string starts with certain string (used to test for illegal strings)
31
function stringStartsWith($haystack, $needle, $case = true)
32
{
33
    if ($case) {
34
        return strpos($haystack, $needle, 0) === 0;
35
    }
36
    return stripos($haystack, $needle, 0) === 0;
37
}
38
39
//Function tests if string ends with certain string (used to test for illegal strings)
40
function stringEndsWith($haystack, $needle, $case = true)
41
{
42
    $expectedPosition = strlen($haystack) - strlen($needle);
43
    if ($case) {
44
        return strrpos($haystack, $needle, 0) === $expectedPosition;
45
    }
46
    return strripos($haystack, $needle, 0) === $expectedPosition;
47
}
48
49
class UserController extends Controller
50
{
51
52
    //Statistics of the number of clicks and links
53
    public function index()
54
    {
55
        $userId = Auth::user()->id;
0 ignored issues
show
Bug introduced by
Accessing id on the interface Illuminate\Contracts\Auth\Authenticatable suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
56
57
        $littlelink_name = Auth::user()->littlelink_name;
0 ignored issues
show
Bug introduced by
Accessing littlelink_name on the interface Illuminate\Contracts\Auth\Authenticatable suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
58
        $userinfo = User::find($userId);
59
60
        $links = Link::where('user_id', $userId)->select('link')->count();
61
        $clicks = Link::where('user_id', $userId)->sum('click_number');
62
        $topLinks = Link::where('user_id', $userId)->orderby('click_number', 'desc')
63
            ->whereNotNull('link')->where('link', '<>', '')
64
            ->take(5)->get();
65
66
        $pageStats = [
67
            'visitors' => [
68
                'all' => visits('App\Models\User', $littlelink_name)->count(),
69
                'day' => visits('App\Models\User', $littlelink_name)->period('day')->count(),
70
                'week' => visits('App\Models\User', $littlelink_name)->period('week')->count(),
71
                'month' => visits('App\Models\User', $littlelink_name)->period('month')->count(),
72
                'year' => visits('App\Models\User', $littlelink_name)->period('year')->count(),
73
            ],
74
            'os' => visits('App\Models\User', $littlelink_name)->operatingSystems(),
75
            'referers' => visits('App\Models\User', $littlelink_name)->refs(),
76
            'countries' => visits('App\Models\User', $littlelink_name)->countries(),
77
        ];
78
79
80
81
        return view('studio/index', ['greeting' => $userinfo->name, 'toplinks' => $topLinks, 'links' => $links, 'clicks' => $clicks, 'pageStats' => $pageStats]);
82
    }
83
84
    //Show littlelink page. example => http://127.0.0.1:8000/+admin
85
    public function littlelink(request $request)
86
    {
87
        if(isset($request->useif)){
88
            $littlelink_name = User::select('littlelink_name')->where('id', $request->littlelink)->value('littlelink_name');
89
            $id = $request->littlelink;
90
        } else {
91
            $littlelink_name = $request->littlelink;
92
            $id = User::select('id')->where('littlelink_name', $littlelink_name)->value('id');
93
        }
94
95
        if (empty($id)) {
96
            return abort(404);
0 ignored issues
show
Bug introduced by
Are you sure the usage of abort(404) 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...
97
        }
98
     
99
        $userinfo = User::select('id', 'name', 'littlelink_name', 'littlelink_description', 'theme', 'role', 'block')->where('id', $id)->first();
100
        $information = User::select('name', 'littlelink_name', 'littlelink_description', 'theme')->where('id', $id)->get();
101
        
102
        if ($userinfo->block == 'yes') {
0 ignored issues
show
Bug introduced by
The property block does not seem to exist on Illuminate\Database\Eloq...Relations\HasOneThrough.
Loading history...
Bug introduced by
The property block does not seem to exist on Illuminate\Database\Eloq...elations\HasManyThrough.
Loading history...
103
            return abort(404);
0 ignored issues
show
Bug introduced by
Are you sure the usage of abort(404) 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...
104
        }
105
        
106
        $links = DB::table('links')->join('buttons', 'buttons.id', '=', 'links.button_id')->select('links.link', 'links.id', 'links.button_id', 'links.title', 'links.custom_css', 'links.custom_icon', 'buttons.name')->where('user_id', $id)->orderBy('up_link', 'asc')->orderBy('order', 'asc')->get();
107
108
        return view('linkstack.linkstack', ['userinfo' => $userinfo, 'information' => $information, 'links' => $links, 'littlelink_name' => $littlelink_name]);
109
    }
110
111
    //Show littlelink page as home page if set in config
112
    public function littlelinkhome(request $request)
0 ignored issues
show
Unused Code introduced by
The parameter $request 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

112
    public function littlelinkhome(/** @scrutinizer ignore-unused */ request $request)

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...
113
    {
114
        $littlelink_name = env('HOME_URL');
115
        $id = User::select('id')->where('littlelink_name', $littlelink_name)->value('id');
116
117
        if (empty($id)) {
118
            return abort(404);
0 ignored issues
show
Bug introduced by
Are you sure the usage of abort(404) 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...
119
        }
120
     
121
        $userinfo = User::select('id', 'name', 'littlelink_name', 'littlelink_description', 'theme', 'role', 'block')->where('id', $id)->first();
122
        $information = User::select('name', 'littlelink_name', 'littlelink_description', 'theme')->where('id', $id)->get();
123
        
124
        $links = DB::table('links')->join('buttons', 'buttons.id', '=', 'links.button_id')->select('links.link', 'links.id', 'links.button_id', 'links.title', 'links.custom_css', 'links.custom_icon', 'buttons.name')->where('user_id', $id)->orderBy('up_link', 'asc')->orderBy('order', 'asc')->get();
125
126
        return view('linkstack.linkstack', ['userinfo' => $userinfo, 'information' => $information, 'links' => $links, 'littlelink_name' => $littlelink_name]);
127
    }
128
129
    //Redirect to user page
130
    public function userRedirect(request $request)
131
    {
132
        $id = $request->id;
133
        $user = User::select('littlelink_name')->where('id', $id)->value('littlelink_name');
134
135
        if (empty($id)) {
136
            return abort(404);
0 ignored issues
show
Bug introduced by
Are you sure the usage of abort(404) 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...
137
        }
138
     
139
        if (empty($user)) {
140
            return abort(404);
0 ignored issues
show
Bug introduced by
Are you sure the usage of abort(404) 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...
141
        }
142
143
        return redirect(url('@'.$user));
144
    }
145
146
    //Show add/update form
147
    public function AddUpdateLink($id = 0)
148
    {
149
150
        if ($id !== 0) {
151
            $linkData = Link::find($id);
152
        } elseif ($id == 0) {
153
            $linkData = new Link(['typename' => 'link', 'id'=>'0']);
154
        } else {
155
            $linkData = new Link(['typename' => 'link', 'id'=>'0']);
156
        }
157
        $data['LinkTypes'] = LinkType::get();
0 ignored issues
show
Comprehensibility Best Practice introduced by
$data was never initialized. Although not strictly required by PHP, it is generally a good practice to add $data = array(); before regardless.
Loading history...
158
        $data['LinkData'] = $linkData;
159
        $data['LinkID'] = $id;
160
        $data['linkTypeID'] = "1";
161
        $data['title'] = "Predefined Site";
162
163
        if (Route::currentRouteName() != 'showButtons') {
164
            $links = DB::table('links')->where('id', $id)->first();
165
166
            $bid = $links->button_id;
167
168
            if($bid == 1 or $bid == 2){
169
                $data['linkTypeID'] = "2";
170
            } elseif ($bid == 42) {
171
                $data['linkTypeID'] = "3";
172
            } elseif ($bid == 43) {
173
                $data['linkTypeID'] = "4";
174
            } elseif ($bid == 93) {
175
                $data['linkTypeID'] = "5";
176
            } elseif ($bid == 6 or $bid == 7) {
177
                $data['linkTypeID'] = "6";
178
            } elseif ($bid == 44) {
179
                $data['linkTypeID'] = "7";
180
            } elseif ($bid == 96) {
181
                $data['linkTypeID'] = "8";
182
            } else {
183
                $data['linkTypeID'] = "1";
184
            }
185
186
            $data['title'] = LinkType::where('id', $data['linkTypeID'])->value('title');
187
        }
188
189
        foreach ($data['LinkTypes']->toArray() as $key => $val) {
190
            if ($val['typename'] === $linkData['typename']) {
191
                $data['SelectedLinkType'] = $val;
192
                break;
193
            }
194
        }
195
        
196
        return view('studio/edit-link', $data);
197
    }
198
199
    //Save add link
200
    public function saveLink(request $request)
201
    {
202
        $request->validate([
203
            'link' => 'sometimes|url',
204
        ]);
205
206
        $linkType = LinkType::find($request->linktype_id);
207
        $LinkTitle = ($request->link_text ?? $request->link_title) ?? $request->title;
208
        $LinkURL = $request->link_url ?? $request->link;
209
210
        $OrigLink = Link::find($request->linkid);
211
212
        $customParams = [];
213
        foreach ($request->all() as $key => $param) {
214
            //echo $key . " = " . $param . "<br />";
215
            if (str_starts_with($key, "_") ||  in_array($key, ['linktype_id', 'linktype_title', 'link_text', 'link_url']))
216
                continue;
217
218
            $customParams[$key] = $param;
219
        }
220
221
        $userId = Auth::user()->id;
0 ignored issues
show
Bug introduced by
Accessing id on the interface Illuminate\Contracts\Auth\Authenticatable suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
222
        $button = Button::where('name', $request->button)->first();
223
224
        if ($button && empty($LinkTitle))
225
            $LinkTitle = $button->alt;
226
227
        if ($linkType->typename == 'video' && empty($LinkTitle)) {
228
            $embed = OEmbed::get($LinkURL);
229
            if ($embed) {
230
                $LinkTitle = $embed->data()['title'];
231
            }
232
        }
233
234
        $message = (ucwords($button?->name) ?? ucwords($linkType->typename)). " has been ";
235
236
        if ($OrigLink) {
237
            //EDITING EXISTING
238
239
            $isCustomWebsite = $customParams['GetSiteIcon'] ?? null;
240
            $SpacerHeight = $customParams['height'] ?? null;
0 ignored issues
show
Unused Code introduced by
The assignment to $SpacerHeight is dead and can be removed.
Loading history...
241
242
                if($linkType->typename == "link" and $isCustomWebsite == "1"){
243
                    $OrigLink->update([
244
                        'link' => $LinkURL,
245
                        'title' => $LinkTitle,
246
                        'button_id' => "2",
247
                    ]);
248
                }elseif($linkType->typename == "link"){
249
                    $OrigLink->update([
250
                        'link' => $LinkURL,
251
                        'title' => $LinkTitle,
252
                        'button_id' => "1",
253
                    ]);
254
                }elseif($linkType->typename == "spacer"){
255
                    $OrigLink->update([
256
                        'link' => $LinkURL,
257
                        'title' => $customParams['height'] ?? null,
258
                        'button_id' => "43",
259
                    ]);
260
                }elseif($linkType->typename == "heading"){
261
                    $OrigLink->update([
262
                        'link' => $LinkURL,
263
                        'title' => $LinkTitle,
264
                        'button_id' => "42",
265
                    ]);
266
                }elseif($linkType->typename == "text"){
267
                    $OrigLink->update([
268
                        'button_id' => "93",
269
                        'title' => $request->text,
270
                    ]);
271
                }elseif($linkType->typename == "email"){
272
                    $LinkURL = "mailto:".$LinkURL;
273
                    $OrigLink->update([
274
                        'link' => $LinkURL,
275
                        'button_id' => $button?->id,
276
                        'title' => $LinkTitle,
277
                    ]);
278
                }elseif($linkType->typename == "telephone"){
279
                    $LinkURL = "tel:".$LinkURL;
280
                    $OrigLink->update([
281
                        'link' => $LinkURL,
282
                        'button_id' => $button?->id,
283
                        'title' => $LinkTitle,
284
                    ]);
285
                }elseif($linkType->typename == "vcard"){
286
287
                    $prefix = $request->input('prefix');
0 ignored issues
show
Unused Code introduced by
The assignment to $prefix is dead and can be removed.
Loading history...
288
                    $firstName = $request->input('first_name');
0 ignored issues
show
Unused Code introduced by
The assignment to $firstName is dead and can be removed.
Loading history...
289
                    $middleName = $request->input('middle_name');
0 ignored issues
show
Unused Code introduced by
The assignment to $middleName is dead and can be removed.
Loading history...
290
                    $lastName = $request->input('last_name');
0 ignored issues
show
Unused Code introduced by
The assignment to $lastName is dead and can be removed.
Loading history...
291
                    $suffix = $request->input('suffix');
0 ignored issues
show
Unused Code introduced by
The assignment to $suffix is dead and can be removed.
Loading history...
292
                    $nickname = $request->input('nickname');
0 ignored issues
show
Unused Code introduced by
The assignment to $nickname is dead and can be removed.
Loading history...
293
                    $organization = $request->input('organization');
0 ignored issues
show
Unused Code introduced by
The assignment to $organization is dead and can be removed.
Loading history...
294
                    $vtitle = $request->input('vtitle');
0 ignored issues
show
Unused Code introduced by
The assignment to $vtitle is dead and can be removed.
Loading history...
295
                    $role = $request->input('role');
0 ignored issues
show
Unused Code introduced by
The assignment to $role is dead and can be removed.
Loading history...
296
                    $workUrl = $request->input('work_url');
0 ignored issues
show
Unused Code introduced by
The assignment to $workUrl is dead and can be removed.
Loading history...
297
                    $email = $request->input('email');
0 ignored issues
show
Unused Code introduced by
The assignment to $email is dead and can be removed.
Loading history...
298
                    $workEmail = $request->input('work_email');
0 ignored issues
show
Unused Code introduced by
The assignment to $workEmail is dead and can be removed.
Loading history...
299
                    $homePhone = $request->input('home_phone');
0 ignored issues
show
Unused Code introduced by
The assignment to $homePhone is dead and can be removed.
Loading history...
300
                    $workPhone = $request->input('work_phone');
0 ignored issues
show
Unused Code introduced by
The assignment to $workPhone is dead and can be removed.
Loading history...
301
                    $cellPhone = $request->input('cell_phone');
0 ignored issues
show
Unused Code introduced by
The assignment to $cellPhone is dead and can be removed.
Loading history...
302
                    $homeAddressLabel = $request->input('home_address_label');
0 ignored issues
show
Unused Code introduced by
The assignment to $homeAddressLabel is dead and can be removed.
Loading history...
303
                    $homeAddressStreet = $request->input('home_address_street');
0 ignored issues
show
Unused Code introduced by
The assignment to $homeAddressStreet is dead and can be removed.
Loading history...
304
                    $homeAddressCity = $request->input('home_address_city');
0 ignored issues
show
Unused Code introduced by
The assignment to $homeAddressCity is dead and can be removed.
Loading history...
305
                    $homeAddressState = $request->input('home_address_state');
0 ignored issues
show
Unused Code introduced by
The assignment to $homeAddressState is dead and can be removed.
Loading history...
306
                    $homeAddressZip = $request->input('home_address_zip');
0 ignored issues
show
Unused Code introduced by
The assignment to $homeAddressZip is dead and can be removed.
Loading history...
307
                    $homeAddressCountry = $request->input('home_address_country');
0 ignored issues
show
Unused Code introduced by
The assignment to $homeAddressCountry is dead and can be removed.
Loading history...
308
                    $workAddressLabel = $request->input('work_address_label');
0 ignored issues
show
Unused Code introduced by
The assignment to $workAddressLabel is dead and can be removed.
Loading history...
309
                    $workAddressStreet = $request->input('work_address_street');
0 ignored issues
show
Unused Code introduced by
The assignment to $workAddressStreet is dead and can be removed.
Loading history...
310
                    $workAddressCity = $request->input('work_address_city');
0 ignored issues
show
Unused Code introduced by
The assignment to $workAddressCity is dead and can be removed.
Loading history...
311
                    $workAddressState = $request->input('work_address_state');
0 ignored issues
show
Unused Code introduced by
The assignment to $workAddressState is dead and can be removed.
Loading history...
312
                    $workAddressZip = $request->input('work_address_zip');
0 ignored issues
show
Unused Code introduced by
The assignment to $workAddressZip is dead and can be removed.
Loading history...
313
                    $workAddressCountry = $request->input('work_address_country');
0 ignored issues
show
Unused Code introduced by
The assignment to $workAddressCountry is dead and can be removed.
Loading history...
314
    
315
                    // Create an array with all the input fields
316
                    $data = [
317
                        'prefix' => $request->input('prefix'),
318
                        'first_name' => $request->input('first_name'),
319
                        'middle_name' => $request->input('middle_name'),
320
                        'last_name' => $request->input('last_name'),
321
                        'suffix' => $request->input('suffix'),
322
                        'nickname' => $request->input('nickname'),
323
                        'organization' => $request->input('organization'),
324
                        'vtitle' => $request->input('vtitle'),
325
                        'role' => $request->input('role'),
326
                        'work_url' => $request->input('work_url'),
327
                        'email' => $request->input('email'),
328
                        'work_email' => $request->input('work_email'),
329
                        'home_phone' => $request->input('home_phone'),
330
                        'work_phone' => $request->input('work_phone'),
331
                        'cell_phone' => $request->input('cell_phone'),
332
                        'home_address_label' => $request->input('home_address_label'),
333
                        'home_address_street' => $request->input('home_address_street'),
334
                        'home_address_city' => $request->input('home_address_city'),
335
                        'home_address_state' => $request->input('home_address_state'),
336
                        'home_address_zip' => $request->input('home_address_zip'),
337
                        'home_address_country' => $request->input('home_address_country'),
338
                        'work_address_label' => $request->input('work_address_label'),
339
                        'work_address_street' => $request->input('work_address_street'),
340
                        'work_address_city' => $request->input('work_address_city'),
341
                        'work_address_state' => $request->input('work_address_state'),
342
                        'work_address_zip' => $request->input('work_address_zip'),
343
                        'work_address_country' => $request->input('work_address_country'),
344
                    ];
345
                    
346
                    // Convert the array to JSON format
347
                    $json = json_encode($data);
348
                    
349
                    // Set the JSON as the variable $links->link, or null if the JSON is empty
350
                    $LinkURL = $json ? $json : null;        
351
352
                    $OrigLink->update([
353
                        'link' => $LinkURL,
354
                        'button_id' => 96,
355
                        'title' => $LinkTitle,
356
                    ]);
357
                }else{
358
                    $OrigLink->update([
359
                        'link' => $LinkURL,
360
                        'title' => $LinkTitle,
361
                        'button_id' => $button?->id,
362
                    ]);
363
                }
364
                
365
            $message .="updated";
366
367
        } else {
368
            // ADDING NEW
369
370
            $isCustomWebsite = $customParams['GetSiteIcon'] ?? null;
371
            $SpacerHeight = $customParams['height'] ?? null;
372
            
373
            $links = new Link;
374
            $links->link = $LinkURL;
375
            $links->user_id = $userId;
376
            if($linkType->typename == "spacer"){
377
            $links->title = $SpacerHeight;
378
            }else{
379
            $links->title = $LinkTitle;
380
            }
381
            if($linkType->typename == "link" and $isCustomWebsite == "1"){
382
                $links->button_id = "2";
383
            }elseif($linkType->typename == "link"){
384
                $links->button_id = "1";
385
            }elseif($linkType->typename == "spacer"){
386
                $links->button_id = "43";
387
            }elseif($linkType->typename == "heading"){
388
                $links->button_id = "42";
389
            }elseif($linkType->typename == "text"){
390
                $links->button_id = "93";
391
                $links->title = $request->text;
392
            }elseif($linkType->typename == "email"){
393
                $links->link = "mailto:".$links->link;
394
                $links->button_id = $button?->id;
395
            }elseif($linkType->typename == "telephone"){
396
                $links->link = "tel:".$links->link;
397
                $links->button_id = $button?->id;
398
            }elseif($linkType->typename == "vcard"){
399
400
                $prefix = $request->input('prefix');
401
                $firstName = $request->input('first_name');
402
                $middleName = $request->input('middle_name');
403
                $lastName = $request->input('last_name');
404
                $suffix = $request->input('suffix');
405
                $nickname = $request->input('nickname');
406
                $organization = $request->input('organization');
407
                $vtitle = $request->input('vtitle');
408
                $role = $request->input('role');
409
                $workUrl = $request->input('work_url');
410
                $email = $request->input('email');
411
                $workEmail = $request->input('work_email');
412
                $homePhone = $request->input('home_phone');
413
                $workPhone = $request->input('work_phone');
414
                $cellPhone = $request->input('cell_phone');
415
                $homeAddressLabel = $request->input('home_address_label');
416
                $homeAddressStreet = $request->input('home_address_street');
417
                $homeAddressCity = $request->input('home_address_city');
418
                $homeAddressState = $request->input('home_address_state');
419
                $homeAddressZip = $request->input('home_address_zip');
420
                $homeAddressCountry = $request->input('home_address_country');
421
                $workAddressLabel = $request->input('work_address_label');
422
                $workAddressStreet = $request->input('work_address_street');
423
                $workAddressCity = $request->input('work_address_city');
424
                $workAddressState = $request->input('work_address_state');
425
                $workAddressZip = $request->input('work_address_zip');
426
                $workAddressCountry = $request->input('work_address_country');
427
428
                // Create an array with all the input fields
429
                $data = [
430
                    'prefix' => $request->input('prefix'),
431
                    'first_name' => $request->input('first_name'),
432
                    'middle_name' => $request->input('middle_name'),
433
                    'last_name' => $request->input('last_name'),
434
                    'suffix' => $request->input('suffix'),
435
                    'nickname' => $request->input('nickname'),
436
                    'organization' => $request->input('organization'),
437
                    'vtitle' => $request->input('vtitle'),
438
                    'role' => $request->input('role'),
439
                    'work_url' => $request->input('work_url'),
440
                    'email' => $request->input('email'),
441
                    'work_email' => $request->input('work_email'),
442
                    'home_phone' => $request->input('home_phone'),
443
                    'work_phone' => $request->input('work_phone'),
444
                    'cell_phone' => $request->input('cell_phone'),
445
                    'home_address_label' => $request->input('home_address_label'),
446
                    'home_address_street' => $request->input('home_address_street'),
447
                    'home_address_city' => $request->input('home_address_city'),
448
                    'home_address_state' => $request->input('home_address_state'),
449
                    'home_address_zip' => $request->input('home_address_zip'),
450
                    'home_address_country' => $request->input('home_address_country'),
451
                    'work_address_label' => $request->input('work_address_label'),
452
                    'work_address_street' => $request->input('work_address_street'),
453
                    'work_address_city' => $request->input('work_address_city'),
454
                    'work_address_state' => $request->input('work_address_state'),
455
                    'work_address_zip' => $request->input('work_address_zip'),
456
                    'work_address_country' => $request->input('work_address_country'),
457
                ];
458
                
459
                // Convert the array to JSON format
460
                $json = json_encode($data);
461
                
462
                // Set the JSON as the variable $links->link, or null if the JSON is empty
463
                $links->link = $json ? $json : null;               
464
465
                $links->button_id = 96;
466
            }else{
467
                $links->button_id = $button?->id;
468
            }
469
470
            if(empty($links->button_id)) {
471
                return redirect(route('showButtons')); die;
0 ignored issues
show
Unused Code introduced by
ExitNode is not reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
472
            }
473
            
474
            $links->save();
475
476
            $links->order = ($links->id - 1);
477
            $links->save();
478
            $message .= "added";
479
        }
480
481
            if ($request->input('param') == 'add_more') {
482
                return Redirect('studio/add-link')
483
                ->with('success', $message);
484
            } else {
485
                return Redirect('studio/links')
486
                ->with('success', $message);
487
            }
488
489
    }
490
491
    public function sortLinks(Request $request)
492
    {
493
        $linkOrders  = $request->input("linkOrders", []);
494
        $currentPage = $request->input("currentPage", 1);
495
        $perPage     = $request->input("perPage", 0);
496
497
        if ($perPage == 0) {
498
            $currentPage = 1;
499
        }
500
501
        $linkOrders = array_unique(array_filter($linkOrders));
502
        if (!$linkOrders || $currentPage < 1) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $linkOrders of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
503
            return response()->json([
504
                'status' => 'ERROR',
505
            ]);
506
        }
507
508
        $newOrder = $perPage * ($currentPage - 1);
509
        $linkNewOrders = [];
510
        foreach ($linkOrders as $linkId) {
511
            if ($linkId < 0) {
512
                continue;
513
            }
514
515
            $linkNewOrders[$linkId] = $newOrder;
516
            Link::where("id", $linkId)
517
                ->update([
518
                    'order' => $newOrder
519
                ]);
520
            $newOrder++;
521
        }
522
523
        return response()->json([
524
            'status' => 'OK',
525
            'linkOrders' => $linkNewOrders,
526
        ]);
527
    }
528
529
530
    //Count the number of clicks and redirect to link
531
    public function clickNumber(request $request)
532
    {
533
        $linkId = $request->id;
534
535
        if (substr($linkId, -1) == '+') {
536
            $linkWithoutPlus = str_replace('+', '', $linkId);
537
            return redirect(url('info/'.$linkWithoutPlus));
538
        }
539
    
540
        $link = Link::find($linkId);
541
542
        if (empty($link)) {
543
            return abort(404);
0 ignored issues
show
Bug introduced by
Are you sure the usage of abort(404) 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...
544
        }
545
546
        $link = $link->link;
547
548
        if (empty($linkId)) {
549
            return abort(404);
0 ignored issues
show
Bug introduced by
Are you sure the usage of abort(404) 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...
550
        }
551
552
        Link::where('id', $linkId)->increment('click_number', 1);
553
554
        $response = redirect()->away($link);
555
        $response->header('X-Robots-Tag', 'noindex, nofollow');
556
557
        return $response;
558
    }
559
560
    //Download Vcard
561
    public function vcard(request $request)
562
    {
563
        $linkId = $request->id;
564
565
        // Find the link with the specified ID
566
        $link = Link::findOrFail($linkId);
567
568
        $json = $link->link;
569
570
        // Decode the JSON to a PHP array
571
        $data = json_decode($json, true);
572
        
573
        // Create a new vCard object
574
        $vcard = new VCard();
575
        
576
        // Set the vCard properties from the $data array
577
        $vcard->addName($data['last_name'], $data['first_name'], $data['middle_name'], $data['prefix'], $data['suffix']);
578
        $vcard->addCompany($data['organization']);
579
        $vcard->addJobtitle($data['vtitle']);
580
        $vcard->addRole($data['role']);
581
        $vcard->addEmail($data['email']);
582
        $vcard->addEmail($data['work_email'], 'WORK');
583
        $vcard->addURL($data['work_url'], 'WORK');
584
        $vcard->addPhoneNumber($data['home_phone'], 'HOME');
585
        $vcard->addPhoneNumber($data['work_phone'], 'WORK');
586
        $vcard->addPhoneNumber($data['cell_phone'], 'CELL');
587
        $vcard->addAddress($data['home_address_street'], '', $data['home_address_city'], $data['home_address_state'], $data['home_address_zip'], $data['home_address_country'], 'HOME');
588
        $vcard->addAddress($data['work_address_street'], '', $data['work_address_city'], $data['work_address_state'], $data['work_address_zip'], $data['work_address_country'], 'WORK');
589
        
590
591
        // $vcard->addPhoto(base_path('img/1.png'));
592
        
593
        // Generate the vCard file contents
594
        $file_contents = $vcard->getOutput();
595
        
596
        // Set the file headers for download
597
        $headers = [
598
            'Content-Type' => 'text/x-vcard',
599
            'Content-Disposition' => 'attachment; filename="contact.vcf"'
600
        ];
601
        
602
        Link::where('id', $linkId)->increment('click_number', 1);
603
604
        // Return the file download response
605
        return response()->make($file_contents, 200, $headers);
606
607
    }
608
609
    //Show link, click number, up link in links page
610
    public function showLinks()
611
    {
612
        $userId = Auth::user()->id;
0 ignored issues
show
Bug introduced by
Accessing id on the interface Illuminate\Contracts\Auth\Authenticatable suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
613
        $data['pagePage'] = 10;
0 ignored issues
show
Comprehensibility Best Practice introduced by
$data was never initialized. Although not strictly required by PHP, it is generally a good practice to add $data = array(); before regardless.
Loading history...
614
        
615
        $data['links'] = Link::select('id', 'link', 'title', 'order', 'click_number', 'up_link', 'links.button_id')->where('user_id', $userId)->orderBy('up_link', 'asc')->orderBy('order', 'asc')->paginate(99999);
616
        return view('studio/links', $data);
617
    }
618
619
    //Delete link
620
    public function deleteLink(request $request)
621
    {
622
        $linkId = $request->id;
623
624
        Link::where('id', $linkId)->delete();
625
626
        $directory = base_path("assets/favicon/icons");
627
        $files = scandir($directory);
628
        foreach($files as $file) {
629
        if (strpos($file, $linkId.".") !== false) {
630
        $pathinfo = pathinfo($file, PATHINFO_EXTENSION);}}
631
        if (isset($pathinfo)) {
632
        try{File::delete(base_path("assets/favicon/icons")."/".$linkId.".".$pathinfo);} catch (exception $e) {}
0 ignored issues
show
introduced by
Consider moving this CATCH statement to a new line.
Loading history...
Bug introduced by
The type App\Http\Controllers\exception was not found. Did you mean exception? If so, make sure to prefix the type with \.
Loading history...
633
        }
634
635
        return redirect('/studio/links');
636
    }
637
638
    //Delete icon
639
    public function clearIcon(request $request)
640
    {
641
        $linkId = $request->id;
642
643
        $directory = base_path("assets/favicon/icons");
644
        $files = scandir($directory);
645
        foreach($files as $file) {
646
        if (strpos($file, $linkId.".") !== false) {
647
        $pathinfo = pathinfo($file, PATHINFO_EXTENSION);}}
648
        if (isset($pathinfo)) {
649
        try{File::delete(base_path("assets/favicon/icons")."/".$linkId.".".$pathinfo);} catch (exception $e) {}
0 ignored issues
show
introduced by
Consider moving this CATCH statement to a new line.
Loading history...
650
        }
651
652
        return redirect('/studio/links');
653
    }
654
655
    //Raise link on the littlelink page
656
    public function upLink(request $request)
657
    {
658
        $linkId = $request->id;
659
        $upLink = $request->up;
660
661
        if ($upLink == 'yes') {
662
            $up = 'no';
663
        } elseif ($upLink == 'no') {
664
            $up = 'yes';
665
        }
666
667
        Link::where('id', $linkId)->update(['up_link' => $up]);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $up does not seem to be defined for all execution paths leading up to this point.
Loading history...
668
669
        return back();
670
    }
671
672
    //Show link to edit
673
    public function showLink(request $request)
674
    {
675
        $linkId = $request->id;
676
677
        $link = Link::where('id', $linkId)->value('link');
678
        $title = Link::where('id', $linkId)->value('title');
679
        $order = Link::where('id', $linkId)->value('order');
680
        $custom_css = Link::where('id', $linkId)->value('custom_css');
681
        $buttonId = Link::where('id', $linkId)->value('button_id');
682
        $buttonName = Button::where('id', $buttonId)->value('name');
683
684
        $buttons = Button::select('id', 'name')->orderBy('name', 'asc')->get();
685
686
        return view('studio/edit-link', ['custom_css' => $custom_css, 'buttonId' => $buttonId, 'buttons' => $buttons, 'link' => $link, 'title' => $title, 'order' => $order, 'id' => $linkId, 'buttonName' => $buttonName]);
687
    }
688
689
    //Show custom CSS + custom icon
690
    public function showCSS(request $request)
691
    {
692
        $linkId = $request->id;
693
694
        $link = Link::where('id', $linkId)->value('link');
695
        $title = Link::where('id', $linkId)->value('title');
696
        $order = Link::where('id', $linkId)->value('order');
697
        $custom_css = Link::where('id', $linkId)->value('custom_css');
698
        $custom_icon = Link::where('id', $linkId)->value('custom_icon');
699
        $buttonId = Link::where('id', $linkId)->value('button_id');
700
701
        $buttons = Button::select('id', 'name')->get();
702
703
        return view('studio/button-editor', ['custom_icon' => $custom_icon, 'custom_css' => $custom_css, 'buttonId' => $buttonId, 'buttons' => $buttons, 'link' => $link, 'title' => $title, 'order' => $order, 'id' => $linkId]);
704
    }
705
706
    //Save edit link
707
    public function editLink(request $request)
708
    {
709
        $request->validate([
710
            'link' => 'required|url',
711
            'title' => 'required',
712
            'button' => 'required',
713
        ]);
714
715
        if (stringStartsWith($request->link, 'http://') == 'true' or stringStartsWith($request->link, 'https://') == 'true' or stringStartsWith($request->link, 'mailto:') == 'true')
716
            $link1 = $request->link;
717
        else
718
            $link1 = 'https://' . $request->link;
719
        if (stringEndsWith($request->link, '/') == 'true')
720
            $link = rtrim($link1, "/ ");
721
        else
722
        $link = $link1;
723
        $title = $request->title;
724
        $order = $request->order;
725
        $button = $request->button;
726
        $linkId = $request->id;
727
728
        $buttonId = Button::select('id')->where('name', $button)->value('id');
729
730
        Link::where('id', $linkId)->update(['link' => $link, 'title' => $title, 'order' => $order, 'button_id' => $buttonId]);
731
732
        return redirect('/studio/links');
733
    }
734
735
    //Save edit custom CSS + custom icon
736
    public function editCSS(request $request)
737
    {
738
        $linkId = $request->id;
739
        $custom_icon = $request->custom_icon;
740
        $custom_css = $request->custom_css;
741
742
        if ($request->custom_css == "" and $request->custom_icon = !"") {
0 ignored issues
show
Bug introduced by
The property custom_icon does not seem to exist on Illuminate\Http\Request.
Loading history...
743
            Link::where('id', $linkId)->update(['custom_icon' => $custom_icon]);
744
        } elseif ($request->custom_icon == "" and $request->custom_css = !"") {
0 ignored issues
show
Bug introduced by
The property custom_css does not seem to exist on Illuminate\Http\Request.
Loading history...
745
            Link::where('id', $linkId)->update(['custom_css' => $custom_css]);
746
        } else {
747
            Link::where('id', $linkId)->update([]);
748
        }
749
        return Redirect('#result');
750
    }
751
752
    //Show littlelinke page for edit
753
    public function showPage(request $request)
0 ignored issues
show
Unused Code introduced by
The parameter $request 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

753
    public function showPage(/** @scrutinizer ignore-unused */ request $request)

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...
754
    {
755
        $userId = Auth::user()->id;
0 ignored issues
show
Bug introduced by
Accessing id on the interface Illuminate\Contracts\Auth\Authenticatable suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
756
757
        $data['pages'] = User::where('id', $userId)->select('littlelink_name', 'littlelink_description', 'image', 'name')->get();
0 ignored issues
show
Comprehensibility Best Practice introduced by
$data was never initialized. Although not strictly required by PHP, it is generally a good practice to add $data = array(); before regardless.
Loading history...
758
759
        return view('/studio/page', $data);
760
    }
761
762
    //Save littlelink page (name, description, logo)
763
    public function editPage(Request $request)
764
    {
765
        $userId = Auth::user()->id;
0 ignored issues
show
Bug introduced by
Accessing id on the interface Illuminate\Contracts\Auth\Authenticatable suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
766
        $littlelink_name = Auth::user()->littlelink_name;
0 ignored issues
show
Bug introduced by
Accessing littlelink_name on the interface Illuminate\Contracts\Auth\Authenticatable suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
767
    
768
        $validator = Validator::make($request->all(), [
769
            'littlelink_name' => [
770
                'sometimes',
771
                'max:255',
772
                'string',
773
                'isunique:users,id,'.$userId,
774
            ],
775
            'name' => 'sometimes|max:255|string',
776
            'image' => 'sometimes|image|mimes:jpeg,jpg,png,webp|max:2048', // Max file size: 2MB
777
        ], [
778
            'littlelink_name.unique' => __('messages.That handle has already been taken'),
779
            'image.image' => __('messages.The selected file must be an image'),
780
            'image.mimes' => __('messages.The image must be') . ' JPEG, JPG, PNG, webP.',
781
            'image.max' => __('messages.The image size should not exceed 2MB'),
782
        ]);
783
    
784
        if ($validator->fails()) {
785
            return redirect('/studio/page')->withErrors($validator)->withInput();
786
        }
787
    
788
        $profilePhoto = $request->file('image');
789
        $pageName = $request->littlelink_name;
790
        $pageDescription = strip_tags($request->pageDescription, '<a><p><strong><i><ul><ol><li><blockquote><h2><h3><h4>');
791
        $pageDescription = preg_replace("/<a([^>]*)>/i", "<a $1 rel=\"noopener noreferrer nofollow\">", $pageDescription);
792
        $name = $request->name;
793
        $checkmark = $request->checkmark;
794
        $sharebtn = $request->sharebtn;
795
        $tablinks = $request->tablinks;
796
797
        if(env('HOME_URL') !== '' && $pageName != $littlelink_name && $littlelink_name == env('HOME_URL')){
798
            EnvEditor::editKey('HOME_URL', $pageName);
799
        }
800
    
801
        User::where('id', $userId)->update([
802
            'littlelink_name' => $pageName,
803
            'littlelink_description' => $pageDescription,
804
            'name' => $name
805
        ]);
806
    
807
        if ($request->hasFile('image')) {
808
            $fileName = $userId . '_' . time() . "." . $profilePhoto->extension();
809
            $profilePhoto->move(base_path('assets/img'), $fileName);
810
        }
811
    
812
        if ($checkmark == "on") {
813
            UserData::saveData($userId, 'checkmark', true);
814
        } else {
815
            UserData::saveData($userId, 'checkmark', false);
816
        }
817
    
818
        if ($sharebtn == "on") {
819
            UserData::saveData($userId, 'disable-sharebtn', false);
820
        } else {
821
            UserData::saveData($userId, 'disable-sharebtn', true);
822
        }
823
824
        if ($tablinks == "on") {
825
            UserData::saveData($userId, 'links-new-tab', true);
826
        } else {
827
            UserData::saveData($userId, 'links-new-tab', false);
828
        }
829
    
830
        return Redirect('/studio/page');
831
    }
832
833
    //Upload custom theme background image
834
    public function themeBackground(Request $request)
835
    {
836
        $userId = Auth::user()->id;
0 ignored issues
show
Bug introduced by
Accessing id on the interface Illuminate\Contracts\Auth\Authenticatable suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
837
        $littlelink_name = Auth::user()->littlelink_name;
0 ignored issues
show
Unused Code introduced by
The assignment to $littlelink_name is dead and can be removed.
Loading history...
Bug introduced by
Accessing littlelink_name on the interface Illuminate\Contracts\Auth\Authenticatable suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
838
    
839
        $request->validate([
840
            'image' => 'required|image|mimes:jpeg,jpg,png,webp,gif|max:2048', // Max file size: 2MB
841
        ], [
842
            'image.required' => __('messages.Please select an image'),
843
            'image.image' => __('messages.The selected file must be an image'),
844
            'image.mimes' => __('messages.The image must be') . ' JPEG, JPG, PNG, webP, GIF.',
845
            'image.max' => __('messages.The image size should not exceed 2MB'),
846
        ]);
847
    
848
        $customBackground = $request->file('image');
849
    
850
        if ($customBackground) {
851
            $directory = base_path('assets/img/background-img/');
852
            $files = scandir($directory);
853
            $pathinfo = "error.error";
854
            foreach ($files as $file) {
855
                if (strpos($file, $userId . '.') !== false) {
856
                    $pathinfo = $userId . "." . pathinfo($file, PATHINFO_EXTENSION);
0 ignored issues
show
Bug introduced by
Are you sure pathinfo($file, App\Http...ers\PATHINFO_EXTENSION) of type array|string can be used in concatenation? ( Ignorable by Annotation )

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

856
                    $pathinfo = $userId . "." . /** @scrutinizer ignore-type */ pathinfo($file, PATHINFO_EXTENSION);
Loading history...
857
                }
858
            }
859
    
860
            if (file_exists(base_path('assets/img/background-img/') . $pathinfo)) {
861
                File::delete(base_path('assets/img/background-img/') . $pathinfo);
862
            }
863
    
864
            $fileName = $userId . '_' . time() . "." . $customBackground->extension();
865
            $customBackground->move(base_path('assets/img/background-img/'), $fileName);
866
    
867
            if (extension_loaded('imagick')) {
868
                $imagePath = base_path('assets/img/background-img/') . $fileName;
869
                $image = new \Imagick($imagePath);
870
                $image->stripImage();
871
                $image->writeImage($imagePath);
872
            }
873
    
874
            return redirect('/studio/theme');
875
        }
876
    
877
        return redirect('/studio/theme')->with('error', 'Please select a valid image file.');
878
    }
879
880
    //Delete custom background image
881
    public function removeBackground()
882
    {
883
884
        $user_id = Auth::user()->id;
0 ignored issues
show
Bug introduced by
Accessing id on the interface Illuminate\Contracts\Auth\Authenticatable suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
885
        $path = findBackground($user_id);
886
        $path = base_path('assets/img/background-img/'.$path);
887
        
888
        if (File::exists($path)) {
889
            File::delete($path);
890
        }
891
892
        return back();
893
    }
894
895
896
    //Show custom theme
897
    public function showTheme(request $request)
0 ignored issues
show
Unused Code introduced by
The parameter $request 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

897
    public function showTheme(/** @scrutinizer ignore-unused */ request $request)

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...
898
    {
899
        $userId = Auth::user()->id;
0 ignored issues
show
Bug introduced by
Accessing id on the interface Illuminate\Contracts\Auth\Authenticatable suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
900
901
        $data['pages'] = User::where('id', $userId)->select('littlelink_name', 'theme')->get();
0 ignored issues
show
Comprehensibility Best Practice introduced by
$data was never initialized. Although not strictly required by PHP, it is generally a good practice to add $data = array(); before regardless.
Loading history...
902
903
        return view('/studio/theme', $data);
904
    }
905
906
    //Save custom theme
907
    public function editTheme(request $request)
908
    {
909
        $request->validate([
910
            'zip' => 'sometimes|mimes:zip',
911
        ]);
912
913
        $userId = Auth::user()->id;
0 ignored issues
show
Bug introduced by
Accessing id on the interface Illuminate\Contracts\Auth\Authenticatable suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
914
915
        $zipfile = $request->file('zip');
916
917
        $theme = $request->theme;
918
        $message = "";
919
920
        User::where('id', $userId)->update(['theme' => $theme]);
921
922
923
924
        if (!empty($zipfile)) {
925
926
            $zipfile->move(base_path('/themes'), "temp.zip");
927
928
            $zip = new ZipArchive;
929
            $zip->open(base_path() . '/themes/temp.zip');
930
            $zip->extractTo(base_path() . '/themes');
931
            $zip->close();
932
            unlink(base_path() . '/themes/temp.zip');
933
934
            // Removes version numbers from folder.
935
936
            $folder = base_path('themes');
937
            $regex = '/[0-9.-]/';
938
            $files = scandir($folder);
939
940
            foreach ($files as $file) {
941
                if ($file !== '.' && $file !== '..') {
942
                    if (preg_match($regex, $file)) {
943
                        $new_file = preg_replace($regex, '', $file);
944
                        File::copyDirectory($folder . '/' . $file, $folder . '/' . $new_file);
945
                        $dirname = $folder . '/' . $file;
946
                        if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
947
                            system('rmdir ' . escapeshellarg($dirname) . ' /s /q');
948
                        } else {
949
                            system("rm -rf " . escapeshellarg($dirname));
950
                        }
951
                    }
952
                }
953
            }
954
        }
955
956
957
        return Redirect('/studio/theme')->with("success", $message);
958
    }
959
960
    //Show user (name, email, password)
961
    public function showProfile(request $request)
0 ignored issues
show
Unused Code introduced by
The parameter $request 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

961
    public function showProfile(/** @scrutinizer ignore-unused */ request $request)

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...
962
    {
963
        $userId = Auth::user()->id;
0 ignored issues
show
Bug introduced by
Accessing id on the interface Illuminate\Contracts\Auth\Authenticatable suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
964
965
        $data['profile'] = User::where('id', $userId)->select('name', 'email', 'role')->get();
0 ignored issues
show
Comprehensibility Best Practice introduced by
$data was never initialized. Although not strictly required by PHP, it is generally a good practice to add $data = array(); before regardless.
Loading history...
966
967
        return view('/studio/profile', $data);
968
    }
969
970
    //Save user (name, email, password)
971
    public function editProfile(request $request)
972
    {
973
        $request->validate([
974
            'name' => 'sometimes|required|unique:users',
975
            'email' => 'sometimes|required|email|unique:users',
976
            'password' => 'sometimes|min:8',
977
        ]);
978
979
        $userId = Auth::user()->id;
0 ignored issues
show
Bug introduced by
Accessing id on the interface Illuminate\Contracts\Auth\Authenticatable suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
980
981
        $name = $request->name;
982
        $email = $request->email;
983
        $password = Hash::make($request->password);
984
985
        if ($request->name != '') {
986
            User::where('id', $userId)->update(['name' => $name]);
987
        } elseif ($request->email != '') {
988
            User::where('id', $userId)->update(['email' => $email]);
989
        } elseif ($request->password != '') {
990
            User::where('id', $userId)->update(['password' => $password]);
991
            Auth::logout();
992
        }
993
        return back();
994
    }
995
996
    //Show user theme credit page
997
    public function theme(request $request)
998
    {
999
        $littlelink_name = $request->littlelink;
1000
        $id = User::select('id')->where('littlelink_name', $littlelink_name)->value('id');
1001
1002
        if (empty($id)) {
1003
            return abort(404);
0 ignored issues
show
Bug introduced by
Are you sure the usage of abort(404) 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...
1004
        }
1005
1006
        $userinfo = User::select('name', 'littlelink_name', 'littlelink_description', 'theme')->where('id', $id)->first();
1007
        $information = User::select('name', 'littlelink_name', 'littlelink_description', 'theme')->where('id', $id)->get();
1008
1009
        $links = DB::table('links')->join('buttons', 'buttons.id', '=', 'links.button_id')->select('links.link', 'links.id', 'links.button_id', 'links.title', 'links.custom_css', 'links.custom_icon', 'buttons.name')->where('user_id', $id)->orderBy('up_link', 'asc')->orderBy('order', 'asc')->get();
1010
1011
        return view('components/theme', ['userinfo' => $userinfo, 'information' => $information, 'links' => $links, 'littlelink_name' => $littlelink_name]);
1012
    }
1013
1014
    //Delete existing user
1015
    public function deleteUser(request $request)
1016
    {
1017
1018
        // echo $request->id;
1019
        // echo "<br>";
1020
        // echo Auth::id();
1021
        $id = $request->id;
1022
1023
    if($id == Auth::id() and $id != "1") {
1024
1025
        Link::where('user_id', $id)->delete();
1026
1027
        $user = User::find($id);
1028
1029
        Schema::disableForeignKeyConstraints();
1030
        $user->forceDelete();
1031
        Schema::enableForeignKeyConstraints();
1032
    }
1033
1034
        return redirect('/');
1035
    }
1036
1037
    //Delete profile picture
1038
    public function delProfilePicture()
1039
    {
1040
        $user_id = Auth::user()->id;
0 ignored issues
show
Bug introduced by
Accessing id on the interface Illuminate\Contracts\Auth\Authenticatable suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
1041
        $path = base_path(findAvatar($user_id));
1042
        
1043
        if (File::exists($path)) {
1044
            File::delete($path);
1045
        }
1046
1047
        return back();
1048
    }
1049
1050
    //Export user links
1051
    public function exportLinks(request $request)
0 ignored issues
show
Unused Code introduced by
The parameter $request 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

1051
    public function exportLinks(/** @scrutinizer ignore-unused */ request $request)

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...
1052
    {
1053
        $userId = Auth::id();
1054
        $user = User::find($userId);
1055
        $links = Link::where('user_id', $userId)->get();
1056
        
1057
        if (!$user) {
1058
            // handle the case where the user is null
1059
            return response()->json(['message' => 'User not found'], 404);
1060
        }
1061
1062
        $userData['links'] = $links->toArray();
0 ignored issues
show
Comprehensibility Best Practice introduced by
$userData was never initialized. Although not strictly required by PHP, it is generally a good practice to add $userData = array(); before regardless.
Loading history...
1063
1064
        $domain = $_SERVER['HTTP_HOST'];
1065
        $date = date('Y-m-d_H-i-s');
1066
        $fileName = "links-$domain-$date.json";
1067
        $headers = [
1068
            'Content-Type' => 'application/json',
1069
            'Content-Disposition' => 'attachment; filename="'.$fileName.'"',
1070
        ];
1071
        return response()->json($userData, 200, $headers);
1072
1073
        return back();
0 ignored issues
show
Unused Code introduced by
return back() is not reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
1074
    }
1075
1076
    //Export all user data
1077
    public function exportAll(Request $request)
0 ignored issues
show
Unused Code introduced by
The parameter $request 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

1077
    public function exportAll(/** @scrutinizer ignore-unused */ Request $request)

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...
1078
    {
1079
        $userId = Auth::id();
1080
        $user = User::find($userId);
1081
        $links = Link::where('user_id', $userId)->get();
1082
    
1083
        if (!$user) {
1084
            // handle the case where the user is null
1085
            return response()->json(['message' => 'User not found'], 404);
1086
        }
1087
    
1088
        $userData = $user->toArray();
1089
        $userData['links'] = $links->toArray();
1090
    
1091
        function findAvatar($name){
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
1092
            $directory = base_path('assets/img');
1093
            $files = scandir($directory);
1094
            $pathinfo = "error.error";
1095
            foreach($files as $file) {
1096
            if (strpos($file, $name.'.') !== false) {
1097
            $pathinfo = "/img/" . $name. "." . pathinfo($file, PATHINFO_EXTENSION);
0 ignored issues
show
Bug introduced by
Are you sure pathinfo($file, App\Http...ers\PATHINFO_EXTENSION) of type array|string can be used in concatenation? ( Ignorable by Annotation )

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

1097
            $pathinfo = "/img/" . $name. "." . /** @scrutinizer ignore-type */ pathinfo($file, PATHINFO_EXTENSION);
Loading history...
1098
            }}
1099
            return $pathinfo;
1100
          }
1101
1102
        if (file_exists(base_path(findAvatar($userId)))){
1103
            $imagePath = base_path(findAvatar($userId));
1104
            $imageData = base64_encode(file_get_contents($imagePath));
1105
            $userData['image_data'] = $imageData;
1106
    
1107
            $imageExtension = pathinfo($imagePath, PATHINFO_EXTENSION);
1108
            $userData['image_extension'] = $imageExtension;
1109
        }
1110
    
1111
        $domain = $_SERVER['HTTP_HOST'];
1112
        $date = date('Y-m-d_H-i-s');
1113
        $fileName = "user_data-$domain-$date.json";
1114
        $headers = [
1115
            'Content-Type' => 'application/json',
1116
            'Content-Disposition' => 'attachment; filename="'.$fileName.'"',
1117
        ];
1118
        return response()->json($userData, 200, $headers);
1119
    
1120
        return back();
0 ignored issues
show
Unused Code introduced by
return back() is not reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
1121
    }    
1122
1123
    public function importData(Request $request)
1124
    {
1125
        try {
1126
            // Get the JSON data from the uploaded file
1127
            if (!$request->hasFile('import') || !$request->file('import')->isValid()) {
1128
                throw new \Exception('File not uploaded or is faulty');
1129
            }
1130
            $file = $request->file('import');
1131
            $jsonString = $file->get();
1132
            $userData = json_decode($jsonString, true);
1133
    
1134
            // Update the authenticated user's profile data if defined in the JSON file
1135
            $user = auth()->user();
1136
            if (isset($userData['name'])) {
1137
                $user->name = $userData['name'];
1138
            }
1139
            if (isset($userData['littlelink_name'])) {
1140
                $user->littlelink_name = $userData['littlelink_name'];
1141
            }
1142
            if (isset($userData['littlelink_description'])) {
1143
                $user->littlelink_description = $userData['littlelink_description'];
1144
            }
1145
            if (isset($userData['image_data'])) {
1146
                // Decode the image data from Base64
1147
                $imageData = base64_decode($userData['image_data']);
1148
                
1149
                // Save the image to the correct path with the correct file name and extension
1150
                $filename = $user->id . '.' . $userData['image_extension'];
1151
                file_put_contents(base_path('img/' . $filename), $imageData);
1152
                
1153
                // Update the user's image field with the correct file name
1154
                $user->image = $filename;
1155
            }
1156
            $user->save();
1157
    
1158
            // Delete all links for the authenticated user
1159
            Link::where('user_id', $user->id)->delete();
1160
    
1161
            // Loop through each link in $userData and create a new link for the user
1162
            foreach ($userData['links'] as $linkData) {
1163
                $newLink = new Link();
1164
    
1165
                // Copy over the link data from $linkData to $newLink
1166
                $newLink->button_id = $linkData['button_id'];
1167
                $newLink->link = $linkData['link'];
1168
                $newLink->title = $linkData['title'];
1169
                $newLink->order = $linkData['order'];
1170
                $newLink->click_number = $linkData['click_number'];
1171
                $newLink->up_link = $linkData['up_link'];
1172
                $newLink->custom_css = $linkData['custom_css'];
1173
                $newLink->custom_icon = $linkData['custom_icon'];
1174
    
1175
                // Set the user ID to the current user's ID
1176
                $newLink->user_id = $user->id;
1177
    
1178
                // Save the new link to the database
1179
                $newLink->save();
1180
            }
1181
    
1182
            return redirect('studio/profile')->with('success', __('messages.Profile updated successfully!'));
1183
        } catch (\Exception $e) {
1184
            return redirect('studio/profile')->with('error', __('messages.An error occurred while updating your profile.'));
1185
        }
1186
    }
1187
    
1188
1189
    // Hanle reports
1190
    function report(Request $request)
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
1191
    {
1192
        $formData = $request->all();
1193
    
1194
        try {
1195
            Mail::to(env('ADMIN_EMAIL'))->send(new ReportSubmissionMail($formData));
1196
            
1197
            return redirect('report')->with('success', __('messages.report_success'));
1198
        } catch (\Exception $e) {
1199
            return redirect()->back()->with('error', __('messages.report_error'));
1200
        }
1201
    }
1202
1203
    //Edit/save page icons
1204
    public function editIcons(Request $request)
1205
    {
1206
        $inputKeys = array_keys($request->except('_token'));
1207
1208
        $validationRules = [];
1209
1210
        foreach ($inputKeys as $platform) {
1211
            $validationRules[$platform] = 'nullable|url|max:255';
1212
        }
1213
1214
        $request->validate($validationRules);
1215
1216
        foreach ($inputKeys as $platform) {
1217
            $link = $request->input($platform);
1218
1219
            if (!empty($link)) {
1220
                $iconId = $this->searchIcon($platform);
1221
1222
                if (!is_null($iconId)) {
1223
                    $this->updateIcon($platform, $link);
1224
                } else {
1225
                    $this->addIcon($platform, $link);
1226
                }
1227
            }
1228
        }
1229
1230
        return redirect('studio/links#icons');
1231
    }
1232
1233
    private function searchIcon($icon)
1234
    {
1235
        return DB::table('links')
1236
            ->where('user_id', Auth::id())
1237
            ->where('title', $icon)
1238
            ->where('button_id', 94)
1239
            ->value('id');
1240
    }
1241
1242
    private function addIcon($icon, $link)
1243
    {
1244
        $userId = Auth::user()->id;
0 ignored issues
show
Bug introduced by
Accessing id on the interface Illuminate\Contracts\Auth\Authenticatable suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
1245
        $links = new Link;
1246
        $links->link = $link;
1247
        $links->user_id = $userId;
1248
        $links->title = $icon;
1249
        $links->button_id = '94';
1250
        $links->save();
1251
        $links->order = ($links->id - 1);
1252
        $links->save();
1253
    }
1254
1255
    private function updateIcon($icon, $link)
1256
    {
1257
        Link::where('id', $this->searchIcon($icon))->update([
1258
            'button_id' => 94,
1259
            'link' => $link,
1260
            'title' => $icon
1261
        ]);
1262
    }
1263
}