--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/addressbook.class.php Tue Oct 25 22:24:36 2011 +0200
@@ -0,0 +1,75 @@
+<?
+interface AdressBook_Interface {
+ public function get_entries();
+ public function search_entries($pattern);
+ public function add_entry($entry);
+}
+
+class AddressBook implements AdressBook_Interface {
+
+ const RS = "\n";
+ const FS = "\t";
+
+ private $fh;
+ private $file;
+
+ function __construct($file) {
+ @mkdir(dirname($file));
+ $this->fh = fopen($file, "a+b");
+ flock($this->fh, LOCK_EX);
+ $stat = fstat($this->fh);
+ if ($stat['size'] == 0) {
+ fputs($this->fh, join(self::FS, array("Hans Hanson", "0815", "hans@hanson.de"))
+ . self::RS);
+ }
+ flock($this->fh, LOCK_SH);
+ fseek($this->fh, 0, SEEK_SET);
+ }
+
+ function get_entries() {
+ $entries = array();
+ fseek($this->fh, 0, SEEK_SET);
+ while($line = stream_get_line($this->fh, 0, self::RS)) {
+ if ($line === FALSE) break;
+ $entries[] = explode(self::FS, $line);
+ }
+ return $entries;
+ }
+
+ function add_entry($entry) {
+ $fields = array('name', 'tel', 'mail');
+
+ $new = array();
+ foreach($fields as $key) {
+ if (!isset($entry[$key])) return false;
+ $new[$key] = trim($entry[$key]);
+ $new[$key] = preg_replace('/['.self::RS.self::FS.' ]+/', ' ', $new[$key]);
+ if (empty($new[$key])) return false;
+ }
+
+ flock($this->fh, LOCK_EX);
+ fputs($this->fh, join(self::FS, $new) . self::RS);
+ flock($this->fh, LOCK_UN);
+
+ return true;
+ }
+
+ function search_entries($pattern) {
+ $pattern = trim($pattern);
+ if (empty($pattern)) return;
+ $pattern = preg_replace('/\//', '\/', $pattern);
+ fseek($this->fh, 0, SEEK_SET);
+ $entries = array();
+ while ($line = stream_get_line($this->fh, 0, self::RS)) {
+ if ($line === FALSE) break;
+ if (!preg_match("/$pattern/i", $line)) continue;
+ $entry = explode(self::FS, $line);
+ $entries[] = array('name' => $entry[0],
+ 'tel' => $entry[1],
+ 'mail' => $entry[2]);
+ }
+ return $entries;
+ }
+}
+
+?>