<?php

/*
 
 File: mailbox.php3
 $Author: rkrusty $
 $Revision: 1.166 $
 $Date: 1999/04/14 06:37:41 $
 
 IMP: Copyright 1999 Charles J. Hagenbuch <chuck@horde.org>
 
 You should have received a copy of the GNU Public
 License along with this package; if not, write to the
 Free Software Foundation, Inc., 59 Temple Place - Suite 330,
 Boston, MA 02111-1307, USA.
 
 */

/* display_toaddress: check the user's address and list of addresses that To: should be displayed for */
function display_toaddress ($user, $server, $from) {
   return is_int(strpos($from, get_barefrom($user, $server)));
}


$need_horde_db = 1;
$db_lib_loaded = 0;
if (!defined("HORDE_LIB")) include ('../lib/horde.lib');
if (!defined("IMP_LIB")) include ('./lib/imp.lib');
require ('./lib/mimetypes.lib');
require ('./config/defaults.php3');

/* Html styles configuration */
require('./config/html.php3');
/* Mailbox configuration */
require('./config/mailbox.php3');
/* include mime and language configuration */
require('./config/mime.php3');
require('./config/lang.php3');

if (isset($new_lang)) {
  $language = $new_lang;
} else {
  $language = select_lang();
}
require ("./locale/$language/mailbox.lang");
require ('./locale/local/mailbox.lang');

$this_client = new WebClient;

error_reporting($default->error_level);

/* send headers to ensure that the page will reload correctly. */
caching_headers();

/* Set or read session */
$session = create_session_object();
if (isset($actionID) && ($actionID == IMP_LOGIN) ) {
   $user    = $session->set_user($user);
   $pass    = $session->set_password($pass);
   $server  = $session->set_server($server);
   $port    = $session->set_port($port);
   $folders = $session->set_folder($folders);
} else {
   $user    = $session->get_user();
   $pass    = $session->get_password();
   $server  = $session->get_server();
   $port    = $session->get_port();
   $folders = $session->get_folder();
}

/* This is for v2 database support */
if ($default->v2_database) {
   /*
    Validate the login against the database, and pull their imap
    server stuff out of the database.
    */
   /* Remap the Fields needed for the login to their appropiate items */
   /*
    $user    -> username
    $pass    -> password
    $server  -> imap server
    $port    -> imap server port
    $folders -> ???
    */
   $temp_user = new HordeUser;
   $temp_user->user_name = $user;
   $temp_user->password  = $pass;
   $return_arr = $db->User->Verify( $temp_user );
   if ($return_arr[ 0 ] == true) {
      /* Sucessful login */
      /* Pull their settings for this form */
      echo( '<b>Good Login</b>' );
   } else {
      /*
       $return_arr[ 0 ] == false;
       -- Note : Place autocreation code here !!! ---
       */
   }
}


if (!isset($mailbox)) $mailbox = 'INBOX';
if (!isset($sortby)) $sortby = $default->sort_crit;
if (!isset($sort_reverse)) $sort_reverse = $default->sort_dir;

$current_mbox = str_replace("{$server}$folders", '', $mailbox);
if (strlen($default->personal_folders) > 0) $current_mbox = str_replace("$default->personal_folders", '', $current_mbox);

/* only proceed on a valid login */
$mbox = validate_login($server, $port, $mailbox, $user, $pass);

/* indicates invalid login or expired login so skip all the crap below */
if (isset($mbox) && (!$mbox)) exit;

if (!isset($plural)) $plural = false;

/* Run through the action handlers */

$status_string = '';
$status_color = 'green';

