<?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
*/

// Fetchmail
// Moregroupware.org

$myEnv["module"] = "webmail2";
$myEnv["stdsmenu"] = false;
$myEnv["output"] = "html";

include("../../config.inc.php");
include(INCLUDEPATH . "container.inc.php");
include(WM2_INC_DIR.'fetchmail_inc.php');

error_reporting  (E_ERROR | E_WARNING | E_PARSE | E_NOTICE);
 
require_once(WM2_INC_DIR.'imap/imap.php');
require_once(WM2_INC_DIR.'class.pop3.php');
require_once(WM2_INC_DIR."rfc822.php");
require_once(INCLUDEPATH . "crypt.inc.php");

$myvars = array("new","account");
foreach ($myvars as $thevar) {
  ${$thevar} = (isset($_GET[$thevar])) ? $_GET[$thevar] : (isset($_POST[$thevar]) ? $_POST[$thevar] : "");
}
$MGW = $_SESSION["MGW"];
$user_id = $MGW->userid;
$username = $MGW->username;

$mysession_vars = array("fetcharr");
foreach ($mysession_vars as $thevar) {
  if (isset($_SESSION["webmail2_fetch_".$thevar])) {
    ${$thevar} = $_SESSION["webmail2_fetch_".$thevar];
  }
}

$users = getallusers2();

if ($new=="yes") {
  $fetcharr = crowdfetcharr();
}

$account = -1;
if (isset($fetcharr) and is_array($fetcharr) and count($fetcharr)>0) {
foreach ($fetcharr as $key=>$key2) {
  if ($account == -1 and $key2[1] == "fetching ...") { $account = $key; }
}
}

$totalsize = 0;
$msg_no = 0;
$spammessages = 0;
$oversize_messages = 0;
$havefetched = 0;
$keepmessages = false;
  
