-
Notifications
You must be signed in to change notification settings - Fork 1
/
stanford.log.database.php
387 lines (276 loc) · 9.8 KB
/
stanford.log.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
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
<?php
/**
* @author ddonahue
*
* Copyright 2008,2009 Board of Trustees, Leland Stanford Jr. University
* See LICENSE for licensing terms.
*
*/
// Include StanfordLog
require_once(dirname(__FILE__) . "/stanford.log.php");
// Include StanfordDatabase
require_once(dirname(__FILE__) . "/stanford.database.php");
class StanfordLogDatabase extends StanfordLog {
const VERSION = '1.0.0'; // Class version
private $db; // MySQLi object
private $table; // Name of database table
// Field names
private $fields = array("id", "log_time", "remote_addr", "script", "query_string", "message");
/**
* Creates a new StanfordLogDatabase
*
* @param MySQLi db A valid MySQLi/StanfordDatabase object
* @param string table The name of the database table
* @param boolean create Create the table if it does not exist
*/
function __construct($db, $table, $create=false) {
// Set the database connection handler
if($db) {
$this->set_database_connection($db);
// Set the database table
if($table) {
$this->set_table($table, $create);
}
}
}
/**
* Gets the version number of the class
*
* @return string The version number
*/
function get_version() {
return self::VERSION;
}
/**
* Sets the database connection and connects if necessary
*
* @param MySQLi db A valid, preconfigured MySQLi/StanfordDatabase object
*/
function set_database_connection($db) {
// Check DB
if($db instanceof MySQLi == false) {
throw new Exception("Must set the database connection to a valid MySQLi or StanfordDatabase object");
}
// Connect to DB
if($db instanceof StanfordDatabase) {
$db->connect(); // Will throw an exception on failure
}
// Valid database connection
$this->db = $db;
return true;
}
/**
* Sets the name of the table to use
*
* @param string table The name of the table
* @param boolean create_if_nonexistent Auto-create table if it does not exist? Defaults to false. Optional.
*
* @return boolean Status
*/
function set_table($table, $create_if_nonexistent = false) {
// Check table name
if($table == '') {
throw new Exception("Table name is null");
}
// Create table
if($create_if_nonexistent == true) {
// Check database connection
if($this->is_valid_db() == false) {
throw new Exception("Not connected to database; cannot check/create table.");
}
// Check if table exists
$sql = "DESCRIBE " . $this->db->escape_string($table);
$result = $this->db->query($sql);
// Table does not exist..
if($result == 0 || mysqli_num_rows($result) == 0) {
// Construct query to create new table
$sql = "CREATE TABLE " . $this->db->escape_string($table) . " (";
$sql .= "id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,";
$sql .= "log_time TIMESTAMP DEFAULT NOW() NOT NULL,";
$sql .= "remote_addr INT UNSIGNED NOT NULL,";
$sql .= "script VARCHAR(500) NOT NULL,";
$sql .= "query_string VARCHAR(1000) NOT NULL,";
$sql .= "message TEXT";
$sql .= ");";
// Execute query
$result = $this->db->query($sql);
// Check result
if($result == false) {
throw new Exception("Unable to create table " . $table . " -- " . $this->db->error);
}
}
else {
// Log table already exists -- not a serious error, but enough to notify the developer
$this->table = $this->db->escape_string($table);
throw new Exception("Notice: Log table already exists. You may now set the create_if_nonexistent parameter to false or simply omit it.");
}
}
// No errors occurred, set table name and return success
$this->table = $this->db->escape_string($table);
return true;
}
/**
* Appends a message to the log table
*
* @param string message The message to log
*
* @return boolean Status
*/
function append($message) {
// Check DB
if($this->is_valid_db() == false) {
throw new Exception("Cannot append to log -- not connected to database");
}
// Check table
if($this->table == '') {
throw new Exception("Cannot append to log -- table not set");
}
// Get IP address
$remote_addr = $this->db->escape_string($_SERVER['REMOTE_ADDR']);
// Get requested script
$script = $this->db->escape_string($_SERVER['PHP_SELF']);
// Get query string
$query_string = $this->db->escape_string(urldecode($_SERVER['QUERY_STRING']));
// Escape the message and table name
$message = $this->db->escape_string($message);
$table = $this->db->escape_string($this->table);
// Create query (all input has been escaped)
$sql = "INSERT INTO $table (remote_addr, script, query_string, message) ";
$sql .= "VALUES (INET_ATON('$remote_addr'), '$script', '$query_string', '$message')";
// Execute query
$result = $this->db->query($sql);
// Check result
if($result == false) {
throw new Exception("Unable to write to database -- " . $this->db->error);
}
// If e-mail settings have been defined
if($this->email_settings instanceof StanfordLogEmailSettings) {
// Send via e-mail if it is time to do so
$this->send_if_delay_is_up();
}
// Return success
return true;
}
/**
* Determines if it is time to send the log through e-mail
* If true, also sets the body of the e-mail to the most recent log messages
*
* @return boolean True or false
*/
function is_time_to_send() {
// Check e-mail settings before proceeding
if($this->email_settings instanceof StanfordLogEmailSettings == false) {
throw new Exception("E-mail settings not defined");
}
// Check database
if($this->is_valid_db() == false) {
throw new Exception("Not connected to database");
}
// Get marker
$marker = $this->db->escape_string(self::MARKER);
// Construct query to find the time that the last e-mail was sent
$sql = "SELECT * FROM $this->table WHERE message = \"$marker\" ORDER BY id DESC LIMIT 1";
// Get result
$result = $this->db->query($sql);
// Check result
if($result) {
// Get data
$data = mysqli_fetch_assoc($result);
// Get the timestamp
$time_sent = strtotime($data['log_time']);
// Check if it is time to send the message
if(time() - $time_sent >= $this->email_settings->get_delay()) {
// It is time to send the message if data is available
$time_to_send = true;
// Get the ID of the last sent message
$id = $data['id'];
}
}
else {
// There was no sent marker
// Send everything currently in the database table
$time_to_send = true;
}
// Time to send
if($time_to_send == true) {
// Get all log entries
$sql = "SELECT log_time, INET_NTOA(remote_addr) AS ip, script, query_string, message FROM $this->table";
// If ID is set, get all log entries after it (ID is of the last sent marker)
if($id > 0) {
$sql .= " WHERE id > " . $this->db->escape_string($id);
}
// Order by ID
$sql .= " ORDER BY id";
// Execute query
$result = $this->db->query($sql);
// Check result
if($result) {
// Initialize e-mail body
$email_body = '';
// Get the data and create the body of the e-mail
while($row = mysqli_fetch_assoc($result)) {
// Add log entry to message
$email_body .= $this->array_to_csv_string($row);
}
// Set the body of the message
$this->email_settings->set_body($email_body);
// Return true - time to send the e-mail
return true;
}
}
// Not yet time to send (there is no data to send or the delay is not up)
return false;
}
/**
* Checks if it is time to send the log through e-mail
*
* @return boolean True when the e-mail was sent, false if not
*/
function send_if_delay_is_up() {
if($this->is_time_to_send() == true) {
return $this->send_email();
}
else {
return false;
}
}
/**
* Truncates the log to zero length
*
* @return boolean The result, true or false
*/
function truncate() {
// Check database
if($this->is_valid_db() == false) {
throw new Exception("Not connected to database");
}
// Check table name
if($this->table == '') {
throw new Exception("Unable to truncate -- table name is null");
}
// Escape table name
$table = $this->db->escape_string($this->table);
// Construct truncate statement
$sql = "TRUNCATE TABLE $table";
// Execute statement
$result = $this->db->query($sql);
// Check result
if($result == true) {
return true;
}
else {
throw new Exception("Unable to truncate -- " . $this->db->error);
}
}
/**
* Checks if the database connection is valid
*
* @return boolean True or false
*/
function is_valid_db() {
$is_mysqli = ($this->db instanceof MySQLi == true && $this->db instanceof StanfordDatabase == false);
$is_stanforddb = ($this->db instanceof StanfordDatabase && $this->db->is_connected());
return ($is_mysqli || $is_stanforddb);
}
}
?>