-
-
Notifications
You must be signed in to change notification settings - Fork 388
Expand file tree
/
Copy pathUserController.php
More file actions
executable file
·1170 lines (925 loc) · 41.4 KB
/
UserController.php
File metadata and controls
executable file
·1170 lines (925 loc) · 41.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Cohensive\OEmbed\Facades\OEmbed;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Response;
use JeroenDesloovere\VCard\VCard;
use Illuminate\Validation\Rule;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Mail;
use App\Mail\ReportSubmissionMail;
use GeoSot\EnvEditor\Facades\EnvEditor;
use Auth;
use DB;
use ZipArchive;
use File;
use App\Models\User;
use App\Models\Button;
use App\Models\Link;
use App\Models\LinkType;
use App\Models\UserData;
//Function tests if string starts with certain string (used to test for illegal strings)
function stringStartsWith($haystack, $needle, $case = true)
{
if ($case) {
return strpos($haystack, $needle, 0) === 0;
}
return stripos($haystack, $needle, 0) === 0;
}
//Function tests if string ends with certain string (used to test for illegal strings)
function stringEndsWith($haystack, $needle, $case = true)
{
$expectedPosition = strlen($haystack) - strlen($needle);
if ($case) {
return strrpos($haystack, $needle, 0) === $expectedPosition;
}
return strripos($haystack, $needle, 0) === $expectedPosition;
}
class UserController extends Controller
{
//Statistics of the number of clicks and links
public function index()
{
$userId = Auth::user()->id;
$littlelink_name = Auth::user()->littlelink_name;
$userinfo = User::find($userId);
$links = Link::where('user_id', $userId)->select('link')->count();
$clicks = Link::where('user_id', $userId)->sum('click_number');
$topLinks = Link::where('user_id', $userId)->orderby('click_number', 'desc')
->whereNotNull('link')->where('link', '<>', '')
->take(5)->get();
$pageStats = [
'visitors' => [
'all' => visits('App\Models\User', $littlelink_name)->count(),
'day' => visits('App\Models\User', $littlelink_name)->period('day')->count(),
'week' => visits('App\Models\User', $littlelink_name)->period('week')->count(),
'month' => visits('App\Models\User', $littlelink_name)->period('month')->count(),
'year' => visits('App\Models\User', $littlelink_name)->period('year')->count(),
],
'os' => visits('App\Models\User', $littlelink_name)->operatingSystems(),
'referers' => visits('App\Models\User', $littlelink_name)->refs(),
'countries' => visits('App\Models\User', $littlelink_name)->countries(),
];
return view('studio/index', ['greeting' => $userinfo->name, 'toplinks' => $topLinks, 'links' => $links, 'clicks' => $clicks, 'pageStats' => $pageStats]);
}
//Show littlelink page. example => http://127.0.0.1:8000/+admin
public function littlelink(request $request)
{
if(isset($request->useif)){
$littlelink_name = User::select('littlelink_name')->where('id', $request->littlelink)->value('littlelink_name');
$id = $request->littlelink;
} else {
$littlelink_name = $request->littlelink;
$id = User::select('id')->where('littlelink_name', $littlelink_name)->value('id');
}
if (empty($id)) {
return abort(404);
}
$userinfo = User::select('id', 'name', 'littlelink_name', 'littlelink_description', 'theme', 'role', 'block')->where('id', $id)->first();
$information = User::select('name', 'littlelink_name', 'littlelink_description', 'theme')->where('id', $id)->get();
if ($userinfo->block == 'yes') {
return abort(404);
}
$links = DB::table('links')
->join('buttons', 'buttons.id', '=', 'links.button_id')
->select('links.*', 'buttons.name') // Assuming 'links.*' to fetch all columns including 'type_params'
->where('user_id', $id)
->orderBy('up_link', 'asc')
->orderBy('order', 'asc')
->get();
// Loop through each link to decode 'type_params' and merge it into the link object
foreach ($links as $link) {
if (!empty($link->type_params)) {
// Decode the JSON string into an associative array
$typeParams = json_decode($link->type_params, true);
if (is_array($typeParams)) {
// Merge the associative array into the link object
foreach ($typeParams as $key => $value) {
$link->$key = $value;
}
}
}
}
return view('linkstack.linkstack', ['userinfo' => $userinfo, 'information' => $information, 'links' => $links, 'littlelink_name' => $littlelink_name]);
}
//Show littlelink page as home page if set in config
public function littlelinkhome(request $request)
{
$littlelink_name = env('HOME_URL');
$id = User::select('id')->where('littlelink_name', $littlelink_name)->value('id');
if (empty($id)) {
return abort(404);
}
$userinfo = User::select('id', 'name', 'littlelink_name', 'littlelink_description', 'theme', 'role', 'block')->where('id', $id)->first();
$information = User::select('name', 'littlelink_name', 'littlelink_description', 'theme')->where('id', $id)->get();
$links = DB::table('links')
->join('buttons', 'buttons.id', '=', 'links.button_id')
->select('links.*', 'buttons.name') // Assuming 'links.*' to fetch all columns including 'type_params'
->where('user_id', $id)
->orderBy('up_link', 'asc')
->orderBy('order', 'asc')
->get();
// Loop through each link to decode 'type_params' and merge it into the link object
foreach ($links as $link) {
if (!empty($link->type_params)) {
// Decode the JSON string into an associative array
$typeParams = json_decode($link->type_params, true);
if (is_array($typeParams)) {
// Merge the associative array into the link object
foreach ($typeParams as $key => $value) {
$link->$key = $value;
}
}
}
}
return view('linkstack.linkstack', ['userinfo' => $userinfo, 'information' => $information, 'links' => $links, 'littlelink_name' => $littlelink_name]);
}
//Redirect to user page
public function userRedirect(request $request)
{
$id = $request->id;
$user = User::select('littlelink_name')->where('id', $id)->value('littlelink_name');
if (empty($id)) {
return abort(404);
}
if (empty($user)) {
return abort(404);
}
return redirect(url('@'.$user));
}
//Show add/update form
public function AddUpdateLink($id = 0)
{
$linkData = $id ? Link::find($id) : new Link(['typename' => 'link', 'id' => '0']);
$data = [
'LinkTypes' => LinkType::get(),
'LinkData' => $linkData,
'LinkID' => $id,
'linkTypeID' => "predefined",
'title' => "Predefined Site",
];
$data['typename'] = $linkData->type ?? 'predefined';
return view('studio/edit-link', $data);
}
//Save add link
public function saveLink(Request $request)
{
// Step 1: Validate Request
// $request->validate([
// 'link' => 'sometimes|url',
// ]);
// Step 2: Determine Link Type and Title
$linkType = LinkType::findByTypename($request->typename);
$LinkTitle = $request->title;
$LinkURL = $request->link;
// Step 3: Load Link Type Logic
if($request->typename == 'predefined' || $request->typename == 'link') {
// Determine button id based on whether a custom or predefined button is used
$button_id = ($request->typename == 'link') ? ($request->GetSiteIcon == 1 ? 2 : 1) : null;
$button = ($request->typename != 'link') ? Button::where('name', $request->button)->first() : null;
$linkData = [
'link' => $LinkURL,
'title' => $LinkTitle ?? $button?->alt,
'user_id' => Auth::user()->id,
'button_id' => $button?->id ?? $button_id,
'type' => $request->typename // Save the link type
];
} else {
$linkTypePath = base_path("blocks/{$linkType->typename}/handler.php");
if (file_exists($linkTypePath)) {
include $linkTypePath;
$result = handleLinkType($request, $linkType);
// Extract rules and linkData from the result
$rules = $result['rules'];
$linkData = $result['linkData'];
// Validate the request
$validator = Validator::make($request->all(), $rules);
// Check if validation fails
if ($validator->fails()) {
return back()->withErrors($validator)->withInput();
}
$linkData['button_id'] = $linkData['button_id'] ?? 1; // Set 'button_id' unless overwritten by handleLinkType
$linkData['type'] = $linkType->typename; // Ensure 'type' is included in $linkData
} else {
abort(404, "Link type logic not found.");
}
}
// Step 4: Handle Custom Parameters
// (Same as before)
// Step 5: User and Button Information
$userId = Auth::user()->id;
$button = Button::where('name', $request->button)->first();
if ($button && empty($LinkTitle)) $LinkTitle = $button->alt;
// Step 6: Prepare Link Data
// (Handled by the included file)
// Step 7: Save or Update Link
$OrigLink = Link::find($request->linkid);
$linkColumns = Schema::getColumnListing('links'); // Get all column names of links table
$filteredLinkData = array_intersect_key($linkData, array_flip($linkColumns)); // Filter $linkData to only include keys that are columns in the links table
// Combine remaining variables into one array and convert to JSON for the type_params column
$customParams = array_diff_key($linkData, $filteredLinkData);
// Check if $linkType->custom_html is defined and not null
if (isset($linkType->custom_html)) {
// Add $linkType->custom_html to the $customParams array
$customParams['custom_html'] = $linkType->custom_html;
}
// Check if $linkType->ignore_container is defined and not null
if (isset($linkType->ignore_container)) {
// Add $linkType->ignore_container to the $customParams array
$customParams['ignore_container'] = $linkType->ignore_container;
}
// Check if $linkType->include_libraries is defined and not null
if (isset($linkType->include_libraries)) {
// Add $linkType->include_libraries to the $customParams array
$customParams['include_libraries'] = $linkType->include_libraries;
}
$filteredLinkData['type_params'] = json_encode($customParams);
if ($OrigLink) {
$currentValues = $OrigLink->getAttributes();
$nonNullFilteredLinkData = array_filter($filteredLinkData, function($value) {return !is_null($value);});
$updatedValues = array_merge($currentValues, $nonNullFilteredLinkData);
$OrigLink->update($updatedValues);
$message = "Link updated";
} else {
$link = new Link($filteredLinkData);
$link->user_id = $userId;
$link->save();
$message = "Link added";
}
// Step 8: Redirect
$redirectUrl = $request->input('param') == 'add_more' ? 'studio/add-link' : 'studio/links';
return Redirect($redirectUrl)->with('success', $message);
}
public function sortLinks(Request $request)
{
$linkOrders = $request->input("linkOrders", []);
$currentPage = $request->input("currentPage", 1);
$perPage = $request->input("perPage", 0);
if ($perPage == 0) {
$currentPage = 1;
}
$linkOrders = array_unique(array_filter($linkOrders));
if (!$linkOrders || $currentPage < 1) {
return response()->json([
'status' => 'ERROR',
]);
}
$newOrder = $perPage * ($currentPage - 1);
$linkNewOrders = [];
foreach ($linkOrders as $linkId) {
if ($linkId < 0) {
continue;
}
$linkNewOrders[$linkId] = $newOrder;
Link::where("id", $linkId)
->update([
'order' => $newOrder
]);
$newOrder++;
}
return response()->json([
'status' => 'OK',
'linkOrders' => $linkNewOrders,
]);
}
//Count the number of clicks and redirect to link
public function clickNumber(request $request)
{
$linkId = $request->id;
if (substr($linkId, -1) == '+') {
$linkWithoutPlus = str_replace('+', '', $linkId);
return redirect(url('info/'.$linkWithoutPlus));
}
$link = Link::find($linkId);
if (empty($link)) {
return abort(404);
}
$link = $link->link;
if (empty($linkId)) {
return abort(404);
}
Link::where('id', $linkId)->increment('click_number', 1);
$response = redirect()->away($link);
$response->header('X-Robots-Tag', 'noindex, nofollow');
return $response;
}
//Download Vcard
public function vcard(request $request)
{
$linkId = $request->id;
// Find the link with the specified ID
$link = Link::findOrFail($linkId);
$json = $link->link;
// Decode the JSON to a PHP array
$data = json_decode($json, true);
// Create a new vCard object
$vcard = new VCard();
// Name: pass empty strings if missing
$vcard->addName(
trim((string)($data['last_name'] ?? '')),
trim((string)($data['first_name'] ?? '')),
trim((string)($data['middle_name'] ?? '')),
trim((string)($data['prefix'] ?? '')),
trim((string)($data['suffix'] ?? ''))
);
// Small helper: call $fn only if $value is meaningfully present
$runIf = function ($value, callable $fn) {
if (is_string($value)) $value = trim($value);
if ($value !== null && $value !== '') $fn($value);
};
// Optional fields - Only add if value is present
$runIf($data['organization'] ?? null, fn($v) => $vcard->addCompany($v));
$runIf($data['vtitle'] ?? null, fn($v) => $vcard->addJobtitle($v));
$runIf($data['role'] ?? null, fn($v) => $vcard->addRole($v));
$runIf($data['email'] ?? null, fn($v) => $vcard->addEmail($v));
$runIf($data['work_email'] ?? null, fn($v) => $vcard->addEmail($v, 'WORK'));
$runIf($data['work_url'] ?? null, fn($v) => $vcard->addURL($v, 'WORK'));
$runIf($data['home_phone'] ?? null, fn($v) => $vcard->addPhoneNumber($v, 'HOME'));
$runIf($data['work_phone'] ?? null, fn($v) => $vcard->addPhoneNumber($v, 'WORK'));
$runIf($data['cell_phone'] ?? null, fn($v) => $vcard->addPhoneNumber($v, 'CELL'));
// Addresses: add only if any component exists
$home = [
trim((string)($data['home_address_street'] ?? '')),
trim((string)($data['home_address_city'] ?? '')),
trim((string)($data['home_address_state'] ?? '')),
trim((string)($data['home_address_zip'] ?? '')),
trim((string)($data['home_address_country'] ?? '')),
];
if (implode('', $home) !== '') {
$vcard->addAddress($home[0], '', $home[1], $home[2], $home[3], $home[4], 'HOME');
}
$work = [
trim((string)($data['work_address_street'] ?? '')),
trim((string)($data['work_address_city'] ?? '')),
trim((string)($data['work_address_state'] ?? '')),
trim((string)($data['work_address_zip'] ?? '')),
trim((string)($data['work_address_country'] ?? '')),
];
if (implode('', $work) !== '') {
$vcard->addAddress($work[0], '', $work[1], $work[2], $work[3], $work[4], 'WORK');
}
// $vcard->addPhoto(base_path('img/1.png'));
// Generate the vCard file contents
$file_contents = $vcard->getOutput();
// Set the file headers for download
$headers = [
'Content-Type' => 'text/x-vcard',
'Content-Disposition' => 'attachment; filename="contact.vcf"'
];
Link::where('id', $linkId)->increment('click_number', 1);
// Return the file download response
return response()->make($file_contents, 200, $headers);
}
//Show link, click number, up link in links page
public function showLinks()
{
$userId = Auth::user()->id;
$data['pagePage'] = 10;
$data['links'] = Link::select()->where('user_id', $userId)->orderBy('up_link', 'asc')->orderBy('order', 'asc')->paginate(99999);
return view('studio/links', $data);
}
//Delete link
public function deleteLink(request $request)
{
$linkId = $request->id;
Link::where('id', $linkId)->delete();
$directory = base_path("assets/favicon/icons");
$files = scandir($directory);
foreach($files as $file) {
if (strpos($file, $linkId.".") !== false) {
$pathinfo = pathinfo($file, PATHINFO_EXTENSION);}}
if (isset($pathinfo)) {
try{File::delete(base_path("assets/favicon/icons")."/".$linkId.".".$pathinfo);} catch (exception $e) {}
}
return redirect('/studio/links');
}
//Delete icon
public function clearIcon(request $request)
{
$linkId = $request->id;
$directory = base_path("assets/favicon/icons");
$files = scandir($directory);
foreach($files as $file) {
if (strpos($file, $linkId.".") !== false) {
$pathinfo = pathinfo($file, PATHINFO_EXTENSION);}}
if (isset($pathinfo)) {
try{File::delete(base_path("assets/favicon/icons")."/".$linkId.".".$pathinfo);} catch (exception $e) {}
}
return redirect('/studio/links');
}
//Raise link on the littlelink page
public function upLink(request $request)
{
$linkId = $request->id;
$upLink = $request->up;
if ($upLink == 'yes') {
$up = 'no';
} elseif ($upLink == 'no') {
$up = 'yes';
}
Link::where('id', $linkId)->update(['up_link' => $up]);
return back();
}
//Show link to edit
public function showLink(request $request)
{
$linkId = $request->id;
$link = Link::where('id', $linkId)->value('link');
$title = Link::where('id', $linkId)->value('title');
$order = Link::where('id', $linkId)->value('order');
$custom_css = Link::where('id', $linkId)->value('custom_css');
$buttonId = Link::where('id', $linkId)->value('button_id');
$buttonName = Button::where('id', $buttonId)->value('name');
$buttons = Button::select('id', 'name')->orderBy('name', 'asc')->get();
return view('studio/edit-link', ['custom_css' => $custom_css, 'buttonId' => $buttonId, 'buttons' => $buttons, 'link' => $link, 'title' => $title, 'order' => $order, 'id' => $linkId, 'buttonName' => $buttonName]);
}
//Show custom CSS + custom icon
public function showCSS(request $request)
{
$linkId = $request->id;
$link = Link::where('id', $linkId)->value('link');
$title = Link::where('id', $linkId)->value('title');
$order = Link::where('id', $linkId)->value('order');
$custom_css = Link::where('id', $linkId)->value('custom_css');
$custom_icon = Link::where('id', $linkId)->value('custom_icon');
$buttonId = Link::where('id', $linkId)->value('button_id');
$buttons = Button::select('id', 'name')->get();
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]);
}
//Save edit link
public function editLink(request $request)
{
$request->validate([
'link' => 'required|exturl',
'title' => 'required',
'button' => 'required',
]);
if (stringStartsWith($request->link, 'http://') == 'true' or stringStartsWith($request->link, 'https://') == 'true' or stringStartsWith($request->link, 'mailto:') == 'true')
$link1 = $request->link;
else
$link1 = 'https://' . $request->link;
if (stringEndsWith($request->link, '/') == 'true')
$link = rtrim($link1, "/ ");
else
$link = $link1;
$title = $request->title;
$order = $request->order;
$button = $request->button;
$linkId = $request->id;
$buttonId = Button::select('id')->where('name', $button)->value('id');
Link::where('id', $linkId)->update(['link' => $link, 'title' => $title, 'order' => $order, 'button_id' => $buttonId]);
return redirect('/studio/links');
}
//Save edit custom CSS + custom icon
public function editCSS(request $request)
{
$linkId = $request->id;
$custom_icon = $request->custom_icon;
$custom_css = $request->custom_css;
if ($request->custom_css == "" and $request->custom_icon = !"") {
Link::where('id', $linkId)->update(['custom_icon' => $custom_icon]);
} elseif ($request->custom_icon == "" and $request->custom_css = !"") {
Link::where('id', $linkId)->update(['custom_css' => $custom_css]);
} else {
Link::where('id', $linkId)->update([]);
}
return Redirect('#result');
}
//Show littlelinke page for edit
public function showPage(request $request)
{
$userId = Auth::user()->id;
$data['pages'] = User::where('id', $userId)->select('littlelink_name', 'littlelink_description', 'image', 'name')->get();
return view('/studio/page', $data);
}
//Save littlelink page (name, description, logo)
public function editPage(Request $request)
{
$userId = Auth::user()->id;
$littlelink_name = Auth::user()->littlelink_name;
$validator = Validator::make($request->all(), [
'littlelink_name' => [
'sometimes',
'max:255',
'string',
'isunique:users,id,'.$userId,
],
'name' => 'sometimes|max:255|string',
'image' => 'sometimes|image|mimes:jpeg,jpg,png,webp|max:2048', // Max file size: 2MB
], [
'littlelink_name.unique' => __('messages.That handle has already been taken'),
'image.image' => __('messages.The selected file must be an image'),
'image.mimes' => __('messages.The image must be') . ' JPEG, JPG, PNG, webP.',
'image.max' => __('messages.The image size should not exceed 2MB'),
]);
if ($validator->fails()) {
return redirect('/studio/page')->withErrors($validator)->withInput();
}
$profilePhoto = $request->file('image');
$pageName = $request->littlelink_name;
$pageDescription = strip_tags($request->pageDescription, '<a><p><strong><i><ul><ol><li><blockquote><h2><h3><h4>');
$pageDescription = preg_replace("/<a([^>]*)>/i", "<a $1 rel=\"noopener noreferrer nofollow\">", $pageDescription);
$pageDescription = strip_tags_except_allowed_protocols($pageDescription);
$name = $request->name;
$checkmark = $request->checkmark;
$sharebtn = $request->sharebtn;
$tablinks = $request->tablinks;
if(env('HOME_URL') !== '' && $pageName != $littlelink_name && $littlelink_name == env('HOME_URL')){
EnvEditor::editKey('HOME_URL', $pageName);
}
User::where('id', $userId)->update([
'littlelink_name' => $pageName,
'littlelink_description' => $pageDescription,
'name' => $name
]);
if ($request->hasFile('image')) {
// Delete the user's current avatar if it exists
while (findAvatar($userId) !== "error.error") {
$avatarName = findAvatar($userId);
unlink(base_path($avatarName));
}
$fileName = $userId . '_' . time() . "." . $profilePhoto->extension();
$profilePhoto->move(base_path('assets/img'), $fileName);
}
if ($checkmark == "on") {
UserData::saveData($userId, 'checkmark', true);
} else {
UserData::saveData($userId, 'checkmark', false);
}
if ($sharebtn == "on") {
UserData::saveData($userId, 'disable-sharebtn', false);
} else {
UserData::saveData($userId, 'disable-sharebtn', true);
}
if ($tablinks == "on") {
UserData::saveData($userId, 'links-new-tab', true);
} else {
UserData::saveData($userId, 'links-new-tab', false);
}
return Redirect('/studio/page');
}
//Upload custom theme background image
public function themeBackground(Request $request)
{
$userId = Auth::user()->id;
$littlelink_name = Auth::user()->littlelink_name;
$request->validate([
'image' => 'required|image|mimes:jpeg,jpg,png,webp,gif|max:2048', // Max file size: 2MB
], [
'image.required' => __('messages.Please select an image'),
'image.image' => __('messages.The selected file must be an image'),
'image.mimes' => __('messages.The image must be') . ' JPEG, JPG, PNG, webP, GIF.',
'image.max' => __('messages.The image size should not exceed 2MB'),
]);
$customBackground = $request->file('image');
if ($customBackground) {
$directory = base_path('assets/img/background-img/');
$files = scandir($directory);
$pathinfo = "error.error";
foreach ($files as $file) {
if (strpos($file, $userId . '.') !== false) {
$pathinfo = $userId . "." . pathinfo($file, PATHINFO_EXTENSION);
}
}
// Delete the user's current background image if it exists
while (findBackground($userId) !== "error.error") {
$avatarName = "assets/img/background-img/" . findBackground(Auth::id());
unlink(base_path($avatarName));
}
$fileName = $userId . '_' . time() . "." . $customBackground->extension();
$customBackground->move(base_path('assets/img/background-img/'), $fileName);
if (extension_loaded('imagick')) {
$imagePath = base_path('assets/img/background-img/') . $fileName;
$image = new \Imagick($imagePath);
$image->stripImage();
$image->writeImage($imagePath);
}
return redirect('/studio/theme');
}
return redirect('/studio/theme')->with('error', 'Please select a valid image file.');
}
//Delete custom background image
public function removeBackground()
{
$userId = Auth::user()->id;
// Delete the user's current background image if it exists
while (findBackground($userId) !== "error.error") {
$avatarName = "assets/img/background-img/" . findBackground(Auth::id());
unlink(base_path($avatarName));
}
return back();
}
//Show custom theme
public function showTheme(request $request)
{
$userId = Auth::user()->id;
$data['pages'] = User::where('id', $userId)->select('littlelink_name', 'theme')->get();
return view('/studio/theme', $data);
}
//Save custom theme
public function editTheme(request $request)
{
$request->validate([
'zip' => 'sometimes|mimes:zip',
]);
$userId = Auth::user()->id;
$zipfile = $request->file('zip');
$theme = $request->theme;
$message = "";
User::where('id', $userId)->update(['theme' => $theme]);
if (!empty($zipfile) && Auth::user()->role == 'admin') {
$themesPath = base_path('themes');
$tmpPath = base_path() . '/themes/temp.zip';
$zipfile->move($themesPath, "temp.zip");
$zip = new ZipArchive;
$zip->open($tmpPath);
$zip->extractTo($themesPath);
$zip->close();
unlink($tmpPath);
// Removes version numbers from folder.
$regex = '/[0-9.-]/';
$files = scandir($themesPath);
$files = array_diff($files, array('.', '..'));
foreach ($files as $file) {
$basename = basename($file);
$filePath = $themesPath . '/' . $basename;
if (!is_dir($filePath)) {
try {
File::delete($filePath);
} catch (exception $e) {}
}
if (preg_match($regex, $basename)) {
$newBasename = preg_replace($regex, '', $basename);
$newPath = $themesPath . '/' . $newBasename;
File::copyDirectory($filePath, $newPath);
File::deleteDirectory($filePath);
}
}
}
return Redirect('/studio/theme')->with("success", $message);
}
//Show user (name, email, password)
public function showProfile(request $request)
{
$userId = Auth::user()->id;
$data['profile'] = User::where('id', $userId)->select('name', 'email', 'role')->get();
return view('/studio/profile', $data);
}
//Save user (name, email, password)
public function editProfile(request $request)
{
$request->validate([
'name' => 'sometimes|required|unique:users',
'email' => 'sometimes|required|email|unique:users',
'password' => 'sometimes|min:8',
]);
$userId = Auth::user()->id;
$name = $request->name;
$email = $request->email;
$password = Hash::make($request->password);
if ($request->name != '') {
User::where('id', $userId)->update(['name' => $name]);
} elseif ($request->email != '') {
User::where('id', $userId)->update(['email' => $email]);
} elseif ($request->password != '') {
User::where('id', $userId)->update(['password' => $password]);
Auth::logout();
}
return back();
}
//Show user theme credit page
public function theme(request $request)
{
$littlelink_name = $request->littlelink;
$id = User::select('id')->where('littlelink_name', $littlelink_name)->value('id');
if (empty($id)) {
return abort(404);
}
$userinfo = User::select('name', 'littlelink_name', 'littlelink_description', 'theme')->where('id', $id)->first();
$information = User::select('name', 'littlelink_name', 'littlelink_description', 'theme')->where('id', $id)->get();
$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();
return view('components/theme', ['userinfo' => $userinfo, 'information' => $information, 'links' => $links, 'littlelink_name' => $littlelink_name]);
}
//Delete existing user
public function deleteUser(request $request)
{
// echo $request->id;
// echo "<br>";
// echo Auth::id();
$id = $request->id;
if($id == Auth::id() and $id != "1") {
Link::where('user_id', $id)->delete();
$user = User::find($id);
Schema::disableForeignKeyConstraints();
$user->forceDelete();
Schema::enableForeignKeyConstraints();
}
return redirect('/');
}
//Delete profile picture
public function delProfilePicture()
{
$userId = Auth::user()->id;
// Delete the user's current avatar if it exists
while (findAvatar($userId) !== "error.error") {
$avatarName = findAvatar($userId);
unlink(base_path($avatarName));
}
return back();
}
//Export user links
public function exportLinks(request $request)
{
$userId = Auth::id();
$user = User::find($userId);
$links = Link::where('user_id', $userId)->get();
if (!$user) {
// handle the case where the user is null
return response()->json(['message' => 'User not found'], 404);
}
$userData['links'] = $links->toArray();
$domain = $_SERVER['HTTP_HOST'];
$date = date('Y-m-d_H-i-s');
$fileName = "links-$domain-$date.json";
$headers = [
'Content-Type' => 'application/json',
'Content-Disposition' => 'attachment; filename="'.$fileName.'"',
];
return response()->json($userData, 200, $headers);
return back();
}
//Export all user data
public function exportAll(Request $request)
{
$userId = Auth::id();
$user = User::find($userId);
$links = Link::where('user_id', $userId)->get();
if (!$user) {
// handle the case where the user is null
return response()->json(['message' => 'User not found'], 404);
}
$userData = $user->toArray();
$userData['links'] = $links->toArray();
if (file_exists(base_path(findAvatar($userId)))){
$imagePath = base_path(findAvatar($userId));
$imageData = base64_encode(file_get_contents($imagePath));
$userData['image_data'] = $imageData;
$imageExtension = pathinfo($imagePath, PATHINFO_EXTENSION);
$userData['image_extension'] = $imageExtension;
}
$domain = $_SERVER['HTTP_HOST'];
$date = date('Y-m-d_H-i-s');
$fileName = "user_data-$domain-$date.json";
$headers = [
'Content-Type' => 'application/json',
'Content-Disposition' => 'attachment; filename="'.$fileName.'"',
];
return response()->json($userData, 200, $headers);
return back();
}
public function importData(Request $request)
{
try {
// Get the JSON data from the uploaded file
if (!$request->hasFile('import') || !$request->file('import')->isValid()) {
throw new \Exception('File not uploaded or is faulty');
}
$file = $request->file('import');