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

// Imap
// Moregroupware.org


/**
 * imap.php
 *
 * Copyright (c) 1999-2002 The SquirrelMail Project Team
 * Licensed under the GNU GPL. For full terms see the file COPYING.
 *
 * This just includes the different sections of the imap functions.
 * They have been organized into these sections for simplicity sake.
 *
 */

function my_imap_header($email,$imap_conn,$my_imap,$msg_no) {
  $header = my_imap_get_headers($email,$imap_conn,$my_imap,$msg_no);
  return $header;
}

function my_imap_delete($email,$imap_conn,$my_imap,$msg_no) {
  if ($my_imap=="ext") {
	$email->delete($msg_no);
	//    @imap_delete($email->mbox, $msg_no);
  } else {
	sqimap_messages_delete($imap_conn, $msg_no, $msg_no, 'INBOX');
  }
}

function my_imap_close($email,$imap_conn,$my_imap) {
  if ($my_imap=="ext") {
	$email->quit();
    // @imap_close($email->mbox,CL_EXPUNGE);
  } else {
    sqimap_mailbox_expunge ($imap_conn, 'INBOX', false);
    sqimap_logout($imap_conn);
  }
}

function my_imap_connect($my_imap,$default_port,$default_protocol,$row,$password,$boxname) {
global $imap_conn_error;

  if ($my_imap=="ext") {
	$email = new pop3();
	if (! $email->connect($row["pophost"],$default_port) ) { $email->error = "failed (invalid hostname)"; } else {
	  if(!$email->user($row["username"]) or $email->pass($password)<0){ $email->error = "failed (invalid username/password)"; }
	  /*
	  $count = $myPOP3->apop($webmailSettings["pop3account"], $webmailSettings["pop3pw"]);
	  if ( $count < 0 ) {
  		$error_msg .= "Failed to login to POP server<br><small>$pop3->ERROR</small>";
  		echo "<b>$error_msg</b><p>";
	  }
	  */
    }
	return $email;
  } else {
	$imap_conn_error = "";
	$imap_conn = sqimap_login($row["username"], $password, $row["pophost"], $default_port, 0);
	if ($imap_conn_error=="") {
	  sqimap_mailbox_select($imap_conn, $boxname);
	}
	return $imap_conn;
  }
}

function my_imap_get_num_messages($email,$imap_conn,$my_imap) {

  if ($my_imap=="ext") {
	$popcount = 0;
	if(!$statArray = $email->popstat()) {
	  die("Fehler. No pop3 connect.");
	}
    $popcount = $statArray[0];
  } else {
	$popcount = sqimap_get_num_messages ($imap_conn,'INBOX');
  }
  return $popcount;
}
	
function my_imap_get_message($email,$imap_conn,$my_imap,$msg_no,$filename) {

  if ($my_imap=="ext") {
    $email2 = $email->get($msg_no,$filename);
	if ($email->ERROR!="") die("Fehler: ".$email->ERROR);
	return $email2;
  } else {
    $sid = sqimap_session_id();
    fputs ($imap_conn, $sid . ' ' . "FETCH ".$msg_no." BODY[]" . "\r\n");
    sqimap_read_data_list2($imap_conn, $sid, true, $a, $b, "FETCH ".$msg_no." BODY[]",$filename);
    $structure = sqimap_get_message($imap_conn, $msg_no);

    if (eregi("\"attachment\"",$structure)) { $email2 = true;} else {$email2 = false;}
    
	return $email2;
  }
}

class msg_header {
    /** msg_header contains generic variables for values that **/
    /** could be in a header.                                 **/

    var $type0 = '', $type1 = '', $boundary = '', $charset = '',
        $encoding = '', $size = 0, $to = array(), $from = '', $date = '',
        $cc = array(), $bcc = array(), $reply_to = '', $subject = '',
        $id = 0, $mailbox = '', $description = '', $filename = '',
        $entity_id = 0, $message_id = 0, $name = '', $priority = 3, $type = '';
}

function quoteIMAP($str) {
    return ereg_replace('(["\\])', '\\\\1', $str);
}

