-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.php
2710 lines (2411 loc) · 96.8 KB
/
index.php
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
/**
* SyncMarks
*
* @version 2.0.2
* @author Offerel
* @copyright Copyright (c) 2024, Offerel
* @license GNU General Public License, version 3
*/
session_start();
include_once "config.inc.php.dist";
include_once "config.inc.php";
define("CONFIG", [
'db' => $database,
'logfile' => $logfile,
'realm' => $realm,
'loglevel' => $loglevel,
'sender' => $sender,
'suser' => $suser,
'spwd' => $spwd,
'cexp' => $cexpjson,
'enckey' => $enckey,
'enchash' => $enchash,
'expireDays'=> (!isset($expireDays)) ? 7:$expireDays
]);
class language {
public $data;
function __construct($language) {
$defaultFile = "./locale/en.json";
$requestFile = "./locale/".$language.".json";
$languagFile = file_exists($requestFile) ? $requestFile:$defaultFile;
$rdata = file_get_contents($languagFile);
$ddata = file_get_contents($defaultFile);
$r_object = json_decode($rdata);
$d_object = json_decode($ddata);
foreach ($d_object as $key => $area) {
foreach ($area as $index => $value) {
if(isset($r_object->$key->$index)) {
$d_object->$key->$index = $r_object->$key->$index;
} else {
$d_object->$key->$index = $d_object->$key->$index;
}
}
}
$this->data = $d_object;
}
function translate() {
return $this->data;
}
}
$le = "";
set_error_handler("e_log");
$version = explode ("\n", file_get_contents('./CHANGELOG.md',NULL,NULL,0,30))[1];
$version = explode(" ", $version)[1];
$headers = getallheaders();
if(isset($headers['X-Action']) && $headers['X-Action'] === 'verify') {
header("X-SyncMarks: $version");
die(http_response_code(204));
}
if(!isset($_SESSION['sauth'])) checkDB();
$htmlFooter = "<div id = \"mnubg\"></div><div id='pwamessage'></div></body></html>";
saveRequest();
$lang = setLang();
if(isset($_GET['reset'])){
$reset = filter_var($_GET['reset'], FILTER_SANITIZE_STRING);
$headers = "From: SyncMarks <".CONFIG['sender'].">"."\r\n";
switch($reset) {
case "request":
$user = filter_var($_GET['u'], FILTER_SANITIZE_STRING);
e_log(8,"Password Reset request for '$user'");
$user = filter_var($_GET['u'], FILTER_SANITIZE_STRING);
$query = "SELECT `userID`, `userMail` FROM `users` WHERE `userName` = '$user';";
$result = db_query($query)[0];
$uid = $result['userID'];
$mail = $result['userMail'];
$token = openssl_random_pseudo_bytes(16);
$token = bin2hex($token);
$time = time();
$query = "DELETE FROM `reset` WHERE `userID` = $uid;";
db_query($query);
$query = "INSERT INTO `reset`(`userID`,`tokenTime`,`token`) VALUES ($uid,'$time','$token');";
if(db_query($query)) {
$message = "Hello $user,\r\nYou requested a new password for your account. If this is correct, please open the following link, to confirm creating a new password:\n".$_SERVER['REQUEST_SCHEME']."://".$_SERVER['HTTP_HOST'].$_SERVER['SCRIPT_NAME']."?reset=confirm&t=$token\r\nIf this request is not from your side, you should click the following link to chancel the request:\n".$_SERVER['REQUEST_SCHEME']."://".$_SERVER['HTTP_HOST'].$_SERVER['SCRIPT_NAME']."?reset=chancel&t=$token";
if(!mail($mail, "Password request confirmation", $message, $headers)) {
e_log(1,"Error sending password reset request to user");
}
}
die(json_encode("1"));
break;
case "chancel":
$token = filter_var($_GET['t'], FILTER_SANITIZE_STRING);
$query = "SELECT `r`.`userID`, `u`.`userName`, `u`.`userMail`, `r`.`tokenTime`, `r`.`token` FROM `reset` `r` INNER JOIN `users` `u` ON `u`.`userID` = `r`.`userID` WHERE `token` = '$token';";
$result = db_query($query)[0];
e_log(8,"Password Reset chancel for token '$token', '".$result['userName']."'");
$query = "DELETE FROM `reset` WHERE `token` = '$token';";
if(db_query($query)) {
e_log(8,"Request removed successful");
$message = "Hello ".$result['userName'].",\r\nYour password request is canceled, You can login with your old credentials at ".$_SERVER['REQUEST_SCHEME']."://".$_SERVER['HTTP_HOST'].$_SERVER['SCRIPT_NAME'].". If you want to make sure, that your account is healthy, you should change your password to a new one after logging in.";
if(!mail($result['userMail'], "Password request canceled", $message, $headers)) {
e_log(1,"Error sending remove chancel to ".$result['userName']);
}
}
echo htmlHeader();
echo "<div id='loginbody'>
<div id='loginform'>
<div id='loginformh'>".$lang->messages->welcome."</div>
<div id='loginformt'>".$lang->messages->resetCancelHint."</div>
<div id='loginformf'><a class='abtn' href='?'>".$lang->actions->login."</a></div>
</div>
</div>";
echo $htmlFooter;
die();
break;
case "confirm":
$token = filter_var($_GET['t'], FILTER_SANITIZE_STRING);
$query = "SELECT `r`.`userID`, `u`.`userName`, `u`.`userMail`, `r`.`tokenTime`, `r`.`token` FROM `reset` `r` INNER JOIN `users` `u` ON `u`.`userID` = `r`.`userID` WHERE `token` = '$token';";
$result = db_query($query)[0];
e_log(8,"Password Reset confirmation for token '$token', '".$result['userName']."'");
$tdiff = time() - $result['tokenTime'];
if($tdiff <= 300) {
$npwd = gpwd(16);
$pwd = password_hash($npwd,PASSWORD_DEFAULT);
$query = "UPDATE `users` SET `userHash` = '$pwd' WHERE `userID` = ".$result['userID'].";";
if(db_query($query)) {
$query = "DELETE FROM `reset` WHERE `token` = '$token';";
if(db_query($query)) {
e_log(8,"New password set successful");
$message = "Hello ".$result['userName'].",\r\nYour new password is set successful, please use:\n$npwd\n\nYou can login at:\n".$_SERVER['REQUEST_SCHEME']."://".$_SERVER['HTTP_HOST'].$_SERVER['SCRIPT_NAME'];
if(!mail($result['userMail'], "New password", $message, $headers)) {
e_log(1,"Error sending new password to ".$result['userName']);
}
}
} else {
e_log(1,"Password reset failed");
die(json_encode("Password reset failed"));
}
echo htmlHeader();
echo "<div id='loginbody'>
<div id='loginform'>
<div id='loginformh'>".$lang->messages->welcome."</div>
<div id='loginformt'>".$lang->messages->resetSuccessHint."</div>
<div id='loginformf'><a class='abtn' href='?'>".$lang->actions->login."</a></div>
</div>
</div>";
echo $htmlFooter;
} else {
echo htmlHeader();
echo "<div id='loginbody'>
<div id='loginform'>
<div id='loginformh'>".$lang->messages->welcome."</div>
<div id='loginformt'>".$lang->messages->tokenExpired."</div>
<div id='loginformf'><a class='abtn' href='?'>".$lang->actions->login."</a></div>
</div>
</div>";
echo $htmlFooter;
e_log(1,"Token expired, Password reset failed");
$query = "DELETE FROM `reset` WHERE `token` = '$token';";
db_query($query);
die();
}
break;
default:
die(e_log(1,"Undefined Request"));
}
die();
}
if(!isset($_SESSION['sauth'])) checkLogin(CONFIG['realm']);
if(!isset($_SESSION['sud'])) getUserdataS();
$lang = setLang();
if (isset($_GET['api'])) {
$jdata = json_decode(file_get_contents('php://input'), true);
$jerror = json_last_error();
$jerrmsg = parseJError($jerror);
saveDebugJSON("api_request", $jdata);
if($jerror == JSON_ERROR_NONE) {
if(isset($jdata['action'])) {
$action = $jdata['action'];
$client = $jdata['client'];
$data = isset($jdata['data']) ? $jdata['data']:false;
$time = round(microtime(true) * 1000);
$ctype = getClientType(isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT']:"Unknown");
$uid = $_SESSION['sud']['userID'];
switch($action) {
case "clientCheck":
$response = clientCheck($client, $time, $ctype, $uid);
break;
case "clientRename":
$response = clientRename($client, $data, $uid);
if(!is_array($response)) die($response);
break;
case "clientInfo":
$response = clientInfo($client, $uid);
break;
case "clientList":
$response = clientList($client, $uid);
break;
case "clientRemove":
$response = clientRemove($client, $data);
break;
case "clientSendOptions":
$response = clientSaveOptions($client, $data, $uid);
break;
case "clientGetOptions":
$response = clientGetOptions($client, $uid);
e_log(2, print_r($response, true));
break;
case "pushURL":
$response = ntfyNotification($data, $uid);
break;
case "pushGet":
$response = pushGet($client, $uid);
break;
case "pushHide":
$response = durl($data, $uid);
break;
case "bookmarkExport":
$response = bookmarkExport($ctype, $time, $data, $client);
break;
case "bookmarkImport":
$response = bookmarkImport($data, $client, $ctype, $time, $uid);
break;
case "bookmarkAdd":
$response = bookmarkAdd($data, $time, $ctype, $client);
break;
case "bookmarkDel":
$response = bookmarkDel($data, $uid);
break;
case "bookmarkMove":
$response = bookmarkMove($data, $client, $time, $uid);
break;
case "bookmarkEdit":
$response = (array_key_exists('url', $data)) ? editBookmark($data, $time, $uid):editFolder($data, $time, $uid);
break;
case "tabsGet":
$response = tabsGet($uid);
break;
case "tabsSend":
$response = tabsSend($data, $uid, $time);
break;
default:
$response['message'] = "Undefined action '$action'";
$response['code'] = 501;
}
}
} else {
e_log(1, "JSON error: ".$jerrmsg);
saveDebugJSON("incom_jerr", $jdata);
$response['message'] = 'Invalid JSON. '.$jerrmsg;
$response['code'] = 500;
}
sendJSONResponse($response);
}
if(isset($_POST['action'])) {
$uid = $_SESSION['sud']['userID'];
$client = (isset($_POST['client'])) ? filter_var($_POST['client'], FILTER_SANITIZE_STRING) : '0';
$data = filter_var($_POST['data'], FILTER_SANITIZE_STRING);
$time = round(microtime(true) * 1000);
$ctype = getClientType($_SERVER['HTTP_USER_AGENT']);
$add = filter_var($_POST['add'], FILTER_SANITIZE_STRING);
switch($_POST['action']) {
case "getclients":
$response = clientList($client, $uid);
sendJSONResponse($response);
break;
case "gurls":
$response = pushGet($client, $uid);
sendJSONResponse($response);
break;
case "bexport":
$response = bookmarkExport($ctype, $time, $data, $client);
sendJSONResponse($response);
break;
case "addmark":
$bookmark = json_decode($_POST['data'], true);
$response = bookmarkAdd($bookmark, $time, $ctype, $client, $add);
sendJSONResponse($response);
break;
case "pushHide":
e_log(8,"Hide notification");
$page = filter_var($_POST['data'], FILTER_VALIDATE_INT);
$query = "UPDATE `pages` SET `nloop`= 0, `ntime`= '".time()."' WHERE `pid` = $page AND `userID` = $uid";
sendJSONResponse(db_query($query));
break;
case "arename":
$client = filter_var($_POST['client'], FILTER_SANITIZE_STRING);
$response = clientRename($add, $data, $uid, true);
sendJSONResponse($response);
break;
case "cfolder":
sendJSONResponse(cfolder($time, $data, $add));
break;
case "rmessage":
$message = isset($_POST['data']) ? filter_var($_POST['data'], FILTER_VALIDATE_INT):0;
$loop = filter_var($_POST['add'], FILTER_SANITIZE_STRING) == 'aNoti' ? 1:0;
if($message > 0) {
e_log(8,"Try to delete page $message");
$query = "DELETE FROM `pages` WHERE `userID` = ".$_SESSION['sud']['userID']." AND `pid` = $message;";
$count = db_query($query);
($count === 1) ? e_log(8,"Notification successfully removed") : e_log(9,"Error, removing notification");
}
sendJSONResponse(notiList($uid, $loop));
break;
case "soption":
$value = filter_var(filter_var($_POST['add'], FILTER_SANITIZE_NUMBER_INT), FILTER_VALIDATE_INT);
e_log(8,"Option received: ".$data.":".$value);
$oOptionsA = json_decode($_SESSION['sud']['uOptions'],true);
$oOptionsA[$data] = $value;
$query = "UPDATE `users` SET `uOptions`='".json_encode($oOptionsA)."' WHERE `userID`=$uid;";
header("Content-Type: application/json");
if(db_query($query) !== false) {
e_log(8,"Option saved");
sendJSONResponse(json_encode(true));
} else {
e_log(9,"Error, saving option");
sendJSONResponse(json_encode(false));
}
break;
case "bmedt":
$bookmark = json_decode($_POST['data'], true);
$title = filter_var($bookmark['title'], FILTER_SANITIZE_STRING);
$id = filter_var($bookmark['id'], FILTER_SANITIZE_STRING);
$url = (isset($bookmark['url']) && strlen($bookmark['url']) > 4) ? '\''.validate_url($bookmark['url']).'\'' : 'NULL';
e_log(8, "Edit entry '$title'");
$query = "UPDATE `bookmarks` SET `bmTitle` = '$title', `bmURL` = $url, `bmAdded` = '$time' WHERE `bmID` = '$id' AND `userID` = $uid;";
$count = db_query($query);
($count > 0) ? sendJSONResponse(true):sendJSONResponse(false);
break;
case "bmmv":
e_log(8,"Move bookmark $add");
$query = "SELECT IFNULL(MAX(bmIndex), 0) + 1 AS 'index' FROM `bookmarks` WHERE `bmParentID` = '$data';";
$folderData = db_query($query);
$query = "SELECT `bmParentID` FROM `bookmarks` WHERE `bmID` = '$add' AND `userID` = $uid;";
$oFolder = db_query($query)[0]['bmParentID'];
$query = "UPDATE `bookmarks` SET `bmIndex` = ".$folderData[0]['index'].", `bmParentID` = '$data', `bmAdded` = '$time' WHERE `bmID` = '$add' AND `userID` = $uid;";
$count = db_query($query);
reIndex($oFolder, $folderData[0]['index']);
$response = array("id" => $add, "folder" => $data);
($count > 0) ? sendJSONResponse($response):sendJSONResponse(false);
break;
case "adel":
$client = filter_var($_POST['data'], FILTER_SANITIZE_STRING);
e_log(8,"Delete client $client");
$query = "DELETE FROM `clients` WHERE `userID` = ".$_SESSION['sud']['userID']." AND `cid` = '$client';";
$count = db_query($query);
($count > 0) ? sendJSONResponse(bClientlist($_SESSION['sud']['userID'])):sendJSONResponse(false);
break;
case "cmail":
e_log(8,"Change e-mail for ".$_SESSION['sud']['userName']);
$nmail = filter_var($_POST['mail'],FILTER_SANITIZE_EMAIL);
header("Content-Type: application/json");
if(filter_var($nmail, FILTER_VALIDATE_EMAIL)) {
$query = "UPDATE `users` SET `userMail` = '$nmail' WHERE `userID` = ".$_SESSION['sud']['userID'].";";
die(json_encode(db_query($query)));
} else {
e_log(1,"No valid E-Mail. Stop changing E-Mail");
die(json_encode("No valid mail address. Mail not changed."));
}
die();
break;
case "muedt":
if($_SESSION['sud']['userType'] < 2) {
e_log(1,"Stop user change, no sufficient privileges.");
die();
}
$del = false;
$headers = "From: SyncMarks <".CONFIG['sender'].">"."\r\n";
$url = $_SERVER['REQUEST_SCHEME']."://".$_SERVER['HTTP_HOST'].$_SERVER['SCRIPT_NAME'];
$data = json_decode($_POST['data'], true);
$variant = filter_var($data['type'], FILTER_VALIDATE_INT);
$password = (isset($data['p']) && $data['p'] != '') ? filter_var($data['p'], FILTER_SANITIZE_STRING):gpwd(16);
$userLevel = filter_var($data['userLevel'], FILTER_VALIDATE_INT);
$user = filter_var($data['nuser'], FILTER_SANITIZE_STRING);
$mail = filter_var($user, FILTER_VALIDATE_EMAIL) ? $user:null;
switch($variant) {
case 1:
$pwd = password_hash($password,PASSWORD_DEFAULT);
e_log(8,"Try to add new user $user");
$query = "INSERT INTO `users` (`userName`,`userMail`,`userType`,`userHash`) VALUES ('$user', NULLIF('$mail',''), '$userLevel', '$pwd')";
$nuid = db_query($query);
if($nuid > 0) {
if(filter_var($mail, FILTER_VALIDATE_EMAIL)) {
$response = $nuid;
$message = "Hello,\r\na new account with the following credentials is created for SyncMarks:\r\nUsername: $user\r\nPassword: $password\r\n\r\nYou can login at $url";
if(!mail ($mail, "Account created",$message,$headers)) {
e_log(1,"Error sending data for created user account to user");
$response = "User created successful, E-Mail could not send";
}
} else {
$response = $nuid;
}
$bmAdded = round(microtime(true) * 1000);
$query = "INSERT INTO `bookmarks` (`bmID`,`bmIndex`, `bmType`, `bmAdded`, `userID`) VALUES ('root________', 0, 'folder', $bmAdded, $nuid);";
db_query($query);
$query = "INSERT INTO `bookmarks` (`bmID`,`bmParentID`,`bmIndex`,`bmTitle`,`bmType`,`bmURL`,`bmAdded`,`userID`) VALUES ('unfiled_____', 'root________', 0, 'Other Bookmarks', 'folder', NULL, $bmAdded, $nuid)";
db_query($query);
$query = "INSERT INTO `bookmarks` (`bmID`,`bmParentID`,`bmIndex`,`bmTitle`,`bmType`,`bmURL`,`bmAdded`,`userID`) VALUES ('".unique_code(12)."', 'unfiled_____', 0, 'Git Repository', 'bookmark', 'https://codeberg.org/Offerel', $bmAdded, $nuid)";
db_query($query);
} else {
$response = "User creation failed";
}
break;
case 2:
e_log(8,"Updating user $user");
$uID = filter_var($data['userSelect'], FILTER_VALIDATE_INT);
$query = "UPDATE `users` SET `userName`= '$user', `userType`= '$userLevel' WHERE `userID` = $uID;";
if(db_query($query) == 1) {
if(filter_var($user, FILTER_VALIDATE_EMAIL)) {
$response = "User changed successful, Try to send E-Mail to user";
$message = "Hello,\r\nyour account is changed for SyncMarks. You can login at $url";
if(!mail ($user, "Account changed",$message,$headers)) e_log(1,"Error sending email for changed user account");
} else {
$response = "User changed successful, No mail send to user";
}
} else {
$response = "User change failed";
}
break;
case 3:
e_log(8,"Delete user $user");
$uID = filter_var($data['userSelect'], FILTER_VALIDATE_INT);
$query = "DELETE FROM `users` WHERE `userID` = $uID;";
if(db_query($query) == 1) {
if(filter_var($user, FILTER_VALIDATE_EMAIL)) {
$response = "User deleted, Try to send E-Mail to user";
$message = "Hello,\r\nyour account '$user' and all it's data is removed from $url.";
if(!mail ($user, "Account removed",$message,$headers)) e_log(1,"Error sending data for created user account to user");
} else {
$response = "User deleted successful, No mail send to user";
}
} else {
$response = "Delete user failed";
}
break;
default:
$response = "Unknown action for managing users";
e_log(1,$response);
}
sendJSONResponse($response);
break;
case "mlog":
if($_SESSION['sud']['userType'] > 1) {
$lfile = is_dir(CONFIG['logfile']) ? CONFIG['logfile'].'/syncmarks.log':CONFIG['logfile'];
sendJSONResponse(file_get_contents($lfile));
} else {
$message = "Not allowed to read server logfile.";
e_log(2,$message);
sendJSONResponse($message);
}
break;
case "mrefresh":
if($_SESSION['sud']['userType'] > 1) {
$lfile = is_dir(CONFIG['logfile']) ? CONFIG['logfile'].'/syncmarks.log':CONFIG['logfile'];
sendJSONResponse(file_get_contents($lfile));
} else {
$message = "Not allowed to read server logfile.";
e_log(2,$message);
sendJSONResponse($message);
}
break;
case "mclear":
e_log(8,"Clear logfile");
if($_SESSION['sud']['userType'] > 1) {
$lfile = is_dir(CONFIG['logfile']) ? CONFIG['logfile'].'/syncmarks.log':CONFIGg['logfile'];
file_put_contents($lfile,"");
sendJSONResponse(file_get_contents($lfile));
}
die();
break;
case "mdel":
$bmID = json_decode($_POST['data'], true);
$response = delMark($bmID);
sendJSONResponse($bmID);
break;
case "logout":
e_log(8,"Logout user ".$_SESSION['sauth']);
unset($_SESSION['sauth']);
clearAuthCookie();
e_log(8,"User logged out");
if(!isset($_POST['client'])) {
echo htmlHeader();
echo "<div id='loginbody'>
<div id='loginform'>
<div id='loginformh'>".$lang->messages->logoutSuccess."</div>
<div id='loginformt'>".$lang->messages->logoutSuccessHint."</div>
<div id='loginformf'><a class='abtn' href='?'>".$lang->actions->login."</a></div>
</div>
</div>";
echo $htmlFooter;
}
session_destroy();
exit;
break;
case "ntfyupdate":
e_log(8,"ntfy: Updating ntfy information.");
$password = filter_var($_POST['password'], FILTER_SANITIZE_STRING);
$cnoti = filter_var($_POST['cnoti'], FILTER_VALIDATE_INT);
$ntfyInstance = filter_var($_POST['ntfyInstance'], FILTER_SANITIZE_STRING);
$ntfyToken = filter_var($_POST['ntfyToken'], FILTER_SANITIZE_STRING);
if(password_verify($password,$_SESSION['sud']['userHash'])) {
$ntfyToken = edcrpt('en', $ntfyToken);
$oOptionsA = json_decode($_SESSION['sud']['uOptions'],true);
$oOptionsA['notifications'] = $cnoti;
$oOptionsA['ntfy']['instance'] = $ntfyInstance;
$oOptionsA['ntfy']['token'] = $ntfyToken;
$query = "UPDATE `users` SET `uOptions`='".json_encode($oOptionsA)."' WHERE `userID`=".$_SESSION['sud']['userID'].";";
$count = db_query($query);
($count === 1) ? e_log(8,"Option saved") : e_log(9,"Error, saving option");
header("location: ?");
die();
}
else {
e_log(1,"Password mismatch. ntfy info not updated.");
die("Password mismatch. ntfy info not updated.");
}
die();
break;
case "langupdate":
$nlng = filter_var($_POST['data'], FILTER_SANITIZE_STRING);
$oOptionsA = json_decode($_SESSION['sud']['uOptions'],true);
$oOptionsA['language'] = $nlng;
$query = "UPDATE `users` SET `uOptions`='".json_encode($oOptionsA)."' WHERE `userID`=".$_SESSION['sud']['userID'].";";
(db_query($query) === 1) ? e_log(8,"Language option saved") : e_log(9,"Error, saving language option");
$_SESSION['sud']['uOptions'] = json_encode($oOptionsA);
die("1");
break;
case "uupdate":
e_log(8,"User change: Updating user name started");
$opassword = filter_var($_POST['opassword'], FILTER_SANITIZE_STRING);
$username = filter_var($_POST['username'], FILTER_SANITIZE_STRING);
if($opassword != "") {
e_log(8,"User change: Data complete entered");
if(password_verify($opassword, $_SESSION['sud']['userHash'])) {
e_log(8,"User change: Verify original password");
$query = "UPDATE `users` SET `userName`='$username' WHERE `userID`=".$_SESSION['sud']['userID'].";";
db_query($query);
e_log(8,"User change: Username changed");
}
else {
e_log(2,"User change: Failed to verify original password");
}
}
else {
e_log(2,"User change: Data missing");
}
unset($_SESSION['sauth']);
e_log(8,"User logged out");
echo htmlHeader();
echo "<div id='loginbody'>
<div id='loginform'>
<div id='loginformh'>".$lang->messages->logoutSuccess."</div>
<div id='loginformt'>".$lang->messages->logoutSuccessHint."</div>
<div id='loginformf'><a class='abtn' href='?'>".$lang->actions->login."</a></div>
</div>
</div>";
echo $htmlFooter;
die();
break;
case "getUsers":
header("Content-Type: application/json");
if($_SESSION['sud']['userType'] == 2) {
$query = "SELECT `userID`, `userName`, `userType` FROM `users` ORDER BY `userName`;";
$uData = db_query($query);
die(json_encode($uData));
} else {
die(json_encode('Editing users not allowed'));
}
break;
case "checkdups":
e_log(8,"Checking for duplicated bookmarks by url");
$query = "SELECT `bmID`, `bmTitle`, `bmURL` FROM `bookmarks` WHERE `bmType` = 'bookmark' AND `userID` = ".$_SESSION['sud']['userID']." GROUP BY `bmURL` HAVING COUNT(`bmURL`) > 1;";
$dubData = db_query($query);
foreach($dubData as $key => $dub) {
$query = "SELECT `bmID`, `bmParentID`, `bmTitle`, `bmAdded` FROM `bookmarks` WHERE `bmType` = 'bookmark' AND `bmURL` = '".$dub['bmURL']."' AND `userID` = ".$_SESSION['sud']['userID']." ORDER BY `bmParentID`, `bmIndex`;";
$subData = db_query($query);
foreach($subData as $index => $entry) {
$subData[$index]['fway'] = fWay($entry['bmParentID'], $_SESSION['sud']['userID'],'');
}
$dubData[$key]['subs'] = $subData;
}
e_log(2, print_r($dubData, true));
sendJSONResponse($dubData);
break;
default:
die(e_log(1, "Unknown Action ".$_POST['action']));
}
}
if(isset($_GET['link'])) {
$url = validate_url(trim($_GET["link"]));
e_log(9,"URL add request: " . $url);
$bookmark['url'] = $url;
$bookmark['folder'] = 'unfiled_____';
$bookmark['title'] = (isset($_GET["title"]) && $_GET["title"] != '') ? filter_var($_GET["title"], FILTER_SANITIZE_STRING):getSiteTitle($url);;
$bookmark['id'] = unique_code(12);
$bookmark['type'] = 'bookmark';
$bookmark['added'] = round(microtime(true) * 1000);
$uas = array(
"HttpShortcuts",
"Tasker",
"Android"
);
$so = false;
foreach($uas as $ua) {
if(strpos($_SERVER['HTTP_USER_AGENT'], $ua) !== false || isset($_GET["client"])) {
$so = true;
break;
}
}
saveDebugJSON("addmark", $bookmark);
$res = addBookmark($bookmark);
if($res == "Bookmark added") {
$message = ($so) ? "URL added.":"<script>window.onload = function() { window.close();}</script>";
} else {
$message = $res;
}
e_log(8, $message);
die($message);
}
if(isset($_GET['push'])) {
$url = validate_url($_GET['push']);
e_log(8,"Received new pushed URL from bookmarklet: ".$url);
$data['url'] = $url;
$data['target'] = (isset($_GET['tg'])) ? filter_var($_GET['tg'], FILTER_SANITIZE_STRING):NULL;
if(ntfyNotification($data, $_SESSION['sud']['userID']) !== 0) die('Pushed');
}
echo htmlHeader();
echo htmlForms();
echo showBookmarks(2);
echo $htmlFooter;
function setLang() {
$lng = isset($_SESSION['sud']) ? json_decode($_SESSION['sud']['uOptions'], true)['language']:substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
$lng = isset($lng) ? $lng:'en';
$language = new language($lng);
$lang = $language->translate();
return $lang;
}
function tabsSend($jtabs, $user, $added) {
$urls = [];
foreach ($jtabs as $tab) {
$urls[] = $tab['url'];
}
$jurls = trim(json_encode($urls, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), '[]');
$query = "DELETE FROM `bookmarks` WHERE `bmID` IN (SELECT `bmID` FROM `bookmarks` WHERE `bmURL` NOT IN ($jurls) AND `bmType` = 'tab' AND `userID` = $user);";
$res = db_query($query);
foreach ($jtabs as $key => $tab) {
$tID = unique_code(12);
$title = trim($tab['title']);
$url = $tab['url'];
$query = "SELECT count(*) AS count FROM `bookmarks` WHERE `bmType` = 'tab' AND `bmURL` = '$url' AND `userID` = $user;";
$res = db_query($query)[0]['count'];
if($res == 0) {
$query = "INSERT INTO `bookmarks` (`bmID`, `bmIndex`, `bmTitle`, `bmType`, `bmURL`, `bmAdded`, `userID`) VALUES ('$tID', $key, '$title', 'tab', '$url', '$added', $user);";
$res = db_query($query);
}
}
$response['tabs'] = count($jtabs);
return $response;
}
function clientGetOptions($client, $uid) {
e_log(8, "Request of client settings");
$query = "SELECT `cid`, IFNULL(`cname`, `cid`) AS `cname`, `cOptions` FROM `clients` WHERE `userID` = $uid AND `cOptions` IS NOT NULL AND `cid` != '$client';";
$cOptions = db_query($query);
$response['cOptions'] = $cOptions;
$response['code'] = 200;
return $response;
}
function clientRemove($client, $data) {
$old = $data['old'];
$new = $data['new'];
$res = 0;
e_log(8, "A client has been restored from the server configuration. This new client requested to remove the old client '$old'");
$query = "DELETE FROM `clients` WHERE `cid` = '$old';";
$res = db_query($query);
if($res == 1) {
$response['message'] = "Old client removed";
$response['code'] = 200;
$res = 8;
} else {
$response['message'] = "Could not remove old client";
$response['code'] = 500;
$res = 1;
}
e_log($res, $response['message']);
return $response;
}
function tabsGet($user) {
e_log(8, "Request tabs for user '$user'");
$query = "SELECT * FROM `bookmarks` WHERE `bmType` = 'tab' AND `userID` = $user;";
$tabs = db_query($query);
$response['tabs'] = $tabs;
return $response;
}
function durl($pid, $uid) {
e_log(8,"Hide notification");
if(db_query("UPDATE `pages` SET `nloop`= 0, `ntime`= '".time()."' WHERE `pid` = $pid AND `userID` = $uid;") == 1) {
$response['message'] = "Notification is now hidden";
$response['code'] = 200;
} else {
$response['error'] = "Update failed";
$response['code'] = 500;
}
return $response;
}
function pushGet($client, $uid) {
e_log(8,"Request pushed sites for '$client'");
$query = "SELECT * FROM `pages` WHERE `nloop` = 1 AND `userID` = $uid AND (`cid` IN ('$client') OR `cid` IS NULL);";
$options = json_decode($_SESSION['sud']['uOptions'],true);
$notificationData = db_query($query);
if (!empty($notificationData)) {
e_log(8,"Found ".count($notificationData)." links. Will send them to the client.");
foreach($notificationData as $key => $notification) {
$myObj[$key]['title'] = html_entity_decode($notification['ptitle'], ENT_QUOTES | ENT_XML1, 'UTF-8');
$myObj[$key]['url'] = $notification['purl'];
$myObj[$key]['nkey'] = $notification['pid'];
}
$response['enabled'] = $options['notifications'];
$response['notifications'] = $myObj;
} else {
$msg = "No pushed sites found";
e_log(8,$msg);
$response['message'] = $msg;
$response['code'] = 200;
}
if(isset($_COOKIE['syncmarks']))
e_log(8,'Cookie is available');
else
e_log(8,'Cookie is not set');
return $response;
}
function clientSaveOptions($client, $cOptions) {
e_log(8,"Save client options to database");
$jOptions = json_encode($cOptions);
$name = $cOptions['name'];
$query = "UPDATE `clients` SET `cOptions` = '$jOptions', `cname` = '$name' WHERE `cid` = '$client';";
$result = db_query($query);
if($result == 1) {
$response['message'] = "Client settings saved";
$response['code'] = 200;
$lvl = 8;
} else {
$response['message'] = "No client data changed";
$response['code'] = 200;
$lvl = 1;
}
return $response;
}
function clientList($client, $uid) {
e_log(8,"Try to get list of clients");
$query = "SELECT `cid`, IFNULL(`cname`, `cid`) `cname`, `ctype`, `lastseen` FROM `clients` WHERE `userID` = $uid AND NOT `cid` = '$client';";
$clientList = db_query($query);
e_log(8,"Found ".count($clientList)." clients. Send list to '$client'.");
uasort($clientList, function($a, $b) {
return strnatcasecmp($a['cname'], $b['cname']);
});
if (!empty($clientList)) {
foreach($clientList as $key => $clients) {
$myObj[$key]['id'] = $clients['cid'];
$myObj[$key]['name'] = $clients['cname'];
$myObj[$key]['type'] = $clients['ctype'];
$myObj[$key]['date'] = $clients['lastseen'];
}
$all = array('id'=>'0', 'name'=>'All Clients', 'type'=>'', 'date'=>'');
array_unshift($myObj, $all);
} else {
$myObj[0]['id'] = '0';
$myObj[0]['name'] = 'All Clients';
$myObj[0]['type'] = '';
$myObj[0]['date'] = '';
$response['error'] = "No clients found";
$response['code'] = 500;
}
saveDebugJSON("clist", $myObj);
$response['clients'] = $myObj;
return $response;
}
function parseJError($jerror) {
switch ($jerror) {
case JSON_ERROR_NONE:
$jerrmsg = '';
break;
case JSON_ERROR_DEPTH:
$jerrmsg = 'Maximum stack depth exceeded';
break;
case JSON_ERROR_STATE_MISMATCH:
$jerrmsg = 'Underflow or the modes mismatch';
break;
case JSON_ERROR_CTRL_CHAR:
$jerrmsg = 'Unexpected control character found';
break;
case JSON_ERROR_SYNTAX:
$jerrmsg = 'Syntax error, malformed JSON';
break;
case JSON_ERROR_UTF8:
$jerrmsg = 'Malformed UTF-8 characters, possibly incorrectly encoded';
break;
default:
$jerrmsg = 'Unknown error';
}
return $jerrmsg;
}
function bookmarkExport($ctype, $ctime, $format, $client) {
e_log(8,"Request bookmark export");
switch($format) {
case "html":
e_log(8,"Exporting in HTML format for download");
$response['bookmarks'] = html_export();
break;
case "json":
e_log(8,"Exporting in JSON format");
$bookmarks = getBookmarks();
saveDebugJSON("export", $bookmarks);
$bcount = count($bookmarks);
e_log(8,"Send $bcount bookmarks to '$client'");
updateClient($client, $ctype, $ctime);
$response['bookmarks'] = $bookmarks;
break;
default:
$msg = "Unknown export format, exit process";
e_log(2, $msg);
$response['error'] = $msg;
$response['code'] = 501;
}
return $response;
}
function bookmarkImport($jmarks, $client, $ctype, $ctime, $user) {
saveDebugJSON("import", $jmarks);
if(is_array($jmarks)) {
if(isset($jmarks[0]['children'])) {
delUsermarks($user);
$armarks = parseJSON($jmarks);
$response = importMarks($armarks, $user);
} else {
$response['message'] = "Invalid import data";
$response['code'] = 500;
}
} else {
$response['message'] = "Import data is not an array";
$response['code'] = 500;
}
updateClient($client, $ctype, $ctime);
return $response;
}
function bookmarkAdd($bookmark, $stime, $ctype, $client, $add = null) {
$bookmark = (is_array($bookmark)) ? $bookmark:json_decode($bookmark, true);
$bookmark['added'] = $stime;
$bookmark['title'] = ($bookmark['title'] === '') ? getSiteTitle(trim($bookmark['url'])):htmlspecialchars(mb_convert_encoding(htmlspecialchars_decode($bookmark['title'], ENT_QUOTES),"UTF-8"),ENT_QUOTES,'UTF-8', false);
e_log(8,"Try to add new bookmark '".$bookmark['title']."'");
e_log(9, print_r($bookmark, true));
if(array_key_exists('url',$bookmark)) $bookmark['url'] = validate_url($bookmark['url']);
if($ctype != "firefox") $bookmark = cfolderMatching($bookmark);
if($bookmark['type'] == 'bookmark' && isset($bookmark['url'])) {
$erg['message'] = addBookmark($bookmark);
$erg['code'] = ($erg['message'] === 'Bookmark added') ? 200:500;
if($add === '2') {
if($erg['message'] === "Bookmark added") {
e_log(8, $erg['message']);
$erg['html_bookmarks'] = bmTree();
} else {
$erg['message'] = 'Bookmark not added';
$erg['code'] = 417;
}
} else {
updateClient($client, $ctype, $stime);
}
} else if($bookmark['type'] == 'folder') {
$erg['addFolder'] = addFolder($bookmark);
updateClient($client, $ctype, $stime);
} else {
$message = "This bookmark is not added, some parameters are missing";
e_log(1, $message);
$erg['message'] = $message;
$erg['code'] = 500;
}
return $erg;
}
function bookmarkDel($bookmark, $user) {
$bookmark = json_decode($bookmark, true);
e_log(8,"Try to identify bookmark to delete");
if(isset($bookmark['url'])) {
$query = "SELECT DISTINCT a.bmID FROM `bookmarks` a INNER JOIN `bookmarks` b ON a.bmParentID = b.bmID WHERE a.`bmURL` = '".$bookmark['url']."' AND a.`userID` = $user AND b.bmTitle = '".$bookmark['nfolder']."';";
} else {
$query = "SELECT `bmID` FROM `bookmarks` WHERE `bmType` = 'folder' AND `bmTitle` = '".$bookmark['title']."' AND `userID` = $user;";
}
$bData = db_query($query);
if(count($bData) > 0) {
e_log(8, "Bookmark found, trying to remove it");
$bookmarks = array();
foreach ($bData as $key => $bookmark) {
$bookmarks[] = $bookmark['bmID'];
}
$erg = delMark($bookmarks);
$message = ($erg == 1) ? "Bookmark deleted":"Delete Bookmark failed";
$code = ($erg == 1) ? 200:500;
} else {
$message = "Bookmark not found, mark as deleted";
$code = 200;
e_log(2, $message);
}
$response['message'] = $message;
$response['code'] = $code;
return $response;
}
function bookmarkMove($bookmark, $client, $ctime, $ctype) {
saveDebugJSON("movemark", $bookmark);
$response = moveBookmark($bookmark);
updateClient($client, $ctype, $ctime);
return $response;
}