3 # Copyright (C) 2007 Jason Woofenden
5 # This file is part of wfpl.
7 # wfpl is free software; you can redistribute it and/or modify it under the
8 # terms of the GNU Lesser General Public License as published by the Free
9 # Software Foundation; either version 2.1 of the License, or (at your option)
12 # wfpl is distributed in the hope that it will be useful, but WITHOUT ANY
13 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
14 # FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for
17 # You should have received a copy of the GNU Lesser General Public License
18 # along with wfpl; if not, write to the Free Software Foundation, Inc., 51
19 # Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
22 # This file contains code to use a web-writeable directory full of files as a
23 # very simple database.
25 # Keys are truncated to 32 bytes, made lowercase, and all characters that are
26 # not alpha/numeric are replaced with underscores. Periods and hyphens are only
27 # replaced if they are at the begining.
29 # Data can be either a string or an array.
31 # To set up the database, make a directory that's writeable by PHP and call
32 # fdb_set_dir() passing the path to that directory.
35 require_once('code/wfpl/file.php');
36 require_once('code/wfpl/binary.php');
38 # call this to set what directory is used to store the files
39 function fdb_set_dir($dir) {
40 $GLOBALS['fdb_dir'] = $dir;
43 function fdb_get_dir() {
44 if(!isset($GLOBALS['fdb_dir'])) {
45 die('you must call fdb_set_dir() before calling other functions in code/wfpl/fdb.php');
47 return $GLOBALS['fdb_dir'];
51 function fdb_fix_key($key) {
52 $key = ereg_replace('[^a-z0-9.-]', '_', strtolower($key));
53 $key = ereg_replace('^[-.]', '_', strtolower($key));
54 return substr($key, 0, 32);
58 function fdb_get_raw($key) {
59 $key = fdb_fix_key($key);
60 return read_whole_file_or_false(fdb_get_dir() . "/$key");
63 function fdb_set_raw($key, $data) {
64 $key = fdb_fix_key($key);
65 write_whole_file(fdb_get_dir() . "/$key", $data);
68 # like fdb_get() except it returns an array even when there's just one element
69 function fdb_geta($key) {
70 $key = fdb_fix_key($key);
71 $data = fdb_get_raw($key);
75 return raw_to_array($data);
80 # false if the key is not found in the database
82 # an array from the file otherwise
84 # a string if there's one field in that file (use fdb_geta() if you want an
85 # array in this case too)
86 function fdb_get($key) {
87 $ret = fdb_geta($key);
91 if(count($ret) == 1) {
98 # data can be a string or array
99 function fdb_set($key, $data) {
100 $key = fdb_fix_key($key);
101 if(!is_array($data)) {
102 $data = array($data);
104 fdb_set_raw($key, array_to_raw($data));
107 function fdb_delete($key) {
108 $key = fdb_fix_key($key);
109 $path = fdb_get_dir() . "/$key";
110 if(file_exists($path)) {
111 return unlink($path);