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

// Maillist
// Moregroupware.org

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

include("../../config.inc.php");
include(INCLUDEPATH . "container.inc.php");
include(WM2_INC_DIR."imap/date.php");
require_once(WM2_INC_DIR."maillist_inc.php");

error_reporting  (E_ERROR | E_WARNING | E_PARSE | E_NOTICE);

$myvars = array("mbox_id","searchfor","searchfor2","searchin","msg_begin","newsort","newsort2","makeread","makenormalpriority","msg_no","markmessage","reload","account");
foreach ($myvars as $thevar) {
  ${$thevar} = (isset($_GET[$thevar])) ? $_GET[$thevar] : (isset($_POST[$thevar]) ? $_POST[$thevar] : "");
}
$searchfor = stripslashes(myquote($searchfor));

$MGW = $_SESSION["MGW"];
$user_id = $MGW->userid;
$username = $MGW->username;

if ($account == "") { $account = 0; }
if (!is_numeric($mbox_id)) {$mbox_id="";}

if ($reload == "draft") { $reload = getboxid("draft",0,$user_id); }
  else if ($reload == "sent") { $reload = getboxid("sent",0,$user_id); }

if ($reload != "" and is_numeric($reload)) {
  $sql = "select message_id from mgw_webmail2_messages where mbox_id=".(int)$reload;
  if(!$res = $conn->Execute($sql)) die(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
  $second_messagecount = $res->RecordCount();

  $sql = "select message_id from mgw_webmail2_messages where mbox_id=".(int)$reload." and readbit=1";
  if(!$res = $conn->Execute($sql)) die(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
  $second_messagecount_unread = $res->RecordCount();
} else {
  $second_messagecount = 0;
  $second_messagecount_unread = 0;
}

$mbox_exist = false;
$imap_isintrash = false;

if ($account!=0 and $mbox_id!="" and file_exists(CACHE_FOLDER."imap/tree/".$account.".php")) {

  include CACHE_FOLDER."imap/tree/".$account.".php";

  foreach ($folders as $folder) {
    if ($folder[1] == $mbox_id) {
      $mboxname = $folder[2];
      $mbox_id_name = $folder[7];
      
      if (strpos("@".strtolower($mbox_id_name),"inbox.trash")==1 or strpos("@".strtolower($mbox_id_name),"inbox/trash")==1 or strpos("@".strtolower($mbox_id_name),"trash")==1) {
        $imap_isintrash = true;
      }
      
      $sql = "select * from mgw_webmail2_accounts where mailboxname!='' and activated='checked' and servertype='wm2_servertype_imap_only' and id=".(int)$account." and user_id=".(int)$user_id;
      if(!$res = $conn->Execute($sql)) die(showSQLerror($sql, $conn->ErrorMsg(), __LINE__,__FILE__));

      if ($res->RecordCount() != 0) {
        $mbox_exist = true;
        $account_row = $res->FetchRow();
      }
    }
  }
}

if (!$mbox_exist and $account==0 and $mbox_id!="" and boxexist($mbox_id,$user_id)) {
  $mbox_exist = true;
  $mboxname = getboxname($mbox_id);
}
if (!$mbox_exist and $account==0 and $mbox_id!="" and boxexist($mbox_id,0)) {
  $mbox_exist = true;
  $mboxname = getboxname($mbox_id);
  $user_id = 0;
}
if ($mbox_id=="" or !$mbox_exist) {
  $mbox_id = getboxid("inbox",0,$user_id);
  $mboxname = "inbox";
  $account = 0;
}

if ($account==0) { $mboxname = mboxname_replace($mboxname); } else { $mboxname = mboxname_replace_imap($mboxname); }
if ($account==0 and !has_read_rights_mbox($mbox_id,$user_id)) { die("Access denied."); }

$firstdataset = "";
$indexes = "";
$important = "";
$highlighted = "";
$webmails = array();

  if ($msg_begin=="")
    if (isset($_SESSION["MGW"]->settings["wm2_default_msg_begin"])) $msg_begin=$_SESSION["MGW"]->settings["wm2_default_msg_begin"]; else $msg_begin=1;
  if (!is_numeric($msg_begin) or $msg_begin<=0) $msg_begin=1;
    
  if ($markmessage=="")
    if (isset($_SESSION["MGW"]->settings["wm2_default_markmessage"])) $markmessage=$_SESSION["MGW"]->settings["wm2_default_markmessage"]; else $markmessage=-1;

  store_webmail_maillist($mbox_id, $account, $msg_begin);
  
  $from_to = $hashmap["maillist_from"];
  
  make_sorts();
  
  $smarty->assign("ascdesc_pic", $thesort);
  $smarty->assign("ascdesc_type", $ad_type);

  if ($thesort == "") {$thesort = "message_id";}
  $thesort = $thesort2.$thesort." ".$ad_type;

  if ($searchfor2 != "") {
    $searchfor = "";
    $searchin = "";
  }

  $user_id2 = $user_id;
  $myrow = array();

  if ($MGW->settings["wm2_emailsperpage"] == 0) {$MGW->settings["wm2_emailsperpage"] = 1;}

  if ($account == 0) {

    $sql = "select isdraft from mgw_webmail2_mailboxes where mbox_id=".(int)$mbox_id;
    if(!$res2 = $conn->Execute($sql)) die(showSQLerror($sql, $conn->ErrorMsg(), __LINE__,__FILE__));
    $row2 = $res2->FetchRow();
    if ($row2["isdraft"]==1 or $row2["isdraft"]==2) { $from_to = $hashmap["maillist_to"]; $thesort = str_replace("from","to",$thesort); }
    if ($row2["isdraft"]==1) {$is_draft = "true";} else {$is_draft = "false";}

    list($sql,$sql2) = get_maillist_searches();
  
    if(!$res = $conn->Execute($sql2)) die(showSQLerror($sql2, $conn->ErrorMsg(), __LINE__, __FILE__));
    $messagecount = $res->RecordCount();

	if ($messagecount < $msg_begin) $msg_begin = 1;
	
    $sql2 .= " and readbit=1";
    if(!$res = $conn->Execute($sql2)) die(showSQLerror($sql2, $conn->ErrorMsg(), __LINE__, __FILE__));
    $messagecount_unread = $res->RecordCount();
	
    if(!$res = $conn->SelectLimit($sql,$MGW->settings["wm2_emailsperpage"],($msg_begin-1))) die(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
    $messagecount2 = $res->RecordCount();

    while($row = $res->FetchRow()) {
      $myrow[] = array(
	    "type" => $row["type"],
        "mbox_id"        => $row["mbox_id"], "header_size"    => $row["header_size"],
        "header_to"      => $row["header_to"], "header_from"    => $row["header_from"],
        "attachbit"      => $row["attachbit"], "header_subject" => htmlspecial_mime($row["header_subject"]),
        "header_date"    => $row["header_date"], "message_id"     => $row["message_id"],
        "account_name"   => $row["account_name"], "flaggedbit"     => $row["flaggedbit"],
        "readbit"        => $row["readbit"], "forwardbit"     => $row["forwardbit"],
        "replybit"       => $row["replybit"], "deletedbit"       => 0,

        "importantbit"   => ($row["labelbit"]==1?1:0),
        "workbit"        => ($row["labelbit"]==2?1:0),
        "personalbit"    => ($row["labelbit"]==3?1:0),
        "todobit"        => ($row["labelbit"]==4?1:0),
        "laterbit"       => ($row["labelbit"]==5?1:0),
      );
    }
  } else {
    
    $mbox_name2 = trim(strtolower($mboxname));
    if ($mbox_name2 == "sent" or $mbox_name2 == "drafts") {
      $from_to = $hashmap["maillist_to"];
    }

    if (strpos("@".strtolower($mbox_id_name),"drafts")==1 or strpos("@".strtolower($mbox_id_name),"inbox.drafts")==1) {
      $is_draft = "true";
    } else {$is_draft = "false";}

	if ($is_draft=="true" or strpos("@".strtolower($mbox_id_name),"sent")==1 or strpos("@".strtolower($mbox_id_name),"inbox.sent")==1) {
	  $from_to = $hashmap["maillist_to"];
	  $thesort = str_replace("from","to",$thesort);     
	}

    include(WM2_INC_DIR.'fetchmail_inc.php');
    require_once(WM2_INC_DIR.'imap/imap.php');
    require_once(INCLUDEPATH . "crypt.inc.php");
    $myC = new Crypto();
    $password = $myC->decrypt($username, $account_row["password"]);
  
    if ($account_row["enable_ssl"]=="checked") {
      $default_port = "993";
    } else {
      $default_port = "143";
	}

    $email = my_imap_connect("int",$default_port,"imap",$account_row,$password,$mbox_id_name);
    $imap_conn = $email;
    $messagecount = 0; $messagecount2 = 0; $messagecount_unread = 0;

    if (!isset($imap_conn_error) or $imap_conn_error=="") {

      $messagecount = sqimap_get_num_messages($email, $mbox_id_name);
      $messagecount2 = ($messagecount < $MGW->settings["wm2_emailsperpage"] ? $messagecount : $MGW->settings["wm2_emailsperpage"]);
      
	  if ($msg_begin > $messagecount) $msg_begin = 1;
      $limit = ($messagecount < $MGW->settings["wm2_emailsperpage"] ? $messagecount : $MGW->settings["wm2_emailsperpage"] + $msg_begin-1);
      if ($limit > $messagecount) {$limit = $messagecount; }
      
      if ($messagecount != 0) {
        $messagecount_unread = sqimap_unseen_messages($email, $mbox_id_name);
        
		$sort = strtoupper(str_replace(array("header_"," desc"," asc","account_name,"),"",$thesort));
          
		if ($sort!="MESSAGE_ID" and $sort!="") {
		  $sort_array = sqimap_get_sort_order ($email, $sort, $mbox_id_name);
		} else {
		  $sort_array = range(1,$messagecount);
		}
		if (!is_array($sort_array)) $sort_array = range(1,$messagecount);
		
		if (strpos($thesort,"desc")) $sort_array = array_reverse($sort_array);

	    for ($msg_no3=$msg_begin;$msg_no3 <= $limit;$msg_no3++) {
		  $msg_no2 = $sort_array[$msg_no3-1];
          
          $msg_no = $msg_no2;
          
          $header = my_imap_header($email,$imap_conn,"int",$msg_no);
          $structure = sqimap_get_message($email, $msg_no);
          
          $flags = return_flags($email,$msg_no);

          if (eregi("\"attachment\"",$structure)) { $flags["attaches"] = 1;} else {$flags["attaches"] = 0;}

          if (isset($header->toaddress)) {$header->toaddress=trim($header->toaddress);} else {$header->toaddress="";}
          if (isset($header->fromaddress)) {$header->fromaddress=trim($header->fromaddress);} else {$header->fromaddress="";}
          if (!isset($header->date)) {$header->date="";}
          if (!isset($header->subject)) {$header->subject="";}
          if (!isset($header->priority)) {$header->priority="";}
          if (isset($header->Size)) {$size = $header->Size;} else {$size = "0";}
          
          if ($header->priority==1 or $header->priority==2) { $flags["flagged"] = 1; }
          
          $myrow[] = array(
            "type"        => "eml",
            "mbox_id"        => $mbox_id,
            "header_size"    => $size,
            "header_to"      => decode_mime_string($header->toaddress),
            "header_from"    => decode_mime_string($header->fromaddress),
            "attachbit"      => $flags["attaches"],
            "header_subject" => decode_mime_string($header->subject),
            "header_date"    => $header->date,
            "message_id"     => $msg_no,
            "account_name"   => $account,
            "deletedbit"     => $flags["deleted"],
            "flaggedbit"     => $flags["flagged"],
            "readbit"        => $flags["seen"],
            "forwardbit"     => $flags["forward"],
            "replybit"       => $flags["reply"],

            "importantbit"   => $flags["important"],
            "workbit"        => $flags["work"],
            "personalbit"    => $flags["personal"],
            "todobit"        => $flags["todo"],
            "laterbit"       => $flags["later"],
          );
        }
      }
    } else {
	  echo "<br><center><font color='#FF0000'><b>No Connection. ".$imap_conn_error."</b></font></center><br>";
	}
  }

  $i = 0;
  $oldaccount = "abc";
  $oldmbox = -1;
  $webmails = array();

  foreach ($myrow as $row) {
    if ($searchfor != "" and !isset($rights[$row["mbox_id"]])) {
      $rights[$row["mbox_id"]] = has_read_rights_mbox($row["mbox_id"],$user_id);
    }
    
    if ($searchfor == "" or $rights[$row["mbox_id"]]) {

    $i++;
	
    $row["header_size"]=format_filesize($row["header_size"]);
	if ($from_to == $hashmap["maillist_to"]) {$header_from_to=$row["header_to"];}
	  else {$header_from_to=$row["header_from"];}

    $attach = $row["attachbit"];

    if ($MGW->settings["wm2_showshort_from_to"]) {$header_from_to = shorten2($header_from_to); }

    $header_from_to = shorten_sub_string($header_from_to,23);
    $header_from_to = shorten(htmlspecial_mime($header_from_to));

	$header_subject_2 = decode_mime_string(str_replace(array("\n","\r"),array("",""),trim($row["header_subject"])));
	
    $row["header_subject"] = shorten_sub_string($row["header_subject"],49);
	

    if ($row["header_subject"] == "") {$row["header_subject"] = htmlspecialchars($hashmap["maillist_empty_account"]);}

    if ($header_from_to == "") {$header_from_to = htmlspecialchars($hashmap["maillist_empty_account"]);}

	$row["header_date"] = getDateString($row["header_date"]);

	if ($row["message_id"]==$markmessage or ($markmessage==-1 and $i==1)) {$firstdataset=$row["message_id"];}
	
	if ($searchfor=="" and $thesort2!="" and $row["account_name"]!=$oldaccount) {
	  if ($row["account_name"]=="") {$newline = htmlspecialchars($hashmap["maillist_empty_account"]);}
	    else {$newline = $row["account_name"];}
	} elseif ($searchfor!="" and $row["mbox_id"]!=$oldmbox and $searchin!="this") {
      $newline = "<a href='maillist.php?searchfor2=reset&account=".$account."&mbox_id=".$row["mbox_id"]."&".SID."'>".mboxname_replace(getboxname($row["mbox_id"]))."</a>";
	} else {$newline = "";}

    if ($row["flaggedbit"] == "1" or $row["flaggedbit"] == "2") {$row["flaggedbit"] = "1";}
    
    if ($indexes != "") {$indexes .= ",";}
    $indexes .= "\"".$row["message_id"]."\"";

    if ($row["readbit"]) {
      if ($highlighted != "") {$highlighted .= ",";}
      $highlighted .= "\"".$row["message_id"]."\"";
    }

    if ($row["flaggedbit"] == 1) {
      if ($important != "") {$important .= ",";}
      $important .= "\"".$row["message_id"]."\"";
    }
	
	$labelclass = "";
	if ($row["importantbit"]=="1") { $labelclass = "important"; }
	  elseif ($row["workbit"]) { $labelclass = "work"; }
	  elseif ($row["personalbit"]) { $labelclass = "personal"; }
	  elseif ($row["todobit"]) { $labelclass = "todo"; }
	  elseif ($row["laterbit"]) { $labelclass = "later"; }

	if ($labelclass!="") {
  	  $labelclass_title = $hashmap["webmail2_maillist_".$labelclass];
	} else {
	  $labelclass_title = "";
	}
	
	$webmails[] = array($row["message_id"],trim($header_from_to),trim($row["header_subject"]),$row["header_date"],
    $row["header_size"],$row["readbit"],$row["replybit"],$row["flaggedbit"],$attach,$row["forwardbit"],$newline,$row["mbox_id"],$row["deletedbit"],$hashmap["mail_".$attach.$row["forwardbit"].$row["replybit"]],$labelclass,$labelclass_title,$header_subject_2,$row["type"]);

	$oldaccount = $row["account_name"];
	$oldmbox = $row["mbox_id"];
  }
}

if ($messagecount!=0 and $messagecount2!=0 and (!isset($firstdataset) or $firstdataset=="") and count($webmails)!=0 and count($webmails[0])!=0) {$firstdataset = $webmails[0][0];}

if ($msg_begin!=1) {$prev_page = '<a href="maillist.php?searchfor='.$searchfor.'&searchin='.$searchin.'&account='.$account.'&mbox_id='.$mbox_id.'&msg_begin='.($msg_begin-$MGW->settings["wm2_emailsperpage"]).'&'.SID.'">'.$hashmap["maillist_previous"].'</a>'; $prev_page2 = '<a href="maillist.php?searchfor='.$searchfor.'&searchin='.$searchin.'&account='.$account.'&mbox_id='.$mbox_id.'&msg_begin='.($msg_begin-$MGW->settings["wm2_emailsperpage"]).'&'.SID.'"><img src="templates/default/media/arrow_left.gif" title="'.$hashmap["maillist_previous"].'" width="10" height="11" border="0"></a>';} else {$prev_page='';$prev_page2 = "";}
if ($msg_begin <= $messagecount - $MGW->settings["wm2_emailsperpage"]) {
$next_page = '<a href="maillist.php?searchfor='.$searchfor.'&searchin='.$searchin.'&account='.$account.'&mbox_id='.$mbox_id.'&msg_begin='.($msg_begin + $MGW->settings["wm2_emailsperpage"]).'&'.SID.'">'.$hashmap["maillist_next"].'</a>'; $next_page2 = '<a href="maillist.php?searchfor='.$searchfor.'&searchin='.$searchin.'&account='.$account.'&mbox_id='.$mbox_id.'&msg_begin='.($msg_begin + $MGW->settings["wm2_emailsperpage"]).'&'.SID.'"><img src="templates/default/media/arrow_right.gif" title="'.$hashmap["maillist_next"].'" width="10" height="11" border="0"></a>';} else {$next_page="";$next_page2="";}

$pages = get_maillist_pages($messagecount);

if (($account==0 and isintrash($mbox_id)) or ($account != 0 and $imap_isintrash)) {
  $smarty->assign("confirmdelete", "if (confirm('".addslashes($hashmap["maillist_delete_confirm"])."')) {");
  $smarty->assign("confirmdelete2", "}");
} else {
  $smarty->assign("confirmdelete", "");
  $smarty->assign("confirmdelete2", "");
}

$smarty->assign("firstdataset", $firstdataset);
$smarty->assign("show_size", $MGW->settings["wm2_show_size_in_maillist"]);
$smarty->assign("is_draft", $is_draft);
$smarty->assign("username", ucfirst($username));
$smarty->assign("mboxname", $mboxname);
$smarty->assign("prev_page", $prev_page);
$smarty->assign("next_page", $next_page);
$smarty->assign("prev_page2", $prev_page2);
$smarty->assign("next_page2", $next_page2);
$smarty->assign("countwebmails", count($webmails));

$smarty->assign("second_messagecount", $second_messagecount);
$smarty->assign("second_messagecount_unread", $second_messagecount_unread);
$smarty->assign("reload", addslashes($reload));

$smarty->assign("messagecount", $messagecount);
$smarty->assign("messagecount_unread", $messagecount_unread);
$smarty->assign("mbox_id", $mbox_id);
$smarty->assign("account", $account);
$smarty->assign("highlighted", $highlighted);
$smarty->assign("nextsort", $nextsort);
$smarty->assign("msg_begin", $msg_begin);
$smarty->assign("from_to", $from_to);
$smarty->assign("webmails", $webmails);
$smarty->assign("pages", $pages);
$smarty->assign("indexes", $indexes);
$smarty->assign("searchfor", htmlspecialchars($searchfor));
$smarty->assign("searchin", $searchin);

$smarty->assign("sortbyaccount", $thesort2);

$smarty->display("maillist.tpl");
?>