if ($account != -1) {
  $sql = "select * from mgw_webmail2_accounts where mailboxname='".addslashes($fetcharr[$account][0])."' and user_id=".(int)$user_id;
  if(!$res = $conn->Execute($sql)) die(showSQLerror($sql, $conn->ErrorMsg(), __LINE__,__FILE__));
  $row = $res->FetchRow();

  $rules = array();
  $sql = "select * from mgw_webmail2_filters where (account_id=".(int)$row["id"]." or account_id=-1) and user_id=".(int)$user_id;
  if(!$res2 = $conn->Execute($sql)) die(showSQLerror($sql, $conn->ErrorMsg(), __LINE__,__FILE__));
  while ($row2 = $res2->FetchRow()) {
    if ($row2["copy_to_folder"]=="checked") {
	  if ($row2["target_folder"]!="" and is_numeric($row2["target_folder"]) and (boxexist($row2["target_folder"],$user_id) or boxexist($row2["target_folder"],0)) and has_write_rights_mbox($row2["target_folder"],$user_id)) {
	  }	else {
		$row2 = "";
	  }
	}
    if ($row2["copy_to_user"]=="checked") {
	  if ($row2["target_user"]!="" and is_numeric($row2["target_user"]) and isset($users[$row2["target_user"]])) {
	    if (!getboxid("inbox",0,$row2["target_user"])) {
          create_boxes(array(array("inbox",0,$row2["target_user"])));        
		}
	  }	else {
		$row2 = "";
	  }
	}
	if ($row2!="" and ($row2["copy_to_folder"]=="checked" or $row2["copy_to_user"]=="checked" or $row2["mark_as_read"]=="checked" or $row2["mark_as_flagged"]=="checked" or $row2["delete_message"]=="checked" or $row2["change_flag_to"]=="checked")) {
      $rules[] = $row2;
	}
  }

  if ($row["leavemessages"]) {$keepmessages = true;}

  $my_imap = "int";
  $default_protocol = "imap";
  $default_port = "143";

  if ($row["servertype"]=="wm2_servertype_pop3") {
    $my_imap = "ext";
    $default_protocol = "pop3";
    if ($row["enable_ssl"]=="checked") {
      $default_port = "995";
    } else {
    $default_port = "110";
    }
  } elseif($row["servertype"]=="wm2_servertype_imap") {
    if ($row["enable_ssl"]=="checked") {
      $default_port = "993";
    }
  }
  
  $myC = new Crypto();
  $password = $myC->decrypt($username, $row["password"]);
  
  $email = my_imap_connect($my_imap,$default_port,$default_protocol,$row,$password,"INBOX");
  $fetch_host = $row["pophost"];
  $fetch_username = $row["username"];
  
  $imap_conn = $email;

  if (($my_imap=="int" and (!isset($imap_conn_error) or $imap_conn_error=="")) or ($my_imap=="ext" and (!isset($email->error) or $email->error==""))) {
    if ($keepmessages) {
	  $leavemessages = explode(",",$row["leaveoldmails"]);
	}
	$fullmessagecount = my_imap_get_num_messages($email,$imap_conn,$my_imap);
  
	$demo = false;
	
	$to_folder_inbox = getboxid("inbox",0,$user_id);
    $trash_id = getboxid("trash",0,$user_id);
    
    if ($trash_id != "") {
      $to_folder_spam = getboxid("spam",$trash_id,$user_id);
      if ($to_folder_spam == "") {
        create_boxes(array(array("spam",$trash_id,$user_id)));        
        $to_folder_spam = getboxid("spam",$trash_id,$user_id);
      }
    } else {
      create_boxes(array(array("trash",0,$user_id)));        
      $trash_id = getboxid("trash",0,$user_id);

      create_boxes(array(array("spam",$trash_id,$user_id)));        
      $to_folder_spam = getboxid("spam",$trash_id,$user_id);
    }
    
	$to_folder_spam = getboxid("spam",getboxid("trash",0,$user_id),$user_id);

    if ($to_folder_inbox == "") {
  	  $to_folder_inbox = getboxid("inbox",0,$user_id);
      if ($to_folder_inbox == "") {
        create_boxes(array(array("inbox",0,$user_id)));
  	    $to_folder_inbox = getboxid("inbox",0,$user_id);
      }
    }
    
	if ($to_folder_spam == "") {die("Database: Trash/spam doesn't exist !!!");}
	if ($to_folder_inbox == "") {die("Database: Inbox doesn't exist !!!");}

	$popcount = $fullmessagecount;
    while ($popcount!=0) {
      $popcount = $popcount-1;
      $msg_no++;
	  $header = my_imap_header($email,$imap_conn,$my_imap,$msg_no);
	  
	  $header->message_id = getmessage_id($header);

      $oversize = false;
      if (isset($MGW->settings["wm2_fetch_limit"]) and $MGW->settings["wm2_fetch_limit"] != "" and is_numeric($MGW->settings["wm2_fetch_limit"]) and $MGW->settings["wm2_fetch_limit"]!=0 and ($MGW->settings["wm2_fetch_limit"]*1024) < $header->Size) {
        $oversize = true;
      } else {
	  if ($keepmessages) {$newleavemessages[] = str_replace(",",".",$header->message_id);}
      }

	  if (!$keepmessages and !$demo and is_spam_admin($header->fromaddress,$header->subject)) {
		my_imap_delete($email,$imap_conn,$my_imap,$msg_no);
	  } elseif ($demo or (!$oversize and (!$keepmessages or !in_array(str_replace(",",".",$header->message_id),$leavemessages)))) {
	    $havefetched++; 

        if (isset($header->toaddress)) {$header->toaddress=trim($header->toaddress);} else {$header->toaddress="";}
        if (!isset($header->date)) {$header->date="";}
        if (isset($header->fromaddress)) {$header->fromaddress=trim($header->fromaddress);} else {$header->fromaddress="";}
        if (!isset($header->subject)) {$header->subject="";}
        if (isset($header->reply_toaddress)) {$header->reply_toaddress=trim($header->reply_toaddress);} else {$header->reply_toaddress="";}
        if (!isset($header->ccaddress))  {$header->ccaddress=trim($header->ccaddress);} else {$header->ccaddress="";}
        if (!isset($header->priority)) {$header->priority="";}
        if (!isset($header->in_reply_to)) {$header->in_reply_to="";}
        if (isset($header->Size)) {$size = $header->Size;} else {$size = "0";}

		$totalsize = $totalsize + $size;
//		if ($totalsize > 2097152) {$limit=1;}

	    $uid = $header->message_id;

        if (strlen($uid) < 12 or !strpos($uid,"@")) {
          $uid = "<".date("YmdHi").".".substr(ereg_replace("/","X",md5(mt_rand(1,6000))),0,12)."@".$_SERVER["SERVER_NAME"].">";
        }

        if (isset($overview[0]->recent)) {$recent = $overview[0]->recent;} else {$recent = "0";}
        if (isset($overview[0]->flagged)) {$flagged = $overview[0]->flagged;} else {$flagged = "0";}
        if (isset($overview[0]->answered)) {$answered = $overview[0]->answered;} else {$answered = "0";}
        if (isset($overview[0]->draft)) {$draft = $overview[0]->draft;} else {$draft = "0";}

		if ($flagged == 0 and $header->priority!="") {$flagged = $header->priority;}
		
        if (isset($overview[0]->seen)) {$seen = $overview[0]->seen;} else {$seen = "1";}

		$header->subject = str_replace(array("&gt;", "&lt;","&quot;", "&amp;"), array(">","<", "\"", "&"), $header->subject);

	    $msg_id = mgw_genID('mgw__seq_messages');

		if ($msg_id%10000==0) {
		  $dir_nr = $msg_id/10000;
		} else {$dir_nr = 0;}
		checkdir(STORE_FOLDER.$dir_nr."/",false);

		$actname_temp = STORE_FOLDER ."temp-".$user_id.$username.".eml";

		@set_time_limit(0);

		if (my_imap_get_message($email,$imap_conn,$my_imap,$msg_no,$actname_temp)) {
		  $attachbit = 1;
		} else {$attachbit = 0;}
		if (!file_exists($actname_temp)) {die("The E-Mail could not be fetched !!");}
  
		if (!$demo) { 
          mt_srand((double)microtime()*10000);
          $act_name = STORE_FOLDER.$dir_nr. "/" . $msg_id. "-" .date("dmY-His")."-". ereg_replace("/","X",md5(mt_rand(1,6000))).".eml";

		  $filter_store = false;
		  $filter_delete_message = false;
		  
		  $filter_flagged = false;
		  $filter_seen = false;
		  
		  $save_flagged = $flagged;
		  $save_seen = 1;
		  $save_labelbit = 0;
		  
		  if (count($rules)>0) {
		    foreach ($rules as $rule) {
			  if (($rule["spam_flag"]=="checked" and $header->is_spam) or
			      ($rule["match_type"]=="header_subject" and $rule["match_str"]!="" and ($rule["match_str"]=="*all*" or strpos("@".strtolower($header->subject),strtolower($rule["match_str"]))>0)) or
				  ($rule["match_type"]=="header_from" and $rule["match_str"]!="" and ($rule["match_str"]=="*all*" or is_spam2($header->fromaddress,$rule["match_str"]))) or 
				  ($rule["match_type"]=="header_to" and $rule["match_str"]!="" and ($rule["match_str"]=="*all*" or is_spam2($header->toaddress,$rule["match_str"])) )
				) {
			    
			    $seen2 = $seen;
  			    if ($rule["mark_as_read"]=="checked") $seen2 = "0";
			  
			    $flagged2 = $flagged;
  			    if ($rule["mark_as_flagged"]=="checked") $flagged2 = "1";
			  
			    $labelbit2 = 0;
  			    if ($rule["change_flag_to"]=="checked") $labelbit2 = $rule["target_flag"];
			  
			    if ($rule["copy_to_user"]!="checked" and $rule["copy_to_folder"]!="checked") {
				  $save_seen = $seen2;
				  $save_flagged = $flagged2;
				  $save_labelbit = $labelbit2;
				}
			  
  			    if ($rule["copy_to_user"]=="checked") {
			      $rule_to_folder_id = getboxid("inbox",0,$rule["target_user"]);
            	  $sql = "insert into mgw_webmail2_messages (cal_accepted,notified,message_id,account_name,uid,type,mbox_id,header_from,header_to,header_cc,header_replyto,header_date,header_subject,header_size,header_inreplyto,msg_body,recentbit,readbit,replybit,draftbit,flaggedbit,forwardbit,attachbit,labelbit) values('0','0',".(int)mgw_genID('mgw__seq_messages').",'".addslashes($fetch_username."@".$fetch_host)."','".addslashes($uid)."','eml',".(int)$rule_to_folder_id.",'".addslashes(decode_mime_string($header->fromaddress))."','".addslashes(decode_mime_string($header->toaddress))."','".addslashes(decode_mime_string($header->ccaddress))."','".addslashes(decode_mime_string($header->reply_toaddress))."','".addslashes($header->date)."','".addslashes(decode_mime_string($header->subject))."','".addslashes($size)."','".addslashes(decode_mime_string($header->in_reply_to))."','".addslashes($act_name)."','".addslashes($recent)."','".addslashes($seen2)."','".addslashes($answered)."','".addslashes($draft)."','".addslashes($flagged2)."','0','".addslashes($attachbit)."','".addslashes($labelbit2)."')";
		    	  if(!$res = $conn->Execute($sql)) die(showSQLerror($sql, $conn->ErrorMsg(), __LINE__,__FILE__));
				  $filter_store = true;
			    }

  			    if ($rule["copy_to_folder"]=="checked") {
			      $rule_to_folder_id = $rule["target_folder"];
            	  $sql = "insert into mgw_webmail2_messages (cal_accepted,notified,message_id,account_name,uid,type,mbox_id,header_from,header_to,header_cc,header_replyto,header_date,header_subject,header_size,header_inreplyto,msg_body,recentbit,readbit,replybit,draftbit,flaggedbit,forwardbit,attachbit,labelbit) values('0','0',".(int)mgw_genID('mgw__seq_messages').",'".addslashes($fetch_username."@".$fetch_host)."','".addslashes($uid)."','eml',".(int)$rule_to_folder_id.",'".addslashes(decode_mime_string($header->fromaddress))."','".addslashes(decode_mime_string($header->toaddress))."','".addslashes(decode_mime_string($header->ccaddress))."','".addslashes(decode_mime_string($header->reply_toaddress))."','".addslashes($header->date)."','".addslashes(decode_mime_string($header->subject))."','".addslashes($size)."','".addslashes(decode_mime_string($header->in_reply_to))."','".addslashes($act_name)."','".addslashes($recent)."','".addslashes($seen2)."','".addslashes($answered)."','".addslashes($draft)."','".addslashes($flagged2)."','0','".addslashes($attachbit)."','".addslashes($labelbit2)."')";
		    	  if(!$res = $conn->Execute($sql)) die(showSQLerror($sql, $conn->ErrorMsg(), __LINE__,__FILE__));
				  $filter_store = true;
			    }
			  
			    if ($rule["delete_message"]) {
				  $filter_delete_message = true;
				}
			  }
		    }
		  }

		  if (!$filter_delete_message) {
		    $to_folder_id = $to_folder_inbox;
            $sql = "insert into mgw_webmail2_messages (cal_accepted,notified,message_id,account_name,uid,type,mbox_id,header_from,header_to,header_cc,header_replyto,header_date,header_subject,header_size,header_inreplyto,msg_body,recentbit,readbit,replybit,draftbit,flaggedbit,forwardbit,attachbit,labelbit) values('0','0',".(int)$msg_id.",'".addslashes($fetch_username."@".$fetch_host)."','".addslashes($uid)."','eml',".(int)$to_folder_id.",'".addslashes(decode_mime_string($header->fromaddress))."','".addslashes(decode_mime_string($header->toaddress))."','".addslashes(decode_mime_string($header->ccaddress))."','".addslashes(decode_mime_string($header->reply_toaddress))."','".addslashes($header->date)."','".addslashes(decode_mime_string($header->subject))."','".addslashes($size)."','".addslashes(decode_mime_string($header->in_reply_to))."','".addslashes($act_name)."','".addslashes($recent)."','".addslashes($save_seen)."','".addslashes($answered)."','".addslashes($draft)."','".addslashes($save_flagged)."','0','".addslashes($attachbit)."','".addslashes($save_labelbit)."')";
		    if(!$res = $conn->Execute($sql)) die(showSQLerror($sql, $conn->ErrorMsg(), __LINE__,__FILE__));
			$filter_store = true;
		  }
		  
		  if ($filter_store) rename($actname_temp,$act_name);
		    else unlink($actname_temp);
		}
		
		if (!$keepmessages and !$demo and !$oversize) {
		  my_imap_delete($email,$imap_conn,$my_imap,$msg_no);
		}
	  } elseif ($oversize) {
        $oversize_messages++;
	  }
    }
	my_imap_close($email,$imap_conn,$my_imap);

	$newleaves = "";
	if (isset($newleavemessages) and is_array($newleavemessages)) {
	  foreach ($newleavemessages as $newleave) {
	    if ($newleave!="") {
	      if ($newleaves!="") {$newleaves .= ",";}
	      $newleaves .= $newleave;
	    }
	  }
	}

	if ($keepmessages and !$demo) {
      $sql = "update mgw_webmail2_accounts set leaveoldmails='".addslashes($newleaves)."' where user_id=".(int)$user_id." and mailboxname='".addslashes($fetcharr[$account][0])."'";
      if(!$res = $conn->Execute($sql)) die(showSQLerror($sql, $conn->ErrorMsg(), __LINE__,__FILE__));
	}
	$fetcharr[$account][2] = "OK";
  } else {
    if (isset($imap_conn_error)) {$error = $imap_conn_error;} else {$error = $email->error;}
	$fetcharr[$account][2] = $error;
  }
  $fetcharr[$account][1] = "finished";
}

