-
Notifications
You must be signed in to change notification settings - Fork 2
/
site_functions.php
2420 lines (2165 loc) · 86.6 KB
/
site_functions.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
function utilityForm($user, $foundData) {
$out = "";
if(array_key_exists("form", $foundData)){
$out .= "<div class='issuesheader'>" . $foundData["label"]. "</div>";
$out .= "<div>" . $foundData["description"] . "</div>";
$mergedData = $foundData["form"];
$form = genericForm($mergedData, "Run", "Running " . $foundData["label"], $user);
$confirmJs = "";
if($foundData["skip_confirmation"] === false) {
$confirmJs = "onclick=\"return(confirm('Are you sure you want to run " . $foundData["label"] . "?'))\"";
}
$form = str_replace("value='Run' type='submit'/>", "value='Run' type='submit' " . $confirmJs . "/>", $form);
$out .= $form;
}
return $out;
}
function doesUserHaveRole($user, $role) {
if($role == "") {
return true;
}
if(array_key_exists("role", $user)){
if(gvfa("role", $user) == $role || strtolower(gvfa("role", $user)) == "admin" ) {
return true;
}
}
return false;
}
function getUtilityInfo($user, $key){
//echo $key;
$data = utilities($user, "data");
//var_dump($data);
//echo "$" . $key . "$";
$searchValue = $key;
$resultArray = array_filter($data, function ($subData) use ($searchValue) {
return $subData["key"] == $searchValue;
});
$foundData = reset($resultArray);
return $foundData;
}
function bodyWrap($content, $user, $deviceId, $poser = null) {
global $timezone;
$out = "<!doctype html>";
$out .= "<html>\n";
$out .= "<head>\n";
$out .= '<link rel="icon" type="image/x-icon" href="./favicon.ico" />';
$siteName = "Remote Controller";
$version = filemtime("./index.php");
$out .= "<script>window.timezone ='" . $timezone . "'</script>\n";
$out .= "<script src='tablesort.js?version=" . urlencode($version) . "'></script>\n";
$out .= "<script src='tool.js?version=" . urlencode($version) . "'></script>\n";
$out .= "<link rel='stylesheet' href='tool.css?version=" . urlencode($version) . "'>\n";
$out .= "<title>" . $siteName . "</title>\n";
$out .= "</head>\n";
$out .= "<body>\n";
$out .= topmostNav();
$out.= "<div class='logo'>" . $siteName . "</div> \n";
$out .= "<div class='waitingouter' id='waitingouter'><div class='waiting' id='waiting'><img width='200' height='200' src='./images/signs.gif'></div><div id='waitingmessage' class='waitingmessage'>Waiting...</div></div>\n";
$out .= "<div class='outercontent'>\n";
$poserString = "";
if($user) {
if($poser) {
$poserString = " posing as <span class='poserindication'>" . $poser["email"] . "</span> (<a href='?action=disimpersonate'>unpose</a>)";
}
$out .= "<div class='loggedin'>You are logged in as <b>" . $user["email"] . "</b>" . $poserString . " on " . $user["name"] . " <div class='basicbutton'><a href=\"?action=logout\">logout</a></div></div>\n";
}
else
{
//$out .= "<div class='loggedin'>You are logged out. </div>\n";
}
$out .= "<div>\n";
$out .= "<div class='devicedescription'>";
$out .= "</div>";
$out .= tabNav($user);
$out .= "<div class='innercontent'>\n";
$out .= $content;
$out .= "</div>\n";
$out .= "</div>\n";
$out .= "</div>\n";
$out .= "</body>\n";
$out .= "</html>\n";
return $out;
}
function filterCommasAndDigits($input) {
// Use a regular expression to keep only commas and digits
return preg_replace('/[^,\d]/', '', $input);
}
function filterStringForSqlEntities($input) {
// Replace characters that are not letters, numbers, dashes, or underscores with an empty string
$filtered = preg_replace('/[^a-zA-Z0-9-_]/', '', $input);
return $filtered;
}
function autoLogin() {
Global $cookiename;
Global $tenantCookieName;
//var_dump($_COOKIE);
if(!isset($_COOKIE[$cookiename]) || !isset($_COOKIE[$tenantCookieName])) {
//die("wuuup");
return false;
} else {
$cookieValue = $_COOKIE[$cookiename];
$email = siteDecrypt($cookieValue);
$tenantId = siteDecrypt($_COOKIE[$tenantCookieName]);
if(strpos($email, "@") > 0){
//die("yeee!!");
return getUser($email, $tenantId);
} else {
return false;
}
}
}
function disImpersonate() {
Global $poserCookieName;
setcookie($poserCookieName, "");
return false;
}
function logOut() {
Global $cookiename;
Global $tenantCookieName;
setcookie($cookiename, "");
setcookie($tenantCookieName, "");
return false;
}
function loginForm() {
$out = "";
$out .= "<form method='post' name='loginform' id='loginform'>\n";
$out .= "<strong>Login here:</strong> email: <input name='email' type='text'>\n";
$out .= "password: <input name='password' type='password'>\n";
$out .= "<input name='tenant_id' value='" . gvfa("tenant_id", $_GET). "' type='hidden'>\n";
$out .= "<input name='action' value='login' type='submit'>\n";
$out .= "<div> or <div class='basicbutton'><a href=\"tool.php?table=user&action=startcreate\">Create Account</a></div></div>\n";
$out .= "</form>\n";
return $out;
}
function newUserForm($error = NULL, $encryptedTenantId = NULL) {
$formData = array(
[
'label' => 'email',
'name' => 'email',
'value' => gvfa("email", $_POST),
'error' => gvfa('email', $error)
],
[
'title' => 'password',
'name' => 'password',
'type' => 'password',
'value' => gvfa("password", $_POST),
'error' => gvfa('error', $error)
],
[
'label' => 'password (again)',
'name' => 'password2',
'type' => 'password',
'value' => gvfa("password2", $_POST),
'error' => gvfa('password2', $error)
]
);
if($encryptedTenantId) {
if(!$encryptedTenantId) {
$encryptedTenantId = gvfw("encrypted_tenant_id");
}
$formData[] = [
'name' => 'encrypted_tenant_id',
'type' => 'hidden',
'value' => $encryptedTenantId,
'error' => gvfa('encrypted_tenant_id', $error)
];
}
$out = genericForm($formData, "create user");
$out.= "<div style='padding-left:180px'><a href='?action=login'>Go back to login</a></div>";
return $out;
}
function presentList($data) {
$out = "<ul class='utilitylist'>\n";
foreach ($data as $item) {
$out .= "<li>\n";
if(array_key_exists('url', $item)){
$url = $item['url'];
} else if(array_key_exists('key', $item)) {
$url = "?table=utilities&action=" . $item['key'];
}
$out .= '<a href="' . $url . '">' . htmlspecialchars($item['label']) . '</a>';
$out .= ' - ' . htmlspecialchars($item['description']);
$out .= "\n</li>\n";
}
$out .= "</ul>\n";
return $out;
}
function camelCaseToWords($input) { //thanks, chatgpt!
// Use a regular expression to add spaces before each uppercase letter
$result = preg_replace('/(?<!^)([A-Z])/', ' $1', $input);
// Convert the result to lowercase
$result = strtolower($result);
return $result;
}
function generateSubFormFromJson($parentKey, $jsonString, $template) {
$templateArray = (array)json_decode($template);
//var_dump($templateArray);
// Decode the JSON string
$data = (array)json_decode($jsonString, true);
if($templateArray && false){
$keysToAdd = array_diff_key($data, $templateArray);
$data = $data + $keysToAdd;
}
// Start building the form
// Generate form elements recursively
return generateFormElements($parentKey, $data);
}
function generateFormElements($parentKey, $data) {
$formElements = '<div class="genericform">';
foreach ($data as $key => $value) {
//$formElements .= '<div>';
// Create a label based on the key
$formElements .= '<div class="genericformelementlabel" for="' . $key . '">' . camelCaseToWords($key) . '</div>';
if (is_array($value)) {
// Recursively generate form elements for arrays
$formElements .= generateFormElements($key, $value);
} else {
// Create an input field for non-array values
$formElements .= '<div class="genericformelementinput"><input style="width:200px" type="text" name="' . $parentKey . "|" . $key . '" id="' . $key . '" value="' . htmlspecialchars($value) . '"></div>';
}
//$formElements .= '</div>';
}
$formElements .= '</div>';
return $formElements;
}
//also returns pk by reference
function schemaArrayFromSchema($table, &$pk){
Global $conn;
$sql = "EXPLAIN " . $table;
$result = mysqli_query($conn, $sql);
$headerData = [];
if($result) {
$rows = mysqli_fetch_all($result, MYSQLI_ASSOC);
foreach($rows as $row) {
$fieldName = $row["Field"];
$type = "string";
if($row["Key"] == "PRI"){
$pk = $fieldName;
$type = "hidden";
}
if($row["Type"] == "tinyint(4)" ){
$type = "bool";
}
if(beginswith($row["Type"] , "int") || beginswith($row["Type"] , "decim")|| beginswith($row["Type"] , "float") ){
$type = "number";
}
if($fieldName != "tenant_id") {
$record = ["label" => $fieldName, "name" => $fieldName, "type" => $type ];
if($type == "bool" || $type == "number" ){
$record["changeable"] = true;
}
$headerData[] = $record;
}
}
}
return $headerData;
}
function generateCsvContent(array $dataRows) {
// Open a memory stream to store CSV data
$output = fopen('php://temp', 'r+');
// Get headers from the first row and write to CSV
if (!empty($dataRows)) {
fputcsv($output, array_keys($dataRows[0]));
}
// Write each row of data to CSV
foreach ($dataRows as $row) {
fputcsv($output, $row);
}
// Rewind the memory stream and fetch the contents
rewind($output);
$csvContent = stream_get_contents($output);
// Close the memory stream
fclose($output);
return $csvContent;
}
function genericEntityList($tenantId, $table, $outputFormat = "html") {
Global $conn;
$headerData = schemaArrayFromSchema($table, $pk);
$additionalValueQueryString = "";
foreach($_REQUEST as $key=>$value){ //slurp up values passed in
if(endsWith($key, "_id")){
$additionalValueQueryString .= "&" . $key . "=" . urlencode($value);
}
}
$thisDataSql = "SELECT * FROM " . $table;
if($table != "tenant" && $table != "user") {
$thisDataSql .= " WHERE tenant_id=" . intval($tenantId);
}
$deviceId = gvfw("device_id");
if($deviceId && $table== "device_feature" ){
$thisDataSql .= " AND device_id=" . intval($deviceId);
}
$thisDataResult = mysqli_query($conn, $thisDataSql);
$out = "<div class='listtools'><div class='basicbutton'><a href='?table=" . $table . "&action=startcreate" . $additionalValueQueryString . "'>Create</a></div> a new " . $table . "<//div>\n";
if($thisDataResult) {
$thisDataRows = mysqli_fetch_all($thisDataResult, MYSQLI_ASSOC);
$toolsTemplate = "<a href='?table=" . $table . "&" . $table . "_id=<" . $table . "_id/>'>Edit Info</a>";
$toolsTemplate .= " | " . deleteLink($table, $table. "_id" );
if(strtolower($outputFormat) == "csv") {
$content = generateCsvContent($thisDataRows);
download($path, $friendlyName, $content = "");
die();
} else {
$out .= genericTable($thisDataRows, $headerData, $toolsTemplate, null, $table, $pk);
}
}
return $out;
}
function genericEntityForm($tenantId, $table, $errors){
Global $conn;
$data = schemaArrayFromSchema($table, $pk);
$pkValue = gvfa($pk, $_GET);
$thisDataSql = "SELECT * FROM " . $table . " WHERE " . $pk . " = '" . $pkValue . "'";
if($table != "user" && $table != "tenant") {
$thisDataSql .= " AND tenant_id=" . intval($tenantId);
}
$thisDataResult = mysqli_query($conn, $thisDataSql);
if($thisDataResult) {
$thisDataRows = mysqli_fetch_all($thisDataResult, MYSQLI_ASSOC);
if($thisDataRows && count($thisDataRows) > 0) {
$data = updateDataWithRows($data, $thisDataRows[0]);
}
}
return genericForm($data, "Save " . $table, "Saving...");
}
function genericEntitySave($user, $table) {
Global $conn;
Global $encryptionPassword;
$tenantId = $user["tenant_id"];
$tablesThatRequireUser = tablesThatRequireUser();
//$data = schemaArrayFromSchema($table, $pk);
$pk = $table . "_id";
$data = $_POST;
if(array_key_exists("password", $data) && (array_key_exists("_new_password", $data) && gvfa("_new_password", $data) == true)){
$data["password"] = crypt($data["password"], $encryptionPassword);
}
if(in_array($table, $tablesThatRequireUser)){
$data["user_id"] = $user["user_id"];
}
unset($data['action']);
unset($data[$pk]);
unset($data['created']);
if($table != "user" && $table != "tenant") {
$data["tenant_id"] = $tenantId;
} else {
//unset($data["tenant_id"]);
}
$sql = insertUpdateSql($conn, $table, array($pk => gvfw($table . '_id')), $data);
//echo $sql;
//die();
if (mysqli_multi_query($conn, $sql)) {
do {
// Store first result set
if ($result = mysqli_store_result($conn)) {
while ($row = mysqli_fetch_row($result)) {
printf("%s\n", $row[0]);
}
mysqli_free_result($result);
}
// if there are more result-sets, the print a divider
if (mysqli_more_results($conn)) {
printf("-------------\n");
}
//Prepare next result set
} while (mysqli_next_result($conn));
}
$id = mysqli_insert_id($conn);
$url = "?table=" . $table;
$deviceId = gvfw("device_id");
if($deviceId && $table != "device"){
$url .= "&device_id=" . $deviceId;
}
header("Location: " . $url);
}
function updateDataWithRows($data, $thisDataRows) {
// Iterate over each row in $thisDataRows
foreach ($thisDataRows as $key => $value) {
// Iterate over each associative array in $data
foreach ($data as &$item) {
// Check if the "name" key in the current item matches the key in $thisDataRows
if (isset($item['name']) && $item['name'] == $key) {
// Set the "value" of the current item to the value in $thisDataRows
$item['value'] = $value;
// Break out of the inner loop since we found a match
break;
}
}
}
return $data;
}
function genericForm($data, $submitLabel, $waitingMesasage = "Saving...", $user = null, $onload = "") { //$data also includes any errors
Global $conn;
$textareaIds = [];
$out = "";
$noWaiting = false;
$onSubmitManyToManyItems = [];
$out .= "<script>\n";
$out .= "let formSpec = " . json_encode($data) . ";";
$out .= "</script>\n";
$out .= "<div class='genericform'>\n";
$columnCount = 0;
if(!$data){
return;
}
foreach($data as &$datum) {
$label = gvfa("label", $datum);
$frontendValidation = gvfa("frontend_validation", $datum);
$validationString = "";
if($frontendValidation){
$validationString = ' onblur=\" . $frontendValidation . "\"';
}
$value = str_replace("\\\\", "\\", gvfa("value", $datum));
//var_dump($datum);
$name = gvfa("name", $datum);
$changeFunction = gvfa("change-function", $datum);
$type = strtolower(gvfa("type", $datum));
$accentColor = gvfa("accent_color", $datum, "#66eeee");
//echo $name . " " . $accentColor . "<BR>";
$width = 200;
if(endsWith($name, "_id") && $columnCount == 0 && ($type == "" || $type == "number")) { //make first column read-only if it's an _id
$type = "read_only";
}
if(gvfa("width", $datum)){
$width = gvfa("width", $datum);
}
$height = '';
if(gvfa("height", $datum)){
$height = gvfa("height", $datum);
}
$noSyntaxHighlighting = false;
$noSyntaxHighlighting =gvfa("no_syntax_highlighting", $datum);
$values =gvfa("values", $datum);
$error = gvfa("error", $datum);
if($label == "") {
$label = $name;
}
if($type == "") {
$type = "text";
}
$idString = "";
if($type == "file") {
$idString = "id='file'";
$waitingMesasage = "Uploading...";
}
if($type == "hidden") {
$out .= "<input name='" . $name . "' value=\"" . ($value) . "\" type='" . $type . "'/>";
} else {
$out .= "<div class='genericformelementlabel'>" . $label . ": </div>";
$out .= "<div class='genericformelementinput'>";
$out .= "<div class='genericformerror'>" . $error . "</div>";
$template = gvfa("template", $datum);
if($type == 'json') {
if($value) {
$out .= generateSubFormFromJson($name, $value, $template);
} else {
$out .= generateSubFormFromJson($name, $template, $template);
}
} else if($type == 'multiselect') {
foreach($values as $specificValue){
$checkPart = "";
if(is_array($value)) {
foreach($value as $selectedValue){
if($selectedValue == $specificValue){
$checkPart = " checked='checked'";
}
}
}
$out .= "<input style='accent-color:" . $accentColor . "' type='checkbox' name='" . $name . "[]' value='" . $specificValue . " " . $checkPart . "'/> " . $specificValue . "<br/>";
}
} else if($type == 'select') {
//echo $values;
$onChangePart = "";
if($changeFunction) {
$onChangePart = " onchange=\"" . $changeFunction . "\" ";
}
$out .= "<select " . $onChangePart. " name='" . $name . "' />";
if(is_string($values)) {
$out .= "<option value='0'>none</option>";
//var_dump($user);
if($user) {
$values = tokenReplace($values, $user); //I'd has something embarrassingly hardcoded here until I had $user available
}
$result = mysqli_query($conn, $values); //REALLY NEED TO SANITIZE $values since it contains RAW SQL!!!
if($result){
$rows = mysqli_fetch_all($result, MYSQLI_ASSOC);
if($rows){
foreach($rows as $row){
$selected = "";
if(!$value){
$value = gvfw($name);
}
if($row[$name] == $value) {
$selected = " selected='selected' ";
}
$out .= "<option " . $selected . " value='". $row[$name] . "'>" . $row["text"] . "</option/>\n";
}
}
}
} else if(is_array($values)){
$out .= "<option value=''>none</option>";
foreach($values as &$optionValue) {
$selected = "";
if($value == $optionValue){
$selected = "selected";
}
$out .= "<option ". $selected . ">" . $optionValue . "</option/>\n";
}
}
$out .= "</select>";
} else if ($type == "many-to-many") {
//echo $values;
$result = mysqli_query($conn, $values); //REALLY NEED TO SANITIZE $values since it contains RAW SQL!!!
$rows = null;
$itemTool = gvfa("item_tool", $datum);
$itemToolString = "";
if($itemTool){
$itemToolString = " onmouseup='" . $itemTool . "(this)' ";
}
if($result) {
$rows = mysqli_fetch_all($result, MYSQLI_ASSOC);
}
$out .= "<div class='destinationitems'>\n";
$out .= "attached:<br/>";
if($height == ""){
$height = 5;
}
$out .= "<select style='accent-color:" . $accentColor . "' multiple='multiple' name='" . $name . "[]' id='dest_" . $name . "' size='" . intval($height) . "'/>";
if($rows) {
foreach($rows as $row){
$selected = "";
if(!$value){
$value = gvfw($name);
}
if($row[$name] == $value) {
$selected = " selected='selected' ";
}
if($row["has"] ){
$out .= "<option " . $itemToolString . $selected . " value='". $row[$name] . "'>" . $row["text"] . "</option/>\n";
}
}
}
$out .= "</select>";
$onSubmitManyToManyItems[] = $name;
$out .= "</div>\n";
$out .= "<div class='manytomanytools'>\n";
$out .= "<button onclick='return copyManyToMany(\"source_" . $name ."\", \"dest_" . $name ."\")'><</button>";
$out .= "<button onclick='return copyManyToMany(\"dest_" . $name ."\", \"source_" . $name ."\")'>></button>";
$out .= "</div>\n";
$out .= "<div class='sourceitems'>\n";
$out .= "available:<br/>";
$out .= "<select style='accent-color:" . $accentColor . "' name='source_" . $name . "' id='source_" . $name . "' size='" . intval($height) . "'/>";
if($rows) {
foreach($rows as $row){
$selected = "";
if(!$value){
$value = gvfw($name);
}
if($row[$name] == $value) {
$selected = " selected='selected' ";
}
if(!$row["has"] ){
$out .= "<option " . $itemToolString . $selected . " value='". $row[$name] . "'>" . $row["text"] . "</option/>\n";
}
}
}
$out .= "</select>";
$out .= "</div>\n";
$out .= "<div class='toolpanel' id='panel_" . $name . "'>\n";
$out .= "</div>\n";
} else if ($type == "bool" || $type == "checkbox"){
$checked = "";
if($value) {
$checked = "checked";
}
$out .= "<input style='accent-color:" . $accentColor . "' value='1' name='" . $name . "' " . $checked . " type='checkbox'/>\n";
} else if ($type == "read_only"){
$out .= $value . "\n";
} else {
if($height){
$textAreaId = "id-" . $name;
$idString = "id='" . $textAreaId . "'";
if(!$noSyntaxHighlighting) {
array_push($textareaIds, $textAreaId);
}
$codeLanguage = gvfa("code_language", $datum, "html");
$out .= "<textarea " . $validationString . " " . $idString . " style='width:" . $width . "px;height:" . $height . "px;accent-color:" . $accentColor . "' name='" . $name . "' />" . $value . "</textarea>\n";
} else {
$specialNumberAttribs = "";
if ($type == "number") {
$specialNumberAttribs = " step='0.0000000000001' ";
}
if ($type == "int") {
$type == "number";
$specialNumberAttribs = " step='1' ";
}
$inputJavascript = "";
if($type == "plaintext_password") {
$inputJavascript = "onchange=\"document.getElementById('_new_password').checked=true\"";
}
$out .= "<input " . $inputJavascript . " " . $validationString . " style='width:" . $width . "px;accent-color:" . $accentColor . "' " . $idString. " " . $specialNumberAttribs . " name='" . $name . "' value=\"" . $value . "\" type='" . $type . "'/>\n";
if($type == "plaintext_password") {
$out .= "<input id='_new_password' name='_new_password' value='1' type='checkbox'>\n password not yet encrypted";
}
}
}
$out .= "</div>\n";
}
$columnCount++;
}
$out .= "<div class='genericformelementlabel'><input name='action' id='action' value='" . $submitLabel. "' type='submit'/></div>\n";
$out .= "<input name='_data' value=\"" . htmlspecialchars(json_encode($data)) . "\" type='hidden'/>";
$out .= "</div>\n";
$out .= "</form>\n";
$out .= "\n<script>let onSubmitManyToManyItems=['" . implode("','", $onSubmitManyToManyItems) . "'];</script>\n";
$onSubmit = "onsubmit='formSubmitTasks();startWaiting(\"" . $waitingMesasage . "\")'";
$out = "<form name='genericForm' " . $onSubmit . " method='post' name='genericform' id='genericform' enctype='multipart/form-data'>\n" . $out;
if(count($textareaIds) > 0){
$out .= "<script src=\"./tinymce/tinymce.min.js\" referrerpolicy=\"origin\"></script>\n";
/*
$out .= "<link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/styles/default.min.css\">\n";
$out .= "<script src=\"https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/highlight.min.js\"></script>\n";
*/
/*
$out .= "<link href=\"https://cdnjs.cloudflare.com/ajax/libs/prism/1.27.0/themes/prism.min.css\" rel=\"stylesheet\" />\n";
$out .= "<script src=\"https://cdnjs.cloudflare.com/ajax/libs/prism/1.27.0/prism.min.js\"></script>\n";
$out .= "<script src=\"https://cdnjs.cloudflare.com/ajax/libs/prism/1.27.0/plugins/line-numbers/prism-line-numbers.min.js\"></script>\n";
$out .= "<link href=\"https://cdnjs.cloudflare.com/ajax/libs/prism/1.27.0/plugins/line-numbers/prism-line-numbers.min.css\" rel=\"stylesheet\" />\n";
$out .= "<script src=\"https://cdnjs.cloudflare.com/ajax/libs/prism/1.27.0/components/prism-sql.min.js\"></script>\n";
*/
$out .= "<link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.5/codemirror.min.css\">\n";
$out .= "<script src=\"https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.5/codemirror.min.js\"></script>\n";
$out .= "<script src=\"https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.5/mode/sql/sql.min.js\"></script>\n";
$out .= "<script src=\"https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.5/mode/javascript/javascript.min.js\"></script>\n";
$out .= "\n<script>\n";
$out.= "let textAreaCount = 0;\n";
$out.= "let textareaIds = ['" . implode("','", $textareaIds) . "'];\n";
$out .= "\ntextareaIds.forEach(id => {\n";
$out .= "let textArea = document.getElementById(id);\n";
$out .= "let textAreaName = textArea.name;\n";
$out .= "let formItemInfoRecord = findObjectByName(formSpec, textAreaName);\n";
$out .= "let codeLanguage = formItemInfoRecord[\"code_language\"];\n";
$out .= "formattedCode = textArea.value;\n";
$out .= "mode = 'text/x-html';";
$out .= "if (codeLanguage == 'sql'){;\n";
$out .= " formattedCode = formatSQL(textArea.value);\n";
$out .= " mode = 'text/x-' + codeLanguage;\n";
$out .= "}\n;";
$out .= "if (codeLanguage == 'json'){;\n";
$out .= " formattedCode = formatJSON(textArea.value);\n";
$out .= " mode = 'application/' + codeLanguage;\n";
$out .= "}\n;";
$out .= "textArea.value = formattedCode;\n";
$out .= "let editor = CodeMirror.fromTextArea(textArea, {\n";
$out .= "lineNumbers: true,\n";
$out .= " mode: mode,\n";
$out .= " theme: \"default\",\n";
$out .= "tabSize: 2,\n";
$out .= "indentWithTabs: true,\n";
$out .= "smartIndent: true,\n";
$out .= "autoCloseBrackets: true,\n";
$out .= "lineWrapping: true\n";
$out .= "});\n";
$out .= "editor.setSize(formItemInfoRecord['width'] + 'px', formItemInfoRecord['height'] + 'px');\n";
$out .= "editor.on('blur', (cm) => {
console.log('Editor lost focus');
// Handle your blur event here
console.log(formItemInfoRecord);
editor.save();
eval(formItemInfoRecord[\"frontend_validation\"]);
//console.log('CodeMirror content:', value);
});\n";
$out.= "textAreaCount++;\n";
$out .= "});\n";
//$out.= "setTimeout(()=>{\n";
/*
$out .= "\ntextareaIds.forEach(id => {\n";
$out .= "\n tinymce.init({\n";
$out .= "\nselector: `#$" . "{id}`,\n";
$out .= "\nbranding: false,\n";
$out .= "\nforce_br_newlines : true,\n";
$out .= "\nlicense_key: 'gpl' ,\n";
$out .= "\npromotion: false,\n";
$out .= "\nplugins: 'codesample code',\n";
$out .= "\ntoolbar: 'codesample code',\n";
$out .= "codesample_languages: [
{text: 'HTML/XML', value: 'markup'},
{text: 'JavaScript', value: 'javascript'},
{text: 'CSS', value: 'css'},
{text: 'PHP', value: 'php'},
{text: 'Ruby', value: 'ruby'},
{text: 'Python', value: 'python'},
{text: 'Java', value: 'java'},
{text: 'C', value: 'c'},
{text: 'C#', value: 'csharp'},
{text: 'C++', value: 'cpp'},
{text: 'SQL', value: 'sql'}
],";
*/
/*
$out .= "\nsetup: function(editor) {\n";
$out .= "\neditor.on('change', function() {\n";
$out .= "\neditor.save();\n";
$out .= "\n document.querySelectorAll('pre code').forEach((block) => {\n";
$out .= "\n hljs.highlightElement(block);\n";
$out .= "\n });\n";
$out .= "\n});\n";
$out .= "\n }\n";
$out .= "\n});\n";
$out .= "\n });\n";
*/
/*
$out .= "\nsetup: function(editor) {\n";
$out .= "\n editor.on('init', function() {\n";
$out .= "\n editor.on('NodeChange', function(e) {\n";
$out .= "\nconsole.log('cccc');\n";
$out .= "\n // Highlight the code block using Prism.js when the editor content changes\n";
$out .= "\n Prism.highlightAllUnder(editor.getBody());\n";
$out .= "\n });\n";
$out .= "\n});\n";
$out .= "\n}\n";
$out .= "\n});\n";
$out .= "\n });\n";
*/
//$out.= "\n}, 8000)\n";
$out .= "\n</script>\n";
}
if($onload){
$out .= "\n<script>" . $onload . "</script>\n";
}
return $out;
}
function assembledJsonData($template, $parentName, $sourceData){
//var_dump($template);
//echo gettype($sourceData);
//echo $sourceData["config|excludeNumbers"] . "^";
foreach($template as $key => $value){
if (is_array($value)) {
$out[$key] = assembledJsonData($template[$key], $key, $sourceData);
} else {
$out[$key] = $sourceData[$parentName . "|" . $key];
}
}
return $out;
}
function reassembleFormJson($formData, $sourceData){
//echo gettype($sourceData);
foreach($formData as &$datum) {
$datum = (array)$datum;
$label = gvfa("label", $datum);
$value = str_replace("\\\\", "\\", gvfa("value", $datum));
$name = gvfa("name", $datum);
$type = strtolower(gvfa("type", $datum));
$values =gvfa("values", $datum);
$error = gvfa("error", $datum);
if($type == "json"){
if($datum["template"]) {
$out = json_encode(assembledJsonData(json_decode($datum["template"]), $name, $sourceData));
return $out;
//foreach($formData["template"] as $key => $value){
}
}
}
die();
}
function getUserById($id) {
Global $conn;
$sql = "SELECT * FROM `user` WHERE user_id = " . intval($id);
$result = mysqli_query($conn, $sql);
$row = $result->fetch_assoc();
return $row;
}
//needs to be made so users and tenants can be many to many
//also returns tenant information
function getUser($email, $tenantId = null) {
Global $conn;
$user = null;
$sql = "SELECT * FROM `user` WHERE email = '" . mysqli_real_escape_string($conn, $email) . "'";
$result = mysqli_query($conn, $sql);
if($result){
$user = $result->fetch_assoc();
$role = $user["role"];
$sql = "SELECT * FROM `tenant_user` tu JOIN tenant t ON tu.tenant_id=t.tenant_id WHERE user_id = '" . $user["user_id"] . "'";
if($tenantId){
$sql .= " AND t.tenant_id = " . intval($tenantId);
}
//echo $sql;
$result = mysqli_query($conn, $sql);
$user["tenants"] = null;
if($result){
$tenants = mysqli_fetch_all($result, MYSQLI_ASSOC);
//var_dump($tenants);
if(count($tenants) > 0) {
$tenant = $tenants[0];
$tenant["role"] = $role;//a temporary hack that will probably be good for awhile -- overwrite the mapping table role with the user role;
$user["tenants"] = $tenants;
$user = array_merge($user, $tenant);
}
}
}
//var_dump($user);
return $user;
}
function impersonateUser($impersonatedUserId) {
Global $poserCookieName;
setcookie($poserCookieName, siteEncrypt($impersonatedUserId), time() + (30 * 365 * 24 * 60 * 60));
header("location: .");
}
function getImpersonator($justId = true){
Global $poserCookieName;
$poserId = siteDecrypt(gvfa($poserCookieName, $_COOKIE));
//die($poserCookieName . " " . $poserId );
if($justId){
return $poserId;
}
return getUserById($poserId);
}
function setTenant($encryptedTenantId){
Global $tenantCookieName;
setcookie($tenantCookieName, $encryptedTenantId, time() + (30 * 365 * 24 * 60 * 60));
header('Location: '.$_SERVER['PHP_SELF']);
}
function availableRoles(){
return ["", "viewer", "operator", "subadmin", "admin", "super"];
}
function loginUser($source = NULL, $tenant_id = NULL) {
Global $conn;
Global $encryptionPassword;
Global $cookiename;
Global $tenantCookieName;
if($source == NULL) {
$source = $_REQUEST;
}
$email = gvfa("email", $source);
$passwordIn = gvfa("password", $source);
$sql = "SELECT `email`, `password`, t.tenant_id, name as tenant_name, about FROM `user` u JOIN tenant_user tu ON u.user_id=tu.user_id JOIN tenant t ON tu.tenant_id = t.tenant_id WHERE email = '" . mysqli_real_escape_string($conn, $email) . "' AND (u.expired IS NULL OR u.expired>NOW()) AND (t.expired IS NULL OR t.expired>NOW()) ";
if($tenant_id){
$sql .= " AND t.tenant_id = " . $tenant_id;
}
//die($sql);
$result = mysqli_query($conn, $sql);
if(!$result){
header("location: .");
die();
}
//try{
$row = NULL;
$iv = "0x12345678123456";
$rows = mysqli_fetch_all($result, MYSQLI_ASSOC);
//var_dump( $rows);
if(count($rows) > 1) {
$out ="<div class='tenantpicker'>\n";
$out .="<div class='listtitle'>Pick a Tenant</div>\n";
$row = $rows[0];
$email = $row["email"];
$passwordHashed = $row["password"];
if (password_verify($passwordIn, $passwordHashed)) {
//die("we are setting a cookie");
setcookie($cookiename, siteEncrypt($email), time() + (30 * 365 * 24 * 60 * 60));
foreach($rows as &$row) {
$out .="<div><a href='?action=settenant&encrypted_tenant_id=" . urlencode(siteEncrypt($row["tenant_id"])). "'>" .$row["tenant_name"] . "</a> <div class='description'>" . $row["about"] . "</div></div>";
}
//echo $out;
return $out;
}
$out .="</div>\n";
} else if($rows && count($rows) > 0) {
$row = $rows[0];
}
if($row && $row["email"] && $row["password"]) {
//$tenant_id = $row["tenant_id"];
$email = $row["email"];
$passwordHashed = $row["password"];
//die($passwordHashed . "*" . $passwordIn);
//for debugging:
//echo crypt($passwordIn, $encryptionPassword);
//die(crypt("public", $encryptionPassword) . "*" . $passwordIn . "*" . crypt($passwordIn, $encryptionPassword) . "*" . $passwordHashed . "*" .password_verify($passwordIn, $passwordHashed) . "*");
if (password_verify($passwordIn, $passwordHashed)) {
setcookie($cookiename, siteEncrypt($email), time() + (30 * 365 * 24 * 60 * 60));
setcookie($tenantCookieName, siteEncrypt($tenant_id), time() + (30 * 365 * 24 * 60 * 60));
header('Location: '.$_SERVER['PHP_SELF']);
//echo "LOGGED IN!!!" . $email ;
die;
}
}
return false;
//} catch(Exception $e) {
//header("location: .");
//}
}
function siteEncrypt($text){
Global $encryptionPassword;
$ivLength = openssl_cipher_iv_length('AES-128-CTR');
$iv = openssl_random_pseudo_bytes($ivLength);