<?php
if(!defined('sugarEntry'))define('sugarEntry', true);
/*********************************************************************************
 * SugarCRM is a customer relationship management program developed by
 * SugarCRM, Inc. Copyright (C) 2004 - 2007 SugarCRM Inc.
 * 
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the GNU General Public License version 3 as published by the
 * Free Software Foundation with the addition of the following permission added
 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
 * 
 * This program 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
 * this program; if not, see http://www.gnu.org/licenses or write to the Free
 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
 * 02110-1301 USA.
 * 
 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
 * 
 * The interactive user interfaces in modified source and object code versions
 * of this program must display Appropriate Legal Notices, as required under
 * Section 5 of the GNU General Public License version 3.
 * 
 * In accordance with Section 7(b) of the GNU General Public License version 3,
 * these Appropriate Legal Notices must retain the display of the "Powered by
 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
 * technical reasons, the Appropriate Legal Notices must display the words
 * "Powered by SugarCRM".
 ********************************************************************************/
require_once('include/entryPoint.php');
global $sugar_config;
global $locale;

session_cache_limiter('public');
session_start();

if(empty($_REQUEST['id']) || empty($_REQUEST['type']) || !isset($_SESSION['authenticated_user_id'])) {
	die("Not a Valid Entry Point");
} else {
	// cn: bug 8753: current_user's preferred export charset not being honored
	$current_user->retrieve($_SESSION['authenticated_user_id']);
	$current_language = $_SESSION['authenticated_user_language'];
	$app_strings = return_application_language($current_language);
	$local_location = (isset($_REQUEST['isTempFile'])) ? "{$sugar_config['cache_dir']}/modules/Emails/{$_REQUEST['ieId']}/attachments/{$_REQUEST['id']}"
		 : $sugar_config['upload_dir']."/".$_REQUEST['id'];
	
	
	if(!file_exists( $local_location )) {
		die($app_strings['ERR_INVALID_FILE_REFERENCE']);
	} elseif(strpos($local_location, "../") || strpos($local_location, "..\\") ) {
		die($app_strings['ERR_INVALID_FILE_REFERENCE']);
	} else {
		$doQuery = true;
		
		if(strtolower($_REQUEST['type']) == 'documents') {
			// cn: bug 9674 document_revisions table has no 'name' column.
			$query = "SELECT filename name FROM document_revisions WHERE id = '" . $_REQUEST['id'] ."'";
		} elseif(strtolower($_REQUEST['type']) == 'notes') {
			$query = "SELECT filename name FROM notes WHERE id = '" . $_REQUEST['id'] ."'";
		} elseif(strtolower($_REQUEST['type']) == 'temp') {
			$doQuery = false;
		}
		
		if($doQuery) {
			$rs = $db->query($query);
			$row = $db->fetchByAssoc($rs);
			
			if(empty($row)){
				die($app_strings['ERR_INVALID_FILE_REFERENCE']);
			}
	
			// cn: leave name charset translation to the browsers - they will handle it better than 2nd guessing.
			$emailStrings = return_module_language($current_language, 'Emails');
			$name = urldecode(str_replace($emailStrings['LBL_EMAIL_ATTACHMENT'].': ', '', $row['name']));
			
			if(isset($_SERVER['HTTP_USER_AGENT']) && preg_match("/MSIE/", $_SERVER['HTTP_USER_AGENT'])) {
				// cn: bug 7870 IE cannot handle MBCS in filenames gracefully. set $name var to filename
				$name = str_replace("+", "_", $row['name']);
				$name = $locale->translateCharset($name, 'UTF-8', $locale->getOutboundEmailCharset());
			} else {
				// ff 1.5+
				$name = mb_encode_mimeheader($name, $locale->getOutboundEmailCharset(), 'Q');
			}




			$download_location = $sugar_config['upload_dir']."/".$_REQUEST['id'];
		} else {
			// downloading a temp file (email 2.0)
			$name = $_REQUEST['tempName'];
			$download_location = $local_location;
			if(isset($_SERVER['HTTP_USER_AGENT']) && preg_match("/MSIE/", $_SERVER['HTTP_USER_AGENT'])) {
				// cn: bug 7870 IE cannot handle MBCS in filenames gracefully. set $name var to filename
				$name = str_replace("+", "_", $name);
				$name = $locale->translateCharset($name, 'UTF-8', $locale->getOutboundEmailCharset());
			} else {
				// ff 1.5+
				$name = mb_encode_mimeheader($name, $locale->getOutboundEmailCharset(), 'Q');
			}
		}

		header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
		header("Content-type: application/force-download");
		header("Content-Length: " . filesize($local_location));
		header("Content-disposition: attachment; filename=\"".$name."\";");
//		header("Pragma: ");
		header("Expires: 0");
		set_time_limit(0);
		
		@ob_end_clean();
		ob_start();
		if(filesize($local_location) < 2097152) {
			readfile($download_location);
		} else {
			readfile_chunked($download_location);
		}
		@ob_flush();
	}
}
?>
