<?php
/*
This file is part of Thomas Bley's moregroupware webmail2/calendar2/admin2 module. (tb-mgw)

More information:
-----------------

Simple Groupware Solutions Thomas Bley
Fichtenstr. 23
Germany, 85640 Putzbrunn

Contact:
--------

info@simple-groupware.de

http://www.simple-groupware.de


Copyright 2002-2003 Thomas Bley
tb-mgw is distributed under the terms of the GNU General Public License 

tb-mgw 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; either version 2 of the License, or
(at your option) any later version.

tb-mgw 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 tb-mgw; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*/

// Sendmail_post-inc
// Moregroupware.org

function getallusers3() {
  global $conn;
  $sql = "select email,username from mgw_users";
  if(!$res = $conn->Execute($sql)) die(showSQLerror($sql, $conn->ErrorMsg(), __LINE__,__FILE__));
  $users = array();
  while ($row = $res->FetchRow()) {
    $users[$row["username"]] = strtolower($row["email"]);
  }
  return $users;
}

function show_webmail_error ($message,$myarray) {
  global $smarty;

  if (is_array($myarray) and count($myarray)!=0) {
	foreach($myarray as $item) {$message .= " ".$item;}
  }
  $smarty->assign("waittime", "1000");
  $smarty->assign("message", $message);
	
  $smarty->display("sendmail_post.tpl");
  die;	  
}

function get_group_members ($key) {
  global $conn,$users;
  $result = array();
  $sql = "select userid from mgw_groups_members where groupid=".(int)$key;
  if(!$res = $conn->Execute($sql)) die(showSQLerror($sql, $conn->ErrorMsg(), __LINE__,__FILE__));
  while ($row = $res->FetchRow()) {
    if (isset($users[$row["userid"]])) {
      $result[$row["userid"]] = $users[$row["userid"]];
    }
  }
  return $result;
}

function get_group_members_contacts ($key) {
  global $conn,$users,$user_id;
  $result = array();

  if (isModuleInstalled("contact")) {
  $sql = "select email from mgw_contacts where groupid=".(int)$key." and email<>'' and (ispublic=1 or owner=".(int)$user_id.") order by lastname";
  if(!$res = $conn->Execute($sql)) die(showSQLerror($sql, $conn->ErrorMsg(), __LINE__,__FILE__));
  while ($row = $res->FetchRow()) {
    $result[$row["email"]] = $row["email"];
  }

  $sql = "select email from mgw_companies where groupid=".(int)$key." and email<>'' and (ispublic=1 or owner=".(int)$user_id.") order by name1";
  if(!$res = $conn->Execute($sql)) die(showSQLerror($sql, $conn->ErrorMsg(), __LINE__,__FILE__));
  while ($row = $res->FetchRow()) {
    $result[$row["email"]] = $row["email"];
  }
  }

  return $result;
}

function add_adr_to_arr(&$arr) {
  global $users, $users2, $groups, $groups_contacts;
  global $tolocalarrgroup, $tolocalarr, $togroup_contacts;
  
  foreach ($arr as $key=>$key2) {
    if ($key2 != "") {
      if ($key2[0] == "@") {
        $key2 = substr(strtolower($key2),1);
        if (in_array($key2,$groups) and !in_array($key2,$tolocalarrgroup)) {
          
		  if (isset($_SESSION["MGW"]->settings["wm2_disable_local_send"]) and $_SESSION["MGW"]->settings["wm2_disable_local_send"]) {
		    $members = get_group_members(array_search($key2,$groups));
		    foreach ($members as $key3=>$key4) {
			  if (isset($users2[$key4])) $arr[] = $users2[$key4];
		    }
		    unset($arr[$key]);
		  } else {
          $tolocalarrgroup[array_search($key2,$groups)] = $key2;
          unset($arr[$key]);
		  }
        } else if (in_array($key2,$groups_contacts) and !in_array($key2,$togroup_contacts)) {
          $togroup_contacts[array_search($key2,$groups_contacts)] = $key2;
          unset($arr[$key]);
        } else if (in_array($key2,$groups) and in_array($key2,$tolocalarrgroup)) {
          unset($arr[$key]);
        }
      } else {
        $key2 = strtolower($key2);
        if (in_array($key2,$users) and !in_array($key2,$tolocalarr)) {

		  if (isset($_SESSION["MGW"]->settings["wm2_disable_local_send"]) and $_SESSION["MGW"]->settings["wm2_disable_local_send"]) {
		    $arr[$key] = $users2[$key2];
		  } else {
          $tolocalarr[array_search($key2,$users)] = $key2;
          unset($arr[$key]);
		  }
        } elseif (in_array($key2,$users) and in_array($key2,$tolocalarr)) {
          unset($arr[$key]);
        }
      }
    }
  }
}

