3 # Copyright (C) 2007 Jason Woofenden
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.
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.
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/>.
19 # This file contains code to use a web-writeable directory full of files as a
20 # very simple database.
22 # Keys are truncated to 32 bytes, made lowercase, and all characters that are
23 # not alpha/numeric are replaced with underscores. Periods and hyphens are only
24 # replaced if they are at the begining.
26 # Data can be either a string or an array.
28 # To set up the database, make a directory that's writeable by PHP and call
29 # fdb_set_dir() passing the path to that directory.
32 require_once('code/wfpl/file.php');
33 require_once('code/wfpl/binary.php');
35 # call this to set what directory is used to store the files
36 function fdb_set_dir($dir) {
37 $GLOBALS['fdb_dir'] = $dir;
40 function fdb_get_dir() {
41 if(!isset($GLOBALS['fdb_dir'])) {
42 die('you must call fdb_set_dir() before calling other functions in code/wfpl/fdb.php');
44 return $GLOBALS['fdb_dir'];
48 function fdb_fix_key($key) {
49 $key = ereg_replace('[^a-z0-9.-]', '_', strtolower($key));
50 $key = ereg_replace('^[-.]', '_', strtolower($key));
51 return substr($key, 0, 32);
55 function fdb_get_raw($key) {
56 $key = fdb_fix_key($key);
57 return read_whole_file_or_false(fdb_get_dir() . "/$key");
60 function fdb_set_raw($key, $data) {
61 $key = fdb_fix_key($key);
62 write_whole_file(fdb_get_dir() . "/$key", $data);
65 # like fdb_get() except it returns an array even when there's just one element
66 function fdb_geta($key) {
67 $key = fdb_fix_key($key);
68 $data = fdb_get_raw($key);
72 return raw_to_array($data);
77 # false if the key is not found in the database
79 # an array from the file otherwise
81 # a string if there's one field in that file (use fdb_geta() if you want an
82 # array in this case too)
83 function fdb_get($key) {
84 $ret = fdb_geta($key);
88 if(count($ret) == 1) {
95 # data can be a string or array
96 function fdb_set($key, $data) {
97 $key = fdb_fix_key($key);
98 if(!is_array($data)) {
101 fdb_set_raw($key, array_to_raw($data));
104 function fdb_delete($key) {
105 $key = fdb_fix_key($key);
106 $path = fdb_get_dir() . "/$key";
107 if(file_exists($path)) {
108 return unlink($path);