if (isset($actionID)) {
   if (isset($indices) && !is_array($indices)) { $indices = Array($indices); }
   
   switch ($actionID) {
    case NO_ACTION:
      $status_string = $lang->mailbox . $current_mbox;
      break;
      
    case DELETE_MESSAGES:
      if (isset($indices) && $indices && $mailbox) {
	 for ($i = 0; $i < count($indices); $i++) {
	    if (!(imap_delete($mbox, imap_msgno($mbox, $indices[$i])))) {
	       $status_string = $lang->error($current_mbox, 'deletion');
	       $status_color = 'red';
	    }
	 }
	 if (!$status_string) {
	    if ($i != 1) $plural = true;
	    $status_string = $lang->success1($current_mbox, 'deleted', $i, $plural);
	 }
      }
      if (!$status_string) {
	 $status_string = $lang->error($current_mbox, 'deletion');
	 $status_color = 'red';
      }
      break;
      
    case UNDELETE_MESSAGES:
      if (isset($indices) && $mailbox && $indices) {
	 for ($i = 0; $i < count($indices); $i++) {
	    if (!(imap_undelete($mbox, imap_msgno($mbox, $indices[$i])))) {
	       $status_string = $lang->error($current_mbox, 'undeletion');
	       $status_color = 'red';
	    }
	 }
	 if (!$status_string) {
	    if ($i != 1) $plural = true;
	    $status_string = $lang->success1($current_mbox, 'undeleted', $i, $plural);
	 }
      }
      if (!$status_string) {
	 $status_string = $lang->error($current_mbox, 'undeletion');
	 $status_color = 'red';
      }
      break;
      
    case MOVE_MESSAGES:
      if (isset($indices) && isset($targetMbox) && $targetMbox && $indices) {
	 $msg_list = implode($indices, ',');
	 if (! (imap_mail_copy($mbox, $msg_list, $targetMbox, CP_UID|CP_MOVE)) ) {
	    $status_string = $lang->error($current_mbox, 'move');
	    $status_color = 'red';
	 } else {
	    if (count($indices) != 1) $plural = true;
	    $status_string = $lang->success2($current_mbox, $targetMbox, 'moved', count($indices), $plural);
	 }
      }
      if (!$status_string) {
	 $status_string = $lang->error($current_mbox, 'move');
	 $status_color = 'red';
      }
      break;
      
    case COPY_MESSAGES:
      if (isset($targetMbox) && isset($indices) && $targetMbox && $indices) {
	 $msg_list = implode($indices, ',');
	 if (!(imap_mail_copy($mbox, $msg_list, $targetMbox, CP_UID)) ) {
            $status_string = $lang->error($current_mbox, 'copy');
	    $status_color = 'red';
	 } else {
	    if (count($indices) != 1) $plural = true;
	    $status_string = $lang->success2($current_mbox, $targetMbox, 'copied', count($indices), $plural);
	 }
      }
      if (!$status_string) {
	 $status_string = $lang->error($current_mbox, 'copy');
	 $status_color = 'red';
      }
      break;
      
    case EXPUNGE_MAILBOX:
      if ($mailbox) {
	 if (!(imap_expunge($mbox))) {
            $status_string = $lang->error($current_mbox, 'expunge');
	    $status_color = 'red';
	 } else {
	    $status_string = $lang->mailbox . ': ' . $current_mbox . ': ' . $lang->expunged;
	 }
      }
      if (!$status_string) {
	 $status_string = $lang->error($current_mbox, 'expunge');
	 $status_color = 'red';
      }
      break;
      
    case IMP_LOGIN:
      $status_string = $lang->mailbox . ': ' . $current_mbox;
      if (isset($new_lang)) {
         $session->set_lang($new_lang);
         $language = $new_lang;
      }
      break;
   }
   
} else $status_string = $lang->mailbox . ': ' . $current_mbox;


$check = imap_check($mbox);
$options = mailbox_list($mailbox, true);

if ($check->Nmsgs != 0) $sorted = imap_sort($mbox, $sortby, $sort_reverse, SE_UID);
else $sorted = array();
$session->set_msgl($sorted);

$sidebar = false;
require ("$default->include_dir/doctype.inc");    /* doctype */

require ("$default->include_dir/generic-header.inc");
$nummsgs = $check->Nmsgs;  /* removed call to imap_num_msgs - cbj */