function make_str_from_arr_adr($arr) {
  $str = "";
  foreach ($arr as $key=>$key2) {
    if ($str != "") {$str .= ", ";}
    $str .= $key2;
  }
  return $str;
}

function make_array_adr($str) {

  $result = array();
  if ($str != "") {
    $arr = explode(",",$str);
    foreach ($arr as $key=>$key2) {
      $result[] = getmailadr(trim($key2));
    }
  }
  return $result;
}

function getallgroups2() {
  global $conn;
  $sql = "select name,id from mgw_groups";
  if(!$res = $conn->Execute($sql)) die(showSQLerror($sql, $conn->ErrorMsg(), __LINE__,__FILE__));
  $groups = array();
  while ($row = $res->FetchRow()) {
    $groups[$row["id"]] = strtolower($row["name"]);
  }
  return $groups;
}

function getallgroups2_contacts() {
  global $conn;
  $groups = array();

  if (isModuleInstalled("contact")) {
  $sql = "select name_key,id from mgw_contacts_groups";
  if(!$res = $conn->Execute($sql)) die(showSQLerror($sql, $conn->ErrorMsg(), __LINE__,__FILE__));
  while ($row = $res->FetchRow()) {
    $groups[$row["id"]] = strtolower($row["name_key"]);
  }
  }
  return $groups;
}

function delete_open_attachments($webmail_sendmail_temp_dir) {
  $handle=opendir($webmail_sendmail_temp_dir);
  while ($file = readdir($handle)) {
    $file1 = strstr($file,session_id());
    if ($file1) {
      if (file_exists($webmail_sendmail_temp_dir.$file)) {
        unlink($webmail_sendmail_temp_dir.$file);
      }
    } 
  }
  closedir($handle);
}

function writetofile_sendmail($act_name,$body,$feed="\n") {
  global $mail_attachments;

  $fd = fopen($act_name, "wb");

  if (count($mail_attachments)!=0) {
    $data2 = explode($feed,$body);

    foreach ($data2 as $line) {
      if (in_array($line,$mail_attachments) and file_exists($line)) {

        $filename = basename($line);
        $ext = strtolower(substr($line,-strpos(strrev($line),'.')));

        if($fp = fopen($line, 'rb')){
          while(!feof($fp)){
            $line3 = fread($fp, 1440);
            if ($ext!="eml" and $ext!="ics" and $ext!="vcs" and $filename!="rfc822") {
              $line3 = rtrim(chunk_split(base64_encode($line3), 72, $feed));
            }
		    $result = fwrite($fd, $line3.$feed);
	  	  }
		  fclose($fp);
        }
      } else {
        fwrite($fd, $line.$feed);
      }
    }
  } else {                
    fwrite($fd, $body);
  }
  fclose($fd);
}

function check_pop_sendmail($row,$saveto,$i) {
  global $back_button,$hashmap,$password;
  if ($row["popbeforesmtp"]=="checked" and $saveto != "draft" and $i != 0) {
    require_once(WM2_INC_DIR.'class.pop3.php');
    $email = new pop3();

    if (!$email->connect($row["pophost"]) ) {	show_webmail_error($back_button.$hashmap["sendmail_popbeforesmtpfailed_host"],""); }
    if (!$email->user($row["username"]) or $email->pass($password)<0){ show_webmail_error($back_button.$hashmap["sendmail_popbeforesmtpfailed_userpwd"],""); }
  }
}

