<?php
    /*
     * $Id: view.php 1498 2010-07-08 01:58:44Z dmorton $
     *
     * MAIA MAILGUARD LICENSE v.1.0
     *
     * Copyright 2004 by Robert LeBlanc <rjl@renaissoft.com>
     *                   David Morton   <mortonda@dgrmm.net>
     * All rights reserved.
     *
     * PREAMBLE
     *
     * This License is designed for users of Maia Mailguard
     * ("the Software") who wish to support the Maia Mailguard project by
     * leaving "Maia Mailguard" branding information in the HTML output
     * of the pages generated by the Software, and providing links back
     * to the Maia Mailguard home page.  Users who wish to remove this
     * branding information should contact the copyright owner to obtain
     * a Rebranding License.
     *
     * DEFINITION OF TERMS
     *
     * The "Software" refers to Maia Mailguard, including all of the
     * associated PHP, Perl, and SQL scripts, documentation files, graphic
     * icons and logo images.
     *
     * GRANT OF LICENSE
     *
     * Redistribution and use in source and binary forms, with or without
     * modification, are permitted provided that the following conditions
     * are met:
     *
     * 1. Redistributions of source code must retain the above copyright
     *    notice, this list of conditions and the following disclaimer.
     *
     * 2. Redistributions in binary form must reproduce the above copyright
     *    notice, this list of conditions and the following disclaimer in the
     *    documentation and/or other materials provided with the distribution.
     *
     * 3. The end-user documentation included with the redistribution, if
     *    any, must include the following acknowledgment:
     *
     *    "This product includes software developed by Robert LeBlanc
     *    <rjl@renaissoft.com>."
     *
     *    Alternately, this acknowledgment may appear in the software itself,
     *    if and wherever such third-party acknowledgments normally appear.
     *
     * 4. At least one of the following branding conventions must be used:
     *
     *    a. The Maia Mailguard logo appears in the page-top banner of
     *       all HTML output pages in an unmodified form, and links
     *       directly to the Maia Mailguard home page; or
     *
     *    b. The "Powered by Maia Mailguard" graphic appears in the HTML
     *       output of all gateway pages that lead to this software,
     *       linking directly to the Maia Mailguard home page; or
     *
     *    c. A separate Rebranding License is obtained from the copyright
     *       owner, exempting the Licensee from 4(a) and 4(b), subject to
     *       the additional conditions laid out in that license document.
     *
     * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS
     * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
     * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
     * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
     * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
     * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
     * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
     * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
     * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
     * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
     * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
     *
     */

    require_once ("core.php");
    require_once ("authcheck.php");
    require_once ("display.php");
    require_once ("maia_db.php");
    require_once ("mime.php");
    require_once ("Mail/mimeDecode.php");  // PEAR::Mail::mimeDecode.php
    if (extension_loaded('mcrypt')) {
        require_once ("encrypt.php");
    }
    $display_language = get_display_language($euid);
    require_once ("./locale/$display_language/display.php");
    require_once ("./locale/$display_language/db.php");
    require_once ("./locale/$display_language/mime.php");
    require_once ("./locale/$display_language/reportspam.php");
    require_once ("./locale/$display_language/quarantine.php");
    require_once ("./locale/$display_language/viewmail.php");
    require_once ("./locale/$display_language/listcache.php");

	require_once ("smarty.php");
