Browse Source

Cleanup some technical debt

Skylar Ittner 4 months ago
parent
commit
0e094809fa
10 changed files with 24 additions and 224 deletions
  1. 1
    1
      action.php
  2. 6
    6
      api.php
  3. 3
    3
      app.php
  4. 2
    2
      index.php
  5. 3
    3
      lib/IPUtils.lib.php
  6. 1
    1
      lib/Log.lib.php
  7. 4
    4
      lib/User.lib.php
  8. 1
    1
      mobile/index.php
  9. 2
    202
      required.php
  10. 1
    1
      setup.php

+ 1
- 1
action.php View File

@@ -70,7 +70,7 @@ switch ($VARS['action']) {
70 70
         returnToSender("new_pin_mismatch");
71 71
         break;
72 72
     case "add2fa":
73
-        if (is_empty($VARS['secret'])) {
73
+        if (empty($VARS['secret'])) {
74 74
             returnToSender("invalid_parameters");
75 75
         }
76 76
         $user = new User($_SESSION['uid']);

+ 6
- 6
api.php View File

@@ -206,7 +206,7 @@ switch ($VARS['action']) {
206 206
         exit(json_encode(["status" => "OK", "managers" => $managers]));
207 207
         break;
208 208
     case "usersearch":
209
-        if (is_empty($VARS['search']) || strlen($VARS['search']) < 3) {
209
+        if (empty($VARS['search']) || strlen($VARS['search']) < 3) {
210 210
             exit(json_encode(["status" => "OK", "result" => []]));
211 211
         }
212 212
         $data = $database->select('accounts', ['uid', 'username', 'realname (name)'], ["OR" => ['username[~]' => $VARS['search'], 'realname[~]' => $VARS['search']], "LIMIT" => 10]);
@@ -234,7 +234,7 @@ switch ($VARS['action']) {
234 234
     case "mobileenabled":
235 235
         exit(json_encode(["status" => "OK", "mobile" => MOBILE_ENABLED]));
236 236
     case "mobilevalid":
237
-        if (is_empty($VARS['username']) || is_empty($VARS['code'])) {
237
+        if (empty($VARS['username']) || empty($VARS['code'])) {
238 238
             http_response_code(400);
239 239
             die("\"400 Bad Request\"");
240 240
         }
@@ -243,12 +243,12 @@ switch ($VARS['action']) {
243 243
         exit(json_encode(["status" => "OK", "valid" => $user_key_valid]));
244 244
     case "alertemail":
245 245
         engageRateLimit();
246
-        if (is_empty($VARS['username']) || !User::byUsername($VARS['username'])->exists()) {
246
+        if (empty($VARS['username']) || !User::byUsername($VARS['username'])->exists()) {
247 247
             http_response_code(400);
248 248
             die("\"400 Bad Request\"");
249 249
         }
250 250
         $appname = "???";
251
-        if (!is_empty($VARS['appname'])) {
251
+        if (!empty($VARS['appname'])) {
252 252
             $appname = $VARS['appname'];
253 253
         }
254 254
         $result = User::byUsername($VARS['username'])->sendAlertEmail($appname);
@@ -325,7 +325,7 @@ switch ($VARS['action']) {
325 325
         exit(json_encode(["status" => "OK", "groups" => $groups]));
326 326
         break;
327 327
     case "groupsearch":
328
-        if (is_empty($VARS['search']) || strlen($VARS['search']) < 2) {
328
+        if (empty($VARS['search']) || strlen($VARS['search']) < 2) {
329 329
             exit(json_encode(["status" => "OK", "result" => []]));
330 330
         }
331 331
         $data = $database->select('groups', ['groupid (id)', 'groupname (name)'], ['groupname[~]' => $VARS['search'], "LIMIT" => 10]);
@@ -333,7 +333,7 @@ switch ($VARS['action']) {
333 333
         break;
334 334
     case "checkpin":
335 335
         $pin = "";
336
-        if (is_empty($VARS['pin'])) {
336
+        if (empty($VARS['pin'])) {
337 337
             http_response_code(400);
338 338
             die("\"400 Bad Request\"");
339 339
         }

+ 3
- 3
app.php View File

@@ -14,7 +14,7 @@ if ($_SESSION['loggedin'] != true) {
14 14
 require_once __DIR__ . "/pages.php";
15 15
 
16 16
 $pageid = "home";
17
-if (isset($_GET['page']) && !is_empty($_GET['page'])) {
17
+if (isset($_GET['page']) && !empty($_GET['page'])) {
18 18
     $pg = strtolower($_GET['page']);
19 19
     $pg = preg_replace('/[^0-9a-z_]/', "", $pg);
20 20
     if (array_key_exists($pg, PAGES) && file_exists(__DIR__ . "/pages/" . $pg . ".php")) {
@@ -66,9 +66,9 @@ header("Link: <static/js/bootstrap.bundle.min.js>; rel=preload; as=script", fals
66 66
 
67 67
         <?php
68 68
 // Alert messages
69
-        if (isset($_GET['msg']) && !is_empty($_GET['msg']) && array_key_exists($_GET['msg'], MESSAGES)) {
69
+        if (isset($_GET['msg']) && !empty($_GET['msg']) && array_key_exists($_GET['msg'], MESSAGES)) {
70 70
             // optional string generation argument
71
-            if (!isset($_GET['arg']) || is_empty($_GET['arg'])) {
71
+            if (!isset($_GET['arg']) || empty($_GET['arg'])) {
72 72
                 $alertmsg = $Strings->get(MESSAGES[$_GET['msg']]['string'], false);
73 73
             } else {
74 74
                 $alertmsg = $Strings->build(MESSAGES[$_GET['msg']]['string'], ["arg" => strip_tags($_GET['arg'])], false);

+ 2
- 2
index.php View File

@@ -50,7 +50,7 @@ if (empty($VARS['progress'])) {
50 50
                     $username_ok = true;
51 51
                     break;
52 52
                 default:
53
-                    if (!is_empty($error)) {
53
+                    if (!empty($error)) {
54 54
                         $alert = $error;
55 55
                     } else {
56 56
                         $alert = $Strings->get("login error", false);
@@ -99,7 +99,7 @@ if (empty($VARS['progress'])) {
99 99
     }
100 100
 } else if ($VARS['progress'] == "chpasswd") {
101 101
     engageRateLimit();
102
-    if (!is_empty($_SESSION['username'])) {
102
+    if (!empty($_SESSION['username'])) {
103 103
         $user = User::byUsername($_SESSION['username']);
104 104
 
105 105
         try {

+ 3
- 3
lib/IPUtils.lib.php View File

@@ -77,7 +77,7 @@ class IPUtils {
77 77
             ];
78 78
             $valid = false;
79 79
             foreach ($cloudflare_ips_v6 as $cidr) {
80
-                if (ip6_in_cidr($_SERVER["REMOTE_ADDR"], $cidr)) {
80
+                if ($this::ip6_in_cidr($_SERVER["REMOTE_ADDR"], $cidr)) {
81 81
                     $valid = true;
82 82
                     break;
83 83
                 }
@@ -102,7 +102,7 @@ class IPUtils {
102 102
             ];
103 103
             $valid = false;
104 104
             foreach ($cloudflare_ips_v4 as $cidr) {
105
-                if (ip4_in_cidr($_SERVER["REMOTE_ADDR"], $cidr)) {
105
+                if ($this::ip4_in_cidr($_SERVER["REMOTE_ADDR"], $cidr)) {
106 106
                     $valid = true;
107 107
                     break;
108 108
                 }
@@ -120,7 +120,7 @@ class IPUtils {
120 120
         // If CloudFlare is in the mix, we should use it.
121 121
         // Check if the request is actually from CloudFlare before trusting it.
122 122
         if (isset($_SERVER["HTTP_CF_CONNECTING_IP"])) {
123
-            if (validateCloudflare()) {
123
+            if ($this::validateCloudflare()) {
124 124
                 return $_SERVER["HTTP_CF_CONNECTING_IP"];
125 125
             }
126 126
         }

+ 1
- 1
lib/Log.lib.php View File

@@ -18,7 +18,7 @@ class Log {
18 18
     public static function insert($type, $user, string $data = "") {
19 19
         global $database;
20 20
         // find IP address
21
-        $ip = getClientIP();
21
+        $ip = IPUtils::getClientIP();
22 22
         if (gettype($type) == "object" && is_a($type, "LogType")) {
23 23
             $type = $type->getType();
24 24
         }

+ 4
- 4
lib/User.lib.php View File

@@ -63,7 +63,7 @@ class User {
63 63
         global $database;
64 64
         $database->insert('accounts', [
65 65
             'username' => strtolower($username),
66
-            'password' => (is_null($password) ? null : encryptPassword($password)),
66
+            'password' => (is_null($password) ? null : password_hash($password, PASSWORD_BCRYPT)),
67 67
             'realname' => $realname,
68 68
             'email' => $email,
69 69
             'phone1' => $phone1,
@@ -215,10 +215,10 @@ class User {
215 215
     }
216 216
 
217 217
     function sendAlertEmail(string $appname = SITE_TITLE) {
218
-        if (is_empty(ADMIN_EMAIL) || filter_var(ADMIN_EMAIL, FILTER_VALIDATE_EMAIL) === FALSE) {
218
+        if (empty(ADMIN_EMAIL) || filter_var(ADMIN_EMAIL, FILTER_VALIDATE_EMAIL) === FALSE) {
219 219
             return "invalid_to_email";
220 220
         }
221
-        if (is_empty(FROM_EMAIL) || filter_var(FROM_EMAIL, FILTER_VALIDATE_EMAIL) === FALSE) {
221
+        if (empty(FROM_EMAIL) || filter_var(FROM_EMAIL, FILTER_VALIDATE_EMAIL) === FALSE) {
222 222
             return "invalid_from_email";
223 223
         }
224 224
 
@@ -251,7 +251,7 @@ class User {
251 251
         $mail->addAddress(ADMIN_EMAIL, "System Admin");
252 252
         $mail->isHTML(false);
253 253
         $mail->Subject = $Strings->get("admin alert email subject", false);
254
-        $mail->Body = $Strings->build("admin alert email message", ["username" => $this->username, "datetime" => date("Y-m-d H:i:s"), "ipaddr" => getClientIP(), "appname" => $appname], false);
254
+        $mail->Body = $Strings->build("admin alert email message", ["username" => $this->username, "datetime" => date("Y-m-d H:i:s"), "ipaddr" => IPUtils::getClientIP(), "appname" => $appname], false);
255 255
 
256 256
         if (!$mail->send()) {
257 257
             return $mail->ErrorInfo;

+ 1
- 1
mobile/index.php View File

@@ -23,7 +23,7 @@ if (MOBILE_ENABLED !== TRUE) {
23 23
 }
24 24
 
25 25
 // Make sure we have a username and access key
26
-if (is_empty($VARS['username']) || is_empty($VARS['key'])) {
26
+if (empty($VARS['username']) || empty($VARS['key'])) {
27 27
     http_response_code(401);
28 28
     die(json_encode(["status" => "ERROR", "msg" => "Missing username and/or access key."]));
29 29
 }

+ 2
- 202
required.php View File

@@ -133,42 +133,6 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST') {
133 133
     define("GET", true);
134 134
 }
135 135
 
136
-/**
137
- * Checks if a string or whatever is empty.
138
- * @param $str The thingy to check
139
- * @return boolean True if it's empty or whatever.
140
- */
141
-function is_empty($str) {
142
-    return (is_null($str) || !isset($str) || $str == '');
143
-}
144
-
145
-/**
146
- * Checks if an email address is valid.
147
- * @param string $email Email to check
148
- * @return boolean True if email passes validation, else false.
149
- */
150
-function isValidEmail($email) {
151
-    return filter_var($email, FILTER_VALIDATE_EMAIL);
152
-}
153
-
154
-/**
155
- * Hashes the given plaintext password
156
- * @param String $password
157
- * @return String the hash, using bcrypt
158
- */
159
-function encryptPassword($password) {
160
-    return password_hash($password, PASSWORD_BCRYPT);
161
-}
162
-
163
-/**
164
- * Securely verify a password and its hash
165
- * @param String $password
166
- * @param String $hash the hash to compare to
167
- * @return boolean True if password OK, else false
168
- */
169
-function comparePassword($password, $hash) {
170
-    return password_verify($password, $hash);
171
-}
172 136
 
173 137
 function dieifnotloggedin() {
174 138
     if ($_SESSION['loggedin'] != true) {
@@ -193,44 +157,6 @@ function checkDBError($specials = []) {
193 157
     }
194 158
 }
195 159
 
196
-/*
197
- * http://stackoverflow.com/a/20075147
198
- */
199
-if (!function_exists('base_url')) {
200
-
201
-    function base_url($atRoot = FALSE, $atCore = FALSE, $parse = FALSE) {
202
-        if (isset($_SERVER['HTTP_HOST'])) {
203
-            $http = isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) !== 'off' ? 'https' : 'http';
204
-            $hostname = $_SERVER['HTTP_HOST'];
205
-            $dir = str_replace(basename($_SERVER['SCRIPT_NAME']), '', $_SERVER['SCRIPT_NAME']);
206
-
207
-            $core = preg_split('@/@', str_replace($_SERVER['DOCUMENT_ROOT'], '', realpath(dirname(__FILE__))), NULL, PREG_SPLIT_NO_EMPTY);
208
-            $core = $core[0];
209
-
210
-            $tmplt = $atRoot ? ($atCore ? "%s://%s/%s/" : "%s://%s/") : ($atCore ? "%s://%s/%s/" : "%s://%s%s");
211
-            $end = $atRoot ? ($atCore ? $core : $hostname) : ($atCore ? $core : $dir);
212
-            $base_url = sprintf($tmplt, $http, $hostname, $end);
213
-        } else
214
-            $base_url = 'http://localhost/';
215
-
216
-        if ($parse) {
217
-            $base_url = parse_url($base_url);
218
-            if (isset($base_url['path']))
219
-                if ($base_url['path'] == '/')
220
-                    $base_url['path'] = '';
221
-        }
222
-
223
-        return $base_url;
224
-    }
225
-
226
-}
227
-
228
-function redirectToPageId($id, $args, $dontdie) {
229
-    header('Location: ' . URL . '?id=' . $id . $args);
230
-    if (is_null($dontdie)) {
231
-        die("Please go to " . URL . '?id=' . $id . $args);
232
-    }
233
-}
234 160
 
235 161
 function redirectIfNotLoggedIn() {
236 162
     if ($_SESSION['loggedin'] !== TRUE) {
@@ -239,132 +165,6 @@ function redirectIfNotLoggedIn() {
239 165
     }
240 166
 }
241 167
 
242
-/**
243
- * Check if a given ipv4 address is in a given cidr
244
- * @param  string $ip    IP to check in IPV4 format eg. 127.0.0.1
245
- * @param  string $range IP/CIDR netmask eg. 127.0.0.0/24, also 127.0.0.1 is accepted and /32 assumed
246
- * @return boolean true if the ip is in this range / false if not.
247
- * @author Thorsten Ott <https://gist.github.com/tott/7684443>
248
- */
249
-function ip4_in_cidr($ip, $cidr) {
250
-    if (strpos($cidr, '/') == false) {
251
-        $cidr .= '/32';
252
-    }
253
-    // $range is in IP/CIDR format eg 127.0.0.1/24
254
-    list( $cidr, $netmask ) = explode('/', $cidr, 2);
255
-    $range_decimal = ip2long($cidr);
256
-    $ip_decimal = ip2long($ip);
257
-    $wildcard_decimal = pow(2, ( 32 - $netmask)) - 1;
258
-    $netmask_decimal = ~ $wildcard_decimal;
259
-    return ( ( $ip_decimal & $netmask_decimal ) == ( $range_decimal & $netmask_decimal ) );
260
-}
261
-
262
-/**
263
- * Check if a given ipv6 address is in a given cidr
264
- * @param string $ip IP to check in IPV6 format
265
- * @param string $cidr CIDR netmask
266
- * @return boolean true if the IP is in this range, false otherwise.
267
- * @author MW. <https://stackoverflow.com/a/7952169>
268
- */
269
-function ip6_in_cidr($ip, $cidr) {
270
-    $address = inet_pton($ip);
271
-    $subnetAddress = inet_pton(explode("/", $cidr)[0]);
272
-    $subnetMask = explode("/", $cidr)[1];
273
-
274
-    $addr = str_repeat("f", $subnetMask / 4);
275
-    switch ($subnetMask % 4) {
276
-        case 0:
277
-            break;
278
-        case 1:
279
-            $addr .= "8";
280
-            break;
281
-        case 2:
282
-            $addr .= "c";
283
-            break;
284
-        case 3:
285
-            $addr .= "e";
286
-            break;
287
-    }
288
-    $addr = str_pad($addr, 32, '0');
289
-    $addr = pack("H*", $addr);
290
-
291
-    $binMask = $addr;
292
-    return ($address & $binMask) == $subnetAddress;
293
-}
294
-
295
-/**
296
- * Check if the REMOTE_ADDR is on Cloudflare's network.
297
- * @return boolean true if it is, otherwise false
298
- */
299
-function validateCloudflare() {
300
-    if (filter_var($_SERVER["REMOTE_ADDR"], FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) {
301
-        // Using IPv6
302
-        $cloudflare_ips_v6 = [
303
-            "2400:cb00::/32",
304
-            "2405:8100::/32",
305
-            "2405:b500::/32",
306
-            "2606:4700::/32",
307
-            "2803:f800::/32",
308
-            "2c0f:f248::/32",
309
-            "2a06:98c0::/29"
310
-        ];
311
-        $valid = false;
312
-        foreach ($cloudflare_ips_v6 as $cidr) {
313
-            if (ip6_in_cidr($_SERVER["REMOTE_ADDR"], $cidr)) {
314
-                $valid = true;
315
-                break;
316
-            }
317
-        }
318
-    } else {
319
-        // Using IPv4
320
-        $cloudflare_ips_v4 = [
321
-            "103.21.244.0/22",
322
-            "103.22.200.0/22",
323
-            "103.31.4.0/22",
324
-            "104.16.0.0/12",
325
-            "108.162.192.0/18",
326
-            "131.0.72.0/22",
327
-            "141.101.64.0/18",
328
-            "162.158.0.0/15",
329
-            "172.64.0.0/13",
330
-            "173.245.48.0/20",
331
-            "188.114.96.0/20",
332
-            "190.93.240.0/20",
333
-            "197.234.240.0/22",
334
-            "198.41.128.0/17"
335
-        ];
336
-        $valid = false;
337
-        foreach ($cloudflare_ips_v4 as $cidr) {
338
-            if (ip4_in_cidr($_SERVER["REMOTE_ADDR"], $cidr)) {
339
-                $valid = true;
340
-                break;
341
-            }
342
-        }
343
-    }
344
-    return $valid;
345
-}
346
-
347
-/**
348
- * Makes a good guess at the client's real IP address.
349
- *
350
- * @return string Client IP or `0.0.0.0` if we can't find anything
351
- */
352
-function getClientIP() {
353
-    // If CloudFlare is in the mix, we should use it.
354
-    // Check if the request is actually from CloudFlare before trusting it.
355
-    if (isset($_SERVER["HTTP_CF_CONNECTING_IP"])) {
356
-        if (validateCloudflare()) {
357
-            return $_SERVER["HTTP_CF_CONNECTING_IP"];
358
-        }
359
-    }
360
-
361
-    if (isset($_SERVER["REMOTE_ADDR"])) {
362
-        return $_SERVER["REMOTE_ADDR"];
363
-    }
364
-
365
-    return "0.0.0.0"; // This will not happen unless we aren't a web server
366
-}
367
-
368 168
 /**
369 169
  * Check if the client's IP has been doing too many brute-force-friendly
370 170
  * requests lately.
@@ -378,12 +178,12 @@ function engageRateLimit() {
378 178
     global $database;
379 179
     $delay = date("Y-m-d H:i:s", strtotime("-2 seconds"));
380 180
     $database->delete('rate_limit', ["lastaction[<]" => $delay]);
381
-    if ($database->has('rate_limit', ["AND" => ["ipaddr" => getClientIP()]])) {
181
+    if ($database->has('rate_limit', ["AND" => ["ipaddr" => IPUtils::getClientIP()]])) {
382 182
         http_response_code(429);
383 183
         // JSONify it so API clients don't scream too loud
384 184
         die(json_encode(["status" => "ERROR", "msg" => "You're going too fast.  Slow down, mkay?"]));
385 185
     } else {
386 186
         // Add a record for the IP address
387
-        $database->insert('rate_limit', ["ipaddr" => getClientIP(), "lastaction" => date("Y-m-d H:i:s")]);
187
+        $database->insert('rate_limit', ["ipaddr" => IPUtils::getClientIP(), "lastaction" => date("Y-m-d H:i:s")]);
388 188
     }
389 189
 }

+ 1
- 1
setup.php View File

@@ -14,7 +14,7 @@ if ($database->has('accounts', ["[>]assigned_permissions" => ["uid" => "uid"]],
14 14
     die("An admin account already exists, exiting.");
15 15
 }
16 16
 
17
-if (is_empty($_POST['username']) || is_empty($_POST['password']) || is_empty($_POST['realname'])) {
17
+if (empty($_POST['username']) || empty($_POST['password']) || empty($_POST['realname'])) {
18 18
     ?>
19 19
     <!DOCTYPE html>
20 20
     <title>Admin Account Creation</title>

Loading…
Cancel
Save