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