-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdb.php
More file actions
491 lines (432 loc) · 15.6 KB
/
db.php
File metadata and controls
491 lines (432 loc) · 15.6 KB
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
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
<?php
namespace SmartHistoryTourManager;
require_once(dirname(__FILE__) . '/logging.php');
/**
* This provides sanitizing of sql queris as well as their execution.
* (The class should care about the form but not about the content of queries.)
*/
class DB {
private static $prefix = 'shtm_';
private static $transaction_running = false;
const BAD_ID = -1;
/**
* Returns the first id for the table in question.
* NOTE: Since this is used only for internal functionality, the table name
* is NOT sanitized.
*
* @return int The id in question or DB::BAD_ID if the table is empty.
*/
public static function first_id($table) {
$sql = "SELECT id FROM $table ORDER BY id ASC LIMIT 0,1";
global $wpdb;
$result = $wpdb->get_results($sql);
if(empty($result) || !isset($result[0]->id)) {
return self::BAD_ID;
} else {
return intval($result[0]->id);
}
}
/**
* Returns the last id for the table in question.
* NOTE: Since this is used only for internal functionality, the table name
* is NOT sanitized.
*
* @return int The id in question or DB::BAD_ID if the table is empty.
*/
public static function last_id($table) {
$sql = "SELECT id FROM $table ORDER BY id DESC LIMIT 0,1";
global $wpdb;
$result = $wpdb->get_results($sql);
if(empty($result) || !isset($result[0]->id)) {
return self::BAD_ID;
} else {
return intval($result[0]->id);
}
}
/**
* Checks if an id is present in the provided table.
* NOTE: Since this is used only for internal functionality, the table name
* is NOT sanitized.
*
* @return bool true if result was found else false.
*/
public static function valid_id($table, $id) {
$id = intval($id);
if($id <= 0) {
return false;
}
$sql = "SELECT 1 FROM $table";
$result = self::get($sql, array('id' => $id));
if(empty($result)) {
return false;
} else {
return true;
}
}
/**
* Count rows in the table where the conditions match.
* NOTE: Since this is used only for internal functionality, the table name
* is NOT sanitized (but the where conditions are).
*
* @return bool|int The count's result on success or false
*/
public static function count($table_name, $where = null) {
$sql = "SELECT COUNT(*) AS count FROM $table_name";
if(!empty($where)) {
$sql .= ' ' . self::where_clause($where);
}
$query = self::prepare($sql, array($table_name));
global $wpdb;
$result = $wpdb->get_results($query);
if(!empty($result) && isset($result[0]) && isset($result[0]->count)) {
return intval($result[0]->count);
} else {
return false;
}
}
// Method to retrieve multiple objects, expects a sanitized query as input.
private static function _list($query) {
global $wpdb;
$result = $wpdb->get_results($query);
if(empty($result)) {
debug_log("DB: Could not retrieve list with: $query");
}
return $result;
}
/**
* Returns a list of results from the database using in the conditions of
* the where clause and setting offset and limit.
*
* @param string $select_sql A string starting the sql query with
* @param array $where An array of conditions, e.g. (user_id => 3)
* @param int $offset Offset in the table, default: 0
* @param int $limit Limit of objects retrieved, default:
* PHP_INT_MAX
* @param string $orederby A string to append to an "ORDER BY" clause
* (Note: internal use only, not escaped)
*
* @return array The result of the query as an associative array
*/
public static function list($select_sql, $where, $offset = 0,
$limit = PHP_INT_MAX, $orderby = null)
{
$sql = $select_sql . " ";
$sql .= self::where_clause($where);
if(!is_null($orderby) && is_string($orderby)) {
$sql .= " ORDER BY $orderby";
}
$sql .= " LIMIT %d, %d";
$query = self::prepare($sql, array($offset, $limit));
return self::_list($query);
}
/**
* Returns a list of results from the database using in the conditions of
* the where clause and setting offset and limit.
*
* @param string $query The query with sprintf-like placeholders.
* @param array $args The values to replace and escape in the query.
*
* @return array The result of the query as an associative array.
*/
public static function list_by_query($query, $args = array()) {
return self::_list(self::prepare($query, $args));
}
// Method to retrieve a single object, expects a sanitized query as input.
private static function _get($query) {
global $wpdb;
$result = $wpdb->get_results($query);
if(empty($result)) {
debug_log("DB: Could not retrieve row with: $query");
$wpdb->print_error();
return null;
} else if(count($result) != 1) {
$count = count($result);
debug_log("DB: Bad result count: $count for: $query).");
$wpdb->print_error();
return null;
}
return $result[0];
}
/**
* Retrieves a single object from the database. Builds a where clause
* from the specified conditions and appends it to the selection sql to
* achieve that.
*
* @return array|null The table row as an associative array or null on
* failure.
*
* @throws DB_Exception If a value in the where conditions is of an unknown
* tpye (not int, float, string or array)
*/
public static function get($select_sql, $where = array()) {
$sql = $select_sql . " ";
$sql .= self::where_clause($where);
$query = self::prepare($sql);
return self::_get($query);
}
/**
* Retrieves a single object from the database. Replaces placeholders in
* the query with the supplied arguments.
*
* @return array|null The table row as an associative array or null on
* failure.
*/
public static function get_by_query($query, $args = array()) {
return self::_get(self::prepare($query, $args));
}
/**
* Update a single table row at the specified id, using values.
*
* @param string $table_name The table to update.
* @param int $id Row's id to update.
* @param array $values The values to update, e.g. ['name' => 'str']
*
* @return bool Whether the update was successful or not.
*/
public static function update($table_name, $id, $values) {
global $wpdb;
$result = $wpdb->update($table_name, $values, array('id' => $id));
if($result == 0) {
$msg = "DB: Updating ${table_name} for id: '${id}' had no effect.";
debug_log($msg);
} else if($result != 1) {
$msg = "DB: Error updating ${table_name} for id: '${id}'";
$msg .= " (affected rows: $result)";
debug_log($msg);
$wpdb->print_error();
return false;
}
return true;
}
/**
* @param $table_name
* @param $values
* @param $where
* @return bool
*/
public static function update_where($table_name, $values, $where) {
global $wpdb;
$result = $wpdb->update($table_name, $values, $where);
if($result == 0) {
$msg = "DB: Updating ${table_name} for where: '" . var_dump($where, 1) . "' had no effect.";
debug_log($msg);
} else if($result != 1) {
$msg = "DB: Error updating ${table_name} for where: '" . var_dump($where, 1) . "'";
$msg .= " (affected rows: $result)";
debug_log($msg);
$wpdb->print_error();
return false;
}
return true;
}
/**
* @param $table_name
* @param $values
* @return bool
*/
public static function replace($table_name, $values) {
global $wpdb;
$result = $wpdb->replace($table_name, $values);
if($result === false) {
$msg = "DB: Error for replace on ${table_name} with values " . print_r($values, 1);
debug_log($msg);
$wpdb->print_error();
return false;
}
return true;
}
/**
* Replaces all placeholders in sql by the supplied values, then runs the
* query.
*
* (This is a small wrapper around wpdb->query(), adds preparation step.)
*
* @return int|false Number of rows affected or false on error
*/
public static function query($sql, $values) {
global $wpdb;
$query = self::prepare($sql, $values);
return $wpdb->query($query);
}
/**
* @return int The id of the new obj or DB::BAD_ID on failure.
*/
public static function insert($table_name, $values) {
global $wpdb;
$result = $wpdb->insert($table_name, $values);
if($result === false) {
debug_log("DB: Error inserting into '$table_name'.");
$wpdb->print_error();
return self::BAD_ID;
}
return $wpdb->insert_id;
}
/**
* @return int|false The number of rows updated (1), or false on error.
*/
public static function delete_single($table_name, $id) {
$result = self::delete($table_name, array('id' => $id));
if ($result !== 1) {
debug_log(
"DB: Wrong row count on delete: $result ($table_name, $id).");
return false;
}
return $result;
}
/**
* @param array $where An array of where conditions, e.g.: area_id => 2
*
* @return int|false The number of rows deleted, or false on error.
*/
public static function delete($table_name, $where) {
global $wpdb;
$result = $wpdb->delete($table_name, $where);
if($result === false) {
$msg = "DB: Error deleting from $table_name with: ";
$msg .= var_export($where, true);
debug_log($msg);
$wpdb->print_error();
return false;
}
return $result;
}
/**
* A custom function to retrieve the id of a mediaitem by it's url (the
* guid database field.)
*
* Needed because wordpress has no support for something like this. (NOTE:
* There is wp's attachment_url_to_postid() but it does not what we want.)
*/
function get_wp_media_id($media_url) {
global $wpdb;
$sql = "SELECT ID FROM $wpdb->posts WHERE guid='%s'";
$result = $wpdb->get_col($wpdb->prepare($sql, $media_url ));
return $result[0];
}
/**
* A wrapper around wpdb->prepare(). Here just used to insert variables into
* sql in a sane manner.
*
* @param string $sql
* @param array $args
*/
public static function prepare($sql, $args = array()) {
global $wpdb;
return $wpdb->prepare($sql, $args);
}
/**
* Start a transaction that can later be committed or rolled back.
*
* @throws TransactionException If a transaction is already running.
* @return null
*/
public static function start_transaction() {
if(self::$transaction_running) {
throw new TransactionException("Transaction already running.");
}
global $wpdb;
$result = $wpdb->query("START TRANSACTION");
self::$transaction_running = true;
}
/**
* Commit the current transaction.
*
* @throws TransactionException If no transaction is running.
* @return null
*/
public static function commit_transaction() {
if(!self::$transaction_running) {
throw new TransactionException("No transaction to commit.");
}
global $wpdb;
$result = $wpdb->query("COMMIT");
self::$transaction_running = false;
}
/**
* Roll back the current transaction.
*
* @throws TransactionException If no transaction is running.
* @return null
*/
public static function rollback_transaction() {
if(!self::$transaction_running) {
throw new TransactionException("No transaction to rollback.");
}
global $wpdb;
$wpdb->query("ROLLBACK");
// TODO: Check if there is a way to check wpdbs status on a transaction
self::$transaction_running = false;
}
/**
* Return the table name with all necessary prefixes prepended.
*
* @param string $type The table name to prefix, e.g. 'places'
*
* @return string The table name with prefixes.
*/
public static function table_name($type) {
global $wpdb;
return $wpdb->prefix . self::$prefix . $type;
}
/**
* Builds a where clause for an sql query using the conditions array.
*
* @param $where_conditions An array of conditions, eg.
* ['id' => 3, 'name' => 'test']
* values must be of type int, float, string or
* a sub array of those.
*
* @return string A full where clause with the secified conditions joined
* by AND, e.g. "id = 3 AND name = 'test'"
*
* @throws DB_Exception If a value in the conditions is of an unknown
* type (neither int, float, str, array).
*/
public static function where_clause($where_conditions) {
// return empty string if there are no condition to build
if(empty($where_conditions)) {
return "";
}
// equality strings with placeholders for values , e.g. 'id = %d'
$equals = array();
// arguments that will be mapped to the placeholders
$args = array();
foreach($where_conditions as $key => $value) {
if(is_array($value)) {
// treat each value in the array as a single condition
foreach($value as $value_elem) {
$equals[] = self::equals_str($key, $value_elem);
$args[] = $value_elem;
}
} else {
// build an equality string from the key value pair
$equals[] = self::equals_str($key, $value);
$args[] = $value;
}
}
// glue the equals strings together
$clause = 'WHERE ' . implode(' AND ', $equals);
// return the string with placeholders replaced and values sanitized
return self::prepare($clause, $args);
}
// builds an equality condition used in an sql WHERE clause, e.g. 'id = %d'
// placeholders for int, float and string values are supported
// throws a DB_Exception if the type of $values is otherwise
private static function equals_str($key, $value) {
$placeholder = null;
if(is_int($value)) {
$placeholder = "%d";
} else if(is_string($value)) {
$placeholder = "%s";
} else if(is_float($value)) {
$placeholder ="%f";
} else {
throw new DB_Exception("DB: Bad value in WHERE of unknown type: $value");
}
return "$key = $placeholder";
}
}
class DB_Exception extends \Exception {}
// does not extend DB_Exception to not be easily caught
class TransactionException extends \Exception {}
?>