function my_imap_get_headers($email,$imap_conn,$my_imap,$msgs) {

  $msg_list[0] = $msgs;
  
  $maxmsg = sizeof($msg_list);
  $results = array();
  $read_list = array();
  $sizes_list = array();

  if ($my_imap=="int") {
    $sid = sqimap_session_id();
    $msgs_str = sqimap_message_list_squisher($msg_list);

    $query = "$sid FETCH $msgs_str BODY.PEEK[HEADER.FIELDS (Date To From Cc Subject Message-Id X-Priority Content-Type In-Reply-To Reply-To X-Spam-Flag X-Spam-Status)]\r\n";
    fputs ($imap_conn, $query);
    $readin_list = sqimap_read_data_list($imap_conn, $sid, true, $response, $message);
  
    for ($i = 0; $i < sizeof($msg_list); $i++) {
      $id2index[$msg_list[$i]] = $i;
    }

    foreach ($readin_list as $r) {
      if (!eregi("^\\* ([0-9]+) FETCH", $r[0], $regs)) {
        echo '<br><b><font color=$color[2]>' ."ERROR : Could not complete request." .'</b><br>' . "Unknown response from IMAP server: " . ' 1.' .$r[0] . "</font><br>\n";
      } else if (! isset($id2index[$regs[1]]) || !count($id2index[$regs[1]])) {
        echo '<br><b><font color=$color[2]>' ."ERROR : Could not complete request." .'</b><br>' . "Unknown message number in reply from server: " . $regs[1] . "</font><br>\n";
      } else {
        $read_list[$id2index[$regs[1]]] = $r;
      }
    }

    $query = "$sid FETCH $msgs_str RFC822.SIZE\r\n";
    fputs ($imap_conn, $query);
    $sizesin_list = sqimap_read_data_list($imap_conn, $sid, true, $response, $message);

    foreach ($sizesin_list as $r) {
      if (!eregi("^\\* ([0-9]+) FETCH", $r[0], $regs)) {
        echo "<br><b><font color=$color[2]>\n"."ERROR : Could not complete request."."</b><br>\n"."Unknown response from IMAP server: " . ' 2.'.$r[0] . "</font><br>\n";
        exit;
      }
      if (!count($id2index[$regs[1]])) {
        echo "<br><b><font color=$color[2]>\n"."ERROR : Could not complete request."."</b><br>\n"."Unknown messagenumber in reply from server: ".$regs[1] . "</font><br>\n";
        exit;
      }
      $sizes_list[$id2index[$regs[1]]] = $r;
    }
  } else {
  	$read_list[] = $email->top($msgs, 0);
  }
  
  for ($msgi = 0; $msgi < $maxmsg; $msgi++) {
    $subject = "(no subject)";
    $from = "Unknown Sender";
    $priority = 0;
    $messageid = "<>";
    $cc = "";
    $to = "";
    $date = "";
    $type[0] = "";
    $type[1] = "";
    $inrepto = "";
    $replyto = "";
    $is_spam = false;
    $read = $read_list[$msgi];

    $prevline = false;
	foreach ($read as $read_part) {
      //unfold multi-line headers
      while ($prevline && strspn($read_part, "\t ") > 0) {
        $read_part = substr($prevline, 0, -2) . ' ' . ltrim($read_part);
      }
      $prevline = $read_part;
      if (eregi ("^to:(.*)$", $read_part, $regs)) {
        $to = $regs[1];
      } else if (eregi ("^from:(.*)$", $read_part, $regs)) {
        $from = $regs[1];
      } else if (eregi ("^x-priority:(.*)$", $read_part, $regs)) {
        $priority = trim($regs[1]);
      } else if (eregi ("^message-id:(.*)$", $read_part, $regs)) {
        $messageid = trim($regs[1]);
      } else if (eregi ("^cc:(.*)$", $read_part, $regs)) {
        $cc = $regs[1];
      } else if (eregi ("^date:(.*)$", $read_part, $regs)) {
        $date = $regs[1];
      } else if (eregi ("^reply-to:(.*)$", $read_part, $regs)) {
        $replyto = $regs[1];
      } else if (eregi ("^subject:(.*)$", $read_part, $regs)) {
        $subject = htmlspecialchars(trim($regs[1]));
        if ($subject == "") { $subject = "(no subject)"; }
      } else if (eregi ("^content-type:(.*)$", $read_part, $regs)) {
        $type = strtolower(trim($regs[1]));
        if ($pos = strpos($type, ";")) { $type = substr($type, 0, $pos); }
        $type = explode("/", $type);
        if (!isset($type[1])) { $type[1] = ''; }
      } else if (eregi ("^in-reply-to:(.*)$", $read_part, $regs)) {
        $inrepto = trim($regs[1]);
      } else if (eregi ("^x-spam-flag:(.*)$", $read_part, $regs)) {
	    if (strtolower(trim($regs[1]))=="yes") {
          $is_spam = true;
		}
      } else if (eregi ("^x-spam-status:(.*)$", $read_part, $regs)) {
	    $regs[1] = trim($regs[1]);
		if (strlen($regs[1])>3) $regs[1] = substr($regs[1],0,3);
	    if (strtolower($regs[1])=="yes") {
          $is_spam = true;
		}
      }
    }

	if ($my_imap=="int") {
      eregi("([0-9]+)[^0-9]*$", $sizes_list[$msgi][0], $regs);
      $size = $regs[1];
    } else { $size = $email->pop_list($msgs); }
	
	if ($date!="") {
      $date = getTimeStamp(explode(' ', trim(str_replace('  ', ' ', $date))));
	} else {$date = time();}
//      $messages[$j]['DATE_STRING'] = 	getDateString();
// echo getDateString($date);

    $header->fromaddress = $from;
    $header->date = $date;
    $header->subject = $subject;
    $header->toaddress = $to;
    $header->reply_toaddress = $replyto;

	if (is_array($priority) and count($priority)>0) {
      $header->priority = $priority[0];
	} else {
      $header->priority = $priority;
	}

    $header->message_id = $messageid;
    $header->ccaddress = $cc;
    $header->Size = $size;
    $header->in_reply_to = $inrepto;
    $header->is_spam = $is_spam;


//    $header->type0 = $type[0];
//    $header->type1 = $type[1];
  }
return $header;
}

require_once(WM2_INC_DIR.'imap/date.php');
require_once(WM2_INC_DIR.'imap/imap_mailbox.php');
require_once(WM2_INC_DIR.'imap/imap_messages.php');
require_once(WM2_INC_DIR.'imap/imap_general.php');

?>