function add_attachments_sendmail() {
  global $webmail_sendmail_temp_dir,$mail,$attaches;

  $attaches = 0;
  $handle=opendir($webmail_sendmail_temp_dir);
  while ($file = readdir($handle)) {
    $file1 = strstr($file,session_id());
    if ($file1) {
      $attach_name = urldecode(substr(strstr($file,"######"),6));
//	  $attachment = $mail->get_file($webmail_sendmail_temp_dir.$file);
	  $ext = strtolower(substr($attach_name,-strpos(strrev($attach_name),'.')));
	  if ($ext=="vcs") {
	    $mail->add_attachment($webmail_sendmail_temp_dir.$file, $attach_name, 'text/calendar', '7bit');
	  } elseif ($ext=="ics") {
	    $mail->add_attachment($webmail_sendmail_temp_dir.$file, $attach_name, 'text/calendar', '7bit','');
	  } elseif ($attach_name=="rfc822" or $ext=="eml") {
	    $mail->add_attachment($webmail_sendmail_temp_dir.$file, '', 'message/rfc822', '7bit');
	  } else {
        $attaches++;
	    $image_types = array(
		  'gif'   => 'image/gif',
		  'jpg'	  => 'image/jpeg',
		  'jpeg'  => 'image/jpeg',
		  'jpe'	  => 'image/jpeg',
		  'bmp'	  => 'image/bmp',
	      'png'	  => 'image/png',
	      'tif'	  => 'image/tiff',
		  'tiff'  => 'image/tiff',
		  'swf'	  => 'application/x-shockwave-flash'
	    );
        if (isset($image_types[$ext])) { $mime_type = $image_types[$ext]; } else {$mime_type = 'application/zip';}
        // $attachment
        $mail->add_attachment($webmail_sendmail_temp_dir.$file, $attach_name, $mime_type);
	  }
    }
  }
  closedir($handle);
}

function add_to_replied($replyto2,$msg_id,$to22) {
  global $conn;
  
  $sql = "select replied from mgw_webmail2_messages where message_id=".(int)$replyto2;
  if(!$res = $conn->Execute($sql)) die(showSQLerror($sql, $conn->ErrorMsg(), __LINE__,__FILE__));
  $row2 = $res->FetchRow();

  if (!isset($row2["replied"]) or $row2["replied"]=="") { $replied = "'".time().";#;".$to22.";#;".$msg_id.";@;'"; } else { $replied = $conn->concat("'".time().";#;".$to22.";#;".$msg_id.";@;'","replied");}

  $sql = "update mgw_webmail2_messages set replybit=1,replied=".$replied." where message_id=".(int)$replyto2;
  if(!$res = $conn->Execute($sql)) die(showSQLerror($sql, $conn->ErrorMsg(), __LINE__,__FILE__));
}

function add_to_forwarded($forward,$msg_id,$to22) {
  global $conn;
  
  $sql = "select forwarded from mgw_webmail2_messages where message_id=".(int)$forward;
  if(!$res = $conn->Execute($sql)) die(showSQLerror($sql, $conn->ErrorMsg(), __LINE__,__FILE__));
  $rowforward = $res->FetchRow();

  if (!isset($rowforward["forwarded"]) or $rowforward["forwarded"]=="") { $forwarded = "'".time().";#;".$to22.";#;".$msg_id.";@;'"; } else { $forwarded = $conn->concat("'".time().";#;".$to22.";#;".$msg_id.";@;'","forwarded");}

  $sql = "update mgw_webmail2_messages set forwardbit=1,forwarded=".$forwarded." where message_id=".(int)$forward;
  if(!$res = $conn->Execute($sql)) die(showSQLerror($sql, $conn->ErrorMsg(), __LINE__,__FILE__));
}

function assign_rec_arrays($var1,$var2) {
  global ${$var1},${$var2};

  foreach (${$var1} as $key=>$key2) {
    $members = get_group_members($key);
    foreach ($members as $key3=>$key4) {
      if (!in_array($key4,${$var2})) { ${$var2}[$key3] = $key4; }
    }
  }
}

function assign_rec_arrays_contacts($var1,$var2) {
  global ${$var1},${$var2};

  foreach (${$var1} as $key=>$key2) {
    $members = get_group_members_contacts($key);
    foreach ($members as $key3=>$key4) {
      if (!in_array($key4,${$var2})) { ${$var2}[$key3] = $key4; }
    }
  }
}

?>
