add handling for mails that have no valid recipient when we try to send them
[php-utility-classes.git] / include / classes / email.php-class
index 0ea1698b3a5fc26ab18f8def1e84915e1498d5c8..c7e1ee4f657e3d95fef5d852bde131b84267f09f 100755 (executable)
 <?php
+/* ***** BEGIN LICENSE BLOCK *****
+ *
+ * The contents of this file are subject to Austrian copyright reegulations
+ * ("Urheberrecht"); you may not use this file except in compliance with
+ * those laws.
+ * This contents and any derived work, if it gets distributed in any way,
+ * is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND,
+ * either express or implied.
+ *
+ * The Original Code is KaiRo's E-Mail module.
+ *
+ * The Initial Developer of the Original Code is
+ * KaiRo - Robert Kaiser.
+ * Portions created by the Initial Developer are Copyright (C) 2003-2006
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s): Robert Kaiser <kairo@kairo.at>
+ *
+ * ***** END LICENSE BLOCK ***** */
+
 class email {
   // email PHP class
   // class/object for creating a new mail and send it
   //
-  // function email()
+  // function __construct()
   //   CONSTRUCTOR
   //
-  // var $debug_toSingleAddress
+  // private $debug_toSingleAddress
   //   address to send mail to in debug mode
   //
-  // var $subject
+  // private $subject
   //   the mail's subject line
   //
-  // var $sender
+  // private $sender
   //   the mail's sender (array; fields see recipients)
   //
-  // var $replyto
+  // private $replyto
   //   Reply-to address (array; fields see recipients)
   //
-  // var $recipients
+  // private $recipients
   //   array of recipients (To: line)
   //   fields: name - real name
   //           mail - email address
   //
-  // var $cc
+  // private $cc
   //   array of CC recipients (fields like recipients)
   //
-  // var $bcc
+  // private $bcc
   //   array of BCC recipients (fields like recipients)
   //
-  // var $headers
+  // private $headers
   //   array containing all additional headers
   //   fields: name - headers name
   //           content - header content
   //
-  // var $content_type
+  // private $content_type
   //   the mail's content type (MIME-type) [default: text/plain]
   //
-  // var $charset
+  // private $charset
   //   the mail's charset [default: iso-8859-15]
   //
-  // var $mailtext
+  // private $mailtext
   //   the main mail body
   //
-  // var $attachments
+  // private $attachments
   //   array containing all attachments
   //   fields: name - attachment name
   //           content - attachment content
   //           type - MIME type of that attachment
   //
-  // function setDebugAddress($debug_email)
+  // public function setDebugAddress($debug_email)
   //   debug mode: send only to this address
   //
-  // function setSubject($newsubject)
+  // public function setSubject($newsubject)
   //   set subject of mail
   //
-  // function setSender($email, [$name])
+  // public function setSender($email, [$name])
   //   set sender of mail
   //
-  // function setReplyTo($email, [$name])
+  // public function setReplyTo($email, [$name])
   //   set reply-to address
   //
-  // function addRecipient($email, [$name])
+  // public function addRecipient($email, [$name])
   //   add a recipient to the mail
   //
-  // function addCC($email, [$name])
+  // public function addCC($email, [$name])
   //   add a CC recipient to the mail
   //
-  // function addBCC($email, [$name])
+  // public function addBCC($email, [$name])
   //   add a BCC recipient to the mail
   //
-  // function addHeader($hname, [$hcontent])
+  // public function addHeader($hname, [$hcontent])
   //   add a header to the mail
   //
-  // function addMailText($textpart)
+  // public function addHeaderAddress($hname, $email, [$name])
+  //   add an address header to the mail, possibly with both name and mail parts
+  //
+  // public function addMailText($textpart)
   //   add some text to the mail
   //
-  // function send()
+  // public function addAttachment($aname, $acontent, [$atype])
+  //   add an attachment to the mail, use given file name, content and MIME type (defaults to application/octet-stream)
+  //
+  // public function send()
   //   really send the mail
   //
-  // function mimeencode($fieldtext)
+  // private function mimeencode($fieldtext, [$stringescape])
   //   helper function:
-  //   encode given field text, ready to be placed into an e-mail MIME header
-
-  var $debug_toSingleAddress = "";
-  var $subject;
-  var $sender = array();
-  var $replyto = array();
-  var $recipients = array();
-  var $cc = array();
-  var $bcc = array();
-  var $headers = array();
-  var $content_type = "text/plain";
-  var $charset = "iso-8859-15";
-  var $mailtext = "";
-  var $attachments = array();
-
-  function email() {
+  //     encode given field text, ready to be placed into an e-mail MIME header
+  //     if the boolean $stringescape is true, make sure this is sent as a single word in RFC2822 context (e.g. for names)
+  //     see http://www.ietf.org/rfc/rfc2822.txt for the RFC in question
+
+  private $debug_toSingleAddress = '';
+  private $subject;
+  private $sender = array();
+  private $replyto = array();
+  private $recipients = array();
+  private $cc = array();
+  private $bcc = array();
+  private $headers = array();
+  private $content_type = 'text/plain';
+  private $charset = 'iso-8859-15';
+  private $mailtext = '';
+  private $attachments = array();
+
+  function __construct() {
     // *** constructor ***
   }
 
-  function setDebugAddress($debug_email) { $this->debug_toSingleAddress = $debug_email; }
+  public function setDebugAddress($debug_email) { $this->debug_toSingleAddress = $debug_email; }
 
-  function setSubject($newsubject) { $this->subject = $newsubject; }
+  public function setSubject($newsubject) { $this->subject = $newsubject; }
 
-  function setSender($email, $name = "") { $this->sender = array("mail" => $email, "name" => $name); }
+  public function setSender($email, $name = '') { $this->sender = array('mail' => $email, 'name' => $name); }
 
-  function setReplyTo($email, $name = "") { $this->replyto = array("mail" => $email, "name" => $name); }
+  public function setReplyTo($email, $name = '') { $this->replyto = array('mail' => $email, 'name' => $name); }
 
-  function addRecipient($email, $name = "") {
-    $this->recipients[] = array("mail" => $email, "name" => $name);
+  public function addRecipient($email, $name = '') {
+    $this->recipients[] = array('mail' => $email, 'name' => $name);
   }
 
-  function addCC($email, $name = "") {
-    $this->cc[] = array("mail" => $email, "name" => $name);
+  public function addCC($email, $name = '') {
+    $this->cc[] = array('mail' => $email, 'name' => $name);
   }
 
-  function addBCC($email, $name = "") {
-    $this->bcc[] = array("mail" => $email, "name" => $name);
+  public function addBCC($email, $name = '') {
+    $this->bcc[] = array('mail' => $email, 'name' => $name);
   }
 
-  function addHeader($hname, $hcontent = "") {
-    $this->headers[] = array("name" => $hname, "content" => $hcontent);
+  public function addHeader($hname, $hcontent = '') {
+    $this->headers[] = array('name' => $hname, 'content' => $hcontent);
   }
 
-  function addMailText($textpart) { $this->mailtext .= $textpart; }
+  public function addHeaderAddress($hname, $email, $name = '') {
+    if (strlen($name)) { $hcontent = $this->mimeencode($name, true).' <'.$email.'>'; }
+    else { $hcontent = $email; }
+    $this->headers[] = array('name' => $hname, 'content' => $hcontent);
+  }
+
+  public function addMailText($textpart) { $this->mailtext .= $textpart; }
 
-  function addAttachment($aname, $acontent, $atype = "application/octet-stream") {
-    $this->attachments[] = array("name" => $aname, "content" => $acontent, "type" => $atype);
+  public function addAttachment($aname, $acontent, $atype = 'application/octet-stream') {
+    $this->attachments[] = array('name' => $aname, 'content' => $acontent, 'type' => $atype);
   }
 
-  function send() {
+  public function send() {
     global $util;
-    $mtxt = "";
-    $hdrs = "MIME-Version: 1.0\n";
+    $mtxt = '';
+    $hdrs = 'MIME-Version: 1.0'."\n";
     $subj = $this->mimeencode($this->subject);
-    if (strlen($this->sender["name"])) {
-      $hdrs .= "From: ".$this->mimeencode($this->sender["name"])." <".$this->sender["mail"].">\n";
+    if (strlen($this->sender['name'])) {
+      $hdrs .= 'From: '.$this->mimeencode($this->sender['name'], true).' <'.$this->sender['mail'].'>'."\n";
     }
-    else { $hdrs .= "From: ".$this->sender["mail"]."\n"; }
+    else { $hdrs .= 'From: '.$this->sender['mail']."\n"; }
     if (count($this->replyto)) {
-      if (strlen($this->replyto["name"])) {
-        $hdrs .= "Reply-to: ".$this->mimeencode($this->replyto["name"])." <".$this->replyto["mail"].">\n";
+      if (strlen($this->replyto['name'])) {
+        $hdrs .= 'Reply-to: '.$this->mimeencode($this->replyto['name'], true).' <'.$this->replyto['mail'].'>'."\n";
       }
-      else { $hdrs .= "Reply-to: ".$this->replyto["mail"]."\n"; }
+      else { $hdrs .= 'Reply-to: '.$this->replyto['mail']."\n"; }
     }
     if (count($this->recipients)) {
-      $recpt = "";
+      $recpt = '';
       foreach ($this->recipients as $address) {
-        if (strlen($address["name"])) { $recpt .= $this->mimeencode($address["name"])." <".$address["mail"].">,"; }
-        else { $recpt .= $address["mail"].","; }
+        if (strlen(@$address['mail'])) {
+          if (strlen($address['name'])) { $recpt .= $this->mimeencode($address['name'], true).' <'.$address['mail'].'>,'; }
+          else { $recpt .= $address['mail'].','; }
+        }
       }
-      $recpt = ereg_replace(",$", "", $recpt);
+      $recpt = preg_replace('/,$/', '', $recpt);
+    }
+    if (!strlen($recpt)) {
+      return null;
     }
     if (count($this->cc)) {
-      $adrs = "";
+      $adrs = '';
       foreach ($this->cc as $address) {
-        if (strlen($address["name"])) { $adrs .= $this->mimeencode($address["name"])." <".$address["mail"].">,"; }
-        else { $adrs .= $address["mail"].","; }
+        if (strlen($address['name'])) { $adrs .= $this->mimeencode($address['name'], true).' <'.$address['mail'].'>,'; }
+        else { $adrs .= $address['mail'].','; }
       }
-      $adrs = ereg_replace(",$", "", $adrs);
-      $hdrs .= (strlen($this->debug_toSingleAddress)?"X-Real-":"")."Cc: $adrs\n";
+      $adrs = preg_replace('/,$/', '', $adrs);
+      $hdrs .= (strlen($this->debug_toSingleAddress)?'X-Real-':'').'Cc: '.$adrs."\n";
     }
     if (count($this->bcc)) {
-      $adrs = "";
+      $adrs = '';
       foreach ($this->bcc as $address) {
-        if (strlen($address["name"])) { $adrs .= $this->mimeencode($address["name"])." <".$address["mail"].">,"; }
-        else { $adrs .= $address["mail"].","; }
+        if (strlen($address['name'])) { $adrs .= $this->mimeencode($address['name'], true).' <'.$address['mail'].'>,'; }
+        else { $adrs .= $address['mail'].','; }
       }
-      $adrs = ereg_replace(",$", "", $adrs);
-      $hdrs .= (strlen($this->debug_toSingleAddress)?"X-Real-":"")."Bcc: $adrs\n";
+      $adrs = preg_replace('/,$/', '', $adrs);
+      $hdrs .= (strlen($this->debug_toSingleAddress)?'X-Real-':'').'Bcc: '.$adrs."\n";
     }
     if (count($this->headers)) {
       foreach ($this->headers as $header) {
-        $hdrs .= $header["name"].": ".$header["content"]."\n";
+        $hdrs .= $header['name'].': '.$header['content']."\n";
       }
     }
     if (count($this->attachments)) {
-      $boundary = "KaiRoJVPSteyr1030713";
-      $hdrs .= "Content-Type: multipart/mixed; boundary=\"$boundary\";\n";
-      $hdrs .= "Content-Transfer-Encoding: 7bit\n";
-      $mtxt .= "This part of the E-mail should never be seen. If\n";
-      $mtxt .= "you are reading this, consider upgrading your e-mail\n";
-      $mtxt .= "client to a MIME-compatible client.\n";
-      $mtxt .= "--$boundary\n";
-      if (ereg("text/.*", $this->content_type)) {
-        $mtxt .= "Content-Type: ".$this->content_type."; charset=\"".$this->charset."\"\n";
+      // create random boundary, 20 chars, always beginning with KaiRo ;-)
+      $boundary = 'KaiRo';
+      for ($i = 1; $i <= 15; $i++)     {
+        $r = rand(0, 61);
+        if ($r < 10) { $boundary .= chr($r + 48); }
+        elseif ($r < 36) { $boundary .= chr($r + 55); }
+        elseif ($r < 62) { $boundary .= chr($r + 61); }
+      }
+      $hdrs .= 'Content-Type: multipart/mixed; boundary="'.$boundary.'";'."\n";
+      $hdrs .= 'Content-Transfer-Encoding: 7bit'."\n";
+      $mtxt .= 'This part of the E-mail should never be seen. If'."\n";
+      $mtxt .= 'you are reading this, consider upgrading your e-mail'."\n";
+      $mtxt .= 'client to a MIME-compatible client.'."\n";
+      $mtxt .= "\n".'--'.$boundary."\n";
+      if (preg_match('|^text/|', $this->content_type)) {
+        $mtxt .= 'Content-Type: '.$this->content_type.'; charset="'.$this->charset.'"'."\n";
       }
       else {
-        $mtxt .= "Content-Type: ".$this->content_type."\n";
+        $mtxt .= 'Content-Type: '.$this->content_type."\n";
       }
-      $mtxt .= "Content-Transfer-Encoding: 8bit\n\n";
+      $mtxt .= 'Content-Transfer-Encoding: 8bit'."\n\n";
     }
     else {
-      if (ereg("text/.*", $this->content_type)) {
-        $hdrs .= "Content-Type: ".$this->content_type."; charset=\"".$this->charset."\"\n";
+      if (preg_match('|^text/|', $this->content_type)) {
+        $hdrs .= 'Content-Type: '.$this->content_type.'; charset="'.$this->charset.'"'."\n";
       }
       else {
-        $hdrs .= "Content-Type: ".$this->content_type."\n";
+        $hdrs .= 'Content-Type: '.$this->content_type."\n";
       }
-      $hdrs .= "Content-Transfer-Encoding: 8bit\n";
+      $hdrs .= 'Content-Transfer-Encoding: 8bit'."\n";
     }
     $mtxt .= stripslashes($this->mailtext);
     if (count($this->attachments)) {
       foreach ($this->attachments as $attach) {
-        $mtxt .= "--$boundary\n";
-        $mtxt .= "Content-Type: ".$attach["type"]."; name=\"".$attach["name"]."\";\n";
-        $mtxt .= "Content-Transfer-Encoding: base64\n";
-        $mtxt .= "Content-Disposition: attachment\n\n";
-        $mtxt .= rtrim(chunk_split(base64_encode($attach["content"]), 76)); ;
-        $mtxt .= "\n";
+        $mtxt .= "\n".'--'.$boundary."\n";
+        $mtxt .= 'Content-Type: '.$attach['type'].'; name="'.$attach['name'].'";'."\n";
+        if (preg_match('/^(text|message)\//', $attach['type'])) {
+          $mtxt .= 'Content-Transfer-Encoding: 8bit'."\n";
+          $mtxt .= 'Content-Disposition: attachment'."\n\n";
+          $mtxt .= $attach['content'];
+          $mtxt .= "\n";
+        }
+        else {
+          $mtxt .= 'Content-Transfer-Encoding: base64'."\n";
+          $mtxt .= 'Content-Disposition: attachment'."\n\n";
+          $mtxt .= rtrim(chunk_split(base64_encode($attach['content']), 76)); ;
+          $mtxt .= "\n";
+        }
       }
-      $mtext .= "--$boundary--\n";
+      $mtxt .= '--'.$boundary.'--'."\n";
     }
 
     if (strlen($this->debug_toSingleAddress)) {
-      $hdrs .= "X-Real-To: $recpt\n";
+      $hdrs .= 'X-Real-To: '.$recpt."\n";
       $recpt = $this->debug_toSingleAddress;
     }
 
-    //print("Subject: ".$util->htmlify($subj)."<br>\n");
-    //print("To: ".$util->htmlify($recpt)."<br>\n");
+    //print('Subject: '.$util->htmlify($subj).'<br>'."\n");
+    //print('To: '.$util->htmlify($recpt).'<br>'."\n");
     //print(nl2br($util->htmlify($hdrs)));
     //print(nl2br($util->htmlify($mtxt)));
-    mail($recpt, $subj, $mtxt, $hdrs);
+    return mail($recpt, $subj, $mtxt, $hdrs);
   }
 
-  function mimeencode($fieldtext) {
+  private function mimeencode($fieldtext, $stringescape = false) {
     $mText = imap_8bit($fieldtext);
-    if ($mText != $fieldtext) {
-      $trans = array("_" => "=5F", " " => "_", "?" => "=3F");
-      $mText = strtr($mText, $trans);
-      $mText = "=?ISO-8859-15?Q?".$mText."?=";
+    $is_qpformat = ($mText != $fieldtext);
+    if ($stringescape && preg_match('/[^\w !#$%&\'*+\/=?^`{|}~-]/', $mText)) {
+      // if needed, make this a quoted-string instead of an atom (to speak in RFC2822 language)
+      $mText = '"'.strtr($mText, array('"' => '\"', '\\' => '\\\\')).'"';
+    }
+    if ($is_qpformat) {
+      $mText = strtr($mText, array('_' => '=5F', ' ' => '_', '?' => '=3F'));
+      $mText = '=?'.strtoupper($this->charset).'?Q?'.$mText.'?=';
     }
   return $mText;
   }