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