if ($nummsgs > $default->max_messages_page) {
   $page_count = ceil($nummsgs/$default->max_messages_page);
   
   /* Figure out which page to display */
   if (isset($page) && $page) {
      /* actually, do need to do something here: make sure we're not past the end */
      if ($page > $page_count) $page = $page_count;
   } elseif (isset($start) && $start) {
      /* no idea where/if this is used - cbj */
      /* messages set it when returning to a mailbox - cjh */
      $page = ceil($start/$default->max_messages_page);
   } else {
      $page = 1;
   }
   $begin = ($page - 1) * $default->max_messages_page + 1;
   
   $end = $begin + $default->max_messages_page - 1;
   if ($end > $nummsgs) { $end = $nummsgs; }
   
   if ($page == 1) {
      if (!$this_client->lynx) {
	 $pages_first = "<img src=\"$default->graphics_url/first-grey.gif\" border=\"0\" alt=\"\">";
	 $pages_prev  = "<img src=\"$default->graphics_url/prev-grey.gif\" border=\"0\" alt=\"\">";
      } else {
	 $pages_first = '';
	 $pages_prev  = '';
      }
   } else {
      $prev             = $page - 1;
      $target_first_url = "$default->root_url/mailbox.php3?mailbox=" . urlencode($mailbox) . "&page=1&sortby=$sortby";
      $target_prev_url  = "$default->root_url/mailbox.php3?mailbox=" . urlencode($mailbox) . "&page=$prev&sortby=$sortby";
      if (!$this_client->lynx) {
	 $pages_first = "<a href=\"$target_first_url\"><img src=\"$default->graphics_url/first.gif\" border=\"0\" alt=\"first page\"></a>";
	 $pages_prev  = "<a href=\"$target_prev_url\"><img src=\"$default->graphics_url/prev.gif\" border=\"0\" alt=\"prev page\"></a>";
      } else {
	 $pages_first = "<a href=\"$target_first_url\">&lt;&lt; [ First Page ]";
	 $pages_prev  = "<a href=\"$target_prev_url\">&lt; [ Previous Page ]</a>";
      }
   }
   
   if ($page == $page_count) {
      if (!$this_client->lynx) {
	 $pages_last = "<img src=\"$default->graphics_url/last-grey.gif\" border=\"0\" alt=\"\">";
	 $pages_next = "<img src=\"$default->graphics_url/next-grey.gif\" border=\"0\" alt=\"\">"; 
      } else {
	 $pages_last = '';
	 $pages_next = '';
      }
   } else {
      $next = $page + 1;
      $target_last_url = "$default->root_url/mailbox.php3?mailbox=$mailbox&page=$page_count&sortby=$sortby";
      $target_next_url = "$default->root_url/mailbox.php3?mailbox=$mailbox&page=$next&sortby=$sortby";
      
      if (!$this_client->lynx) {
	 $pages_last = "<a href=\"$target_last_url\"><img src=\"$default->graphics_url/last.gif\" border=\"0\" alt=\"last page\"></a>";
	 $pages_next = "<a href=\"$target_next_url\"><img src=\"$default->graphics_url/next.gif\" border=\"0\" alt=\"next page\"></a>";
      } else {
	 $pages_last = "<a href=\"$target_last_url\">[ Last Page ] &gt;&gt;</a>";
	 $pages_next = "<a href=\"$target_next_url\">[ Next Page ] &gt;</a>";
      }
      
   }
   
} else {
   $begin = 1;
   $end   = $nummsgs;
   $page  = 1;
}

$title = "Index of $current_mbox";

if ($this_client->lynx) {
   include_lynx_menu(IMPMENU_MAIN);
   include("$default->include_dir/mailbox/lynx_header.inc");
   include("$default->include_dir/mailbox/lynx_navbar_top.inc");
   include("$default->include_dir/mailbox/lynx_actions.inc");
   include("$default->include_dir/mailbox/lynx_message_headers.inc");
} else {
   include("$default->include_dir/mailbox/header.inc");
   include("$default->include_dir/mailbox/navbar_top.inc");
   include("$default->include_dir/mailbox/actions.inc");
   include("$default->include_dir/mailbox/message_headers.inc");
}

// hack to read headers twice if there is new mail, to try and get the correct status
$mailinfo = @imap_mailboxmsginfo($mbox);
if ($mailinfo) {
   $num_recent = $mailinfo->Recent;
   if (isset($num_recent) && $num_recent > 0) {
      imap_close($mbox);
      $mbox = imap_open("{$server:$port}$mailbox", $user, $pass, OP_READONLY);
   }
}

