-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathdatabase.php
239 lines (217 loc) · 7.79 KB
/
database.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
<?php
// database.php
if (PHP_SESSION_ACTIVE != session_status()) session_start();
//session_start();
function GetDbFileName()
{
return "vesta.db";
}
function DatabaseInit()
{
if ((file_exists(GetDbFileName())) || (readlink(GetDbFileName()))) {
try {
$db = new PDO("sqlite:".GetDbFileName());
} catch (PDOException $e) {
die("Can't open ".GetDbFileName()." (".$e->getMessage().")");
}
return $db;
} else echo GetDbFileName()," doesn't exist!<br>";
die("Can't find database at ".GetDbFileName());
}
function GetDbFileSize()
{
return filesize(GetDbFileName());
}
function GetCount($db, $table, $qualifier = "")
{
if ($qualifier == "") {
$result = $db->query("SELECT COUNT(*) FROM ".$table);
} else {
$result = $db->query("SELECT COUNT(*) FROM ".$table." WHERE ".$qualifier); # $qualifier may be "devKey= 21" or "timestamp<('now','-2 days')", etc.
}
if ($result != null) {
return $result->fetchColumn();
}
return null;
}
function GetDevCount($db)
{
return GetCount($db, "Devices");
}
function GetDevKey($index, $db)
{
$item = "devKey";
$result = $db->query("SELECT ".$item." from Devices LIMIT 1 OFFSET ".$index);
if ($result != null) {
$result->setFetchMode(PDO::FETCH_ASSOC);
$fetch = $result->fetch();
if ($fetch != null) {
return $fetch[$item];
}
}
return null;
}
function GetDevKeyFromItem($item, $value, $db)
{
$result = $db->query("SELECT devKey FROM Devices WHERE ".$item."=\"".$value."\" COLLATE NOCASE");
if ($result != null) {
$result->setFetchMode(PDO::FETCH_ASSOC);
$fetch = $result->fetch();
if ($fetch != null) {
return $fetch["devKey"];
}
}
return null;
}
function GetDevItem($item, $devKey, $db)
{
$result = $db->query("SELECT ".$item." FROM Devices WHERE devKey=".$devKey);
if ($result != null) {
$result->setFetchMode(PDO::FETCH_ASSOC);
$fetch = $result->fetch();
if ($fetch != null) {
return $fetch[$item];
}
}
return null;
}
function GetTimedLoggedItem($item, $devKey, $time, $db) # For Battery, Signal, Presence, Temperature, PowerReadingW, etc.
{
$result = $db->query("SELECT * FROM ".$item." WHERE devKey=".$devKey." AND timestamp > ".$time." LIMIT 1"); # Get first item after time
if ($result != null) {
$result->setFetchMode(PDO::FETCH_ASSOC);
$fetch = $result->fetch();
return $fetch; # Return value and time
}
return null;
}
function GetLatestLoggedItem($item, $devKey, $db)
{
$result = $db->query("SELECT * FROM ".$item." WHERE devKey=".$devKey." ORDER BY ROWID DESC LIMIT 1"); # Get last item
if ($result != null) {
$result->setFetchMode(PDO::FETCH_ASSOC);
$fetch = $result->fetch();
return $fetch; # Return value and time
}
return null;
}
function UpdateRules($oldUserName, $newUserName, $db)
{
$updates = []; # Get ready to make a list of all the updates
$numRules = 0;
$query = "SELECT rowid, * FROM Rules WHERE rule LIKE '%".$oldUserName."%' "; # Get all rules that mention our old device name
echo "Checking rules using ", $query, "<br>";
$sth = $db->prepare($query);
$sth->execute();
while ($row = $sth->fetch()) {
$ruleTxt = $row['rule'];
$ruleId = $row['rowid'];
echo "Here's a rule that mentions ",$oldUserName, " - ", $ruleTxt, "<br>";
$newRule = str_replace($oldUserName, $newUserName, $ruleTxt); // Replace old with new name
echo "Updated rule that mentions ",$oldUserName, " - ", $newRule, "<br>";
$updates[$numRules++] = "UPDATE Rules SET rule=\"".$newRule."\" WHERE rowid=".$ruleId; # Build query to update existing rule
}
for ($index = 0; $index < $numRules; $index++) {
$count = $db->exec($updates[$index]); # Run all the updates
}
}
function CreateUser($name, $email, $passwordHash, $db)
{
$query = 'SELECT * FROM Users WHERE name = "'.$name.'" OR email = "'.$email.'"'; // Check that name or email doesn't already exist
$sth = $db->prepare($query);
$sth->execute();
$row = $sth->fetch();
if ($row == null) {
$insert = 'INSERT INTO Users (name, passwordHash, email) VALUES("'.$name.'", "'.$passwordHash.'", "'.$email.'")';
$db->exec($insert); # Add the new user
return "New user ".$name." now added"; // Success
} return "Sorry, that username / email is already taken. Please choose another one.";
}
function GetNumUsers($db)
{
$result = $db->query("SELECT COUNT(*) FROM Users");
return $result->fetchColumn();
}
function NewEvent($devKey, $event, $db) # $devKey is the deviceId. Use 0 for hub
{
$insert = 'INSERT INTO Events (timestamp, event, devKey) VALUES("'.date('Y-m-d H:i:s').'", "'.$event.'", '.$devKey.')'; # Insert event with local timestamp
$db->exec($insert); # Add the new event
}
function CheckPasswordCorrectnessAndLogin($name, $password, $db)
{
$query = 'SELECT name, email, passwordHash FROM Users WHERE name = "'.$name.'" OR email = "'.$name.'" LIMIT 1'; // Allow the user to log in with username or email address
$sth = $db->prepare($query);
$sth->execute();
$row = $sth->fetch();
if ($row) {
$passwordHash = password_hash($password, PASSWORD_DEFAULT);
if (password_verify($password, $row['passwordHash'])) { // Using PHP 5.5's password_verify() function to check password
$_SESSION['user_name'] = $row['name'];
echo "Session Name = ".$_SESSION['user_name']."<br>";
$_SESSION['user_email'] = $row['email'];
$_SESSION['user_is_logged_in'] = true;
return ""; // Success if empty string
} return "Wrong password.";
} return "This user does not exist.";
}
function GetAppState($item, $db)
{
$result = $db->query("SELECT Value FROM AppState WHERE Name=\"".$item."\"");
if ($result != null) {
$result->setFetchMode(PDO::FETCH_ASSOC);
$fetch = $result->fetch();
if ($fetch != null) {
return $fetch["Value"];
}
}
return null;
}
function SetAppState($item, $val, $db)
{
$db->exec("REPLACE INTO AppState VALUES(\"".$item."\", \"".$val."\")"); # Run the update
}
function GetConfig($item, $default, $db)
{
$result = $db->query("SELECT value FROM Config WHERE item=\"".$item."\"");
if ($result != null) {
$result->setFetchMode(PDO::FETCH_ASSOC);
$fetch = $result->fetch();
if ($fetch != null) {
return $fetch["value"];
}
}
//if (!$default) $default = ""; # Ensure we have something as a default so we can set the value
$db->exec("INSERT OR REPLACE INTO Config VALUES(\"".$item."\",\"".$default."\")");
return $default;
}
function SetConfig($item, $value, $db)
{
if ($item != "NewItem") { // If item exists
if ($value != "") {
$query = "UPDATE Config SET value=\"".$value."\" WHERE item=\"".$item."\""; # Update existing value
} else {
$query = "DELETE FROM Config WHERE item=\"".$item."\""; # Remove item if value is empty
}
} else { // New Item requested
$query = "INSERT INTO Config (item) VALUES(\"".$value."\")"; # Add new configuration item (named $value), with empty value
}
echo "About to send ",$query, " to DB<br>";
$db->exec($query);
}
function GetVariable($name, $default, $db)
{
$sth = $db->prepare("SELECT value FROM Variables where name=\"".$name."\"");
$sth->execute();
$row = $sth->fetch();
if ($row != null) {
return $row['value'];
}
SetVariable($name, $default, $db);
return $default;
}
function SetVariable($name, $val, $db)
{
$now = date('Y-m-d H:i:s');
$db->exec("INSERT OR REPLACE INTO Variables VALUES(\"".$name."\",\"".$val."\",\"".$now."\")");
}
?>