Merged in f5soh/librepilot/update_credits (pull request #529)
[librepilot.git] / ground / usagetracker / backend / usagetracker.php
blob99389bc8f28c5e32f33a75e367b8397cb41d5876
1 <?php
3 if (!$_SERVER['REQUEST_METHOD'] === 'GET' || empty($_GET['hash'])) {
4 usage_error();
7 // NOTE: $hash not sanitized because of the checksum match test.
8 $hash = $_GET['hash'];
9 $string = str_replace('&hash=' . $hash, '', rawurldecode($_SERVER['QUERY_STRING']));
11 if ($hash != md5($string)) {
12 usage_error();
16 $dbhost = 'localhost';
17 $dbname = '';
18 $dbpasswd = '';
19 $dbuser = '';
21 $db = new mysqli($dbhost, $dbuser, $dbpasswd, $dbname);
22 unset($dbhost, $dbuser, $dbpasswd, $dbname);
24 if ($db->connect_error) {
25 die();
28 $sql = sprintf("SELECT id, last_date FROM usagetracker WHERE hash = '%s' LIMIT 1",
29 $db->real_escape_string($hash)
32 $res = $db->query($sql);
33 if ($res->num_rows > 0) {
34 // Shouldn't normally be here but happens if GCS settings are reset
35 // or if the request come from another source than GCS.
37 $hashUpdate = $res->fetch_assoc();
38 if ($hashUpdate['last_date'] < (time() - 3600)) {
39 // Update timestamp and connection count.
40 $sql = sprintf("UPDATE usagetracker SET last_date = %u, count = count + 1 WHERE id = %u LIMIT 1",
41 time(),
42 $hashUpdate['id']
44 $db->query($sql);
47 else {
48 // New hash
49 $sql = sprintf("INSERT INTO usagetracker (first_date, last_date, ip, data, hash)
50 VALUES (%u, %u, '%s', '%s', '%s')",
51 time(),
52 time(),
53 encode_ip($_SERVER['REMOTE_ADDR']),
54 $db->real_escape_string($string),
55 $db->real_escape_string($_GET['hash'])
58 $db->query($sql);
61 $db->close();
64 function usage_error()
66 //ob_start();
68 header($_SERVER["SERVER_PROTOCOL"]." 404 Not Found");
69 header("Status: 404 Not Found");
71 // Matching server 404 output can be added.
72 exit();
75 function encode_ip($dotquad_ip)
77 $ip_sep = explode('.', $dotquad_ip);
78 return sprintf('%02x%02x%02x%02x', $ip_sep[0], $ip_sep[1], $ip_sep[2], $ip_sep[3]);