//print_r($_POST);
//print_r($_GET);
//      exit();
   // Admins (including the superadmin) should not be looking at
   // other people's mail!
   if (!ok_to_impersonate($euid, $uid)) {
       header("Location: stats.php" . $sid);
       exit;
   }
   if (isset($_GET['mail_id'])) {
	  $id = intval($_GET["mail_id"]);
   } elseif (isset($_GET["id"])) {
      $id = intval($_GET["id"]);
   } else {
      header("Location: list-cache.php" . $msid . "cache_type=ham");
   }
   if (isset($_GET["cache_type"])) {
      $cache_type = trim($_GET["cache_type"]);
   } else {
      header("Location: list-cache.php" . $msid . "cache_type=ham");
   }
   if (isset($_GET["type"])) {//DGM FIXME is this needed?
      $type = trim($_GET["type"]);
   } else {
      $type = "";
   }
   if (isset($_GET["raw"])) { 
      $raw = (trim($_GET["raw"]) == "y");
   } else {
      $raw = false;
   }
   
   if (isset($_REQUEST['ajax']) && $_REQUEST['ajax'] == 'true') {
       $ajax = true;
   } else {
       $ajax = false;
   }

   if ($_SERVER['REQUEST_METHOD'] == 'POST'){
	    require_once ("cache.php");

    	$cache= new MessageCache($cache_type,  $dbh, get_database_type($dbh), $smarty);
	    $message = $cache->confirm_cache($euid);
	    
	    
	    if ($ajax) { //this section should be moved to a template somewhere.
	        ?>
	        tb_remove();
	        <?php
	        if ($cache->confirmed_actions('resent') == 0) { // if a single message was resent we don't delete it from the list ?>
	        $('#row_<?php echo $id; ?>').fadeOut("slow");
	        $('#row_<?php echo $id; ?>').remove();
	        <?php } ?>
	        $('#messagebox').html('<div class="messagebox"><?php 
	            echo strtr($message, array('\\'=>'\\\\',"'"=>"\\'",'"'=>'\\"',"\r"=>'\\r',"\n"=>'\\n','</'=>'<\/')); 
	            //thanks to smarty or that escape function!
	            ?></div>');
	        $('#messagebox div').effect("highlight", { 
                    color: "#FFD324" 
                }, 
                2000);
	            <?php
	        exit;
	    } else {
          $_SESSION['message'] = $message;
          header("Location: list-cache.php" . $msid . "cache_type=" . $cache_type);
        }
   } 
   
    if ($raw) {
        $bodyclass = "rawmail";
    } else {
    	$bodyclass = "decodedmail";
    }

    $use_icons = (get_config_value("use_icons") == "Y");

	$smarty->assign("lang", $lang);
	$smarty->assign("id", $id);
	$smarty->assign("type", $type);
	$smarty->assign("raw", $raw);
	$smarty->assign("cache_type", $cache_type);
	
	
   // Open and read the gzipped mail file, and display the
   // contents for basic MIME types:
   //
   //    text/plain
   //    text/html
   //
   // Decoding is provided for common formats:
   //
   //    base64
   //    quoted-printable
   //    8bit
   //    7bit
   //

   $select = "SELECT maia_mail.contents, maia_mail.sender_email " .
             "FROM maia_mail, maia_mail_recipients " .
             "WHERE maia_mail.id = maia_mail_recipients.mail_id " .
             "AND maia_mail.id = ? " .
             "AND maia_mail_recipients.recipient_id = ?";
   $sth = $dbh->query($select, array($id, $euid));
   if ($row = $sth->fetchrow()) {
       $contents = $row["contents"];
       $sender_email = $row['sender_email'];

       if (extension_loaded('mcrypt')) {
	   if (text_is_encrypted($contents)) {
	   	 $key = get_encryption_key();
	   	 $contents = decrypt_text($key, $contents);
	   }
       }

      $smarty->assign("spamreport_rows", display_spam_report($id));

       if (!$raw) {

          // Try to decode the mail and display all of its parts.
          $mail = new Mail_mimeDecode((get_magic_quotes_gpc() ? stripslashes($contents) : $contents));
          $args['include_bodies'] = true;
          $args['decode_bodies'] = true;
          $args['decode_headers'] = false;  // the inconv decoding will handle the headers
          $structure = $mail->decode($args);
          $smarty->assign("message", display_parts($structure));
          $headers = $structure->headers;
          foreach ($headers  as  $key => $value) {
              if (is_array($value)) {
                  foreach($value as $itemkey => $item) {
                      $headers["$key"][$itemkey] = htmlspecialchars(iconv_mime_decode($item,2, 'utf-8'), ENT_QUOTES, 'utf-8');
                  }
              } else {
                  $headers["$key"] = htmlspecialchars(iconv_mime_decode($value,2, 'utf-8'), ENT_QUOTES, 'utf-8');
              }
          }
          if (isset($headers['content-type'])) {
              unset($headers['content-type']);
          }
          $smarty->assign('headers', $headers);
          $smarty->assign('sender_email', $sender_email);


       } else {

          // Strip out the X-Envelope-To: header for privacy
          $contents = preg_replace("/X-Envelope-To:(.*)\n/i", "", $contents);

          // Dump the raw contents of the e-mail, making sure to
          // escape any HTML tags it might contain, so the raw source
          // gets displayed.
          $smarty->assign("message", "<pre>" . htmlentities(wordwrap($contents, 70)) . "</pre>");

       }
	   $smarty->assign("error","");
   } else {
   	   $smarty->assign("error","error");
      }
   $sth->free();
   $smarty->assign("return_route", "view.php"); // depreciated, needed for legacy support in viewmail.tpl.
   $smarty->assign("ajax", $ajax);
   $smarty->assign("actionlang", response_text($cache_type));
   $smarty->display("view.tpl");
?>