$fetcharr[$account][3] = $msg_no; // = $fullmessagecount
$fetcharr[$account][4] = $keepmessages;
$fetcharr[$account][5] = $havefetched;
$fetcharr[$account][6] = $spammessages;
$fetcharr[$account][7] = $totalsize;
$fetcharr[$account][8] = $oversize_messages;

$smarty->assign("myimgpathmaster", "templates/default/media");


$fetcher = $fetcharr;
foreach ($fetcher as $key=>$key2) {
  if ($key != -1) {
    if ($fetcher[$key][1]=="disabled") {$fetcher[$key][2] = '<font color="#000080">'.$hashmap["fetchmail_disabled"].'</font>';}
    if ($fetcher[$key][2]=="OK") {$fetcher[$key][2] = '<font color="#008000">'.$hashmap["maillist_ok"].'</font>';}
    if ($fetcher[$key][2]=="failed" or $fetcher[$key][2]=="failed (invalid username/password" or $fetcher[$key][2]=="failed (invalid hostname)") {
      $fetcher[$key][2] = '<font color="#ff0000"><b>'.$fetcher[$key][2].'</b></font>';
    }
    if ($fetcher[$key][4]) {$fetcher[$key][4] = $hashmap["fetchmail_left_on_server"];} else {$fetcher[$key][4] = "";}

      $addon = "";
      if (isset($fetcher[$key][8]) and $fetcher[$key][8] != 0) {
        $addon = "<br>(<b>".$fetcher[$key][8]."</b> ".$hashmap["fetchmail_were_oversize"].")";
      }
      if ($fetcher[$key][3] != $fetcher[$key][5]) {
        $fetcher[$key][5] = "<b>".$fetcher[$key][5]."</b> / ".$fetcher[$key][3]." ".$hashmap["fetchmail_fetched"]."<br>(<b>".$fetcher[$key][6]."</b> ".$hashmap["fetchmail_were_spam"].")".$addon;
      } else {
        $fetcher[$key][5] = "<b>".$fetcher[$key][5]."</b> ".$hashmap["fetchmail_fetched"]."<br>(<b>".$fetcher[$key][6]."</b> ".$hashmap["fetchmail_were_spam"].")".$addon;
      }
    $fetcher[$key][7] = format_filesize($fetcher[$key][7]);
  }
}

if ($account == -1) {
  $smarty->assign("fetchmessage", $hashmap["fetchmail_redirect_to_inbox"]);

  $smarty->assign("fetcharr", $fetcher);
  $smarty->display("fetchmail.tpl");

  $_SESSION["webmail2_fetch_fetcharr"] = "";
  unset($_SESSION["webmail2_fetch_fetcharr"]);
  
  $trash_id = getboxid("trash",0,$user_id);
  $to_folder_spam = getboxid("spam",$trash_id,$user_id);

  $mbox_id_inbox = getboxid("inbox",0,$user_id);
  relocate("this.location","index2.php?account=0&reload=fulltree&mbox_id=".(int)$mbox_id_inbox."&".SID,$MGW->settings["wm2_waittime"]*1000);
  die;
}

$_SESSION["webmail2_fetch_fetcharr"] = $fetcharr;

$smarty->assign("fetcharr", $fetcher);
$smarty->display("fetchmail.tpl");
relocate("top.rightframe.location","fetchmail.php?".SID,0);

?>
