Location: PHPKode > scripts > Email Log > email_log.php
<?php

/**
 * EMail_Log Class
 *
 * @category Pseudo Database Backup Engine
 * @package  WSA/Email/
 * @author   Rodrigo Moraes Orph <hide@address.com>
 * @license  Copyright http://www.overflow.biz/
 *
 *  BSD License:
 *
 *  Copyright (c) 2010, Rodrigo Moraes Orph
 *  All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without modification,
 *  are permitted provided that the following conditions are met:
 *
 *  * Redistributions of source code must retain the above copyright notice, this list
 *    of conditions and the following disclaimer.
 *  * Redistributions in binary form must reproduce the above copyright notice, this
 *    list of conditions and the following disclaimer in the documentation and/or other
 *    materials provided with the distribution.
 *  * Neither the name of the Rodrigo Moraes Orph nor the names of its contributors may be
 *    used to endorse or promote products derived from this software without specific
 *    prior written permission.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 *  ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 *  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 *  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
 *  INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 *  NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 *  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 *  WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 *  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 *  POSSIBILITY OF SUCH DAMAGE.
 * 
 */

require_once("wsa_utf8_conversor.php");

if (file_exists(dirname(__FILE__)."/email_log.vars.php"))
	require_once(dirname(__FILE__)."/email_log.vars.php");

interface iEMail_Log {
	public function read($line, $date);
	public function list_entries();
	public function list_date($date);
	public function add($from, $to, $subject, $body);
	public function save();
	public function json_output($data);
}

class EMail_Log extends WSA_UTF8_Conversor implements iEMail_Log {
	public $base_path = "data/";
	public $date_format = "d-m-Y";
	public $delimiter = "\n";
	public $ipp = 31;
	
	protected $ext = ".db";
	protected $new = array();

	/**
	 * Start up with an optional $base_path value
	 *
	 */
	public function __construct($base_path = null) {
		if ($base_path != null)
			$this->base_path = $base_path;
	}

	/**
	 * Check for pending things before ending the program
	 *
	 */
	public function __destruct() {
		if (!empty($this->new))
			$this->save();
	}

	/**
	 * Reads a single entry on the database
	 *
	 * @param $line int entry line
	 * @param $date date($this->date_format) date
	 *
	 * @return string | false
	 *
	 */
	public function read($line, $date) {
		$date = $this->sanitize($date);
		$fn = $this->base_path . $date . $this->ext;
		$line = intval($line);

		if ($line <= 0 || empty($line))
			return false;
		
		if (file_exists($fn)) {
			$fp = fopen($fn, 'r');
			for ($i = 1;!feof($fp);$i++) {
				$buffer = stream_get_line($fp, 10240, $this->delimiter);
				if ($i == $line) {
					fclose($fp);
					return $buffer;
				}
			}
			fclose($fp);
		}
		
		return false;
	}
	
	/**
	 * List entries starting from a date broken between pages
	 *
	 * @opt param $page int current page
	 * @opt param $startDate date($this->date_format) date
	 *
	 * @return array | false
	 *
	 */
	public function list_entries($page = 0) { //, $startDate = -1) {
		$page = intval($page);
		$r = array();
		
		if ($page < 0 || empty($page))
			$page = 0;
			
		/*
		if ($startDate == -1)
			$startDate = date($this->date_format);
		*/

		$raw = array();
		
		// collect files
		foreach (glob($this->base_path . "*" . $this->ext) as $fn) {
			if (!is_dir($fn) && is_readable($fn) && substr(basename($fn), 0, 1) != ".")
				$raw[] = $fn;
		}
		
		$mdt = array();
		
		// sort by date
		foreach ($raw as $key => $fn)
			$mdt[$key] = filemtime($fn);
			
		arsort($mdt, SORT_NUMERIC);
			
		foreach ($mdt as $key => $md)
			$file[] = $raw[$key];
		
		for (
			$i = $page * $this->ipp,
			$pages = count($file),
			$j = min(($page + 1) * $this->ipp, $pages)
		;$i < $j;$i++)
			$r[] = array(
				"entry" => str_replace($this->ext, "", basename($file[$i])),
				"size"  => filesize($file[$i]),
				"items" => count(file($file[$i]))
			);
			
		return empty($r) ?
				false
			:
				array(
					"pages" => ceil($pages / $this->ipp),
					"items" => $r
				)
		;
	}
	
	public function list_date($date, $page = 0) {
		$date = $this->sanitize($date);
		$fn = $this->base_path . $date . $this->ext;
		$r = array();
		
		if (file_exists($fn) && is_readable($fn)) {
			$file = array_reverse(file($fn));
			
			for (
				$i = $page * $this->ipp,
				$pages = count($file),
				$j = min(($page + 1) * $this->ipp, $pages)
			;$i < $j;$i++) {
				$str = explode("|",$file[$i]);
				
				
				$r[] = array(
					"from"    => $str[0],
					"to"      => $str[1],
					"subject" => base64_encode(utf8_encode(base64_decode($str[2]))),
					"line"    => $pages - $i - 1
				);
			}
		}
		
		return empty($r) ? 
				false
			:
				array(
					"pages" => ceil($pages / $this->ipp),
					"items" => $r
				)
		;
	}
	
	/**
	 * Adds email to $new
	 *
	 * @param $from string email sent from
	 * @param $to string email sent to
	 * @param $subject string email's subject
	 * @param $body string email's body
	 * @opt param $date date($this->date_format) date or null (today)
	 *
	 * @return void
	 *
	 */
	public function add($from, $to, $subject, $body, $date = -1) {
		if ($date == -1)
			$date = date($this->date_format);
		$date = $this->sanitize($date);

		if (!isset($this->new[$date]))
			$this->new[$date] = "";

		$this->new[$date] .= base64_encode($from) . "|" . base64_encode($to) . "|" . base64_encode($subject) . "|" . base64_encode($body) . $this->delimiter;
	}
	
	/**
	 * Saves $new into pseudo database
	 *
	 * @return void
	 *
	 */
	public function save() {
		foreach ($this->new as $date => $val) {
			$fn = $this->base_path . $date . $this->ext;
			if (file_exists($fn) && !is_writable($fn))
				throw new Exception("Can't write to: ".$fn);
			
			file_put_contents(
				$fn,
				$val,
				FILE_APPEND
			);
		}
			
		$this->new = array(); // reset array
		
	}
	
	/**
	 * JSON output data
	 *
	 * @param $data string | array to outout
	 *
	 * @return void
	 *
	 */
	public function json_output($data) {
		if (!is_array($data))
			$data = array("r" => $data);
			
		$data = $this->utf8_encode_array($data);

		header('Content-Type: application/json; charset=utf-8');
		echo json_encode($data);
	}
	
	/**
	 * Sanitizes a filename input
	 *
	 * @param $str string to be sanitized
	 *
	 * @return string
	 *
	 */
	protected function sanitize($str) {
		return preg_replace('/![a-zA-Z0-9\-]*/', '', $str);
	}

}
Return current item: Email Log