JasonWoof Got questions, comments, patches, etc.? Contact Jason Woofenden
Fix db_get_value after mysql->mysqli upgrade
[wfpl.git] / db.php
1 <?php
2
3 # This program is in the public domain within the United States. Additionally,
4 # we waive copyright and related rights in the work worldwide through the CC0
5 # 1.0 Universal public domain dedication, which can be found at
6 # http://creativecommons.org/publicdomain/zero/1.0/
7
8
9 require_once(__DIR__.'/'.'encode.php');
10 require_once(__DIR__.'/'.'format.php');
11
12 # db_connect() -- connect to a mysql database (automatically, later, when/if needed)
13 # db_connect_now() -- connect to a mysql database immediately
14 #
15 # PARAMETERS:
16 #
17 #   database: the name of the database you want to connect to. Defaults to the
18 #   second-to-last part of the domain name. eg for foo.example.com it would be
19 #   "example".
20
21 #   user: username for connecting to the database. Defaults to
22 #   $GLOBALS['db_username'] or (if that's not set) "www".
23
24 #   password: password for connecting to the database. Defaults to
25 #   $GLOBALS['db_password'] or (if that's not set "".
26 #
27 # RETURNS:
28 #
29 #   the database connection handle. You'll only need this if you want to have
30 #   multiple databases open at once.
31 function db_connect() {
32         if (isset($GLOBALS['wfpl_db_handle'])) {
33                 mysqli_close($GLOBALS['wfpl_db_handle']);
34                 unset($GLOBALS['wfpl_db_handle']);
35         }
36         $GLOBALS['wfpl_db_connect_args'] = func_get_args();
37 }
38 function db_connect_now($database = 'auto', $user = 'auto', $pass = 'auto', $host = 'localhost', $encoding = 'utf8') {
39         if($database == 'auto') {
40                 if(isset($GLOBALS['db_name'])) {
41                         $database = $GLOBALS['db_name'];
42                 } else {
43                         $host = $_SERVER['SERVER_NAME'];
44                         $host = explode('.', $host);
45                         array_pop($host);
46                         $database = array_pop($host);
47                         unset($host);
48                 }
49         }
50
51         if($user == 'auto') {
52                 if(isset($GLOBALS['db_username'])) {
53                         $user = $GLOBALS['db_username'];
54                 } else {
55                         $user = 'www';
56                 }
57         }
58
59         if($pass == 'auto') {
60                 if(isset($GLOBALS['db_password'])) {
61                         $pass = $GLOBALS['db_password'];
62                 } else {
63                         $pass = '';
64                 }
65         }
66
67         $GLOBALS['wfpl_db_handle'] = @mysqli_connect($host, $user, $pass);
68         if(!$GLOBALS['wfpl_db_handle']) {
69                 die('Server error: Database connection failed');
70                 # to show username and host: mysqli_connect_error()
71         }
72
73         mysqli_set_charset($GLOBALS['wfpl_db_handle'], $encoding);
74
75         if(!mysqli_select_db($GLOBALS['wfpl_db_handle'], $database)) {
76                 die("Couldn not access database \"$database\": " . mysqli_error($GLOBALS['wfpl_db_handle']));
77         }
78
79         return $GLOBALS['wfpl_db_handle'];
80 }
81 # for internal use (helps implement the auto-connect feature of db_connect())
82 function _db_connection_needed() {
83         if (isset($GLOBALS['wfpl_db_handle'])) {
84                 return;
85         }
86         if (isset($GLOBALS['wfpl_db_connect_args'])) {
87                 return call_user_func_array('db_connect_now', $GLOBALS['wfpl_db_connect_args']);
88         }
89         die('Error: you must call db_connect() or db_auto_connect() first!');
90 }
91
92 function db_enc_sql($str) {
93         _db_connection_needed();
94         return mysqli_real_escape_string(isset($GLOBALS['wfpl_db_handle']) ? $GLOBALS['wfpl_db_handle'] : null, $str);
95 }
96
97 # Unless you're doing something unusual like an ALTER TABLE don't call this directly
98 function db_send_query($sql) {
99         _db_connection_needed();
100         #echo("Sending query: " . enc_html($sql) . "<br>\n");
101         $result = mysqli_query($GLOBALS['wfpl_db_handle'], $sql);
102         if(!$result) {
103                 die(enc_html('DATABASE ERROR: ' . mysqli_error($GLOBALS['wfpl_db_handle']) . ' in the following query: ' . $sql));
104         }
105
106         return $result;
107 }
108
109 # All select queries use this to generate the where clause, so they can work
110 # like printf. Currently three % codes are supported:
111 #
112 # %%  put a % in the output
113 # %i  put an integer in the output (strips non-numeric digits, and puts in 0 if blank)
114 # %I  a list of integers (as %i) separated by commas
115 # %f  put a floating point value in the output (strips non-numeric digits, puts in 0.0 if not valid)
116 # %"  output double quotes, surrounding the variable which is encoded to be in there.
117 # %s  output encoded to be in double quotes, but don't output the quotes
118 # %$  output argument as-is, no encoding. Make sure you quote everything from the user!
119 #
120 # complex example: db_get_rows('mytable', 'id', 'where name=%" or company like "%%%s%%"', $name, $company_partial);
121
122 function db_printf($str) {
123         $args = func_get_args();
124         $args = array_slice($args, 1);
125         return _db_printf($str, $args);
126 }
127
128 # This function does the work, but takes the parameters in an array
129 function _db_printf($str, $args) {
130         $out = '';
131         while($str) {
132                 $pos = strpos($str, '%');
133                 if($pos === false) { # not found
134                         # we hit the end.
135                         return $out . $str;
136                 }
137                 # move everything up to (but not including) % to the output
138                 $out .= substr($str, 0, $pos);
139
140                 # grab the character after the %
141                 $chr = substr($str, $pos + 1, 1);
142
143                 # remove the stuff we've read from input
144                 $str = substr($str, $pos + 2);
145
146                 if($chr == '"') {
147                         $out .= '"' . db_enc_sql(array_shift($args)) . '"';
148                 } elseif($chr == 's') {
149                         $out .= db_enc_sql(array_shift($args));
150                 } elseif($chr == 'i') {
151                         $out .= format_int_0(array_shift($args));
152                 } elseif($chr == 'I') {
153                         $arg = array_shift($args);
154                         $first = true;
155                         foreach ($arg as $int) {
156                                 if ($first) {
157                                         $first = false;
158                                 } else {
159                                         $out .= ',';
160                                 }
161                                 $out .= format_int_0($int);
162                         }
163                 } elseif($chr == 'f') {
164                         $arg = array_shift($args);
165                         if(is_numeric($arg)) {
166                                 $arg = sprintf("%f", $arg);
167                         }
168                         $arg = format_decimal($arg);
169                         if(strlen($arg) < 1) {
170                                 $arg = '0.0';
171                         }
172                         $out .= $arg;
173                 } elseif($chr == '$') {
174                         $out .= array_shift($args);
175                 } else {
176                         $out .= $chr;
177                 }
178         }
179
180         return $out;
181 }
182
183
184 # helper function
185 function db_send_get($table, $columns, $where, $args) {
186         $sql = "SELECT $columns FROM $table";
187         if($where) {
188                 $sql .= ' ' . _db_printf($where, $args);
189         }
190
191         return db_send_query($sql);
192 }
193
194
195 # if no results: returs []
196 function db_get_rows($table, $columns, $where = '') {
197         $args = func_get_args();
198         $args = array_slice($args, 3);
199         $result = db_send_get($table, $columns, $where, $args);
200
201         $rows = array();
202         while($row = mysqli_fetch_row($result)) {
203                 $rows[] = $row;
204         }
205
206         mysqli_free_result($result);
207
208         return $rows;
209 }
210
211 # like db_get_rows, but return array of hashes.
212 # if no results: returs []
213 function db_get_assocs($table, $columns, $where = '') {
214         $args = func_get_args();
215         $args = array_slice($args, 3);
216         $result = db_send_get($table, $columns, $where, $args);
217
218         $rows = array();
219         while($row = mysqli_fetch_assoc($result)) {
220                 $rows[] = $row;
221         }
222
223         mysqli_free_result($result);
224
225         return $rows;
226 }
227
228 # if no results: returs []
229 function db_get_column($table, $columns, $where = '') {
230         $args = func_get_args();
231         $args = array_slice($args, 3);
232         $result = db_send_get($table, $columns, $where, $args);
233
234         $column = array();
235         while($row = mysqli_fetch_row($result)) {
236                 $column[] = $row[0];
237         }
238
239         mysqli_free_result($result);
240
241         return $column;
242 }
243
244 # returns first matching row
245 # if no results: returns false
246 function db_get_row($table, $columns, $where = '') {
247         $args = func_get_args();
248         $args = array_slice($args, 3);
249         $result = db_send_get($table, $columns, $where, $args);
250
251         $row = mysqli_fetch_row($result);
252
253         mysqli_free_result($result);
254
255         return $row;
256 }
257
258 # like db_get_row, but return a hash.
259 # if no results: returns false
260 function db_get_assoc($table, $columns, $where = '') {
261         $args = func_get_args();
262         $args = array_slice($args, 3);
263         $result = db_send_get($table, $columns, $where, $args);
264
265         $row = mysqli_fetch_assoc($result);
266
267         mysqli_free_result($result);
268
269         return $row;
270 }
271
272 # if no results: returns false
273 function db_get_value($table, $column, $where = '') {
274         $args = func_get_args();
275         $args = array_slice($args, 3);
276         $result = db_send_get($table, $column, $where, $args);
277
278         $value = mysqli_fetch_row($result);
279         if($value !== NULL) {
280                 $value = $value[0];
281         }
282
283         mysqli_free_result($result);
284
285         return $value;
286 }
287
288 # returns an integer
289 function db_count($table, $where = '') {
290         $args = func_get_args();
291         array_splice($args, 1, 0, array('count(*)'));
292         return (int) call_user_func_array('db_get_value', $args);
293 }
294
295 # call either of these ways:
296 #
297 # db_insert('people', 'name,company', 'jason', 'widgets ltd');
298 # or
299 # db_insert('people', 'name,company', array('jason', 'widgets ltd'));
300 function db_insert($table, $columns, $values) {
301         if(!is_array($values)) {
302                 $values = func_get_args();
303                 $values = array_slice($values, 2);
304         }
305         
306         db_insert_ish('INSERT', $table, $columns, $values);
307 }
308
309 # like db_insert() above, but instead of passing columns and data separately,
310 # you can pass one array with the column names as keys and the data as values
311 function db_insert_assoc($table, $data) {
312         $args = func_get_args();
313         $args = array_slice($args, 2);
314         $columns = array();
315         $values = array();
316         foreach($data as $key => $value) {
317                 $columns[] = $key;
318                 $values[] = $value;
319         }
320         array_unshift($args, $table, join(',', $columns), $values);
321         call_user_func_array('db_insert', $args);
322 }
323
324 # same as above, except uses the "replace" command instead of "insert"
325 function db_replace($table, $columns, $values) {
326         if(!is_array($values)) {
327                 $values = func_get_args();
328                 $values = array_slice($values, 2);
329         }
330         
331         db_insert_ish('REPLACE', $table, $columns, $values);
332 }
333         
334 # return the value mysql made up for the auto_increment field (for the last insert)
335 function db_auto_id() {
336         _db_connection_needed();
337         return mysqli_insert_id($GLOBALS['wfpl_db_handle']);
338 }
339
340
341 # used to implement db_insert() and db_replace()
342 function db_insert_ish($command, $table, $columns, $values) {
343
344         $sql = '';
345         foreach($values as $value) {
346                 if($sql) $sql .= ',';
347                 $sql .= '"' . db_enc_sql($value) . '"';
348         }
349
350         $sql = "$command INTO $table ($columns) values($sql)";
351
352         db_send_query($sql);
353 }
354
355 # to be consistent with the syntax of the other db functions, $values can be an
356 # array, a single value, or multiple parameters.
357 #
358 # as usual the where clause stuff is optional, but it will of course update the
359 # whole table if you leave it off.
360 #
361 # examples:
362 #
363 # # name everybody Bruce
364 # db_update('users', 'name', 'Bruce');
365 #
366 # # name user #6 Bruce
367 # db_update('users', 'name', 'Bruce', 'where id=%i', 6);
368 #
369 # # update the whole bit for user #6
370 # db_update('users', 'name,email,description', 'Bruce', 'bruce@example.com', 'is a cool guy', 'where id=%i', 6);
371 #
372 # # update the whole bit for user #6 (passing data as an array)
373 # $data = array('Bruce', 'bruce@example.com', 'is a cool guy');
374 # db_update('users', 'name,email,description', $data, 'where id=%i', 6);
375
376 # The prototype is really something like this:
377 # db_update(table, columns, values..., where(optional), where_args...(optional))
378 function db_update($table, $columns, $values) {
379         $args = func_get_args();
380         $args = array_slice($args, 2);
381         $columns = explode(',', $columns);
382         $num_fields = count($columns);
383
384         if(is_array($values)) {
385                 $values = array_values($values);
386                 $args = array_slice($args, 1);
387         } else {
388                 $values = array_slice($args, 0, $num_fields);
389                 $args = array_slice($args, $num_fields);
390         }
391
392         $sql = '';
393         for($i = 0; $i < $num_fields; ++$i) {
394                 if($sql != '') {
395                         $sql .= ', ';
396                 }
397                 $sql .= $columns[$i] . ' = "' . db_enc_sql($values[$i]) . '"';
398         }
399
400
401         $sql = "UPDATE $table SET $sql";
402
403         # if there's any more arguments
404         if($args) {
405                 $where = $args[0];
406                 $args = array_slice($args, 1);
407
408                 $sql .= ' ';
409                 # any left for printf arguments?
410                 if($args) {
411                         $sql .= _db_printf($where, $args);
412                 } else {
413                         $sql .= $where;
414                 }
415
416         }
417
418         db_send_query($sql);
419 }
420
421 # like db_update() above, but instead of passing columns and data separately,
422 # you can pass one array with the column names as keys and the data as values
423 function db_update_assoc($table, $data) {
424         $args = func_get_args();
425         $args = array_slice($args, 2);
426         $columns = array();
427         $values = array();
428         foreach($data as $key => $value) {
429                 $columns[] = $key;
430                 $values[] = $value;
431         }
432         array_unshift($args, $values);
433         array_unshift($args, join(',', $columns));
434         array_unshift($args, $table);
435         call_user_func_array('db_update', $args);
436 }
437
438 # pass args for printf-style where clause as usual
439 function db_delete($table, $where = '') {
440         $sql = "DELETE FROM $table";
441         if($where) {
442                 $sql .= ' ';
443                 $args = func_get_args();
444                 $args = array_slice($args, 2);
445                 if($args) {
446                         $sql .= _db_printf($where, $args);
447                 } else {
448                         $sql .= $where;
449                 }
450         }
451
452         db_send_query($sql);
453 }
454
455
456 define('DB_ORD_MAX', 2000000000);
457
458 function db_reposition_respace($table, $field, $where = '') {
459         if($where) {
460                 $andand = " && ($where) ";
461         }
462         $ids = db_get_column($table, 'id', "where $field != 0 $andand order by $field");
463         $c = count($ids);
464         if(!$c) {
465                 # should never happen
466                 return;
467         }
468         $inc = floor(DB_ORD_MAX / ($c + 1));
469         $ord = $inc;
470         $count = count($ids);
471         for ($i = 0; $i < $count; $i += 1000) {
472                 $values = [];
473                 $j_max = min($count, $i + 1000);
474                 for ($j = $i; $j < $j_max; ++$j) {
475                         $id = $ids[$j];
476                         $values[] = "($id,$ord)";
477                         $ord += $inc;
478                 }
479                 $sql =
480                         "insert into $table (id,$field) values "
481                         . implode(',', $values)
482                         . " on duplicate key update $field=VALUES($field)"
483                 ;
484                 db_send_query($sql);
485         }
486 }
487
488 # this function facilitates letting the user manually sort records (with (int) $field != 0)
489 #
490 # When editing a particular row, give the user a pulldown, with 0 -> first, 1 -> second, etc, and pass this integer to db_reposition (3rd parameter). The value "ignored" can be passed, and the row will be given a sort value of 0 and ignored for all sorting.
491 #
492 # $pretty is used in error messages to refer to the row, it defaults to whatever you pass for $table.
493 #
494 # return value is the "ord" value you should set/insert into your database
495
496 function db_reposition($table, $row_id, $new_pos, $field = 'ord', $pretty = 'same as $table', $where = '', $renumbered_already = false) {
497         if($pretty == 'same as $table') {
498                 $pretty = $table;
499         }
500         if($where) {
501                 $andand = " && ($where) ";
502         }
503
504         if($new_pos === 'ignored') {
505                 # not sorted
506                 return '0';
507         }
508
509         # strategy: calculate $prev_ord and $next_ord. If there's no space between, renumber and recurse
510         if($new_pos == '0') {
511                 $row = db_get_row($table, "id,$field", "where $field != 0 $andand order by $field limit 1");
512                 if($row) {
513                         list($first_row_id, $first_row_ord) = $row;
514                         if($first_row_id == $row_id) {
515                                 # already first
516                                 return $first_row_ord;
517                         }
518                         $next_ord = $first_row_ord;
519                 } else {
520                         # this is the only row, put it in the middle
521                         return '' + floor(DB_ORD_MAX / 2);
522                 }
523
524                 $prev_ord = 0;
525         } else {
526                 $new_pos = format_int_0($new_pos);
527                 $rows = db_get_rows($table, "id,$field", "where $field != 0 $andand order by $field limit %i,2", $new_pos - 1);
528                 if(!$rows) {
529                         message("Sorry, couldn't find the $pretty you asked to put this $pretty after. Putting it first instead.");
530                         return db_reposition($table, $row_id, '0', $field, $pretty, $where);
531                 } else {
532                         list($prev_id, $prev_ord) = $rows[0];
533                         if($prev_id == $row_id) {
534                                 # after self? this shouldn't happen
535                                 return $prev_ord;
536                         }
537                         if(count($rows) == 1) {
538                                 # we should be last
539                                 $next_ord = DB_ORD_MAX;
540                         } else {
541                                 list($next_id, $next_ord) = $rows[1];
542                                 if($next_id == $row_id) {
543                                         # after prev (already there)
544                                         return $next_ord;
545                                 }
546                         }
547                 }
548         }
549         if($prev_ord + 1 == $next_ord || $prev_ord == $next_ord) { # the latter should never happen
550                 if($renumbered_already) {
551                         message("Programmer error in $pretty ordering code. Please tell your website administrator.");
552                         return '' . rand(2, DB_ORD_MAX - 2); # reasonably unlikely to be the same as some other ord
553                 }
554                 db_reposition_respace($table, $field, $where);
555                 return db_reposition($table, $row_id, $new_pos, $field, $pretty, $where, $renumbered_already = true);
556         } else {
557                 return $prev_ord + round(($next_ord - $prev_ord) / 2);
558         }
559 }
560
561 # Call this to upgrade your database (using upgrade functions you define.)
562 #
563 # You can call this from config.php right after db_connect() to make sure the
564 # database is up to date.
565 #
566 # When you want to update your schema, define a new function named
567 # db_upgrade_to_X() where X is the next integer (start at 1).
568 #
569 # If there are any page views while your upgrade function is running, they will
570 # stall until the upgrade function completes. This is often better than running
571 # while the databse is in a transitional state, and is way way better than
572 # running the upgrade function multiple times concurrently.
573 #
574 # Efficiency: this function is designed to be lean enough that you'd run it on
575 # every page load, so you never forget to upgrade your schema after uploading
576 # code changes. If your schema is up to date, this will only execute one
577 # database query, and that query loads the persistent data store (used by
578 # persistent_get()), so if you use that, you'll need that query to happen
579 # anyway (giving this function a zero-query overhead).
580
581 function db_upgrade() {
582         if (isset($GLOBALS['wfpl_persistent'])) {
583                 $version = persistent_get('wfpl_db_version');
584         } else {
585                 # custom version of persistent_init() that creates the table if needed
586                 # instead of dying
587                 $GLOBALS['wfpl_persistent'] = array();
588                 _db_connection_needed();
589                 $result = mysqli_query($GLOBALS['wfpl_db_handle'], 'select k,v from wfpl_persistent');
590                 if ($result) {
591                         while($row = mysqli_fetch_assoc($result)) {
592                                 $GLOBALS['wfpl_persistent'][$row['k']] = json_decode($row['v'], true);
593                         } unset($row);
594                         if (isset($GLOBALS['wfpl_persistent']['wfpl_db_version'])) {
595                                 $version = $GLOBALS['wfpl_persistent']['wfpl_db_version'];
596                         } else {
597                                 $version = -1;
598                         }
599                 } else {
600                         db_send_query('create table if not exists wfpl_persistent (k varchar(30) binary not null default "", v mediumblob, primary key (k)) CHARSET=utf8;');
601                         $version = -1;
602                 }
603         }
604
605         if ($version === -1) {
606                 db_send_query('create table if not exists wfpl_mutexes (id int unique auto_increment, name varchar(255) binary, expires int(11)) CHARSET=utf8;');
607                 $version = 0;
608                 # don't save version now in case another thread is doing this too
609         }
610         $next = $version + 1;
611         if (function_exists("db_upgrade_to_$next")) {
612                 require_once(__DIR__.'/'.'persistent.php');
613                 require_once(__DIR__.'/'.'mutex.php');
614                 mutex_lock('wfpl_db_upgrade', 20);
615                 # check version again, in case another thread upgraded the database
616                 # while we waited for a lock just now
617                 persistent_invalidate_cache();
618                 $version = persistent_get('wfpl_db_version');
619                 if ($version === null) {
620                         $version = 0;
621                 }
622
623                 for ($next = $version + 1; function_exists("db_upgrade_to_$next"); ++$next) {
624                         call_user_func("db_upgrade_to_$next");
625                         persistent_set('wfpl_db_version', $next);
626                 }
627                 mutex_unlock('wfpl_db_upgrade');
628         }
629 }