JasonWoof Got questions, comments, patches, etc.? Contact Jason Woofenden
enc_htmlbrtab: don't double spaces
[wfpl.git] / db.php
1 <?php
2
3 #  Copyright (C) 2006 Jason Woofenden
4 #
5 #  This program is free software: you can redistribute it and/or modify
6 #  it under the terms of the GNU General Public License as published by
7 #  the Free Software Foundation, either version 3 of the License, or
8 #  (at your option) any later version.
9 #  
10 #  This program is distributed in the hope that it will be useful,
11 #  but WITHOUT ANY WARRANTY; without even the implied warranty of
12 #  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 #  GNU General Public License for more details.
14 #  
15 #  You should have received a copy of the GNU General Public License
16 #  along with this program.  If not, see <http://www.gnu.org/licenses/>.
17
18
19 require_once(__DIR__.'/'.'encode.php');
20 require_once(__DIR__.'/'.'format.php');
21
22 # db_connect() -- connect to a mysql database
23 #
24 # PARAMETERS:
25 #
26 #   database: the name of the database you want to connect to. Defaults to the
27 #   second-to-last part of the domain name. eg for foo.example.com it would be
28 #   "example".
29
30 #   user: username for connecting to the database. Defaults to
31 #   $GLOBALS['db_username'] or (if that's not set) "www".
32
33 #   password: password for connecting to the database. Defaults to
34 #   $GLOBALS['db_password'] or (if that's not set "".
35 #
36 # RETURNS:
37 #
38 #   the database connection handle. You'll only need this if you want to have
39 #   multiple databases open at once.
40
41 function db_enc_sql($str) {
42         return mysqli_real_escape_string(isset($GLOBALS['wfpl_db_handle']) ? $GLOBALS['wfpl_db_handle'] : null, $str);
43 }
44
45 function db_connect($database = 'auto', $user = 'auto', $pass = 'auto', $host = 'localhost', $encoding = 'utf8') {
46         if($database == 'auto') {
47                 if(isset($GLOBALS['db_name'])) {
48                         $database = $GLOBALS['db_name'];
49                 } else {
50                         $host = $_SERVER['SERVER_NAME'];
51                         $host = explode('.', $host);
52                         array_pop($host);
53                         $database = array_pop($host);
54                         unset($host);
55                 }
56         }
57
58         if($user == 'auto') {
59                 if(isset($GLOBALS['db_username'])) {
60                         $user = $GLOBALS['db_username'];
61                 } else {
62                         $user = 'www';
63                 }
64         }
65
66         if($pass == 'auto') {
67                 if(isset($GLOBALS['db_password'])) {
68                         $pass = $GLOBALS['db_password'];
69                 } else {
70                         $pass = '';
71                 }
72         }
73
74         $GLOBALS['wfpl_db_handle'] = mysqli_connect($host, $user, $pass);
75         if(!$GLOBALS['wfpl_db_handle']) {
76                 die('Could not connect to the database: ' . mysqli_error());
77         }
78
79         mysqli_set_charset($GLOBALS['wfpl_db_handle'], $encoding);
80
81         if(!mysqli_select_db($GLOBALS['wfpl_db_handle'], $database)) {
82                 die("Couldn not access database \"$database\": " . mysqli_error($GLOBALS['wfpl_db_handle']));
83         }
84
85         return $GLOBALS['wfpl_db_handle'];
86 }
87
88 # Unless you're doing something unusual like an ALTER TABLE don't call this directly
89 function db_send_query($sql) {
90         #echo("Sending query: " . enc_html($sql) . "<br>\n");
91         $result = mysqli_query($GLOBALS['wfpl_db_handle'], $sql);
92         if(!$result) {
93                 die(enc_html('DATABASE ERROR: ' . mysqli_error($GLOBALS['wfpl_db_handle']) . ' in the following query: ' . $sql));
94         }
95
96         return $result;
97 }
98
99 # All select queries use this to generate the where clause, so they can work
100 # like printf. Currently three % codes are supported:
101 #
102 # %%  put a % in the output
103 # %i  put an integer in the output (strips non-numeric digits, and puts in 0 if blank)
104 # %f  put a floating point value in the output (strips non-numeric digits, puts in 0.0 if not valid)
105 # %"  output double quotes, surrounding the variable which is encoded to be in there.
106 # %s  output encoded to be in double quotes, but don't output the quotes
107 # %$  output argument as-is, no encoding. Make sure you quote everything from the user!
108 #
109 # complex example: db_get_rows('mytable', 'id', 'where name=%" or company like "%%%s%%"', $name, $company_partial);
110
111 function db_printf($str) {
112         $args = func_get_args();
113         $args = array_slice($args, 1);
114         return _db_printf($str, $args);
115 }
116
117 # This function does the work, but takes the parameters in an array
118 function _db_printf($str, $args) {
119         $out = '';
120         while($str) {
121                 $pos = strpos($str, '%');
122                 if($pos === false) { # not found
123                         # we hit the end.
124                         return $out . $str;
125                 }
126                 # move everything up to (but not including) % to the output
127                 $out .= substr($str, 0, $pos);
128
129                 # grab the character after the %
130                 $chr = substr($str, $pos + 1, 1);
131
132                 # remove the stuff we've read from input
133                 $str = substr($str, $pos + 2);
134
135                 if($chr == '"') {
136                         $out .= '"' . db_enc_sql(array_shift($args)) . '"';
137                 } elseif($chr == 's') {
138                         $out .= db_enc_sql(array_shift($args));
139                 } elseif($chr == 'i') {
140                         $int = format_int(array_shift($args));
141                         if($int == '') $int = '0';
142                         $out .= $int;
143                 } elseif($chr == 'f') {
144                         $arg = array_shift($args);
145                         if(is_numeric($arg)) {
146                                 $arg = sprintf("%f", $arg);
147                         }
148                         $arg = format_decimal($arg);
149                         if(strlen($arg) < 1) {
150                                 $arg = '0.0';
151                         }
152                         $out .= $arg;
153                 } elseif($chr == '$') {
154                         $out .= array_shift($args);
155                 } else {
156                         $out .= $chr;
157                 }
158         }
159
160         return $out;
161 }
162
163
164 # helper function
165 function db_send_get($table, $columns, $where, $args) {
166         $sql = "SELECT $columns FROM $table";
167         if($where) {
168                 $sql .= ' ' . _db_printf($where, $args);
169         }
170
171         return db_send_query($sql);
172 }
173
174
175 # if no results: returs []
176 function db_get_rows($table, $columns, $where = '') {
177         $args = func_get_args();
178         $args = array_slice($args, 3);
179         $result = db_send_get($table, $columns, $where, $args);
180
181         $rows = array();
182         while($row = mysqli_fetch_row($result)) {
183                 $rows[] = $row;
184         }
185
186         mysqli_free_result($result);
187
188         return $rows;
189 }
190
191 # like db_get_rows, but return array of hashes.
192 # if no results: returs []
193 function db_get_assocs($table, $columns, $where = '') {
194         $args = func_get_args();
195         $args = array_slice($args, 3);
196         $result = db_send_get($table, $columns, $where, $args);
197
198         $rows = array();
199         while($row = mysqli_fetch_assoc($result)) {
200                 $rows[] = $row;
201         }
202
203         mysqli_free_result($result);
204
205         return $rows;
206 }
207
208 # if no results: returs []
209 function db_get_column($table, $columns, $where = '') {
210         $args = func_get_args();
211         $args = array_slice($args, 3);
212         $result = db_send_get($table, $columns, $where, $args);
213
214         $column = array();
215         while($row = mysqli_fetch_row($result)) {
216                 $column[] = $row[0];
217         }
218
219         mysqli_free_result($result);
220
221         return $column;
222 }
223
224 # returns first matching row
225 # if no results: returns false
226 function db_get_row($table, $columns, $where = '') {
227         $args = func_get_args();
228         $args = array_slice($args, 3);
229         $result = db_send_get($table, $columns, $where, $args);
230
231         $row = mysqli_fetch_row($result);
232
233         mysqli_free_result($result);
234
235         return $row;
236 }
237
238 # like db_get_row, but return a hash.
239 # if no results: returns false
240 function db_get_assoc($table, $columns, $where = '') {
241         $args = func_get_args();
242         $args = array_slice($args, 3);
243         $result = db_send_get($table, $columns, $where, $args);
244
245         $row = mysqli_fetch_assoc($result);
246
247         mysqli_free_result($result);
248
249         return $row;
250 }
251
252 # if no results: returns false
253 function db_get_value($table, $column, $where = '') {
254         $args = func_get_args();
255         $args = array_slice($args, 3);
256         $result = db_send_get($table, $column, $where, $args);
257
258         $value = mysqli_fetch_row($result);
259         if($value !== false) {
260                 $value = $value[0];
261         }
262
263         mysqli_free_result($result);
264
265         return $value;
266 }
267
268 # returns an integer
269 function db_count($table, $where = '') {
270         $args = func_get_args();
271         array_splice($args, 1, 0, array('count(*)'));
272         return (int) call_user_func_array('db_get_value', $args);
273 }
274
275 # call either of these ways:
276 #
277 # db_insert('people', 'name,company', 'jason', 'widgets ltd');
278 # or
279 # db_insert('people', 'name,company', array('jason', 'widgets ltd'));
280 function db_insert($table, $columns, $values) {
281         if(!is_array($values)) {
282                 $values = func_get_args();
283                 $values = array_slice($values, 2);
284         }
285         
286         db_insert_ish('INSERT', $table, $columns, $values);
287 }
288
289 # like db_insert() above, but instead of passing columns and data separately,
290 # you can pass one array with the column names as keys and the data as values
291 function db_insert_assoc($table, $data) {
292         $args = func_get_args();
293         $args = array_slice($args, 2);
294         $columns = array();
295         $values = array();
296         foreach($data as $key => $value) {
297                 $columns[] = $key;
298                 $values[] = $value;
299         }
300         array_unshift($args, $table, join(',', $columns), $values);
301         call_user_func_array('db_insert', $args);
302 }
303
304 # same as above, except uses the "replace" command instead of "insert"
305 function db_replace($table, $columns, $values) {
306         if(!is_array($values)) {
307                 $values = func_get_args();
308                 $values = array_slice($values, 2);
309         }
310         
311         db_insert_ish('REPLACE', $table, $columns, $values);
312 }
313         
314 # return the value mysql made up for the auto_increment field (for the last insert)
315 function db_auto_id() {
316         return mysqli_insert_id($GLOBALS['wfpl_db_handle']);
317 }
318
319
320 # used to implement db_insert() and db_replace()
321 function db_insert_ish($command, $table, $columns, $values) {
322
323         $sql = '';
324         foreach($values as $value) {
325                 if($sql) $sql .= ',';
326                 $sql .= '"' . db_enc_sql($value) . '"';
327         }
328
329         $sql = "$command INTO $table ($columns) values($sql)";
330
331         db_send_query($sql);
332 }
333
334 # to be consistent with the syntax of the other db functions, $values can be an
335 # array, a single value, or multiple parameters.
336 #
337 # as usual the where clause stuff is optional, but it will of course update the
338 # whole table if you leave it off.
339 #
340 # examples:
341 #
342 # # name everybody Bruce
343 # db_update('users', 'name', 'Bruce');
344 #
345 # # name user #6 Bruce
346 # db_update('users', 'name', 'Bruce', 'where id=%i', 6);
347 #
348 # # update the whole bit for user #6
349 # db_update('users', 'name,email,description', 'Bruce', 'bruce@example.com', 'is a cool guy', 'where id=%i', 6);
350 #
351 # # update the whole bit for user #6 (passing data as an array)
352 # $data = array('Bruce', 'bruce@example.com', 'is a cool guy');
353 # db_update('users', 'name,email,description', $data, 'where id=%i', 6);
354
355 # The prototype is really something like this:
356 # db_update(table, columns, values..., where(optional), where_args...(optional))
357 function db_update($table, $columns, $values) {
358         $args = func_get_args();
359         $args = array_slice($args, 2);
360         $columns = explode(',', $columns);
361         $num_fields = count($columns);
362
363         if(is_array($values)) {
364                 $values = array_values($values);
365                 $args = array_slice($args, 1);
366         } else {
367                 $values = array_slice($args, 0, $num_fields);
368                 $args = array_slice($args, $num_fields);
369         }
370
371         $sql = '';
372         for($i = 0; $i < $num_fields; ++$i) {
373                 if($sql != '') {
374                         $sql .= ', ';
375                 }
376                 $sql .= $columns[$i] . ' = "' . db_enc_sql($values[$i]) . '"';
377         }
378
379
380         $sql = "UPDATE $table SET $sql";
381
382         # if there's any more arguments
383         if($args) {
384                 $where = $args[0];
385                 $args = array_slice($args, 1);
386
387                 $sql .= ' ';
388                 # any left for printf arguments?
389                 if($args) {
390                         $sql .= _db_printf($where, $args);
391                 } else {
392                         $sql .= $where;
393                 }
394
395         }
396
397         db_send_query($sql);
398 }
399
400 # like db_update() above, but instead of passing columns and data separately,
401 # you can pass one array with the column names as keys and the data as values
402 function db_update_assoc($table, $data) {
403         $args = func_get_args();
404         $args = array_slice($args, 2);
405         $columns = array();
406         $values = array();
407         foreach($data as $key => $value) {
408                 $columns[] = $key;
409                 $values[] = $value;
410         }
411         array_unshift($args, $values);
412         array_unshift($args, join(',', $columns));
413         array_unshift($args, $table);
414         call_user_func_array('db_update', $args);
415 }
416
417 # pass args for printf-style where clause as usual
418 function db_delete($table, $where = '') {
419         $sql = "DELETE FROM $table";
420         if($where) {
421                 $sql .= ' ';
422                 $args = func_get_args();
423                 $args = array_slice($args, 2);
424                 if($args) {
425                         $sql .= _db_printf($where, $args);
426                 } else {
427                         $sql .= $where;
428                 }
429         }
430
431         db_send_query($sql);
432 }
433
434
435 define('DB_ORD_MAX', 2000000000);
436
437 function db_reposition_respace($table, $field, $where = '') {
438         if($where) {
439                 $andand = " && ($where) ";
440         }
441         $ids = db_get_column($table, 'id', "where $field != 0 $andand order by $field");
442         $c = count($ids);
443         if(!$c) {
444                 # should never happen
445                 return;
446         }
447         $inc = floor(DB_ORD_MAX / ($c + 1));
448         $cur = $inc;
449         foreach($ids as $id) {
450                 db_update($table, $field, $cur, 'where id=%i', $id);
451                 $cur += $inc;
452         }
453 }
454
455 # this function facilitates letting the user manually sort records (with (int) $field != 0)
456 #
457 # 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.
458 #
459 # $pretty is used in error messages to refer to the row, it defaults to whatever you pass for $table.
460 #
461 # return value is the "ord" value you should set/insert into your database
462
463 function db_reposition($table, $row_id, $new_pos, $field = 'ord', $pretty = 'same as $table', $where = '', $renumbered_already = false) {
464         if($pretty == 'same as $table') {
465                 $pretty = $table;
466         }
467         if($where) {
468                 $andand = " && ($where) ";
469         }
470
471         if($new_pos === 'ignored') {
472                 # not sorted
473                 return '0';
474         }
475
476         # strategy: calculate $prev_ord and $next_ord. If there's no space between, renumber and recurse
477         if($new_pos == '0') {
478                 $row = db_get_row($table, "id,$field", "where $field != 0 $andand order by $field limit 1");
479                 if($row) {
480                         list($first_row_id, $first_row_ord) = $row;
481                         if($first_row_id == $row_id) {
482                                 # already first
483                                 return $first_row_ord;
484                         }
485                         $next_ord = $first_row_ord;
486                 } else {
487                         # this is the only row, put it in the middle
488                         return '' + floor(DB_ORD_MAX / 2);
489                 }
490
491                 $prev_ord = 0;
492         } else {
493                 $new_pos = format_int_0($new_pos);
494                 $rows = db_get_rows($table, "id,$field", "where $field != 0 $andand order by $field limit %i,2", $new_pos - 1);
495                 if(!$rows) {
496                         message("Sorry, couldn't find the $pretty you asked to put this $pretty after. Putting it first instead.");
497                         return db_reposition($table, $row_id, '0', $field, $pretty, $where);
498                 } else {
499                         list($prev_id, $prev_ord) = $rows[0];
500                         if($prev_id == $row_id) {
501                                 # after self? this shouldn't happen
502                                 return $prev_ord;
503                         }
504                         if(count($rows) == 1) {
505                                 # we should be last
506                                 $next_ord = DB_ORD_MAX;
507                         } else {
508                                 list($next_id, $next_ord) = $rows[1];
509                                 if($next_id == $row_id) {
510                                         # after prev (already there)
511                                         return $next_ord;
512                                 }
513                         }
514                 }
515         }
516         if($prev_ord + 1 == $next_ord || $prev_ord == $next_ord) { # the latter should never happen
517                 if($renumbered_already) {
518                         message("Programmer error in $pretty ordering code. Please tell your website administrator.");
519                         return '' . rand(2, DB_ORD_MAX - 2); # reasonably unlikely to be the same as some other ord
520                 }
521                 db_reposition_respace($table, $field, $where);
522                 return db_reposition($table, $row_id, $new_pos, $field, $pretty, $where, $renumbered_already = true);
523         } else {
524                 return $prev_ord + round(($next_ord - $prev_ord) / 2);
525         }
526 }