// now step through each message
for ($i=$begin; $i <= $end; $i++) {
   
   $msgnum = $sorted[$i-1];
   $h=@imap_header($mbox, imap_msgno($mbox, $msgnum), $default->max_frm_chars, $default->max_sub_chars);
   
   /* some balky IMAP servers don't get it right at first... */
   while (!is_object($h) || !imap_ping($mbox)) {
      $mbox = imap_open("{$server:$port}$mailbox", $user, $pass, OP_READONLY);
      $h = @imap_header($mbox,imap_msgno($mbox, $msgnum), $default->max_frm_chars, $default->max_sub_chars);
   }
   
   /* initialize the header fields */
   $dat = '';
   $frm = '';
   $sub = '';
   $msg_size = '?';
   
   /* now pull the IMAP header values into them, decoding and chopping them at the same time */
   if (isset($h->date)) {
      $date = $h->udate;
      if (date('Y') != date('Y', $date))
	$dat = date('M\&\n\b\s\p;d,\&\n\b\s\p;Y', $date);
      elseif (date('Ymd') == date('Ymd', $date))
	$dat = date('H:i', $date);
      else $dat = date('M\&\n\b\s\p;d', $date);
   }
   
   if (isset($h->from[0])) {
      $from = $h->from[0];
      if (isset($from->personal)) {
	 $frm = chop(decode_mime_string($from->personal));
      } else $frm = $from->mailbox . '@' . $from->host;
   } elseif (isset($h->fetchfrom)) $frm = $h->fetchfrom;
   
   if (isset($h->fromaddress) && display_toaddress($user, $server, $h->fromaddress)) {
       if (isset($h->toaddress))
	   $to = chop(decode_mime_string($h->toaddress));
       else
	   $to = $lang->undisclosed_recipients;
       $frm = $lang->to_label . ': ' . $to;
   }
   if (isset($h->fetchsubject)) $sub = trim(decode_mime_string($h->fetchsubject));
   if (isset($h->Size)) $msg_size = ($h->Size > 1024) ? sprintf("%.0f kb", $h->Size / 1024) : $h->Size;
   
   /* make sure that they get put into an HTML readable format */
   $frm = htmlspecialchars($frm);
   $sub = htmlspecialchars($sub);
   
   /* set them to useful things for IMP if they ended up being empty */
   if ($dat == '') { $dat = '&nbsp;'; }
   if ($frm == '') { $frm = '&nbsp;'; }
   if ($sub == '') { $sub = $lang->no_subject; } // make sure to have something here for the link text
   
   $icons = array();
   
   if ($default->fetch_mime_info) {
      $flag = array();
      
      $structure = @imap_fetchstructure($mbox,imap_msgno($mbox, $msgnum));
      
      /* some balky IMAP servers don't get it right at first... */
      while(!is_object($structure)) {
	 $mbox = imap_open("{$server:$port}$mailbox", $user, $pass, OP_READONLY);
	 $structure = imap_fetchstructure($mbox,imap_msgno($mbox, $msgnum));
      }
      
      $num_parts = @count($structure->parts);
      $bodypart = 1;
      $j = 0;
      if (is_array( $structure->parts ) && $num_parts > 0) {
	 if( $num_parts > 9 ) $num_parts = 9;
	 
	 while ($j <= $num_parts) {
	    if( is_object( $structure->parts[$j] ) ) {
	       $mime = new mime_part_data;
	       $mime->set_imap_data( $mailbox, $msgnum, $j );
	       $mime->parse( $structure->parts[$j] );
	       if( $mime->type_text != 'text' || $mime->subtype != 'plain' || $j != 0 ) {
		  if( isset($icons[$mime->text]) )
		    $icons[$mime->text]["count"]++;
		  else {
		     $icons[$mime->text]["display"] = $mime->img_tag();
		     $icons[$mime->text]["count"] = 1;
		  }
	       }
	    }
	    $j++;
	 }
	 for( reset($icons); $key=key($icons); next($icons) ) {
	    $tmp = $icons[$key]['display'];
	    if( $icons[$key]["count"] > 1 ) 
	      $tmp .= '<subscript><b>' . $icons[$key]['count'] . '</b></subscript>';
	    $tmp .= "\n";
	    $flag[] = $tmp;
	 }
	 
      } else {
	 
	 /* Only one part in message, check for an attachment */
	 $mime = new mime_part_data;
	 $mime->set_imap_data( $mailbox, $msgnum, $j );
	 $mime->parse( $structure );
	 if( $mime->type_text != "text" || $mime->subtype != "plain" )
	   $flag[] = $mime->img_tag();
      }
      
   }
   
   include( "$default->include_dir/mailbox/message_summaries.inc" );
}

require("$default->include_dir/mailbox/message_footers.inc");
require("$default->include_dir/mailbox/actions.inc");
require("$default->include_dir/mailbox/navbar_bottom.inc");
require("$default->include_dir/mailbox/footer.inc");
require('./lib/js/open_compose_win.js');
require("$default->include_dir/mailbox/javascript.inc");
require('./lib/js/open_contacts.js');

if ((isset($actionID) && ($actionID == IMP_LOGIN)) ||
    (isset($horde_frames))) {
    include( "$default->include_dir/mailbox/refresh_toolbar-javascript.inc" );
}

if ( ! $this_client->lynx ) {
status($status_string, $status_color);
}

?>
