JasonWoof Got questions, comments, patches, etc.? Contact Jason Woofenden
metaform: fix mtime trick for css file in html editors
[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 # %f  put a floating point value in the output (strips non-numeric digits, puts in 0.0 if not valid)
115 # %"  output double quotes, surrounding the variable which is encoded to be in there.
116 # %s  output encoded to be in double quotes, but don't output the quotes
117 # %$  output argument as-is, no encoding. Make sure you quote everything from the user!
118 #
119 # complex example: db_get_rows('mytable', 'id', 'where name=%" or company like "%%%s%%"', $name, $company_partial);
120
121 function db_printf($str) {
122         $args = func_get_args();
123         $args = array_slice($args, 1);
124         return _db_printf($str, $args);
125 }
126
127 # This function does the work, but takes the parameters in an array
128 function _db_printf($str, $args) {
129         $out = '';
130         while($str) {
131                 $pos = strpos($str, '%');
132                 if($pos === false) { # not found
133                         # we hit the end.
134                         return $out . $str;
135                 }
136                 # move everything up to (but not including) % to the output
137                 $out .= substr($str, 0, $pos);
138
139                 # grab the character after the %
140                 $chr = substr($str, $pos + 1, 1);
141
142                 # remove the stuff we've read from input
143                 $str = substr($str, $pos + 2);
144
145                 if($chr == '"') {
146                         $out .= '"' . db_enc_sql(array_shift($args)) . '"';
147                 } elseif($chr == 's') {
148                         $out .= db_enc_sql(array_shift($args));
149                 } elseif($chr == 'i') {
150                         $int = format_int(array_shift($args));
151                         if($int == '') $int = '0';
152                         $out .= $int;
153                 } elseif($chr == 'f') {
154                         $arg = array_shift($args);
155                         if(is_numeric($arg)) {
156                                 $arg = sprintf("%f", $arg);
157                         }
158                         $arg = format_decimal($arg);
159                         if(strlen($arg) < 1) {
160                                 $arg = '0.0';
161                         }
162                         $out .= $arg;
163                 } elseif($chr == '$') {
164                         $out .= array_shift($args);
165                 } else {
166                         $out .= $chr;
167                 }
168         }
169
170         return $out;
171 }
172
173
174 # helper function
175 function db_send_get($table, $columns, $where, $args) {
176         $sql = "SELECT $columns FROM $table";
177         if($where) {
178                 $sql .= ' ' . _db_printf($where, $args);
179         }
180
181         return db_send_query($sql);
182 }
183
184
185 # if no results: returs []
186 function db_get_rows($table, $columns, $where = '') {
187         $args = func_get_args();
188         $args = array_slice($args, 3);
189         $result = db_send_get($table, $columns, $where, $args);
190
191         $rows = array();
192         while($row = mysqli_fetch_row($result)) {
193                 $rows[] = $row;
194         }
195
196         mysqli_free_result($result);
197
198         return $rows;
199 }
200
201 # like db_get_rows, but return array of hashes.
202 # if no results: returs []
203 function db_get_assocs($table, $columns, $where = '') {
204         $args = func_get_args();
205         $args = array_slice($args, 3);
206         $result = db_send_get($table, $columns, $where, $args);
207
208         $rows = array();
209         while($row = mysqli_fetch_assoc($result)) {
210                 $rows[] = $row;
211         }
212
213         mysqli_free_result($result);
214
215         return $rows;
216 }
217
218 # if no results: returs []
219 function db_get_column($table, $columns, $where = '') {
220         $args = func_get_args();
221         $args = array_slice($args, 3);
222         $result = db_send_get($table, $columns, $where, $args);
223
224         $column = array();
225         while($row = mysqli_fetch_row($result)) {
226                 $column[] = $row[0];
227         }
228
229         mysqli_free_result($result);
230
231         return $column;
232 }
233
234 # returns first matching row
235 # if no results: returns false
236 function db_get_row($table, $columns, $where = '') {
237         $args = func_get_args();
238         $args = array_slice($args, 3);
239         $result = db_send_get($table, $columns, $where, $args);
240
241         $row = mysqli_fetch_row($result);
242
243         mysqli_free_result($result);
244
245         return $row;
246 }
247
248 # like db_get_row, but return a hash.
249 # if no results: returns false
250 function db_get_assoc($table, $columns, $where = '') {
251         $args = func_get_args();
252         $args = array_slice($args, 3);
253         $result = db_send_get($table, $columns, $where, $args);
254
255         $row = mysqli_fetch_assoc($result);
256
257         mysqli_free_result($result);
258
259         return $row;
260 }
261
262 # if no results: returns false
263 function db_get_value($table, $column, $where = '') {
264         $args = func_get_args();
265         $args = array_slice($args, 3);
266         $result = db_send_get($table, $column, $where, $args);
267
268         $value = mysqli_fetch_row($result);
269         if($value !== false) {
270                 $value = $value[0];
271         }
272
273         mysqli_free_result($result);
274
275         return $value;
276 }
277
278 # returns an integer
279 function db_count($table, $where = '') {
280         $args = func_get_args();
281         array_splice($args, 1, 0, array('count(*)'));
282         return (int) call_user_func_array('db_get_value', $args);
283 }
284
285 # call either of these ways:
286 #
287 # db_insert('people', 'name,company', 'jason', 'widgets ltd');
288 # or
289 # db_insert('people', 'name,company', array('jason', 'widgets ltd'));
290 function db_insert($table, $columns, $values) {
291         if(!is_array($values)) {
292                 $values = func_get_args();
293                 $values = array_slice($values, 2);
294         }
295         
296         db_insert_ish('INSERT', $table, $columns, $values);
297 }
298
299 # like db_insert() above, but instead of passing columns and data separately,
300 # you can pass one array with the column names as keys and the data as values
301 function db_insert_assoc($table, $data) {
302         $args = func_get_args();
303         $args = array_slice($args, 2);
304         $columns = array();
305         $values = array();
306         foreach($data as $key => $value) {
307                 $columns[] = $key;
308                 $values[] = $value;
309         }
310         array_unshift($args, $table, join(',', $columns), $values);
311         call_user_func_array('db_insert', $args);
312 }
313
314 # same as above, except uses the "replace" command instead of "insert"
315 function db_replace($table, $columns, $values) {
316         if(!is_array($values)) {
317                 $values = func_get_args();
318                 $values = array_slice($values, 2);
319         }
320         
321         db_insert_ish('REPLACE', $table, $columns, $values);
322 }
323         
324 # return the value mysql made up for the auto_increment field (for the last insert)
325 function db_auto_id() {
326         _db_connection_needed();
327         return mysqli_insert_id($GLOBALS['wfpl_db_handle']);
328 }
329
330
331 # used to implement db_insert() and db_replace()
332 function db_insert_ish($command, $table, $columns, $values) {
333
334         $sql = '';
335         foreach($values as $value) {
336                 if($sql) $sql .= ',';
337                 $sql .= '"' . db_enc_sql($value) . '"';
338         }
339
340         $sql = "$command INTO $table ($columns) values($sql)";
341
342         db_send_query($sql);
343 }
344
345 # to be consistent with the syntax of the other db functions, $values can be an
346 # array, a single value, or multiple parameters.
347 #
348 # as usual the where clause stuff is optional, but it will of course update the
349 # whole table if you leave it off.
350 #
351 # examples:
352 #
353 # # name everybody Bruce
354 # db_update('users', 'name', 'Bruce');
355 #
356 # # name user #6 Bruce
357 # db_update('users', 'name', 'Bruce', 'where id=%i', 6);
358 #
359 # # update the whole bit for user #6
360 # db_update('users', 'name,email,description', 'Bruce', 'bruce@example.com', 'is a cool guy', 'where id=%i', 6);
361 #
362 # # update the whole bit for user #6 (passing data as an array)
363 # $data = array('Bruce', 'bruce@example.com', 'is a cool guy');
364 # db_update('users', 'name,email,description', $data, 'where id=%i', 6);
365
366 # The prototype is really something like this:
367 # db_update(table, columns, values..., where(optional), where_args...(optional))
368 function db_update($table, $columns, $values) {
369         $args = func_get_args();
370         $args = array_slice($args, 2);
371         $columns = explode(',', $columns);
372         $num_fields = count($columns);
373
374         if(is_array($values)) {
375                 $values = array_values($values);
376                 $args = array_slice($args, 1);
377         } else {
378                 $values = array_slice($args, 0, $num_fields);
379                 $args = array_slice($args, $num_fields);
380         }
381
382         $sql = '';
383         for($i = 0; $i < $num_fields; ++$i) {
384                 if($sql != '') {
385                         $sql .= ', ';
386                 }
387                 $sql .= $columns[$i] . ' = "' . db_enc_sql($values[$i]) . '"';
388         }
389
390
391         $sql = "UPDATE $table SET $sql";
392
393         # if there's any more arguments
394         if($args) {
395                 $where = $args[0];
396                 $args = array_slice($args, 1);
397
398                 $sql .= ' ';
399                 # any left for printf arguments?
400                 if($args) {
401                         $sql .= _db_printf($where, $args);
402                 } else {
403                         $sql .= $where;
404                 }
405
406         }
407
408         db_send_query($sql);
409 }
410
411 # like db_update() above, but instead of passing columns and data separately,
412 # you can pass one array with the column names as keys and the data as values
413 function db_update_assoc($table, $data) {
414         $args = func_get_args();
415         $args = array_slice($args, 2);
416         $columns = array();
417         $values = array();
418         foreach($data as $key => $value) {
419                 $columns[] = $key;
420                 $values[] = $value;
421         }
422         array_unshift($args, $values);
423         array_unshift($args, join(',', $columns));
424         array_unshift($args, $table);
425         call_user_func_array('db_update', $args);
426 }
427
428 # pass args for printf-style where clause as usual
429 function db_delete($table, $where = '') {
430         $sql = "DELETE FROM $table";
431         if($where) {
432                 $sql .= ' ';
433                 $args = func_get_args();
434                 $args = array_slice($args, 2);
435                 if($args) {
436                         $sql .= _db_printf($where, $args);
437                 } else {
438                         $sql .= $where;
439                 }
440         }
441
442         db_send_query($sql);
443 }
444
445
446 define('DB_ORD_MAX', 2000000000);
447
448 function db_reposition_respace($table, $field, $where = '') {
449         if($where) {
450                 $andand = " && ($where) ";
451         }
452         $ids = db_get_column($table, 'id', "where $field != 0 $andand order by $field");
453         $c = count($ids);
454         if(!$c) {
455                 # should never happen
456                 return;
457         }
458         $inc = floor(DB_ORD_MAX / ($c + 1));
459         $cur = $inc;
460         foreach($ids as $id) {
461                 db_update($table, $field, $cur, 'where id=%i', $id);
462                 $cur += $inc;
463         }
464 }
465
466 # this function facilitates letting the user manually sort records (with (int) $field != 0)
467 #
468 # 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.
469 #
470 # $pretty is used in error messages to refer to the row, it defaults to whatever you pass for $table.
471 #
472 # return value is the "ord" value you should set/insert into your database
473
474 function db_reposition($table, $row_id, $new_pos, $field = 'ord', $pretty = 'same as $table', $where = '', $renumbered_already = false) {
475         if($pretty == 'same as $table') {
476                 $pretty = $table;
477         }
478         if($where) {
479                 $andand = " && ($where) ";
480         }
481
482         if($new_pos === 'ignored') {
483                 # not sorted
484                 return '0';
485         }
486
487         # strategy: calculate $prev_ord and $next_ord. If there's no space between, renumber and recurse
488         if($new_pos == '0') {
489                 $row = db_get_row($table, "id,$field", "where $field != 0 $andand order by $field limit 1");
490                 if($row) {
491                         list($first_row_id, $first_row_ord) = $row;
492                         if($first_row_id == $row_id) {
493                                 # already first
494                                 return $first_row_ord;
495                         }
496                         $next_ord = $first_row_ord;
497                 } else {
498                         # this is the only row, put it in the middle
499                         return '' + floor(DB_ORD_MAX / 2);
500                 }
501
502                 $prev_ord = 0;
503         } else {
504                 $new_pos = format_int_0($new_pos);
505                 $rows = db_get_rows($table, "id,$field", "where $field != 0 $andand order by $field limit %i,2", $new_pos - 1);
506                 if(!$rows) {
507                         message("Sorry, couldn't find the $pretty you asked to put this $pretty after. Putting it first instead.");
508                         return db_reposition($table, $row_id, '0', $field, $pretty, $where);
509                 } else {
510                         list($prev_id, $prev_ord) = $rows[0];
511                         if($prev_id == $row_id) {
512                                 # after self? this shouldn't happen
513                                 return $prev_ord;
514                         }
515                         if(count($rows) == 1) {
516                                 # we should be last
517                                 $next_ord = DB_ORD_MAX;
518                         } else {
519                                 list($next_id, $next_ord) = $rows[1];
520                                 if($next_id == $row_id) {
521                                         # after prev (already there)
522                                         return $next_ord;
523                                 }
524                         }
525                 }
526         }
527         if($prev_ord + 1 == $next_ord || $prev_ord == $next_ord) { # the latter should never happen
528                 if($renumbered_already) {
529                         message("Programmer error in $pretty ordering code. Please tell your website administrator.");
530                         return '' . rand(2, DB_ORD_MAX - 2); # reasonably unlikely to be the same as some other ord
531                 }
532                 db_reposition_respace($table, $field, $where);
533                 return db_reposition($table, $row_id, $new_pos, $field, $pretty, $where, $renumbered_already = true);
534         } else {
535                 return $prev_ord + round(($next_ord - $prev_ord) / 2);
536         }
537 }