class.Address_Book_File.php
changeset 18 846026b8422b
parent 11 fb55da5ecb8a
equal deleted inserted replaced
17:56308e61381c 18:846026b8422b
     1 <?
     1 <?
     2 require "interface.Address_Book.php";
     2 require_once "interface.Address_Book.php";
     3 
     3 
     4 class Address_Book_File implements Address_Book {
     4 class Address_Book_File implements Address_Book {
     5 	const RS = "\n";
     5 	const RS = "\n";
     6 	const FS = "\t";
     6 	const FS = "\t";
     7 
     7 
    35 	public function add_entry($entry) {
    35 	public function add_entry($entry) {
    36 		$fields = array('name', 'tel', 'mail');
    36 		$fields = array('name', 'tel', 'mail');
    37 		$new = array();
    37 		$new = array();
    38 		foreach($fields as $key) {
    38 		foreach($fields as $key) {
    39 			if (!isset($entry[$key])) return;
    39 			if (!isset($entry[$key])) return;
    40 			$new[$key] = $entry[$key];
    40 			$new[$key] = trim($entry[$key]);
    41 			trim($new[$key]);
    41 			$new[$key] = preg_replace('/['.self::RS.self::FS.' ]+/', ' ', $new[$key]);
    42 			preg_replace('/['.self::RS.self::FS.' ]+/', ' ', $new[$key]);
       
    43 			if (empty($new[$key])) return;
    42 			if (empty($new[$key])) return;
    44 		}
    43 		}
    45 
    44 
    46 		flock($this->fh, LOCK_EX);
    45 		flock($this->fh, LOCK_EX);
    47 		fputs($this->fh, join(self::FS, $new) . self::RS);
    46 		fputs($this->fh, join(self::FS, $new) . self::RS);
    48 		flock($this->fh, LOCK_UN);
    47 		flock($this->fh, LOCK_UN);
    49 		header("Location: $_SERVER[PHP_SELF]?action=add");
       
    50 		exit;
       
    51 	}
    48 	}
    52 
    49 
    53 	public function search_entries($pattern) {
    50 	public function search_entries($pattern) {
       
    51 		$pattern = trim($pattern);
       
    52 		if (empty($pattern)) return array();
    54 		fseek($this->fh, 0, SEEK_SET);
    53 		fseek($this->fh, 0, SEEK_SET);
       
    54 		$pattern = preg_replace('|/|', '\/', $pattern);
    55 		$entries = array();
    55 		$entries = array();
    56 		while ($line = stream_get_line($this->fh, 0, self::RS)) {
    56 		while ($line = stream_get_line($this->fh, 0, self::RS)) {
    57 			if ($line === FALSE) break;
    57 			if ($line === FALSE) break;
    58 			if (!preg_match("/$pattern/i", $line)) continue;
    58 			if (!preg_match("/$pattern/i", $line)) continue;
    59 			$entry = explode(self::FS, $line);
    59 			$entry = explode(self::FS, $line);