-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWebDigServer.php
More file actions
1544 lines (1457 loc) · 71.4 KB
/
WebDigServer.php
File metadata and controls
1544 lines (1457 loc) · 71.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
// increase session timeout
ini_set("session.gc_maxlifetime", 3600);
// the maximum execution time (sec)
set_time_limit( 300 );
// initialize session
session_start();
include_once "msword.php";
$SITE_UNDER_MAINTENANCE = false;
if ( isset($_SESSION["SESSION_USERNAME"]) == false ) { $_SESSION["SESSION_USERNAME"] = "Guest"; }
if ( isset($_SESSION["SESSION_ACCESSLEVELS"]) == false ) { $_SESSION["SESSION_ACCESSLEVELS"] = ""; }
if ( isset($_SESSION["SESSION_START_SECS"]) == false ) { $_SESSION["SESSION_START_SECS"] = ""; } // PHP default session duration is 24 minutes
// make all dates/times to be counted based on NY,USA.
//date_default_timezone_set('America/New_York');
// init parameters
$Username = "";
$Password = "";
$Command = "";
$Arg1 = "";
$Arg2 = "";
$Arg3 = "";
if( isset($_POST["Username"]) ) { $Username = $_POST["Username"]; }
if( isset($_POST["Password"]) ) { $Password = $_POST["Password"]; }
if( isset($_POST["Command"]) ) { $Command = $_POST["Command"]; }
if( isset($_POST["Arg1"]) ) { $Arg1 = $_POST["Arg1"]; }
if( isset($_POST["Arg2"]) ) { $Arg2 = $_POST["Arg2"]; }
if( isset($_POST["Arg3"]) ) { $Arg3 = $_POST["Arg3"]; }
// init state
$UserIP = getClientIP();
$UserTime = 0; // Unix seconds UTC - used for timestamping the password before encryption in order to avoid copying of the ciphertext
$ServerTime = 0; // Unix seconds UTC - used for validating that the password's timestamp is recent enough
// decrypt password when user logs in
if( strlen($Username) > 0 && strlen($Password) > 0 ) {
$private_key = openssl_pkey_get_private( "file://webdig_key_rsa", "gu7c4kmhP4Wzi94ddwA2U2k94BfA8sw7" );
$private_key_details = openssl_pkey_get_details($private_key);
$encrypted_user_data = pack('H*', $Password); // convert data from hexadecimal notation
if (openssl_private_decrypt($encrypted_user_data, $decrypted_user_data, $private_key)) {
try {
$Password = substr($decrypted_user_data, 0, strpos($decrypted_user_data, " "));
$UserTime = intval(substr($decrypted_user_data, strpos($decrypted_user_data, " ")+1)); // Unix seconds UTC
$ServerTime = time(); // Unix seconds UTC
} catch(Exception $e) {
$Password = "wrong encryption format";
$UserTime = 0;
$ServerTime = 0;
}
} else {
$Password = "wrong encryption key";
$UserTime = 0;
$ServerTime = 0;
}
}
if( strcmp($Command, "GetExcavationData") == 0 ) { // ----------------------------------------------------------------------------------------------- GetExcavationData
$Compress = $Arg1;
Raise_ConcurrencyFlag();
$jsonString = file_get_contents("Data/ExcavationData.json");
// %%%%%%%% Guset users cannot see all fields %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if( strlen(trim($_SESSION["SESSION_USERNAME"]))==0 || strcmp($_SESSION["SESSION_USERNAME"],"Guest")==0 ) {
$NoGuestFields = ["Dimensions", "ArtifactDate", "Description", "Comparanda", "Color", "CoverageTemporal", "CoverageEarliest", "CoverageLatest", "CoverageArea", "Modifier", "Hue", "Boundary", "Sorting", "Sieve", "TotalWeight", "FineWareWeight", "CookWareWeight", "TileWeight", "AmphoraToes", "AmphoraLids", "CoarseWareWeight", "BoneFreshBreaksPercent", "BoneBags", "BoneNumberOfSpecimens", "BoneSource", "BoneWeight", "BoneSpecies", "BoneInterpretationOfContext", "BoneSpeciesNotes", "BoneTaphonomyNotes", "IssueAuthority", "Obverse", "Reverse", "Fabric", "Notes", "Denomination", "Diameter", "CoinWeight", "Axis", "Bibliography", "Additional bibliography"];
$ExcData = json_decode($jsonString, true);
for ($i=0; $i<count($ExcData); $i++) {
for ($j=0; $j<count($NoGuestFields); $j++) {
if( isset($ExcData[$i][$NoGuestFields[$j]]) ) unset( $ExcData[$i][$NoGuestFields[$j]] );
}
}
$jsonString = json_encode($ExcData);
}
// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
// Compose the reply, containing the data and their length
if( strcmp($Compress, "true") == 0 ) {
$Content = base64_encode( gzcompress($jsonString) );
} else {
$Content = $jsonString;
}
$ContentLength = strlen($Content);
//$msgJSON->ContentLength = $ContentLength;
//$msgJSON->Content = $Content;
//echo( json_encode($msgJSON) );
header('Content-Length: ' . $ContentLength);
echo( $Content );
LogThis( $UserIP, $_SESSION["SESSION_USERNAME"], $Command, $Compress );
Lower_ConcurrencyFlag();
} else if( strcmp($Command, "GetImagesData") == 0 ) { // ----------------------------------------------------------------------------------------------- GetExcavationData
$Compress = $Arg1;
Raise_ConcurrencyFlag();
$jsonString = file_get_contents("Data/ImagesData.json");
if( strcmp($Compress, "true") == 0 ) {
echo( base64_encode( gzcompress($jsonString) ) );
} else {
$ImagesData = json_decode($jsonString, true);
$jsonString = json_encode($ImagesData); // remove spaces of pretty-print to lessen transaction time
echo( $jsonString );
}
LogThis( $UserIP, $_SESSION["SESSION_USERNAME"], $Command, $Compress );
Lower_ConcurrencyFlag();
} else if( strcmp($Command, "GetItemData") == 0 ) { // ----------------------------------------------------------------------------------------------- GetItemData
$itemUUID = $Arg1;
Raise_ConcurrencyFlag();
$jsonString = file_get_contents("Data/ExcavationData.json");
$ExcData = json_decode($jsonString, true);
$item_idx = -1;
for ($i = 0; $i<count($ExcData); $i++) {
if( strcmp( $ExcData[$i]["IdentifierUUID"], $itemUUID) == 0 ) {
$item_idx = $i; break;
}
}
if ( $item_idx >= 0 ) {
echo( json_encode($ExcData[$item_idx]) );
} else {
echo "Error: Item '" . $itemUUID . "' not found";
}
Lower_ConcurrencyFlag();
} else if( strcmp($Command, "GetPreferences") == 0 ) { // ---------------------------------------------------------------------------------- GetPreferences
$Compress = $Arg1;
$jsonString = file_get_contents("Data/Preferences.json");
if( strcmp($Compress, "true") == 0 ) {
echo( base64_encode( gzcompress($jsonString) ) );
} else {
echo( $jsonString );
}
} else if( strcmp($Command, "GetDataChanges") == 0 ) { // ---------------------------------------------------------------------------------- GetPreferences
$Compress = $Arg1;
Raise_ConcurrencyFlag();
if( file_exists("DataChanges.txt") ) {
$FileContentsString = file_get_contents("DataChanges.txt");
if( strcmp($Compress, "true") == 0 ) {
echo( base64_encode( gzcompress($FileContentsString) ) );
} else {
echo( $FileContentsString );
}
} else {
echo "";
}
Lower_ConcurrencyFlag();
} else if( strcmp($Command, "GiveMeAnyNewData") == 0 ) { // ---------------------------------------------------------------------------------- GiveMeAnyNewData
$after_this_GMT_str = $Arg1; // Format: "Y-m-d H:i:s". Example: "2023-10-25 11:03:42"
Raise_ConcurrencyFlag();
$answer = GetNewData($after_this_GMT_str);
if( strlen($answer) > 10 ) {
echo $answer;
} else { // if there are no new data, then respond with the number of logged in users, so that the client can tune the interval by which pings the server
echo getNumOfActiveUsers()."";
}
Lower_ConcurrencyFlag();
} else if( strcmp($Command, "GetReferenceLinks") == 0 ) { // ------------------------------------------------------------------------------------- GetReferenceLinks
$Compress = $Arg1;
$jsonString = file_get_contents("ReferenceLinks.json");
if( strcmp($Compress, "true") == 0 ) {
echo( base64_encode( gzcompress($jsonString) ) );
} else {
echo( $jsonString );
}
} else if( strcmp($Command, "IdentifierExistsInDB") == 0 ) { // ------------------------------------------------------------------------------------- IdentifierExistsInDB
$Identifier = $Arg1;
Raise_ConcurrencyFlag();
// load the data of the server
$jsonString = file_get_contents("Data/ExcavationData.json");
$ExcData = json_decode($jsonString, true);
// check if the Identifier already exists in the database
$item_idx = -1;
for ($i = 0; $i<count($ExcData); $i++) {
if( strcmp( $ExcData[$i]["Identifier"], $Identifier) == 0 ) {
$item_idx = $i; break;
}
}
if($item_idx == -1) { echo "false"; } else { echo "true"; }
Lower_ConcurrencyFlag();
} else if( strcmp($Command, "Save") == 0 ) { // -------------------------------------------------------------------------------------------------- Save
$NewItemData = $Arg1; // json data of the item to be saved, both altered and not-altered fields
Raise_ConcurrencyFlag();
try {
$newData = json_decode($NewItemData, true);
if( isset($newData["IdentifierUUID"]) == false ) {
echo("I cannot save the new data: there is no IdentifierUUID.");
return;
}
// keep backup if necessary
BackUpExcavationData();
// parse the data of the server and locate the item to be updated
$jsonString = file_get_contents("Data/ExcavationData.json");
$ExcData = json_decode($jsonString, true);
$item_idx = -1;
for ($i = 0; $i<count($ExcData); $i++) {
if( strcmp( $ExcData[$i]["IdentifierUUID"], $newData["IdentifierUUID"]) == 0 ) { // item-data found
$item_idx = $i; break;
}
}
// Check if user has access to alter the data - ACCESS CHECK - ACCESS CHECK - ACCESS CHECK - ACCESS CHECK - ACCESS CHECK
$AccessGranted = false;
if( $item_idx >= 0 ) {
if(strpos( ",".strtolower($_SESSION["SESSION_ACCESSLEVELS"])."," , ",all," )>-1) { $AccessGranted = true; }
else if( isset($ExcData[$item_idx]["Type"]) && strpos( ",".strtolower($_SESSION["SESSION_ACCESSLEVELS"])."," , ",".strtolower($ExcData[$item_idx]["Type"])."," )>-1) { $AccessGranted = true; }
else if( isset($ExcData[$item_idx]["Subtype"]) && strpos( ",".strtolower($_SESSION["SESSION_ACCESSLEVELS"])."," , ",".strtolower($ExcData[$item_idx]["Subtype"])."," )>-1) { $AccessGranted = true; }
} else { // it is a request to save a new item
if(strpos( ",".strtolower($_SESSION["SESSION_ACCESSLEVELS"])."," , ",all," )>-1) { $AccessGranted = true; }
if(strpos( ",".strtolower($_SESSION["SESSION_ACCESSLEVELS"])."," , ",addnew," )>-1) { $AccessGranted = true; }
}
if( strlen(trim($_SESSION["SESSION_USERNAME"]))==0 || strcmp($_SESSION["SESSION_USERNAME"],"Guest")==0 ) $AccessGranted = false;
// ACCESS CHECK - ACCESS CHECK - ACCESS CHECK - ACCESS CHECK - ACCESS CHECK - ACCESS CHECK - ACCESS CHECK
$Identifier_of_new_item_already_exists = false;
if( $AccessGranted ) {
// Remove unecessary run-time fields
if( isset( $newData["Visible"] ) ) unset($newData["Visible"]);
if( isset( $newData["Selected"] ) ) unset($newData["Selected"]);
if( isset( $newData["InPlan"] ) ) unset($newData["InPlan"]);
// Make sure that the Identifier of the new item is unique
if( $item_idx < 0 ) { // it is a request to save a new item
for ($i = 0; $i<count($ExcData); $i++) {
if( strcmp( $ExcData[$i]["Identifier"], $newData["Identifier"]) == 0 ) { // item-data found
$Identifier_of_new_item_already_exists = true; break;
}
}
}
}
// save the item
if( $Identifier_of_new_item_already_exists ) { // it is a request to save a new item, but the identifier already exists in the db
echo "SERVER: An item with Identifier " . $newData["Identifier"] . " already exists in the database.";
} else if( $AccessGranted ) {
$newData["DateModified"] = gmdate("Y-m-d") . " ". gmdate("H:i:s");
$newData["UpdatedByUser"] = $_SESSION["SESSION_USERNAME"];
if( $item_idx >= 0 ) { // it is a request to alter an existing item
// ==== Log it
LogDataChange( $_SESSION["SESSION_USERNAME"], $newData["IdentifierUUID"], getFieldDifferences($newData, $ExcData[$item_idx]) );
// ==== in case the altered item is a Locus then some fields of its child-items must be updated.
if ( isset($newData["Type"]) && strcmp($newData["Type"],"Locus")==0 && isset($newData["RelationIncludesUUID"]) ) {
for ($i=0; $i<count($ExcData); $i++) {
if( isset($ExcData[$i]["RelationBelongsToUUID"]) && strpos($ExcData[$i]["RelationBelongsToUUID"][0], $newData["IdentifierUUID"]) !== false ) { // this is a child element
$ExcData[$i]["Square"] = $newData["Square"];
//if( isset($ExcData[$i]["Category"]) && isset($newData["CoverageEarliest"]) && strcmp($ExcData[$i]["Category"],"Coin") !=0 ) { $ExcData[$i]["CoverageEarliest"] = $newData["CoverageEarliest"]; }
//if( isset($ExcData[$i]["Category"]) && isset($newData["CoverageLatest"]) && strcmp($ExcData[$i]["Category"],"Coin") !=0 ) { $ExcData[$i]["CoverageLatest"] = $newData["CoverageLatest"]; }
if( isset($ExcData[$i]["Type"]) && isset($newData["Title"]) && strcmp($ExcData[$i]["Type"],"Partition")==0 ) { $ExcData[$i]["Title"] = $newData["Title"]; }
}
}
}
// ==== update in memory
$ExcData[ $item_idx ] = $newData;
} else { // it is a request to save a new item
$newData["DateCreated"] = gmdate("Y-m-d") . " ". gmdate("H:i:s");
$newData["DateModified"] = gmdate("Y-m-d") . " ". gmdate("H:i:s");
$newData["UpdatedByUser"] = $_SESSION["SESSION_USERNAME"];
// log the data insertion and save the new item
LogDataChange( $_SESSION["SESSION_USERNAME"], $newData["Identifier"], "New" );
array_push($ExcData, $newData);
// construct belongs-to relation by saving the relation to the parent item
$parent_item_idx = -1;
if ( isset($newData["RelationBelongsToUUID"]) && count($newData["RelationBelongsToUUID"])>0 && strlen($newData["RelationBelongsToUUID"][0])>0 ) {
for ($i = 0; $i<count($ExcData); $i++) { // find the related parent item
if( strcmp($ExcData[$i]["IdentifierUUID"], $newData["RelationBelongsToUUID"][0]) == 0 ) {
$parent_item_idx = $i;
if( isset($ExcData[$i]["RelationIncludesUUID"]) ) {
$ExcData[$i]["RelationIncludesUUID"][0] .= "\n" . $newData["IdentifierUUID"];
} else {
$ExcData[$i]["RelationIncludesUUID"] = [ $newData["IdentifierUUID"] ];
}
break;
}
}
}
}
// >>>>>>>> save data to the server's disk <<<<<<<<
$newJsonString = json_encode($ExcData, JSON_PRETTY_PRINT);
file_put_contents("Data/ExcavationData.json", $newJsonString, LOCK_EX);
if( $item_idx >= 0 ) {
Store_NewData_forPropagation($newData);
} else {
Store_NewData_forPropagation($newData);
if( $parent_item_idx >= 0 ) {
Store_NewData_forPropagation($ExcData[$parent_item_idx]);
}
}
} else {
if( $item_idx < 0 ) {
echo("I am sorry, you do not have the permission to add new items.");
} else {
echo("I am sorry, you do not have the permission to alter the data of item ". $ExcData[$item_idx]["Identifier"] . "\nYou can alter only:\n" . strtolower($_SESSION["SESSION_ACCESSLEVELS"]) );
}
}
} catch(Exception $e) {
echo $e->getMessage();
}
// log it
LogThis( $UserIP, $_SESSION["SESSION_USERNAME"], $Command, $Arg1, $Arg2 );
Lower_ConcurrencyFlag();
} else if( strcmp($Command, "SaveReferenceLinks") == 0 ) { // ------------------------------------------------------------------------------------- SaveReferenceLinks
try {
// Check if user has access to alter the data - ACCESS CHECK - ACCESS CHECK - ACCESS CHECK - ACCESS CHECK - ACCESS CHECK
$AccessGranted = false;
if (strlen($_SESSION["SESSION_ACCESSLEVELS"])>0) $AccessGranted = true;
if( strlen(trim($_SESSION["SESSION_USERNAME"]))==0 || strcmp($_SESSION["SESSION_USERNAME"],"Guest")==0 ) $AccessGranted = false;
// ACCESS CHECK - ACCESS CHECK - ACCESS CHECK - ACCESS CHECK - ACCESS CHECK - ACCESS CHECK - ACCESS CHECK - ACCESS CHECK
if( $AccessGranted ) {
$ReferenceLinks_str = $Arg1; // a json string
// - - - - - - - - keep backup of the old ReferenceLinks file - - - - - - - -
$Now_YMD = gmdate("Y-m-d"); // date string
$Now_HIS = gmdate("H_i_s"); // time string
$sourceFile = "ReferenceLinks.json";
$backupFile = "backup/ReferenceLinks " . $Now_YMD . " ". $Now_HIS . ".json";
copy($sourceFile, $backupFile);
// zip the new backup file
$zipFile = str_replace( ".json", ".zip", $backupFile);
$zip = new ZipArchive;
$zip->open($zipFile, ZipArchive::CREATE);
$zip->addFile( $backupFile );
$zip->close();
// del the unzipped file
unlink($backupFile);
// - - - - - - - - save the new ReferenceLinks data - - - - - - - -
$jsonfile = fopen("ReferenceLinks.json", "w");
fwrite($jsonfile, $ReferenceLinks_str);
fclose($jsonfile);
}
} catch(Exception $e) {
echo $e->getMessage();
}
// log it
LogThis( $UserIP, $_SESSION["SESSION_USERNAME"], $Command, $Arg1 );
} elseif ( strcmp($Command, "UploadPhoto") == 0 ) { // ------------------------------------------------------------------------------------------ UploadPhoto
$itemUUID = $Arg1;
Raise_ConcurrencyFlag();
$error_msg = "";
if ( $_FILES['file']['error'] > 0 ) {
$error_msg = 'Error while uploading photo:<br>' . $_FILES['file']['error'];
}
else {
// construct photo filename for server storage
srand( make_seed() );
$photo_filename_at_server = Lengthen2(gmdate('d')) . Lengthen2(gmdate('m')) . Lengthen2(gmdate('y')) . '-'; //$photo_filename_at_server = Lengthen2(dechex(gmdate('d'))) . Lengthen2(dechex(gmdate('m'))) . Lengthen2(dechex(gmdate('y'))) . '-';
$photo_filename_at_server .= Lengthen2(gmdate('H')) . Lengthen2(gmdate('i')) . Lengthen2(gmdate('s')) . '-'; //$photo_filename_at_server .= Lengthen2(dechex(gmdate('H'))) . Lengthen2(dechex(gmdate('i'))) . Lengthen2(dechex(gmdate('s'))) . '-';
$photo_filename_at_server .= substr( hash('md5', $_FILES['file']['tmp_name']), 0, 8) . '-';
$photo_filename_at_server .= dechex(rand(1,1000));
$photo_filename_at_server = strtoupper( $photo_filename_at_server );
// save photo on server side
move_uploaded_file($_FILES['file']['tmp_name'], "Data/images/" . $photo_filename_at_server . ".jpg");
// create a thumbnail for this image
CreateThumbnail("Data/images/".$photo_filename_at_server.".jpg", "Data/images/thumbnails/", 200);
CreateThumbnail("Data/images/".$photo_filename_at_server.".jpg", "Data/images/thumbnails_mini/", 80);
// ############ Alter the JSON data ############
try {
// parse the data of the server and locate the item to be updated
$jsonString = file_get_contents("Data/ExcavationData.json");
$ExcData = json_decode($jsonString, true);
$item_idx = -1;
for ($i = 0; $i<count($ExcData); $i++) {
if( strcmp( $ExcData[$i]["IdentifierUUID"], $itemUUID) == 0 ) { // item-data found
$item_idx = $i; break;
}
}
if( $item_idx >= 0 ) {
// Check if user has access to alter the data - ACCESS CHECK - ACCESS CHECK - ACCESS CHECK - ACCESS CHECK - ACCESS CHECK
$AccessGranted = false;
if(strpos( ",".strtolower($_SESSION["SESSION_ACCESSLEVELS"])."," , ",all," )>-1) { $AccessGranted = true; }
else if( isset($ExcData[$item_idx]["Type"]) && strpos( ",".strtolower($_SESSION["SESSION_ACCESSLEVELS"])."," , ",".strtolower($ExcData[$item_idx]["Type"])."," )>-1) { $AccessGranted = true; }
else if( isset($ExcData[$item_idx]["Subtype"]) && strpos( ",".strtolower($_SESSION["SESSION_ACCESSLEVELS"])."," , ",".strtolower($ExcData[$item_idx]["Subtype"])."," )>-1) { $AccessGranted = true; }
if( strlen(trim($_SESSION["SESSION_USERNAME"]))==0 || strcmp($_SESSION["SESSION_USERNAME"],"Guest")==0 ) $AccessGranted = false;
// ACCESS CHECK - ACCESS CHECK - ACCESS CHECK - ACCESS CHECK - ACCESS CHECK - ACCESS CHECK - ACCESS CHECK - ACCESS CHECK
if( $AccessGranted ) {
// update json data of the item with the photo's info
$ExcData[ $item_idx ]["RelationIncludesUUID"][0] .= "\n" . $photo_filename_at_server;
if( isset($ExcData[ $item_idx ]["ThumbnailImageUUID"]) == false ) { // if this item has no Thumbnail then make this image its Thumbnail
$ExcData[ $item_idx ]["ThumbnailImageUUID"] = $photo_filename_at_server;
}
$itemType = $ExcData[$item_idx]["Type"];
$itemIdentifier = $ExcData[$item_idx]["Identifier"];
$itemIdentifierUUID = $ExcData[$item_idx]["IdentifierUUID"];
$itemTitle = $ExcData[$item_idx]["Title"];
if( isset($ExcData[$item_idx]["Source"]) && is_null($ExcData[$item_idx]["Source"])==false ) {
$itemSource = $ExcData[$item_idx]["Source"];
} else {
$itemSource = "";
}
$itemTrench = $ExcData[$item_idx]["Trench"];
// update json data with a new photo item
array_push ( $ExcData, json_decode('[{"IdentifierUUID": ' . $photo_filename_at_server . '}]', true));
$new_item_index = count($ExcData) - 1;
$ExcData[$new_item_index]["Type"] = "Image";
$ExcData[$new_item_index]["Title"] = "";
$ExcData[$new_item_index]["IdentifierUUID"] = $photo_filename_at_server;
$ExcData[$new_item_index]["RelationBelongsToUUID"] = [ $ExcData[$item_idx]["IdentifierUUID"] ];
$ExcData[$new_item_index]["Identifier"] = $photo_filename_at_server;
if( strlen($itemSource) > 0 ) {
$ExcData[$new_item_index]["Source"] = $itemSource;
}
$ExcData[$new_item_index]["Trench"] = $itemTrench;
$ExcData[$new_item_index]["FormatImage"] = $photo_filename_at_server . ".jpg";
$ExcData[$new_item_index]["FormatImageHeight"] = "" . $img_height;
$ExcData[$new_item_index]["FormatImageWidth"] = "" . $img_width;
$ExcData[$new_item_index]["DateUTC"] = gmdate("Y-m-d") . "T". gmdate("H:i:s") . "Z" ;
$ExcData[$new_item_index]["Date"] = gmdate("M d, Y");
$ExcData[$new_item_index]["DateModified"] = gmdate("Y-m-d") . "T". gmdate("H:i:s") . "Z" ;
$ExcData[$new_item_index]["DateTimeZone"] = "Europe\/Athens";
// save data to the server's disk
$newJsonString = json_encode($ExcData, JSON_PRETTY_PRINT);
file_put_contents("Data/ExcavationData.json", $newJsonString, LOCK_EX);
LogDataChange( $_SESSION["SESSION_USERNAME"], $itemIdentifierUUID, "AddPhoto" );
echo( "Photograph " . $photo_filename_at_server . " uploaded and linked with item '" . $itemTitle . "'" );
} else {
echo("Error: You do not have permission to alter the data of item " . $ExcData[$item_idx]["Identifier"] );
}
} else {
echo("Error: Unable to find item " . $itemUUID );
}
} catch(Exception $e) {
echo ( "Error:" . $e->getMessage() );
}
LogThis( $UserIP, $_SESSION["SESSION_USERNAME"], $Command, $Arg1, $Arg2, $photo_filename_at_server );
}
if( strlen($error_msg) > 0 ) {
echo ($error_msg);
}
Raise_ConcurrencyFlag();
} else if( strcmp($Command, "Delete") == 0 ) { // -------------------------------------------------------------------------------------------------- Delete
$itemUUID = $Arg1;
Raise_ConcurrencyFlag();
try {
// parse the data of the server and locate the item to be deleted
$jsonString = file_get_contents("Data/ExcavationData.json");
$ExcData = json_decode($jsonString, true);
$item_idx = -1;
for ($i = 0; $i<count($ExcData); $i++) {
if( strcmp( $ExcData[$i]["IdentifierUUID"], $itemUUID) == 0 ) { // item-data found
$item_idx = $i; break;
}
}
if( $item_idx >= 0 ) {
// Check if user has access to alter the data - ACCESS CHECK - ACCESS CHECK - ACCESS CHECK - ACCESS CHECK - ACCESS CHECK
$AccessGranted = false;
if( isset($ExcData[$item_idx]["Type"]) && strpos( ",".strtolower($_SESSION["SESSION_ACCESSLEVELS"])."," , ",".strtolower($ExcData[$item_idx]["Type"])."," )>-1) { $AccessGranted = true; }
if( isset($ExcData[$item_idx]["Subtype"]) && strpos( ",".strtolower($_SESSION["SESSION_ACCESSLEVELS"])."," , ",".strtolower($ExcData[$item_idx]["Subtype"])."," )>-1) { $AccessGranted = true; }
if(strpos( ",".strtolower($_SESSION["SESSION_ACCESSLEVELS"])."," , ",del," ) < 0) { $AccessGranted = false; }
if(strpos( ",".strtolower($_SESSION["SESSION_ACCESSLEVELS"])."," , ",all," ) > -1) { $AccessGranted = true; }
if( strlen(trim($_SESSION["SESSION_USERNAME"]))==0 || strcmp($_SESSION["SESSION_USERNAME"],"Guest")==0 ) $AccessGranted = false;
// ACCESS CHECK - ACCESS CHECK - ACCESS CHECK - ACCESS CHECK - ACCESS CHECK - ACCESS CHECK - ACCESS CHECK - ACCESS CHECK
if( $AccessGranted ) {
LogDataChange( $_SESSION["SESSION_USERNAME"], $ExcData[$item_idx]["Identifier"], "Delete" );
// delete item
array_splice( $ExcData, $item_idx, 1 );
// TODO: Unlink all references to this item - consider this may not be good to do
// save data to the server's disk
$newJsonString = json_encode($ExcData, JSON_PRETTY_PRINT);
file_put_contents("Data/ExcavationData.json", $newJsonString, LOCK_EX);
} else {
echo("I am sorry, you do not have permission to alter the data of item " . $ExcData[$item_idx]["Identifier"] );
}
} else {
echo("Unable to find item " . $itemUUID );
}
} catch(Exception $e) {
echo $e->getMessage();
}
// log it
LogThis( $UserIP, $_SESSION["SESSION_USERNAME"], $Command, $Arg1, $Arg2 );
Lower_ConcurrencyFlag();
} else if( strcmp($Command, "DeleteImage") == 0 ) { // ---------------------------------------------------------------------------------------------- Delete Image
$itemUUID = $Arg1;
$ImageUUID_toDelete = $Arg2;
Raise_ConcurrencyFlag();
try {
// parse the data of the server and locate the item to be deleted
$jsonString = file_get_contents("Data/ExcavationData.json");
$ExcData = json_decode($jsonString, true);
$item_idx = -1;
for ($i = 0; $i<count($ExcData); $i++) {
if( strcmp( $ExcData[$i]["IdentifierUUID"], $itemUUID) == 0 ) { // item-data found
$item_idx = $i; break;
}
}
if( $item_idx >= 0 ) {
// Check if user has access to alter the data - ACCESS CHECK - ACCESS CHECK - ACCESS CHECK - ACCESS CHECK - ACCESS CHECK
$AccessGranted = false;
if(strpos( ",".strtolower($_SESSION["SESSION_ACCESSLEVELS"])."," , ",all," )>-1) { $AccessGranted = true; }
else if( isset($ExcData[$item_idx]["Type"]) && strpos( ",".strtolower($_SESSION["SESSION_ACCESSLEVELS"])."," , ",".strtolower($ExcData[$item_idx]["Type"])."," )>-1) { $AccessGranted = true; }
else if( isset($ExcData[$item_idx]["Subtype"]) && strpos( ",".strtolower($_SESSION["SESSION_ACCESSLEVELS"])."," , ",".strtolower($ExcData[$item_idx]["Subtype"])."," )>-1) { $AccessGranted = true; }
if( strlen(trim($_SESSION["SESSION_USERNAME"]))==0 || strcmp($_SESSION["SESSION_USERNAME"],"Guest")==0 ) $AccessGranted = false;
// ACCESS CHECK - ACCESS CHECK - ACCESS CHECK - ACCESS CHECK - ACCESS CHECK - ACCESS CHECK - ACCESS CHECK - ACCESS CHECK
if( $AccessGranted ) {
// remove the image id from the item's references
$s = $ExcData[$item_idx]["RelationIncludesUUID"][0];
$s = str_replace( $ImageUUID_toDelete . "\n", "", $s );
$s = str_replace( "\n" . $ImageUUID_toDelete, "", $s );
$s = str_replace( $ImageUUID_toDelete , "", $s );
$s = str_replace( "\n\n", "\n", $s );
$ExcData[$item_idx]["RelationIncludesUUID"][0] = $s;
// save data to the server's disk
$newJsonString = json_encode($ExcData, JSON_PRETTY_PRINT);
file_put_contents("Data/ExcavationData.json", $newJsonString, LOCK_EX);
LogDataChange( $_SESSION["SESSION_USERNAME"], $ExcData[$item_idx]["IdentifierUUID"], "DelPhoto" );
} else {
echo("I am sorry, you do not have the permission to alter the data of item " . $ExcData[$item_idx]["Identifier"] );
}
} else {
echo("Unable to find item " . $itemUUID );
}
} catch(Exception $e) {
echo $e->getMessage();
}
// log it
LogThis( $UserIP, $_SESSION["SESSION_USERNAME"], $Command, $Arg1, $Arg2, $Arg3 );
Lower_ConcurrencyFlag();
} else if( strcmp($Command, "WhoAmI") == 0 ) { // ------------------------------------------------------------------------------------------------ Who Am I?
echo $_SESSION["SESSION_USERNAME"];
} else if( strcmp($Command, "GetAccessLevels") == 0 ) { // --------------------------------------------------------------------------------------- GetAccessLevels
echo $_SESSION["SESSION_ACCESSLEVELS"];
} else if( strlen($Username) > 0 && strlen($Password) > 0 ) { // -------------------------------------------------------------------------------- Login
if( $SITE_UNDER_MAINTENANCE == false) {
if( strcmp(strtolower($Username), "guest") == 0 ) { // guest session
$_SESSION["SESSION_USERNAME"] = "Guest";
$_SESSION["SESSION_ACCESSLEVELS"] = "";
$_SESSION["SESSION_START_SECS"] = floor(microtime(true));
// go to the web application
ob_start();
header("Location: app_main.html");
ob_end_flush();
} else {
$_SESSION["SESSION_ACCESSLEVELS"] = getAccessLevels( $Username, $Password );
if( strlen($_SESSION["SESSION_ACCESSLEVELS"]) > 0 ) {
if( abs( $ServerTime - $UserTime ) < 10*60 ) { // 10 min diff allowed between user and system time
$_SESSION["SESSION_USERNAME"] = $Username;
$_SESSION["SESSION_START_SECS"] = floor(microtime(true));
// save the login username and time
$UserLogins = [];
$idx = -1;
if( file_exists("login_times.json") ) {
$jsonString = file_get_contents("login_times.json");
$UserLogins = json_decode($jsonString, true);
for ($i = 0; $i<count($UserLogins); $i++) {
if( strcmp($UserLogins[$i]["Username"], $_SESSION["SESSION_USERNAME"]) == 0 ) {
$idx = $i;
break;
}
}
}
if($idx >= 0) { // username exits in the file
$UserLogins[$idx]["Date"] = gmdate("Y-m-d");
$UserLogins[$idx]["Time"] = gmdate("H:i:s");
} else {
$new_rec = new stdClass();
$new_rec->Username = strtolower($_SESSION["SESSION_USERNAME"]);
$new_rec->Date = gmdate("Y-m-d");
$new_rec->Time = gmdate("H:i:s");
array_push($UserLogins, $new_rec);
}
file_put_contents("login_times.json", json_encode($UserLogins, JSON_PRETTY_PRINT) , LOCK_EX);
// go to the web application
ob_start();
header("Location: app_main.html");
ob_end_flush();
} else {
$_SESSION["SESSION_USERNAME"] = "Guest";
echo "Error: Correct your time:" . "<br>" . gmdate("Y-m-d H:i:s", $UserTime) . " -> " . gmdate("Y-m-d H:i:s", $ServerTime);
}
} else {
$_SESSION["SESSION_USERNAME"] = "Guest";
echo "Login Failed: Wrong credentials.";
}
}
} else {
echo "Maintenance. Please try later.";
}
LogThis( $UserIP, $_SESSION["SESSION_USERNAME"], "LOGIN", $_SESSION["SESSION_ACCESSLEVELS"], $Arg2, $Arg3 );
} else if( strcmp($Command, "chpass") == 0 ) { // ------------------------------------------------------------------------------------------------ Change Password
$OldPassword = $Arg1;
$NewPassword = $Arg2;
$ok = changePassword( $_SESSION["SESSION_USERNAME"], $OldPassword, $NewPassword );
if( $ok == false ) { echo "Wrong Password for " . $_SESSION["SESSION_USERNAME"] . ".\nPassword has not been changed." ; }
} else if( strcmp($Command, "Logout") == 0 ) { // ------------------------------------------------------------------------------------------------ Logout
session_unset(); // remove all session variables
session_destroy(); // close the session
echo "ok";
} else if( strcmp($Command, "ExportMSWord") == 0 ) { // ------------------------------------------------------------------------------------------ Export Word Document
$itemUUIDs = $Arg1; // separated by comma, start with comma, end with comma, no spaces between
$FileName = "tmp_files/" . $Arg2 . ".docx";
$itemUUIDs = str_replace(" ", "", $itemUUIDs); // force no spaces
$itemUUIDs = "," . $itemUUIDs . ","; // force start with comma and end with comma
LogThis( $UserIP, $_SESSION["SESSION_USERNAME"], $Command, $Arg1, "", "" );
$ok = GenerateWordDocument($itemUUIDs, $FileName);
echo $ok;
} else if( strcmp($Command, "GetMaxIdentifier") == 0 ) { // ------------------------------------------------------------------------ search for the max identifier
$UserTyped_txt = $Arg1;
$max = -1;
$jsonString = file_get_contents("Data/ExcavationData.json");
$ExcData = json_decode($jsonString, true);
for ($j = 0; $j<count($ExcData); $j++) { // for each item
if( strcmp($ExcData[$j]["Type"], "Image") != 0 ) { // ignore images
$prefix = substr($ExcData[$j]["Identifier"], 0, strlen($UserTyped_txt));
if( strcmp($prefix, $UserTyped_txt) == 0 ) {
$tmp = substr($ExcData[$j]["Identifier"], strlen($UserTyped_txt) );
$n = intval( $tmp );
if ($n > $max) { $max = $n; }
}
}
}
echo $max;
} else if( strcmp($Command, "AddUser") == 0 ) {
LogThis( $UserIP, $_SESSION["SESSION_USERNAME"], $Command, $new_username );
if( strcmp(strtolower($_SESSION["SESSION_USERNAME"]), "admin") == 0 ) {
$new_username = trim($Arg1);
$new_password = trim($Arg2);
$new_rights = trim($Arg3);
if( strlen(new_username) > 0 ) {
addUser( $new_username, $new_password, $new_rights );
echo( "User " . $new_username . " was added to the system with password " . $new_password . " and access to " . $new_rights . ".");
} else {
echo( "NO new user was created." );
}
} else {
echo("This user does not have access rights for such an action.");
}
} else if( strcmp($Command, "Change_User_Rights") == 0 ) {
LogThis( $UserIP, $_SESSION["SESSION_USERNAME"], $Command, $new_username );
if( strcmp(strtolower($_SESSION["SESSION_USERNAME"]), "admin") == 0 ) {
$username = $Arg1;
$new_rights = $Arg2;
changeAccessLevels( $username, $new_rights );
echo( "User " . $username . " has new access rights: " . $new_rights . ".");
} else {
echo("This user does not have access rights for such an action.");
}
} else if( strcmp($Command, "Import_iDig_Data") == 0 ) {
LogThis( $UserIP, $_SESSION["SESSION_USERNAME"], $Command, "" );
if( strcmp(strtolower($_SESSION["SESSION_USERNAME"]), "admin") == 0 ) {
echo( Import_iDig_Data() );
} else {
echo("User ". $_SESSION["SESSION_USERNAME"] ." does not have access rights for such an action.");
}
} else if( strcmp($Command, "Import_iDig_Images") == 0 ) {
LogThis( $UserIP, $_SESSION["SESSION_USERNAME"], $Command, "" );
if( strcmp(strtolower($_SESSION["SESSION_USERNAME"]), "admin") == 0 ) {
echo( Import_iDig_Images() );
} else {
echo("User ". $_SESSION["SESSION_USERNAME"] ." does not have access rights for such an action.");
}
} else if( strcmp($Command, "DeleteImage") == 0 ) {
} else { // -------------------------------------------------------------------------------------------------------------------------------------- ELSE > check URL params
// the rarely used administration commands can be executed through url params.
if( strcmp($_GET["cmd"], "info") == 0 ) {
echo "WebDig says hello.<br>";
echo "<br>Client IP: <b>" . $UserIP . "</b>";
echo '<br>PHP version: <b>' . phpversion() . "</b>";
echo '<br>Session timeout: <b>' . ini_get("session.gc_maxlifetime") . " sec</b>";
echo "<br>LogFile size: <b>" . filesize("log.txt") . "</b> bytes<br>";
echo "System date and time (UTC): <b>" . gmdate("Y-m-d") . " " . gmdate("H:i:s") . "</b> Unix-Seconds: <b>" . (floor(microtime(true))) . "</b><br>";
echo "Username: <b>" . $_SESSION["SESSION_USERNAME"] . "</b> Session Start: <b>" . $_SESSION["SESSION_START_SECS"]. "</b><br>";
echo "<br>File Counters:<br>";
echo " Plans: " . (count(scandir( "./plans/" ))-2) . " files<br>";
echo " " . "Image files: " . (getFileCount("Data/images/")-getFileCount("Data/images/thumbnails/")) . " images, " . getFileCount("Data/images/thumbnails/") . " thumbnails, " . round(GetDirectorySize("Data/")/1024/1024/1024,2) . " Gbytes<br>";
echo " " . "Backup files: " . getFileCount("Data/backup/" ) . " files, " . round(GetDirectorySize("Data/backup/")/1024/1024,2) . " Mbytes<br><br>";
} else if( strcmp($_GET["cmd"], "orphan") == 0 ) { // displays the image filenames which do not exist in the database and the image-items which do not correspond to a file. Example: WebDigServer.php?cmd=orphan
$jsonString = file_get_contents("Data/ExcavationData.json");
$ExcData = json_decode($jsonString, true);
$Files = scandir( "Data/images/" );
$Thumbs = scandir( "Data/images/thumbnails/" );
echo( "<u>" . count($ExcData) . " json items");
echo ", " . (getFileCount("Data/images/")-getFileCount("Data/images/thumbnails/")) . " images, " . getFileCount("Data/images/thumbnails/") . " thumbnails, " . round(GetDirectorySize("Data/")/1024/1024/1024,2) . " Gbytes</u><br>";
echo ("<br><b>Images which are not included into the database:</b><br>");
for ($i = 0; $i<count($Files); $i++) { // for each image
if( strpos($Files[$i], ".jpg") > 0 ) { // if it is an image
$image_is_orphan = true;
for ($item_idx = 0; $item_idx<count($ExcData); $item_idx++) { // for each item
if( strcmp($ExcData[$item_idx]["Type"], "Image") == 0 && isset($ExcData[$item_idx]["FormatImage"]) && strcmp($ExcData[$item_idx]["FormatImage"], $Files[$i]) == 0 ) {
$image_is_orphan = false;
break;
}
}
if( $image_is_orphan ) echo( " " . $Files[$i] . "<br>" );
}
}
echo ("<br><b>Images which do not exist in the server storage:</b><br>");
for ($item_idx = 0; $item_idx<count($ExcData); $item_idx++) { // for each item
if( strcmp($ExcData[$item_idx]["Type"], "Image") == 0 && isset($ExcData[$item_idx]["FormatImage"]) ) { // if it is an image
$image_is_orphan = true;
for ($i = 0; $i<count($Files); $i++) { // for each image
if( strpos($Files[$i], ".jpg") > 0 && strcmp($ExcData[$item_idx]["FormatImage"], $Files[$i]) == 0 ) {
$image_is_orphan = false;
break;
}
}
if( $image_is_orphan ) echo( " " . $ExcData[$item_idx]["IdentifierUUID"] . "<br>" );
}
}
echo ("<br><b>Image DB items which do not include a photo file:</b><br>");
for ($item_idx = 0; $item_idx<count($ExcData); $item_idx++) { // for each item
if( strcmp($ExcData[$item_idx]["Type"], "Image") == 0 && isset($ExcData[$item_idx]["FormatImage"])==false ) { // if it is an image
echo( " " . $ExcData[$item_idx]["IdentifierUUID"] . "<br>" );
}
}
echo ("<br><b>Image files without a thumbnail:</b><br>");
for ($i = 0; $i<count($Files); $i++) { // for each image
if( strpos($Files[$i], ".jpg") > 0 ) {
$image_is_orphan = true;
for ($j = 0; $j<count($Thumbs); $j++) { // for each thumbnail
if( strcmp($Files[$i], $Thumbs[$j]) == 0 ) {
$image_is_orphan = false;
break;
}
}
if( $image_is_orphan ) echo( " " . $Files[$i] . "<br>" );
}
}
echo ("<br><b>Thumbnail images without an original size image file:</b><br>");
for ($j = 0; $j<count($Thumbs); $j++) { // for each thumbnail
if( strpos($Thumbs[$j], ".jpg") > 0 ) {
$image_is_orphan = true;
for ($i = 0; $i<count($Files); $i++) { // for each image
if( strcmp($Files[$i], $Thumbs[$j]) == 0 ) {
$image_is_orphan = false;
break;
}
}
if( $image_is_orphan ) echo( " " . $Thumbs[$j] . "<br>" );
}
}
} else if( strcmp($_GET["cmd"], "adduser") == 0 ) { // example: WebDigServer.php?cmd=adduser&username=Marion&password=123456&access=Coin,Bone
addUser( $_GET["username"], $_GET["password"], $_GET["access"] );
echo( "User '" . $_GET["username"] . "' added to the system with password " . $_GET["password"] . " and access to " . $_GET["access"] . ".");
} else if( strcmp($_GET["cmd"], "test") == 0 ) { // used for testing. example: WebDigServer.php?cmd=test
//echo "<br>Done.";
}
}
// =========================================================================================================================================================
// =========================================================================================================================================================
// =========================================================================================================================================================
// =========================================================================================================================================================
/**
* Raises the concurrency flag, which is used to prevent data from being accesed by two users at the same time.
* This flag is a file which is created before a save action begins and is deleted after the save action has finished.
* If the flag is already raised the function waits for it to be lowered or until timetout of several seconds is reached.
*/
function Raise_ConcurrencyFlag() {
$FlagFilename = "DataSaving.txt";
// Wait for the saving-concurrency-flag to be lowered.
$NOWsec = floor(microtime(true));
$FLAGCREATIONsec = $NOWsec;
while( file_exists($FlagFilename) && $NOWsec-$FLAGCREATIONsec<8 ) { // a flag which is raised for several seconds is considered obsolete.
usleep(200000); // micro-seconds
$FLAGCREATIONsec = filectime($FlagFilename);
$NOWsec = floor(microtime(true));
}
// raise the saving-concurrency-flag
touch( $FlagFilename );
}
/**
* Lowers the concurrency flag, which is used to prevent data from being accesed by two users at the same time.
* This flag is a file which is created before a save action begins and is deleted after the save action has finished.
* If the flag is already raised the function waits for it to be lowered or until timetout of several seconds is reached.
*/
function Lower_ConcurrencyFlag() {
$FlagFilename = "DataSaving.txt";
unlink( $FlagFilename );
}
/**
* Takes a password and returns the hash value calculated on it
*/
function getPasswordHash( $a_password ) {
return password_hash($a_password, PASSWORD_DEFAULT, ['cost' => 12]);
}
/*
* Adds a user to the system. Example addUser("Marion", "123456", "Coin,Bone")
*/
function addUser( $NewUsername, $NewPassword, $AccessLevels ) {
$fd = fopen("p.txt", "a");
fwrite($fd, $NewUsername . " " . getPasswordHash($NewPassword) . " " . $AccessLevels . "\n");
fclose($fd);
}
/*
* Checks credentials of a user.
* If user is found in the system then the items she can edit is returned as a comma separated string.
* If user is not in the system then an empty string is returned.
* Reference: https://stackoverflow.com/questions/1581610/how-can-i-store-my-users-passwords-safely
*/
function getAccessLevels( $username, $password ) {
$result = "";
$fd = fopen("p.txt", "r");
if ($fd) {
while (($line = fgets($fd)) !== false) {
$rec = explode(" ", $line);
if( strcmp(strtolower($rec[0]), strtolower($username))==0 && password_verify($password, $rec[1]) ) {
$result = $rec[2];
break;
}
}
}
fclose($fd);
$result = str_replace( " ", "", $result );
$result = str_replace( "\r", "", $result );
$result = str_replace( "\t", "", $result );
$result = str_replace( "\n", "", $result );
return $result;
}
/*
* Alters the access levels (=rights) of a user.
* The action is allowed only to admin user and the access levels are stored into a text file along with username and password.
*/
function changeAccessLevels( $username, $new_access_levels ) {
$ok = false;
$oldfile = fopen("p.txt", "r");
if ($oldfile) {
$newfile = fopen("p.tmp", "w");
while (($line = fgets($oldfile)) !== false) { // read all lines from the users file
$rec = explode(" ", $line);
// copy the lines to a new users file, except of the line regarding this username. For it check the credentials and replace with a new line with the new password
if( strcmp(strtolower($rec[0]), strtolower($username))==0 ) {
fwrite($newfile, $rec[0] . " " . $rec[1] . " " . $new_access_levels . "\n");
$ok = true;
} else {
fwrite($newfile, $line);
}
}
fclose($oldfile);
fclose($newfile);
rename("p.tmp", "p.txt");
}
return $ok;
}
/**
* Changes the password of a user.
* Returns true for succes. False means that the okd password was probably incorrect
*/
function changePassword( $username, $OldPassword, $NewPassword ) {
$ok = false;
$oldfile = fopen("p.txt", "r");
if ($oldfile) {
$newfile = fopen("p.tmp", "w");
while (($line = fgets($oldfile)) !== false) { // read all lines from the users file
$rec = explode(" ", $line);
// copy the lines to a new users file, except of the line regarding this username. For it check the credentials and replace with a new line with the new password
if( strcmp(strtolower($rec[0]), strtolower($username))==0 && password_verify($OldPassword, $rec[1]) ) {
fwrite($newfile, $rec[0] . " " . getPasswordHash($NewPassword) . " " . $rec[2] . "\n");
$ok = true;
} else {
fwrite($newfile, $line);
}
}
fclose($oldfile);
fclose($newfile);
rename("p.tmp", "p.txt");
}
return $ok;
}
function LogThis( $a1="", $a2="", $a3="", $a4="", $a5="", $a6="", $a7="", $a8="" ) {
// remove old records if necessary
clearstatcache(); // remove obsolete information about the files
if ( filesize("log.txt") > 2001001 ) { // ~2 Mbyte
$lines_to_del = 500;
$oldfile = fopen("log.txt", "r");
if ($oldfile) {
$newfile = fopen("tmplog.txt", "w");
$line_idx = 0;
while (($line = fgets($oldfile)) !== false) {
$line_idx += 1;
if( $line_idx > $lines_to_del) fwrite($newfile, $line);
}
fclose($oldfile);
fclose($newfile);
rename("tmplog.txt", "log.txt");
}
}
// add the new record
$logfile = fopen("log.txt", "a");
$record_txt = gmdate('d-m-Y H:i:s');
$record_txt .= "\t" . substr($a1, 0, 30);
$record_txt .= "\t" . substr($a2, 0, 30);
$record_txt .= "\t" . substr($a3, 0, 30);
$record_txt .= "\t" . substr($a4, 0, 30);
$record_txt .= "\t" . substr($a5, 0, 30);
$record_txt .= "\t" . substr($a6, 0, 30);
$record_txt .= "\t" . substr($a7, 0, 30);
$record_txt .= "\t" . substr($a8, 0, 30);
fwrite($logfile, $record_txt . "\r\n");
fclose($logfile);
}
/**
* Logs an alteration at the database. The information saved is the date and time of alteration and the information in the arguments
* @param {String} $username: the user who commanded the data alteration
* @param {String} $item_identifier: the identifier of the altered item
* @param {String} $itemfield: the field of the altered item
*/
function LogDataChange( $username, $item_identifier, $altered_fields ) {
// remove fields which do not present valuable information. These are always altered on a data change.
$altered_fields = str_replace(", DateModified", "", $altered_fields);
$altered_fields = str_replace("DateModified, ", "", $altered_fields);
$altered_fields = str_replace("DateModified" , "", $altered_fields);
$altered_fields = str_replace(", UpdatedByUser", "", $altered_fields);
$altered_fields = str_replace("UpdatedByUser, ", "", $altered_fields);
$altered_fields = str_replace("UpdatedByUser" , "", $altered_fields);
$altered_fields = trim($altered_fields);
$record_txt = gmdate('d-m-Y H:i:s');
$record_txt .= "\t" . $username;
$record_txt .= "\t" . $item_identifier;
$record_txt .= "\t" . $altered_fields;
$record_txt .= "\r\n";
file_put_contents("DataChanges.txt", $record_txt, FILE_APPEND | LOCK_EX);
}
/**
* @param {String} $Item1: json object with data of an item
* @param {String} $Item2: json object with data of an item
* @return all field names which have different values between Item1 and Item2 or do not exist in Item2, separated by a comma and a space. Some app-specific fields are ignored.
*/
function getFieldDifferences( $Item1, $Item2 ) {
$result = "";
$field_names = array_keys( $Item1 );
for ($i = 0; $i<count($field_names); $i++) {
try {
$difference_found = false;
// ignore run-time fields
if( strcmp($field_names[$i], "Visible")==0 || strcmp($field_names[$i], "Selected")==0 || strcmp($field_names[$i], "InPlan")==0 ) {
continue;
}
// check if Item1 contains a new field
if( isset($Item2[$field_names[$i]]) == false ) {
$difference_found = true;
} else {
// check field type
if ( strcmp(gettype($Item1[$field_names[$i]]),"array") != 0 && strcmp(gettype($Item2[$field_names[$i]]),"array") != 0 ) {
if( strcmp(strval($Item1[$field_names[$i]]), strval($Item2[$field_names[$i]])) != 0 ) {
$difference_found = true;
}
}
}
//
if( $difference_found ) {
if( strlen($result) > 0 ) $result = $result . ", ";
$result = $result . $field_names[$i];
}
} catch(Exception $e) { }
}
return $result;
}
/**
* @return the IP of the client who has accessed the server
*/
function getClientIP() {
$ip = "";
if(!empty($_SERVER['HTTP_CLIENT_IP'])) { // whether ip is from the share internet
$ip = $_SERVER['HTTP_CLIENT_IP'];
} elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) { // whether ip is from the proxy
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
} else { //whether ip is from the remote address
$ip = $_SERVER['REMOTE_ADDR'];
}
return $ip;
}
/**
* creates and returns a pretty random random-seed number
*/
function make_seed() {
list($usec, $sec) = explode(' ', microtime());
return $sec + $usec * 1000000;
}
/**
* adds zeros to the left of a string so that it has two digits
*/
function Lengthen2( $s ) {
if( strlen($s) == 1 ) {
return "0" . $s;
} else {
return $s;
}
}