<?php
  /*

      mail.php

      Set of mail functions.

      ----
      
      Copyright (C) 2005  1stBnA GmbH
      Copyright (C) 2005  Stephan Kaufhold (s.kauhold@1stbna.com)

      This program is free software; you can redistribute it and/or
      modify it under the terms of the GNU General Public License
      as published by the Free Software Foundation version 2.

      This program is distributed in the hope that it will be useful,
      but WITHOUT ANY WARRANTY; without even the implied warranty of
      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
      GNU General Public License for more details.

      You should have received a copy of the GNU General Public License
      along with this program; if not, write to the Free Software
      Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.

  */

  require_once 'system/db.php';
  require_once 'system/lang.php';

  $mailtemplate['verify']   = "mail_verifyemail.tpl";
  $mailtemplate['assign']   = "mail_assignissue.tpl";
  $mailtemplate['remark']   = "mail_remark.tpl";
  $mailtemplate['newissue'] = "mail_newissue.tpl";
  $mailtemplate['resolve']  = "mail_resolveissue.tpl";

  function send_mail($which, $language, $recipient, $id, $user, $message)
  {
    global $mailtemplate;
    if (!$mailtemplate[$which]) return;
    
    // Find if templates exists for language
    $template = get_template_path($mailtemplate[$which]);
    if (!file_exists($template)) {
      unset($template);
    }

    if ($template) {
      if ($fp = fopen($template,"r")) {
        $repl = false;
        $https = 'http'.($_SERVER['HTTPS'] ? 's' : '');
        $dirname = dirname($_SERVER['PHP_SELF']);
        if (substr($dirname,-1) != '/') $dirname .= '/';
  
        if ($which == "verify") {
          $link = "$https://{$_SERVER['HTTP_HOST']}{$dirname}verifyemail.php?id=$message";
        } else {
          $link = "$https://{$_SERVER['HTTP_HOST']}{$dirname}issue.php?id=$id";
        }
  
        if ($which == "remark" && file_exists(get_template_path("mail_message.inc"))) {
           include get_template_path("mail_message.inc");
          
           //echo "msg:#$message#<br />\n";
           $message = stripslashes($message);
           if ($msg_pattern && $msg_replace) {
             $message = preg_replace($msg_pattern, $msg_replace, $message);
           }
           $repl = true;
        }
  
        $header_search = true;
  
        while ($line = fgets($fp)) {
          if ($header_search) {
            $pos = strpos($line, ';');
            if ($pos !== false) {
              $line = substr($line, 0, $pos);
            }

            $line = trim($line);
            
            if ($line == "<MAILBODY>") {
              $header_search = false;
            } else {
              $pos = strpos($line, '=');
              if ($pos !== false) {
                list($key,$value) = split("=", $line, 2);
                $key = rtrim($key);
                $value = ltrim($value);
                $mailopts[strtolower($key)] = "$value";
              }
            }
          } else {
            // Parse Mailbody
            //echo "$line<br>";
            $line = str_replace('%%ISSUE%%',"$id",$line);
            $line = str_replace('%%SITEURL%%',"$https://{$_SERVER['HTTP_HOST']}/",$line);
            $line = str_replace('%%LINK%%',"$link",$line);
            $line = str_replace('%%USER%%',"$user",$line);
            $line = str_replace('%%MESSAGE%%',"$message",$line);
            $line = str_replace('%%DOMAIN%%',"$_SESSION[_domainname]",$line);
            $body .= $line;
            //echo "$line<br>";
          }
          
          $line = "";  
        }
        
        fclose($fp);
      } 

      if ($mailopts['subject']) {
        $mailopts['subject'] =
          str_replace('%%ISSUE%%',"$id",$mailopts['subject']);
        $mailopts['subject'] = 
          str_replace('%%DOMAIN%%',"$_SESSION[_domainname]",$mailopts['subject']);
      }
    
      if (! $mailopts['charset']) {
        $mailopts['charset'] = "utf-8";
      }
    
    // Checking for attachements

//     $mailopts['signature'] = mk_bool($mailopts['signature']);
//     $mailopts['issue'] = mk_bool($mailopts['issue']);
    
      if (mk_bool($mailopts['signature']) == true) {
        if ($fp = fopen(get_template_path("mail_signature.tpl"), "r")) {
          while ($line = fgets($fp)) {
            $body .= $line;
          }
          fclose($fp);
        }
      }
      
      if (mk_bool($mailopts['issue']) == true) {
        $times = db_recordset('SELECT SUM(time) AS totaltime FROM tbl_Times,'.
          'tbl_Users WHERE tbl_Times.userid = tbl_Users.id AND '.
          'tbl_Times.issue = ' . $id);

        $issue = db_recordset("SELECT * FROM vw_Issues WHERE id=$id");
        $issue = $issue[0];  

        if (file_exists(get_template_path("mail_issue.inc"))) {
          include get_template_path("mail_issue.inc");
        }

         if ((!$repl) && (file_exists(get_template_path("mail_message.inc")))) {
          include get_template_path("mail_message.inc");
        }

        $issuetxt = 
          "{$translation['issueid']}: #$id\n".
          "{$translation['createdbyname']}: {$issue['createdbyname']}\n".
          "{$translation['reportedbyname']}: {$issue['reportedbyname']}\n".
          "{$translation['sitename']}: {$issue['sitename']}\n".
          "{$translation['assignedtoname']}: {$issue['assignedtoname']}\n".
          "{$translation['contact']}: {$issue['contact']}\n".
          "{$translation['location']}: {$issue['location']}\n".
          "{$translation['categoryname']}: ";
        if ($msg_pattern && $msg_replace) {
          $issuetxt .= preg_replace($msg_pattern, $msg_replace, $issue['categoryname'])."\n";
        } else {
          $issuetxt .= $issue['categoryname']."\n";
        }
    
        $issuetxt .= "{$translation['detailname']}: ";
        if ($msg_pattern && $msg_replace) {
           $issuetxt .= preg_replace($msg_pattern, $msg_replace, $issue['detailname'])."\n";
        } else {
          $issuetxt .= $issue['detailname']."\n";
        }
        $issuetxt .= 
          "{$translation['summary']}:\n".add_tab("  ", $issue['summary'])."\n".
          "{$translation['description']}:\n".add_tab("  ", $issue['description'])."\n".
          "{$translation['solution']}:\n".add_tab("  ", $issue['solution'])."\n".
          "{$translation['totaltime']}: {$times[0]['totaltime']}\n".
          "{$translation['priorityname']}: {$issue['priorityname']}\n".
          "{$translation['statusname']}: {$issue['statusname']}\n".
          "{$translation['levelname']}: {$issue['levelname']}\n";

      
        if ($mailopts['remarks']) {
          $issuetxt .= "\n<{$translation['tagremarks']}>\n";
          $remarks = db_recordset(
            "SELECT tbl_Remarks.*,tbl_Users.name AS reportedbyname FROM tbl_Remarks,tbl_Users".
            " WHERE tbl_Remarks.issue=" . $id . " AND tbl_Remarks.reportedby=tbl_Users.id ".
            "AND tbl_Remarks.confidential=0 ORDER BY tbl_Remarks.reportedon DESC"
            );
          foreach ($remarks as $mark) {
            $issuetxt .= "\n------------------------\n";
            $issuetxt .= strftime('%d/%m/%y  %H:%M',$mark[reportedon]). " : ".
              $mark[reportedbyname]. "\n";
            if ($repl) {
                $remark = $mark[remark];
                if ($msg_pattern && $msg_replace) {
                    $remark = preg_replace($msg_pattern, $msg_replace, $remark);
                }
                $issuetxt .= add_tab("  ", $remark);
            }
          
          }
          $issuetxt .= "\n</{$translation['tagremarks']}>\n";
        }
      }
//     foreach ($mailopts as $key => $value)
//     {
//       print "Key: #$key# value: #$value#<br>\n";
//     }
  
      $body =  "Content-Type: text/plain;\n".
        " charset=\"utf-8\"\n".
        "Content-Transfer-Encoding: base64\n\n".
        chunk_split(base64_encode($body));

      //echo nl2br($body);

      $headers = "MIME-Version: 1.0\n".
        "Content-Type: multipart/mixed;\n".
        " boundary=\"----=_NextPart_001_0011_1234ABCD.4321FDAC\";\n".
        " charset=\"us-ascii\"\n".
        "Content-Transfer-Encoding: 7bit\n".
        "X-Mailer: Heldesk V0.9.1\n";
        
      if ($mailopts['sender']) {
        $pos = strpos($mailopts['sender'], '<');
        if ($pos !== false) {
          $mailopts['sender'] =
            str_replace('%%DOMAIN%%',"$_SESSION[_domainname]",$mailopts['sender']);
          if ($mailopts['fcharset']) {
            $headers .= "From: ";
            $sender = preg_replace('/.*<(.+)>.*/', '\1', $mailopts['sender']);
            $sname  = trim(preg_replace('/(.*)<.+>.*/', '\1', $mailopts['sender']));
            $pos = strpos($mailopts['sender'], '(', $pos);
            if ($pos !== false) {
              $scomment = 
                trim(preg_replace('/.*<.+>.*\((.+)\).*/', '\1', $mailopts['sender']));
            }
            if ($sname) {
              //echo "$sname<br />\n";
              $headers .= 
              encode($sname, $mailopts['fcharset']) . "\r\n  ";
            }
          
            //echo "$sender<br />\n";
            $headers .= "<" . $sender .">";
        
            if ($scomment) {
              // echo "$scomment<br />\n";
              $headers .= 
                "(\r\n  " .
                encode($scomment, $mailopts['fcharset']) .
                ")\n";
            }
          } else {
            $headers .= "From: ".$mailopts['sender']."\n";
          }
         } else {
           $headers .= 
             "From: [$_SESSION[_domainname]] <".$mailopts['sender'].">\n";
          $sender = $mailopts['sender'];
        }
      } else {
        $headers .= 
          "From: [$_SESSION[_domainname]] <no-reply>\n";
      }

      $message =
        "This is a multi-part message in MIME format.\n\n".
        "------=_NextPart_001_0011_1234ABCD.4321FDAC\n".
        $body;
      
      if ($issuetxt) {
        $message .=  
          "\n------=_NextPart_001_0011_1234ABCD.4321FDAC\n".
          "Content-Type: text/plain;\n".
          " charset=\"utf-8\"\n";

        if ($mailopts['issuefile'])  {
          $message .=  
            "Content-Disposition: attachment;\n".
            "\tfilename=\"$_SESSION[_domainname]_#$id#.txt\"\n";
        }

        $message .=
          "Content-Transfer-Encoding: base64\n\n".
          chunk_split(base64_encode($issuetxt)).
          "\n\n------=_NextPart_001_0011_1234ABCD.4321FDAC--\n";
      } else {
        $message .=  
          "------=_NextPart_001_0011_1234ABCD.4321FDAC--\n";
      }

      if ($mailopts['scharset']) {
        $mailopts['subject'] = encode($mailopts['subject'], $mailopts['scharset']);
      }

      if ($sender) {
        mail($recipient, $mailopts['subject'], $message, $headers, "-f ".$sender);
      } else {
         mail($recipient, $mailopts['subject'], $message, $headers);
      }
    }
  }


  function mk_bool($str)
  {
    if ($str) {
      $str = strtolower($str);
      if (($str == "1") || ($str == "on") || ($str == "yes")) {
        $str = true;
      } else {
        $str = false;
      }
    } else {
      $str = false;
    }  

    return $str;
  } 

  function add_tab($add, $str)
  {
    $res = "";
    if ($str) {
      $res = preg_replace('/(\n)/','\1'.$add,$str);
      $res = $add . $res;
    }

    return $res;
  }

  function encode($in_str, $charset)
  {
    $out_str = $in_str;
    
    if ($out_str && $charset) {
      // define start delimimter, end delimiter and spacer
      $end = "?=";
      $start = "=?" . $charset . "?B?";

      // determine length of encoded text within chunks
      // and ensure length is even
      $length = 50 - strlen($start) - strlen($end);
      $length = floor($length/2) * 2;

      // split it into chunks and encode the string
      // with spacers after each chunk
      $out_str = chunk_split($out_str, $length, "\n");
      $out_arr = split("\n",$out_str);
      $ii = 0;
      $out_str = "";
      foreach($out_arr as $str) {
        if ($str) {
          if ($ii > 0) {
            $out_str .= "\r\n  ";
          }
          $out_str .= $start . base64_encode($str) . $end;
          $ii++;
        } 
      }
    }
    return $out_str;
  }

?>