-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsite_functions.php
305 lines (285 loc) · 10.1 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
<?php
//generic php library, pruned down to just what is needed, August 9 2024 gus mueller
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 logIn() {
Global $cookiename;
if(!isset($_COOKIE[$cookiename])) {
return false;
} else {
$cookieValue = $_COOKIE[$cookiename];
$email = siteDecrypt($cookieValue);
if(strpos($email, "@") > 0){
return getUser($email);
} else {
return false;
}
}
}
function logOut() {
Global $cookiename;
setcookie($cookiename, "");
return false;
}
function loginForm() {
$out = "";
$out .= "<div class='userform'><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' style='width:100px'>\n";
$out .= "<button name='action' value='login' type='submit'>login</button>\n";
$out .= "<div style='margin-top:6px'> or <div class='basicbutton'><a href=\"?table=user&action=startcreate\">create account</a></div></div>\n";
$out .= "</form></div>\n";
return $out;
}
function newUserForm($error = NULL) {
$formData = array(
[
'label' => 'email',
'name' => 'email',
'width' => 100,
'value' => gvfa("email", $_POST),
'error' => gvfa('email', $error)
],
[
'title' => 'password',
'name' => 'password',
'type' => 'password',
'width' => 100,
'value' => gvfa("password", $_POST),
'error' => gvfa('error', $error)
],
[
'label' => 'password (again)',
'name' => 'password2',
'type' => 'password',
'width' => 100,
'value' => gvfa("password2", $_POST),
'error' => gvfa('password2', $error)
]
);
$out = genericForm($formData, "create user");
$out.= "<div style='padding-top:10px;text-align:right'><a class='basicbutton' href='?action=login'>return to login</a></div>";
return $out;
}
function genericForm($data, $submitLabel, $waitingMesasage = "Saving...") { //$data also includes any errors
Global $conn;
$out = "";
$onSubmitManyToManyItems = [];
$out .= "<div class='genericform'>\n";
$columnCount = 0;
foreach($data as &$datum) {
$label = gvfa("label", $datum);
$value = str_replace("\\\\", "\\", gvfa("value", $datum));
$name = gvfa("name", $datum);
$type = strtolower(gvfa("type", $datum));
$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);
}
$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 == "bool" || $type == "checkbox"){
$checked = "";
if($value) {
$checked = "checked";
}
$out .= "<input value='1' name='" . $name . "' " . $checked . " type='checkbox'/>\n";
} else if ($type == "read_only"){
$out .= $value . "\n";
} else {
if($height){
$out .= "<textarea " . $idString . " style='width:" . $width . "px;height:" . $height . "px' name='" . $name . "' />" . $value . "</textarea>\n";
} else {
$out .= "<input style='width:" . $width . "px' " . $idString. " name='" . $name . "' value=\"" . $value . "\" type='" . $type . "'/>\n";
}
}
$out .= "</div>\n";
}
$columnCount++;
}
$out .= "<div class='genericformelementlabel'><input class='basicbutton' type='submit' name='action' id='action' value='" . $submitLabel . "'/></div>\n";
$out .= "<input name='_data' value=\"" . htmlspecialchars(json_encode($data)) . "\" type='hidden'/>";
$out .= "</div>\n";
$out .= "</form>\n";
$out = "<form name='genericForm' onsubmit='formSubmitTasks();startWaiting(\"" . $waitingMesasage . "\")' method='post' name='genericform' id='genericform' enctype='multipart/form-data'>\n" . $out;
return $out;
}
function getUser($email) {
Global $conn;
$sql = "SELECT * FROM `user` WHERE email = '" . mysqli_real_escape_string($conn, $email) . "'";
$result = mysqli_query($conn, $sql);
$row = $result->fetch_assoc();
return $row;
}
function loginUser($source = NULL) {
Global $conn;
Global $cookiename;
if($source == NULL) {
$source = $_REQUEST;
}
$email = gvfa("email", $source);
$passwordIn = gvfa("password", $source);
$sql = "SELECT `email`, `password` FROM `user` WHERE email = '" . mysqli_real_escape_string($conn, $email) . "' ";
$result = mysqli_query($conn, $sql);
if(!$result){
header("location: .");
die();
}
$row = $result->fetch_assoc();
if($row && $row["email"] && $row["password"]) {
$email = $row["email"];
$passwordHashed = $row["password"];
if (password_verify($passwordIn, $passwordHashed)) {
setcookie($cookiename, siteEncrypt($email), time() + (30 * 365 * 24 * 60 * 60));
header('Location: '.$_SERVER['PHP_SELF']);
die();
}
}
return false;
}
function siteEncrypt($text){
Global $encryptionPassword;
$ivLength = openssl_cipher_iv_length('AES-128-CTR');
$iv = openssl_random_pseudo_bytes($ivLength);
$out = base64_encode($iv . openssl_encrypt($text , "AES-128-CTR", $encryptionPassword, 0, $iv));
return $out;
}
function siteDecrypt($encrytedText){
Global $encryptionPassword;
$ivLength = openssl_cipher_iv_length('AES-128-CTR');
$data = base64_decode($encrytedText);
$iv = substr($data, 0, $ivLength);
$encrypted = substr($data, $ivLength);
return openssl_decrypt($encrypted, 'AES-128-CTR', $encryptionPassword, 0, $iv);
}
function gvfw($name, $fail = false){ //get value from wherever
$out = gvfa($name, $_REQUEST, $fail);
if($out == "") {
$out = gvfa($name, $_POST, $fail);
}
return $out;
}
function gvfa($name, $source, $fail = false){ //get value from associative
if(isset($source[$name])) {
return $source[$name];
}
return $fail;
}
function beginsWith($strIn, $what) {
if (substr($strIn,0, strlen($what))==$what){
return true;
}
return false;
}
function endsWith($strIn, $what) {
if (substr($strIn, strlen($strIn)- strlen($what) , strlen($what))==$what) {
return true;
}
return false;
}
function createUser(){
Global $conn;
Global $encryptionPassword;
$errors = NULL;
$date = new DateTime("now", new DateTimeZone('America/New_York'));//obviously, you would use your timezone, not necessarily mine
$formatedDateTime = $date->format('Y-m-d H:i:s');
$password = gvfa("password", $_POST);
$password2 = gvfa("password2", $_POST);
$email = gvfa("email", $_POST);
if($password != $password2 || $password == "") {
$errors["password2"] = "Passwords must be identical and have a value";
}
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors["email"] = "Invalid email format";
}
if(is_null($errors)) {
$encryptedPassword = crypt($password, $encryptionPassword);
$userList = userList();
if(count(userList()) == 0) {
//if there are no users, create the first one as admin
$sql = "INSERT INTO user(email, password, created, role) VALUES ('" . $email . "','" . mysqli_real_escape_string($conn, $encryptedPassword) . "','" .$formatedDateTime . "','admin')";
} else {
$sql = "INSERT INTO user(email, password, created) VALUES ('" . $email . "','" . mysqli_real_escape_string($conn, $encryptedPassword) . "','" .$formatedDateTime . "')";
}
$result = mysqli_query($conn, $sql);
$id = mysqli_insert_id($conn);
loginUser($_POST);
header("Location: ?");
} else {
return $errors;
}
return false;
}
function userList(){
Global $conn;
$userSql = "SELECT * FROM user";
$thisDataResult = mysqli_query($conn, $userSql);
if($thisDataResult) {
$rows = mysqli_fetch_all($thisDataResult, MYSQLI_ASSOC);
} else {
$rows = [];
}
return $rows;
}
function encryptLongString($plaintext, $password) {
$iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length('aes-256-cbc'));
$ciphertext = openssl_encrypt($plaintext, 'aes-256-cbc', $password, 0, $iv);
$iv = str_pad($iv, 16, "\0");
$ivBase64 = base64_encode($iv);
$ciphertextBase64 = base64_encode($ciphertext);
return $ivBase64 . ':' . $ciphertextBase64;
}
function decryptLongString($encryptedData, $password) {
// Split the IV and ciphertext from the encrypted data
list($ivBase64, $ciphertextBase64) = explode(':', $encryptedData, 2);
$iv = base64_decode($ivBase64);
$ciphertext = base64_decode($ciphertextBase64);
$iv = str_pad($iv, 16, "\0");
$plaintext = openssl_decrypt($ciphertext, 'aes-256-cbc', $password, 0, $iv);
return $plaintext;
}
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;
}