3 # This program is in the public domain within the United States. Additionally,
4 # we waive copyright and related rights in the work worldwide through the CC0
5 # 1.0 Universal public domain dedication, which can be found at
6 # http://creativecommons.org/publicdomain/zero/1.0/
9 # This file contains code to use a web-writeable directory full of files as a
10 # very simple database.
12 # Keys are truncated to 32 bytes, made lowercase, and all characters that are
13 # not alpha/numeric are replaced with underscores. Periods and hyphens are only
14 # replaced if they are at the begining.
16 # Data can be either a string or an array.
18 # To set up the database, make a directory that's writeable by PHP and call
19 # fdb_set_dir() passing the path to that directory.
22 require_once(__DIR__.'/'.'file.php');
23 require_once(__DIR__.'/'.'binary.php');
25 # call this to set what directory is used to store the files
26 function fdb_set_dir($dir) {
27 $GLOBALS['fdb_dir'] = $dir;
30 function fdb_get_dir() {
31 if(!isset($GLOBALS['fdb_dir'])) {
32 die('you must call fdb_set_dir() before calling other functions in wfpl/fdb.php');
34 return $GLOBALS['fdb_dir'];
38 function fdb_fix_key($key) {
39 $key = preg_replace('|[^a-z0-9.-]|', '_', strtolower($key));
40 $key = preg_replace('|^[-.]|', '_', strtolower($key));
41 return substr($key, 0, 32);
45 function fdb_get_raw($key) {
46 $key = fdb_fix_key($key);
47 return read_whole_file_or_false(fdb_get_dir() . "/$key");
50 function fdb_set_raw($key, $data) {
51 $key = fdb_fix_key($key);
52 write_whole_file(fdb_get_dir() . "/$key", $data);
55 # like fdb_get() except it returns an array even when there's just one element
56 function fdb_geta($key) {
57 $key = fdb_fix_key($key);
58 $data = fdb_get_raw($key);
62 return raw_to_array($data);
67 # false if the key is not found in the database
69 # an array from the file otherwise
71 # a string if there's one field in that file (use fdb_geta() if you want an
72 # array in this case too)
73 function fdb_get($key) {
74 $ret = fdb_geta($key);
78 if(count($ret) == 1) {
85 # data can be a string or array
86 function fdb_set($key, $data) {
87 $key = fdb_fix_key($key);
88 if(!is_array($data)) {
91 fdb_set_raw($key, array_to_raw($data));
94 function fdb_delete($key) {
95 $key = fdb_fix_key($key);
96 $path = fdb_get_dir() . "/$key";
97 if(file_exists($path)) {