|
1 <? |
|
2 require_once "interface.Address_Book.php"; |
|
3 |
|
4 class Address_Book_File implements Address_Book { |
|
5 const RS = "\n"; |
|
6 const FS = "\t"; |
|
7 |
|
8 private $fh; |
|
9 public function __construct($file) { |
|
10 @mkdir(dirname($file)); |
|
11 $this->fh = fopen($file, "a+b"); |
|
12 if (!$this->fh) { |
|
13 throw new Exception("Oooops, Problem mit $file"); |
|
14 } |
|
15 flock($this->fh, LOCK_EX); |
|
16 $stat = fstat($this->fh); |
|
17 if ($stat['size'] == 0) { |
|
18 fputs($this->fh, join(self::FS, array("Hans Hanson", "0815", "hans@hanson.de")) |
|
19 . self::RS); |
|
20 } |
|
21 flock($this->fh, LOCK_SH); |
|
22 fseek($this->fh, 0, SEEK_SET); |
|
23 } |
|
24 |
|
25 public function get_all_entries() { |
|
26 $entries = array(); |
|
27 fseek($this->fh, 0, SEEK_SET); |
|
28 while($line = stream_get_line($this->fh, 0, self::RS)) { |
|
29 if ($line === FALSE) break; |
|
30 $entries[] = explode(self::FS, $line); |
|
31 } |
|
32 return $entries; |
|
33 } |
|
34 |
|
35 public function add_entry($entry) { |
|
36 $fields = array('name', 'tel', 'mail'); |
|
37 $new = array(); |
|
38 foreach($fields as $key) { |
|
39 if (!isset($entry[$key])) return; |
|
40 $new[$key] = trim($entry[$key]); |
|
41 $new[$key] = preg_replace('/['.self::RS.self::FS.' ]+/', ' ', $new[$key]); |
|
42 if (empty($new[$key])) return; |
|
43 } |
|
44 |
|
45 flock($this->fh, LOCK_EX); |
|
46 fputs($this->fh, join(self::FS, $new) . self::RS); |
|
47 flock($this->fh, LOCK_UN); |
|
48 } |
|
49 |
|
50 public function search_entries($pattern) { |
|
51 $pattern = trim($pattern); |
|
52 if (empty($pattern)) return array(); |
|
53 fseek($this->fh, 0, SEEK_SET); |
|
54 $pattern = preg_replace('|/|', '\/', $pattern); |
|
55 $entries = array(); |
|
56 while ($line = stream_get_line($this->fh, 0, self::RS)) { |
|
57 if ($line === FALSE) break; |
|
58 if (!preg_match("/$pattern/i", $line)) continue; |
|
59 $entry = explode(self::FS, $line); |
|
60 $entries[] = array('name' => $entry[0], |
|
61 'tel' => $entry[1], |
|
62 'mail' => $entry[2]); |
|
63 } |
|
64 return $entries; |
|
65 } |
|
66 |
|
67 public function delete_entries($ids) { } |
|
68 } |
|
69 |
|
70 ?> |