<?php
/*
 * Mail
 */
class net_Mail {
    protected $to;
    protected $subject = NULL;
    protected $message = NULL;
    protected $headers = array();
    protected $debug = false;

    public function __construct($to = '', $subject = '', $message = '', $headers = NULL) {
        $this->to = $to;
        $this->subject = $subject;
        $this->message = $message;
        if ($headers != NULL) {
            $this->headers = $headers;
        }
    }
	public function setDebug($debug) {
        $this->debug = $debug;
    }
	public function setTo($to) {
        $this->to = $to;
    }
	public function setSubject($subject) {
        $this->subject = $subject;
    }
	public function setMessage($message) {
        $this->message = $message;
    }
	public function addTo($to, $name = NULL) {
        if (! empty($this->to)) {
            $this->to .= ', ';
        }
        if ($name == NULL) {
            $this->to .= $to;
        } else {
            $this->to .= $name . ' <' . $to . '>';
        }
    }
	public function setFrom($from, $name) {
        if ($name == NULL) {
            $this->headers['From'] = $from;
        } else {
            $this->headers['From'] = $name . ' <' . $from . '>';
        }
    }
	public function addHeader($key, $value) {
        if ($value == NULL) {
            unset($this->headers[$key]);
        } else {
            $this->headers[$key] = $value;
        }
    }
	public function send() {
        if ((! array_key_exists('Reply-To', $this->headers)) && array_key_exists('From', $this->headers)) {
            $this->headers['Reply-To'] = $this->headers['From'];
        }
        if (! array_key_exists('MIME-Version', $this->headers)) {
            $this->headers['MIME-Version'] = '1.0';
        }
        if (! array_key_exists('Content-Type', $this->headers)) {
            $this->headers['Content-Type'] = 'text/plain; charset="UTF-8"'; //text/html; charset=UTF-8
        }
        if (count($this->headers) == 0) {
        	if ($this->debug) {
	            echo "<!-- mail($this->to, $this->subject, $this->message) -->";
	            return true;
        	} else {
	            return mail($this->to, $this->subject, $this->message);
        	}
        } else {
            $headers = '';
            foreach ($this->headers as $key => $value) {
                $headers .= $key . ': ' . $value . "\r\n";
            }
        	if ($this->debug) {
	            echo "<!-- mail($this->to, $this->subject, $this->message, $headers) -->";
	            return true;
        	} else {
	            return mail($this->to, $this->subject, $this->message, $headers);
        	}
        }
	}
    public static function emailIsValid($email) {
        $atom = '[-a-z0-9!#$%&\'*+\\/=?^_`{|}~]';
        $domain = '([a-z0-9]([-a-z0-9]*[a-z0-9]+)?)';
        $regex = '/^' . $atom . '+' . '(\.' . $atom . '+)*' .
            '@' . '(' . $domain . '{1,63}\.)+' . $domain . '{2,63}$/i';
        return preg_match($regex, $email);
    }
}
?>