JasonWoof Got questions, comments, patches, etc.? Contact Jason Woofenden
re-licensed under GPLv3
[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('code/wfpl/encode.php');
20 require_once('code/wfpl/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 # %"  output double quotes, surrounding the variable which is encoded to be in there.
99 # %s  output encoded to be in double quotes, but don't output the quotes
100 #
101 # complex example: db_get_rows('mytable', 'id', 'where name=%" or company like "%%%s%%"', $name, $company_partial);
102
103 function db_printf($str) {
104         $args = func_get_args();
105         $args = array_slice($args, 1);
106         return _db_printf($str, $args);
107 }
108
109 # This function does the work, but takes the parameters in an array
110 function _db_printf($str, $args) {
111         $out = '';
112         while($str) {
113                 $pos = strpos($str, '%');
114                 if($pos === false) { # not found
115                         # we hit the end.
116                         return $out . $str;
117                 }
118                 # move everything up to (but not including) % to the output
119                 $out .= substr($str, 0, $pos);
120
121                 # grab the character after the %
122                 $chr = substr($str, $pos + 1, 1);
123
124                 # remove the stuff we've read from input
125                 $str = substr($str, $pos + 2);
126
127                 if($chr == '"') {
128                         $out .= '"' . enc_sql(array_shift($args)) . '"';
129                 } elseif($chr == 's') {
130                         $out .= enc_sql(array_shift($args));
131                 } elseif($chr == 'i') {
132                         $int = format_int(array_shift($args));
133                         if($int == '') $int = '0';
134                         $out .= $int;
135                 } else {
136                         $out .= $chr;
137                 }
138         }
139
140         return $out;
141 }
142
143
144 function db_send_get($table, $columns, $where, $args) {
145         $sql = "SELECT $columns FROM $table";
146         if($where) {
147                 $sql .= ' ' . _db_printf($where, $args);
148         }
149
150         return db_send_query($sql);
151 }
152
153
154 function db_get_rows($table, $columns, $where = '') {
155         $args = func_get_args();
156         $args = array_slice($args, 3);
157         $result = db_send_get($table, $columns, $where, $args);
158
159         $rows = array();
160         while($row = mysql_fetch_row($result)) {
161                 $rows[] = $row;
162         }
163
164         mysql_free_result($result);
165
166         return $rows;
167 }
168
169 function db_get_column($table, $columns, $where = '') {
170         $args = func_get_args();
171         $args = array_slice($args, 3);
172         $result = db_send_get($table, $columns, $where, $args);
173
174         $column = array();
175         while($row = mysql_fetch_row($result)) {
176                 $column[] = $row[0];
177         }
178
179         mysql_free_result($result);
180
181         return $column;
182 }
183
184 function db_get_row($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         $row = mysql_fetch_row($result);
190
191         mysql_free_result($result);
192
193         return $row;
194 }
195
196 function db_get_value($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         $value = mysql_fetch_row($result);
202         if($value !== false) {
203                 $value = $value[0];
204         }
205
206         mysql_free_result($result);
207
208         return $value;
209 }
210
211 function db_count($table, $where = '') {
212         $args = func_get_args();
213         array_splice($args, 1, 0, array('count(*)'));
214         return call_user_func_array('db_get_value', $args);
215 }
216
217 # call either of these ways:
218 #
219 # db_insert('people', 'name,company', 'jason', 'widgets ltd');
220 # or
221 # db_insert('people', 'name,company', array('jason', 'widgets ltd'));
222 function db_insert($table, $columns, $values) {
223         if(!is_array($values)) {
224                 $values = func_get_args();
225                 $values = array_slice($values, 2);
226         }
227         
228         db_insert_ish('INSERT', $table, $columns, $values);
229 }
230 # same as above, except uses the "replace" command instead of "insert"
231 function db_replace($table, $columns, $values) {
232         if(!is_array($values)) {
233                 $values = func_get_args();
234                 $values = array_slice($values, 2);
235         }
236         
237         db_insert_ish('REPLACE', $table, $columns, $values);
238 }
239         
240 # return the value mysql made up for the auto_increment field (for the last insert)
241 function db_auto_id() {
242         return mysql_insert_id($GLOBALS['wfpl_db_handle']);
243 }
244
245
246 # used to implement db_insert() and db_replace()
247 function db_insert_ish($command, $table, $columns, $values) {
248
249         $sql = '';
250         foreach($values as $value) {
251                 if($sql) $sql .= ',';
252                 $sql .= '"' . enc_sql($value) . '"';
253         }
254
255         $sql = "$command INTO $table ($columns) values($sql)";
256
257         db_send_query($sql);
258 }
259
260 # to be consistant with the syntax of the other db functions, $values can be an
261 # array, a single value, or multiple parameters.
262 #
263 # as usual the where clause stuff is optional, but it will ofcourse update the
264 # whole table if you leave it off.
265 #
266 # examples:
267 #
268 # # name everybody Bruce
269 # db_update('users', 'name', 'Bruce');
270 #
271 # # name user #6 Bruce
272 # db_update('users', 'name', 'Bruce', 'where id=%i', 6);
273 #
274 # # update the whole bit for user #6
275 # db_update('users', 'name,email,description', 'Bruce', 'bruce@example.com', 'is a cool guy', 'where id=%i', 6);
276 #
277 # # update the whole bit for user #6 (passing data as an array)
278 # $data = array('Bruce', 'bruce@example.com', 'is a cool guy');
279 # db_update('users', 'name,email,description', $data, 'where id=%i', 6);
280
281 # The prototype is really something like this:
282 # db_update(table, columns, values..., where(optional), where_args...(optional))
283 function db_update($table, $columns, $values) {
284         $args = func_get_args();
285         $args = array_slice($args, 2);
286         $columns = explode(',', $columns);
287         $num_fields = count($columns);
288
289         if(is_array($values)) {
290                 $args = array_slice($args, 1);
291         } else {
292                 $values = array_slice($args, 0, $num_fields);
293                 $args = array_slice($args, $num_fields);
294         }
295
296         $sql = '';
297         for($i = 0; $i < $num_fields; ++$i) {
298                 if($sql != '') {
299                         $sql .= ', ';
300                 }
301                 $sql .= $columns[$i] . ' = "' . enc_sql($values[$i]) . '"';
302         }
303
304
305         $sql = "UPDATE $table SET $sql";
306
307         # if there's any more arguments
308         if($args) {
309                 $where = $args[0];
310                 $args = array_slice($args, 1);
311
312                 $sql .= ' ';
313                 # any left for where claus arguments?
314                 if($args) {
315                         $sql .= _db_printf($where, $args);
316                 } else {
317                         $sql .= $where;
318                 }
319
320         }
321
322         db_send_query($sql);
323 }
324
325 # pass args for printf-style where clause as usual
326 function db_delete($table, $where = '') {
327         $sql = "DELETE FROM $table";
328         if($where) {
329                 $sql .= ' ';
330                 $args = func_get_args();
331                 $args = array_slice($args, 2);
332                 if($args) {
333                         $sql .= _db_printf($where, $args);
334                 } else {
335                         $sql .= $where;
336                 }
337         }
338
339         db_send_query($sql);
340 }
341
342 ?>