<?php
/**
 * @version		$Id: view.feed.php 10381 2008-06-01 03:35:53Z pasamio $
 * @package		Contact_Enhanced
 * @subpackage	Contact
 * @copyright	Copyright (C) 2006 - 2010 Ideal Custom Software Development
 * @author     Douglas Machado {@link http://ideal.fok.com.br}
 * @author     Created on 28-Jul-09
 * @license		GNU/GPL, see license.txt
 * Contact Enhanced  is free software. This version may have been modified pursuant
 * to the GNU General Public License, and as distributed it includes or
 * is derivative of works licensed under the GNU General Public License or
 * other free or open source software licenses.
 */

// Check to ensure this file is included in Joomla!
defined('_JEXEC') or die( 'Restricted access' );

jimport( 'joomla.application.component.controller' );
require_once( JPATH_ADMINISTRATOR.DS.'components'.DS.'com_contact_enhanced'.DS."configuration.php" );
$config	= new CEConfig();

require_once( JPATH_COMPONENT.DS.'helper'.DS."helper.php" );
require_once( JPATH_COMPONENT.DS."defines.php" );

/**
 * Contact Component Controller
 *
 * @static
 * @package		Contact_Enhanced
 * @subpackage	Contact
 * @since 1.5
 */
class ContactController extends JController
{
	var $customfields	= null;
	var $contactId		= null;
	var $emailInfo		= null;
	/**
	 * Display the view
	 */
	function display()
	{
		$document =& JFactory::getDocument();

		if ( ! JRequest::getCmd( 'view' ) ) {
			//$default	= JRequest::getInt('id') ? 'category' : 'category';
			JRequest::setVar('view', 'category' );
		}
		// View caching logic -- simple... are we logged in?
		$user = &JFactory::getUser();
		if ($user->get('id')) {
			parent::display(false);
		} else {
			parent::display(true);
		}
	}


	// 	Get the article name
	function checkUsername(){

		//decode incoming JSON string
		$jsonRequest = json_decode(json_decode(JRequest::getVar('json')));

		//echo '<pre>'; print_r($jsonRequest->username); echo '<pre>'; exit;
		if(strlen($jsonRequest->username) > 3 ){
			$db =& JFactory::getDBO();
			$query = "SELECT id FROM #__users "
			. " WHERE username=".$db->Quote($jsonRequest->username)
			. " LIMIT 1";
			$db->setQuery($query);
			$row = $db->loadObject();
		}
		if ( !isset($row->id) AND strlen($jsonRequest->username) > 3 ) {
			$json	= array('action'=> 'success', 'username' => $jsonRequest->username);
			$this->jsonReturn($json);
		}else{
			$json	=array('action'=> 'error', 'username' => $jsonRequest->username );
			$this->jsonReturn($json);
		}
	}

	/**
	 * Method to send an email to a contact
	 *
	 * @static
	 * @since 1.0
	 */
	function submit()
	{
		global $mainframe;

		$hasFileOver2mb	= false;
		// Check for request forgeries
		//JRequest::checkToken() or jexit( 'Invalid Token' );
		$token		= JUtility::getToken();
		$user		= &JFactory::getUser();
		// Get params and component configurations
		$pparams = &$mainframe->getParams('com_contact_enhanced');
		
		$this->contactId= JRequest::getInt( 'id',	0,	'post' );
		$menuItem = ceHelper::findMenuItem(array('contact'=>$this->contactId));
		if($menuItem){
			$menu = JSite::getMenu();
		    $menuparams = $menu->getParams( $menuItem->id );
		    $pparams->merge( $menuparams );
				
		}

		//Create Cookies in case there is a need to reload the form
		$this->createCookiesFromPost();

		if( ($pparams->get( 'enable_captcha', 2) > 0  AND !$user->get('id') )
		OR $pparams->get( 'enable_captcha', 2) == 2){
			$dispatcher	=& JDispatcher::getInstance();
			// Process the content preparation plugins
			JPluginHelper::importPlugin('content');
			$results = $dispatcher->trigger('onValidateForm', array($pparams));
		}


		// Initialize some variables
		jimport('joomla.mail.helper');
		$mail	= JFactory::getMailer();
		$db		= & JFactory::getDBO();

		$this->emailInfo	= new stdClass();
		$this->emailInfo->siteName		= $mainframe->getCfg('sitename');
		

		// load the contact details
		$model			= &$this->getModel('contact');
		// query options
		$qOptions['id']	= $this->contactId;
		$this->emailInfo->contact		= $model->getContact( $qOptions );


		$default		= JText::sprintf( 'MAILENQUIRY', 	$this->emailInfo->siteName );
		$this->emailInfo->name			= (JRequest::getVar( 'name') ? JRequest::getVar( 'name')	: ($user->get('name') 	? $user->get('name') 	: JText::_('Anonymous User')));
		$_POST['name']					= $this->emailInfo->name;	// Make sure the POST has the correct value
		$this->emailInfo->email			= (JRequest::getVar( 'email')? JRequest::getVar( 'email')	: ($user->get('email') 	? $user->get('email') 	: JText::_('anonymous@user.com')));
		$_POST['email']					= $this->emailInfo->email;	// Make sure the POST has the correct value
		$this->emailInfo->subject		= JRequest::getVar( 'subject',		$default,	'post' );
		$this->emailInfo->emailCopy		= JRequest::getInt( 'email_copy', 	0,			'post' );
		$this->emailInfo->return_url	= JRequest::getVar( 'return_url', 	false,		'post' );

		$this->emailInfo->site_url		= JURI::base();
		$this->emailInfo->site_name		= &$this->emailInfo->siteName;
		$this->emailInfo->site_link		= JHTML::_('link', JURI::base(),$this->emailInfo->siteName);
		$this->emailInfo->contact_url	= JRoute::_('index.php?option=com_contact_enhanced&view=contact&id='.$this->emailInfo->contact->slug.'&catid='.$this->emailInfo->contact->catslug, false);
		$this->emailInfo->contact_link	= JHTML::_('link', $this->emailInfo->contact_url,$this->emailInfo->contact->name);


		$this->customfields	= ceHelper::getCustomFields( $this->emailInfo->contact->catid);

		//Get only the fields used
		$submittedFields	= ceHelper::getSubmitedFields($this->customfields, $pparams);
		$this->emailInfo->cfText		= ''; // For text
		$this->emailInfo->attachments	= '';
		$this->emailInfo->plainTextAttachments	= '';
		$totalFilesize					= 0;
		$this->emailInfo->custom_fields	= '';
		$filesToAttach	= array();
		//testArray($submittedFields);
		//Add fields to message
		$tmplParams	= $this->getTemplateParams($pparams->get('emailOutputType-html-template','default'));

		foreach($submittedFields as $cf){
				
			if($cf->type != 'multiplefiles' AND $cf->type != 'file' ){
				$this->customfields[$cf->type]	= $cf;
				$this->emailInfo->cfText .= $cf->getEmailOutput();
				if($pparams->get('emailOutputType') == 'html' OR $pparams->get('emailOutputTypeCopy') == 'html' OR $pparams->get('thankyoumsg') == 'showmsg'){
					$this->emailInfo->custom_fields .= $cf->getEmailOutput(', ', 'html', array('label'=>$tmplParams->get('style-cf-label'),'value'=>$tmplParams->get('style-cf-value')));
				}
			}
			//If it is a file add as attachment
			if( $cf->type == 'multiplefiles'  ){ //OR $cf->type == 'file'
				// Adds parameter handling

				$customfield = &$cf;

				$max_file_size	= ($cf->params->get( 'max_file_size',300)*1024);

				if($cf->uservalue['name'] != ''){
					for($i=0; $i < count($cf->uservalue['name']); $i++){
							
						if(is_array($cf->uservalue['name'])){
							$filesize	= $cf->uservalue['size'][$i];
							$filename	= JFile::makeSafe($cf->uservalue['name'][$i]);
							$filetemp	= $cf->uservalue['tmp_name'][$i];
						}else{
							$filesize	= $cf->uservalue['size'];
							$filename	= JFile::makeSafe($cf->uservalue['name']);
							$filetemp	= $cf->uservalue['tmp_name'];
						}
						if(	$filesize > $max_file_size ){
							echo '<script>alert("'.JText::sprintf('FILE_TOO_LARGE',$filename,($filesize/1024),($max_file_size/1024)).'");history.back();</script>';
							exit;
						}elseif( !$customfield->validateFileExtension($filename) ){
							echo '<script>alert("'.$customfield->getLastError().'");history.back();</script>';
							exit;
						}
						$totalFilesize += $filesize;
						$filename	= basename($filename);
						if(move_uploaded_file($filetemp, UPLOADED_FILE_PATH.$filename)) {
							if($filesize > 2000000){ /* A little bit lesss than 2MB for safety reasons  */
								$hasFileOver2mb	= true;
							}
							$filesToAttach[]	= $filename;
						} else{
							JError::raiseWarning( 0, $this->file_upload_error_message($cf->uservalue['error'][$i]) );
							return false;
						}


					}
				}
			}
		}

		if($this->emailInfo->contact->email_to == '' && $this->emailInfo->contact->user_id != 0)
		{
			$contact_user = JUser::getInstance($this->emailInfo->contact->user_id);
			$this->emailInfo->contact->email_to = $contact_user->get('email');
		}

		/*
		 * If there is no valid email address or message body then we throw an
		 * error and return false.
		 */

		if (!$this->emailInfo->email || (JMailHelper::isEmailAddress($this->emailInfo->email) == false))
		{
			$this->setError(JText::_('CONTACT_FORM_NC'));
			$this->display();
			return false;
		}

		// Contact plugins
		JPluginHelper::importPlugin( 'contact' );
		$dispatcher	=& JDispatcher::getInstance();

		// Input validation
		if  (!$this->_validateInputs( $this->emailInfo->contact, $this->emailInfo->email, $this->emailInfo->subject, $this->emailInfo->cfText ) ) {
			JError::raiseWarning( 0, $this->getError() );
			return false;
		}

		// Custom handlers
		$post		= JRequest::get( 'post' );
		$results	= $dispatcher->trigger( 'onValidateContact', array( &$this->emailInfo->contact, &$post ) );

		foreach ($results as $result)
		{
			if (JError::isError( $result )) {
				return false;
			}
		}

		// Passed Validation: Process the contact plugins to integrate with other applications
		$results	= $dispatcher->trigger( 'onSubmitContact', array( &$this->emailInfo->contact, &$post ) );

		// Adds parameter handling
		$this->emailInfo->contact->params = new JParameter($this->emailInfo->contact->params);
		$pparams->merge($this->emailInfo->contact->params);

		//Do Registration
		if ( ($pparams->get( 'register', 0 ) > 0  OR JRequest::getVar('username')) AND !$user->get('id') ) {
			$this->_registration($pparams,$this->emailInfo->name,$this->emailInfo->email);
		}

		/**
		 *
		 * */
		$MailFrom 	= $mainframe->getCfg('mailfrom');
		$FromName 	= $mainframe->getCfg('fromname');
			
		$this->emailInfo->subject = $this->getSubject($this->emailInfo->subject);
		$mail->setSubject( $this->emailInfo->subject );
			
		$surname	= ' '.JRequest::getVar( 'cf_surname',	'' );
		// Prepare email body
		$this->emailInfo->enquiry	= JText::sprintf('ENQUIRY_TEXT', JHTML::_('link', $this->emailInfo->contact_url,$this->emailInfo->siteName) )
		."\n<br />".$this->emailInfo->name. $surname .' < '.$this->emailInfo->email.' >';
		$this->emailInfo->body 	= strip_tags($this->emailInfo->enquiry)."\n\n".$this->emailInfo->cfText."\r\n" ;
			
		$mainEmailBody	= ($this->emailInfo->body);
			
			
		//Get System Info (SO, Browser, Screen Resolution, IP, Referrers)
		$this->emailInfo->system_info	= ceHelper::getSystemInfo($pparams);
			
		if($this->emailInfo->emailCopy){
			$this->emailInfo->system_info .= "\n\n\t<hr /><br />".JText::_('The user has requested a copy of this email');
		}
			
		if ( $pparams->get( 'showuserinfo',1) ) {
			$mainEmailBody	= strip_tags($this->emailInfo->body.$this->emailInfo->system_info);
		}
			
		// Save contact if needed
		if($pparams->get( 'saveform',1 ) OR $hasFileOver2mb){

			$date =& JFactory::getDate();

			$emailData				= new stdClass();
			$emailData->id			= 0;
			$emailData->parent		= 0;
			$emailData->from_name	= $this->emailInfo->name;
			$emailData->from_email	= $this->emailInfo->email;
			$emailData->from_id		= $user->id;
			$emailData->subject		= $this->emailInfo->subject;
			$emailData->contact_id	= $this->emailInfo->contact->id;
			$emailData->category_id	= $this->emailInfo->contact->catid;
			$emailData->date		= $date->toMySQL();
			$emailData->reply_date	= '';
			$emailData->replied_by	= '';
			$emailData->message		= $mainEmailBody;
			$emailData->user_ip		= $_SERVER['REMOTE_ADDR'];
				
				
			$emailData->files		= $filesToAttach;
			$emailData->fields		= $submittedFields;
				
			$emailData->id	= $this->saveForm($emailData);
				
			if( count($filesToAttach) > 0 ){
				$this->emailInfo->attachments .= '<div><strong>'.JText::_('Attachments').'</strong></div>';
				//Delete files if the contact will not be saved
				for($i=0; $i<count($filesToAttach);$i++){
					$filesToAttach[$i]	= $emailData->id.'_'.$filesToAttach[$i];
						
					if($totalFilesize <= 2000000){
						$mail->addAttachment(UPLOADED_FILE_PATH.$filesToAttach[$i]);
					}else{
						$this->emailInfo->plainTextAttachments	.= 	ceHelper::formatAttachment($filesToAttach[$i],$emailData->id, 'plain');
					}
						
					$this->emailInfo->attachments	.= '<br />'.ceHelper::formatAttachment($filesToAttach[$i],$emailData->id);
				}
				$filesToAttach	= array(); // reset array
			}
		}elseif( count($filesToAttach) > 0 ){
			//Delete files if the contact will not be saved
			foreach($filesToAttach as $fileToAttach){
				$mail->addAttachment(UPLOADED_FILE_PATH.$fileToAttach);
			}
		}

		$pparams = &$mainframe->getParams('com_contact_enhanced');
		if (!$pparams->get( 'custom_reply' ))
		{
			if($this->emailInfo->plainTextAttachments != ''){
				$mainEmailBody	= $mainEmailBody."\n\n".JText::_('Attachments').':'.$this->emailInfo->plainTextAttachments;
			}
				
			$mail->setBody( $mainEmailBody);
				
			if($pparams->get('emailOutputType') == 'html'){
				$mail->MsgHTML( $this->getEmailHTML($pparams->get('emailOutputType-html-template','default')));
				$mail->AltBody= $mainEmailBody;
			}
				
			// Do we use with the Contact Author plugin?
			if(JRequest::getInt('author_id')){
				$db =&  JFactory::getDBO();
				$db->setQuery('SELECT * FROM #__users WHERE id='.$db->Quote(JRequest::getInt('author_id')));
				$author	= $db->loadObject();
				$recipient	= $author->email;
			}elseif(JRequest::getVar( 'recipient')){
				$recipient	= $this->customfields['recipient']->getSelectedValue(JRequest::getVar( 'recipient'));
			}
			if(!isset($recipient) OR !JMailHelper::isEmailAddress($recipient)){
				$recipient	= explode(',', $this->emailInfo->contact->email_to);
			}
		
			$mail->addRecipient($recipient );
	//$mail->setSender( array( $this->emailInfo->email, $this->emailInfo->name.$surname ) );
$mail->setSender(array('sanjeewak@maliban.com', 'Your Name / Your Company'));
			if($pparams->get('email_bcc')){
				$mail->addBCC(explode(',', $pparams->get('email_bcc')));
			}
			// @todo: remove this if statement from next version 1.5.7.5 or greater
			if($pparams->get('emailcopytoadmin')){
				$mail->addBCC($MailFrom);
			}
				
			$sent = $mail->Send();
				
			if($pparams->get('debug_mode',0) OR $mainframe->getCfg('debug')){
				$this->sendDebugMessage($this->emailInfo->subject);
			}
				
			/*
			 * If we are supposed to copy the sender, do so.
			 */
			// parameter check
			//$params = new JParameter( $this->emailInfo->contact->params );
			$emailcopyCheck = $this->emailInfo->contact->params->get( 'show_email_copy', 1 );

			// check whether email copy function activated
			if ( $this->emailInfo->emailCopy && $emailcopyCheck )
			{

				$copyText 		= JText::sprintf('Copy of:', $this->emailInfo->contact->name, $this->emailInfo->siteName);
				$copyText 		.= "\r\n\r\n".$this->emailInfo->body;
				$copySubject 	= JText::_('Copy of:')." ".$this->emailInfo->subject;

				$mail = JFactory::getMailer();

				if(is_array($recipient)){
					$recipient	= $recipient[0];
				}
				/*$MailFrom 	= $mainframe->getCfg('mailfrom');
				$FromName 	= $mainframe->getCfg('fromname');*/
				$mail->addRecipient( $this->emailInfo->email );
				//$mail->setSender( array( $MailFrom, $FromName ) );
				$mail->setSender( array( $recipient, $FromName ) );
				$mail->setSubject( $copySubject );
				$mail->setBody( $copyText );

				if($pparams->get('emailOutputTypeCopy') == 'html'){
					// reset system info
					$this->emailInfo->system_info = '';
					$this->emailInfo->enquiry	= JText::_('Copy of:').' '.$this->emailInfo->enquiry;
					$mail->MsgHTML( $this->getEmailHTML($pparams->get('emailOutputTypeCopy-html-template','default')));
					$mail->AltBody= $mainEmailBody;
				}
					
				$sent = $mail->Send();
			}
		}

		//No more need for cookies: Destroy them
		$this->detroyPostCookies();

		if( count($filesToAttach) > 0 ){
			//Delete files if the contact will not be saved
			foreach($filesToAttach as $fileToDelete){
				JFile::delete(UPLOADED_FILE_PATH.$fileToDelete);
			}
		}
			
		if($sent){
			$msg = JText::_( 'Thank you for your e-mail');
		}else{
			$msg = JText::_( 'Email not sent, please notify administrator');
		}
		$link = JRoute::_('index.php?option=com_contact_enhanced&view=contact&id='.$this->emailInfo->contact->slug.'&catid='.$this->emailInfo->contact->catslug, false);
		$tmpl	=  (JRequest::getVar('tmpl') ? '&tmpl='.JRequest::getVar('tmpl') : '' );


		//used in plugin system
		if($this->emailInfo->return_url AND $pparams->get( 'thankyoumsg') == 'redirect' ){
			$pparams->set( 'thankyoumsg','redirect' );
			$pparams->set( 'custom_redirect', $this->emailInfo->return_url);
		}
		/**
		 * @FIXME: This is ugly! Create a view & tmpl for this bellow
		 */
		if ( $pparams->get( 'thankyoumsg' ) == 'showmsg' ) {
			echo '<div class="ce-modal-container">';
			if ( $pparams->get( 'show_page_title', 1 ) ) : ?>
				<div class="componentheading<?php echo $pparams->get( 'pageclass_sfx' ); ?>">
					<?php echo $pparams->get( 'page_title' ); ?></div>
			<?php endif;
				ceHelper::loadCSSFiles();
				echo $this->getTemplateHTML($pparams->get('thankyoumsg-showmsg-template','default'),'resultPage');
			echo '</div>';
				
		}else if ( $pparams->get( 'thankyoumsg' ) == 'alert' ) {
			$this->setRedirect($link, $msg);
		}else if ( $pparams->get( 'thankyoumsg' ) == 'redirect' ) {
			//Get custom redirect
			$customRedirect = trim( $pparams->get( 'custom_redirect',false) );
			if( substr( $customRedirect, 0, 9) == 'index.php' ){
				$link = JRoute::_($customRedirect, false);
				$this->setRedirect($link, $msg);
			}elseif( substr( $customRedirect, 0, 4) == 'http' ){
				header("Location: ".$customRedirect);
			}else{
				$link = JRoute::_('index.php?option=com_contact_enhanced&view=contact&id='.$this->emailInfo->contact->slug.'&catid='.$this->emailInfo->contact->catslug, false);
				$this->setRedirect($link, $msg);
			}
		}else{
			$link = JRoute::_('index.php?option=com_contact_enhanced&view=contact&id='.$this->emailInfo->contact->slug.'&catid='.$this->emailInfo->contact->catslug, false);
			$this->setRedirect($link, $msg);
		}

	}

	function saveForm(&$emailData){
		JTable::addIncludePath(ADMIN_COMPONENT_FOLDER.'tables');

		// Initialize variables
		$db		=& JFactory::getDBO();
		$table	=& JTable::getInstance('message', 'Table');

		if (!$table->bind( $emailData )) {
			JError::raiseError(500, $row->getError() );
		}
		if (!$table->store()) {
			JError::raiseError(500, $row->getError() );
		}
		$message_id	= $table->id;
		if( count($emailData->files) > 0 ){
			for($i=0; $i < count($emailData->files); $i++){
				$file = $emailData->files[$i];
				$emailData->files[$i]	= $message_id.'_'.$file;
				JFile::move($file,$emailData->files[$i],UPLOADED_FILE_PATH);
			}
		}

		foreach($emailData->fields as $cf){
			$table	=& JTable::getInstance('messagefields', 'Table');
			$field				= new stdClass();
			$field->id			= 0;
			$field->message_id	= $message_id;
			$field->field_id	= $cf->id;
			$field->field_type	= $cf->type;
			$field->modified	= 0;
			if($cf->type == 'multiplefiles'){
				$field->value	= 	implode(' | ',$emailData->files);
			}elseif($cf->type == 'sql'){
				$field->value	= 	$cf->getMySQLOutput();
			}else{
				$field->value	= $cf->uservalue;
			}
				
			if (!$table->bind( $field )) {
				JError::raiseError(500, $row->getError() );
			}
			if (!$table->store()) {
				JError::raiseError(500, $row->getError() );
			}
				
		}
		return $message_id;

	}



	/**
	 * Method to output a vCard
	 *
	 * @static
	 * @since 1.0
	 */
	function vcard()
	{
		global $mainframe;

		// Initialize some variables
		$db = & JFactory::getDBO();

		$SiteName = $mainframe->getCfg('sitename');
		$contactId = JRequest::getVar('contact_id', 0, '', 'int');
		// Get a Contact table object and load the selected contact details
		JTable::addIncludePath(JPATH_ADMINISTRATOR.DS.'components'.DS.COMPONENT_FOLDER.DS.'tables');
		$contact =& JTable::getInstance('contact', 'Table');
		$contact->load($contactId);
		$user =& JFactory::getUser();

		// Get the contact detail parameters
		$params = new JParameter($contact->params);
		//echo '<pre>'; print_r($contact); echo '<pre>'; exit;
		// Show the Vcard if contact parameter indicates (prevents direct access)
		if (($params->get('allow_vcard', 0)) && ($user->get('aid', 0) >= $contact->access))
		{
			// Parse the contact name field and build the nam information for the vcard.
			$firstname 	= null;
			$middlename = null;
			$surname 	= null;

			// How many parts do we have?
			$parts = explode(' ', $contact->name);
			$count = count($parts);

			switch ($count) {
				case 1 :
					// only a first name
					$firstname = $parts[0];
					break;

				case 2 :
					// first and last name
					$firstname = $parts[0];
					$surname = $parts[1];
					break;

				default :
					// we have full name info
					$firstname = $parts[0];
					$surname = $parts[$count -1];
					for ($i = 1; $i < $count -1; $i ++) {
						$middlename .= $parts[$i].' ';
					}
					break;
			}
			// quick cleanup for the middlename value
			$middlename = trim($middlename);

			// Create a new vcard object and populate the fields
			require_once(JPATH_ADMINISTRATOR.DS.'components'.DS.'com_contact_enhanced'.DS.'helpers'.DS.'vcard.php');
			$v = new JvCard();

			$v->setPhoneNumber($contact->telephone, 'PREF;WORK;VOICE');
			$v->setPhoneNumber($contact->fax, 'WORK;FAX');
			$v->setName($surname, $firstname, $middlename, '');
			$v->setAddress('', '', $contact->address, $contact->suburb, $contact->state, $contact->postcode, $contact->country, 'WORK;POSTAL');
			$v->setEmail($contact->email_to);
			$v->setNote($contact->misc);
			$v->setURL( JURI::base(), 'WORK');
			$v->setTitle($contact->con_position);
			$v->setOrg(html_entity_decode($SiteName, ENT_COMPAT, 'UTF-8'));

			$filename = str_replace(' ', '_', $contact->name);
			$v->setFilename($filename);

			$output = $v->getVCard(html_entity_decode($SiteName, ENT_COMPAT, 'UTF-8'));
			$filename = $v->getFileName();

			// Send vCard file headers
			header('Content-Disposition: attachment; filename='.$filename);
			header('Content-Length: '.strlen($output));
			header('Connection: close');
			header('Content-Type: text/x-vCard; name='.$filename);
			header('Cache-Control: store, cache');
			header('Pragma: cache');

			print $output;
		} else {
			JError::raiseWarning('SOME_ERROR_CODE', 'ContactController::vCard: '.JText::_('ALERTNOTAUTH'));
			return false;
		}
	}

	/**
	 * Validates some inputs based on component configuration
	 *
	 * @param Object	$contact	JTable Object
	 * @param String	$email		Email address
	 * @param String	$subject	Email subject
	 * @param String	$body		Email body
	 * @return Boolean
	 * @access protected
	 * @since 1.5
	 */
	function _validateInputs( $contact, $email, $subject, $body )
	{
		global $mainframe;

		$session =& JFactory::getSession();

		// Get params and component configurations
		$params		= new JParameter($contact->params);
		$pparams	= &$mainframe->getParams('com_contact_enhanced');

		// check for session cookie
		$sessionCheck 	= $pparams->get( 'validate_session', 1 );
		$sessionName	= $session->getName();
		if  ( $sessionCheck ) {
			if ( !isset($_COOKIE[$sessionName]) ) {
				$this->setError( JText::_('ALERTNOTAUTH') );
				return false;
			}
		}

		// Determine banned e-mails
		$configEmail	= $pparams->get( 'banned_email', '' );
		$paramsEmail	= $params->get( 'banned_mail', '' );
		$bannedEmail 	= $configEmail . ($paramsEmail ? ';'.$paramsEmail : '');

		// Prevent form submission if one of the banned text is discovered in the email field
		if(false === $this->_checkText($email, $bannedEmail )) {
			$this->setError( JText::sprintf('MESGHASBANNEDTEXT', 'Email') );
			return false;
		}

		// Determine banned subjects
		$configSubject	= $pparams->get( 'banned_subject', '' );
		$paramsSubject	= $params->get( 'banned_subject', '' );
		$bannedSubject 	= $configSubject . ( $paramsSubject ? ';'.$paramsSubject : '');

		// Prevent form submission if one of the banned text is discovered in the subject field
		if(false === $this->_checkText($subject, $bannedSubject)) {
			$this->setError( JText::sprintf('MESGHASBANNEDTEXT', 'Subject') );
			return false;
		}

		// Determine banned Text
		$configText		= $pparams->get( 'banned_text', '' );
		$paramsText		= $params->get( 'banned_text', '' );
		$bannedText 	= $configText . ( $paramsText ? ';'.$paramsText : '' );

		// Prevent form submission if one of the banned text is discovered in the text field
		if(false === $this->_checkText( $body, $bannedText )) {
			$this->setError( JText::sprintf('MESGHASBANNEDTEXT', 'Message') );
			return false;
		}

		// test to ensure that only one email address is entered
		$check = explode( '@', $email );
		if ( strpos( $email, ';' ) || strpos( $email, ',' ) || strpos( $email, ' ' ) || count( $check ) > 2 ) {
			$this->setError( JText::_( 'You cannot enter more than one email address', true ) );
			return false;
		}

		return true;
	}

	/**
	 * Checks $text for values contained in the array $array, and sets error message if true...
	 *
	 * @param String	$text		Text to search against
	 * @param String	$list		semicolon (;) seperated list of banned values
	 * @return Boolean
	 * @access protected
	 * @since 1.5.4
	 */
	function _checkText($text, $list) {
		if(empty($list) || empty($text)) return true;
		$array = explode(';', $list);
		foreach ($array as $value) {
			$value = trim($value);
			if(empty($value)) continue;
			if ( JString::stristr($text, $value) !== false ) {
				return false;
			}
		}
		return true;
	}


	function _registration(&$pparams,&$name,&$email){
		global $mainframe;
		$lang =& JFactory::getLanguage();
		$lang->load('com_user');
		jimport('joomla.user.helper');

		// Initialize some variables
		$authorize	= & JFactory::getACL();
		$db			= & JFactory::getDBO();
		$MailFrom 	= $mainframe->getCfg('mailfrom');
		$FromName 	= $mainframe->getCfg('fromname');
		$SiteName	= $mainframe->getCfg('sitename');

		// If user registration is not allowed, show notify Site Administrator.
		$usersConfig = &JComponentHelper::getParams( 'com_users' );
		if ($usersConfig->get('allowUserRegistration') == '0') {
				
			$mail = JFactory::getMailer();
			$mail->addRecipient( $MailFrom );
			$mail->setSender( array( $MailFrom, $FromName ) );
			$mail->setSubject( $SiteName .': '.JText::_('Auto Registration not allowed') );
			$body = JText::_('Auto Registration not allowed'). "\n\n"
			. JText::_('Check Joomla Global Configuration or disable Contact Enhanced Silent registration');
			$mail->setBody( $body );
			$mail->Send();
				
			return;
		} //end if

		$username	= preg_replace( "/^([^@]+)(@.*)$/", "$1", $email);
		$username	= JRequest::getVar('username',$username);

		$query = 'SELECT count(*) '
		. ' FROM #__users'
		. ' WHERE username = '.$db->Quote($username)
		. ' OR email = '.  $db->Quote($email)
		;
		$db->setQuery( $query );
		$isRegistered = $db->loadResult();
		// Abort operation if the user is already registered
		if($isRegistered){
			$mainframe->enqueueMessage(JText::sprintf('USER_REGISTERED_OR_USERNAME_NOT_AVAILABLE',$email,$username),'notice');
			return false;
		}

		$password 		= $this->_generatePassword(8);
		$password		= JRequest::getVar('password',$password);

		$info	= array();
		$info['email']	= $email;
		$info['name']	= $name;
		$info['username']	= $username;
		$info['password']	= $password;
		$info['password2']	= $password;

		// Create a new JUser object
		$user = new JUser(0);

		// Initialize new usertype setting
		$newUsertype = $usersConfig->get( 'new_usertype' );
		if (!$newUsertype) {
			$newUsertype = 'Registered';
		}

		if (!$user->bind( $info, 'usertype' )) {
			$mail = JFactory::getMailer();
			$mail->addRecipient( $MailFrom );
			$mail->setSender( array( $MailFrom, $FromName ) );
			$mail->setSubject( $SiteName .': '.JText::_('CANNOT SAVE THE USER INFORMATION') );
				
			$body = JText::_('CANNOT SAVE THE USER INFORMATION'). "\n\n";
			$body .= JText::_('User info'). ":\n";
			$body .= JText::_('Name').":\t".$info['name']."\n";
			$body .= JText::_('Email').":\t".$info['email']."\n";
			$body .= JText::_('Username').":\t".$info['username']."\n";
				
			$mail->setBody( $body );
			$mail->Send();
			return ;
		}

		// Set some initial user values
		$user->set('id', 0);
		$user->set('usertype', '');
		$user->set('gid', $authorize->get_group_id( '', $newUsertype, 'ARO' ));

		$date =& JFactory::getDate();
		$user->set('registerDate', $date->toMySQL());

		// If user activation is turned on, we need to set the activation information
		$useractivation = $usersConfig->get( 'useractivation' );
		if ($useractivation == '1')
		{
			$user->set('activation', JUtility::getHash( $info['password']) );
			$user->set('block', '1');
			$message  = JText::_( 'REG_COMPLETE_ACTIVATE' );
		}else {
			$message = JText::_( 'REG_COMPLETE' );
		}

		// If there was an error with registration, set the message and display form
		if ( !$user->save() )
		{
			$mail = JFactory::getMailer();
			$mail->addRecipient( $MailFrom );
			$mail->setSender( array( $MailFrom, $FromName ) );
			$mail->setSubject( $SiteName .': '.JText::_( $user->getError()) );
			$mail->setBody( JText::_( $user->getError()) );
			$mail->Send();
			return ;
		}else{
			$mainframe->enqueueMessage($message, 'message');
		}

		// Send registration confirmation mail
		ContactController::_sendRegistrationMail($user, $password);

	}

	function _sendRegistrationMail(&$user, $password)
	{
		global $mainframe;
		$lang =& JFactory::getLanguage();
		$lang->load('com_user');

		$db		=& JFactory::getDBO();

		$name 		= $user->get('name');
		$email 		= $user->get('email');
		$username 	= $user->get('username');

		$usersConfig 	= &JComponentHelper::getParams( 'com_users' );
		$sitename 		= $mainframe->getCfg( 'sitename' );
		$useractivation = $usersConfig->get( 'useractivation' );
		$mailfrom 		= $mainframe->getCfg( 'mailfrom' );
		$fromname 		= $mainframe->getCfg( 'fromname' );
		$siteURL		= JURI::base();

		$subject 	= sprintf ( JText::_( 'Account details for' ), $name, $sitename);
		$subject 	= html_entity_decode($subject, ENT_QUOTES);

		if ( $useractivation == 1 ){
			$message = sprintf ( JText::_( 'SEND_MSG_ACTIVATE' ), $name, $sitename, $siteURL."index.php?option=com_user&task=activate&activation=".$user->get('activation'), $siteURL, $username, $password);
		} else {
			$message = sprintf ( JText::_( 'SEND_MSG' ), $name, $sitename, $siteURL);
		}

		$message = html_entity_decode($message, ENT_QUOTES);

		//get all super administrator
		$query = 'SELECT name, email, sendEmail' .
				' FROM #__users' .
				' WHERE LOWER( usertype ) = "super administrator"';
		$db->setQuery( $query );
		$rows = $db->loadObjectList();

		// Send email to user
		if ( ! $mailfrom  || ! $fromname ) {
			$fromname = $rows[0]->name;
			$mailfrom = $rows[0]->email;
		}

		JUtility::sendMail($mailfrom, $fromname, $email, $subject, $message);

		// Send notification to all administrators
		$subject2 = sprintf ( JText::_( 'Account details for' ), $name, $sitename);
		$subject2 = html_entity_decode($subject2, ENT_QUOTES);

		// get superadministrators id
		foreach ( $rows as $row )
		{
			if ($row->sendEmail)
			{
				$message2 = sprintf ( JText::_( 'SEND_MSG_ADMIN' ), $row->name, $sitename, $name, $email, $username);
				$message2 = html_entity_decode($message2, ENT_QUOTES);
				JUtility::sendMail($mailfrom, $fromname, $row->email, $subject2, $message2);
			}
		}
	}

	function _generatePassword($length=6,$level=2){

		list($usec, $sec) = explode(' ', microtime());
		srand((float) $sec + ((float) $usec * 100000));

		$validchars[1] = "0123456789abcdfghjkmnpqrstvwxyz";
		$validchars[2] = "0123456789abcdfghjkmnpqrstvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
		$validchars[3] = "0123456789_!@#$%&*()-=+/abcdfghjkmnpqrstvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ{}[]<>";

		$password  = "";
		$counter	= 0;

		while ($counter < $length) {
			$actChar = substr($validchars[$level], rand(0, strlen($validchars[$level])-1), 1);
			// All character must be different
			if (!strstr($password, $actChar)) {
				$password .= $actChar;
				$counter++;
			}
		}

		return $password;
	}

	function jsonReturn(&$json){

		echo json_encode( $json ); exit();
	}

	/**
	 * Creates cookies from $_POST variable, this way we can retrieve the information in case the captcha code was wrong
	 * @param	int		Unix time;
	 * @author	Douglas Machado {@link http://ideal.fok.com.br}
	 */
	function createCookiesFromPost($lifetime=null){
		$session 		=& JFactory::getSession();
		$session->set('ce_session', null);
		//create a cookie for each item, in case user type a wrong Image Code
		if(!$lifetime){
			$lifetime = time() + 86400; // 86400 = 24*60*60 = 1 day;
		}
		foreach($_POST as $form_field => $field_value){
			if( is_array($field_value) ){
				//setcookie("ce_cookie[$form_field]", $field_value[0], $lifetime, '/' );
				for($i=0; $i < count($field_value); $i++){
					if( array_key_exists('value',$field_value) ){
						
					}else{
						if(isset($field_value[$i]) AND !is_array($field_value[$i]) ){
							$cur_field_value	= $field_value[$i];
							setcookie("ce_cookie[".$form_field."_".$i."]", $cur_field_value, $lifetime, '/' );
						}elseif(isset($field_value[$i]) AND is_array($field_value[$i])){
							// cannot save multi dimensional array in cookie, storing in sessions instead
							$session 		=& JFactory::getSession();
							$ce_session		= $session->get('ce_session', array());
							$ce_session[$form_field]	= $field_value;
							$session->set('ce_session', $ce_session);	
						}
					}
				}
			}else{
				setcookie("ce_cookie[$form_field]", $field_value, $lifetime, '/' );
			}
		}
		if($lifetime < time()){
			$session->set('ce_session', null);
		}
	}

	function detroyPostCookies(){
		$this->createCookiesFromPost(1); // in UNIX time 1 is equivalent to 1/1/1970 00:00:01
	}

	function downloadAttachment($download_mode='attachment'){
		$file		= JRequest::getVar('file');
		$file		= ceHelper::decode($file);
		ceHelper::download($file,$download_mode);
	}

	function viewAttachment(){
		$this->downloadAttachment('inline');
	}

	function getChainSelect(){
		$config		=& JFactory::getConfig();

		JRequest::setVar('tmpl','component');
		//decode incoming JSON string
		$jsonRequest = json_decode(json_decode(JRequest::getVar('json')));

		//echo '<pre>'; print_r($jsonRequest); echo '<pre>'; exit;
		if(	$jsonRequest->fieldID AND $jsonRequest->selectedOption){
			$db =& JFactory::getDBO();
			$query = "SELECT params,value FROM #__contact_enhanced_cf "
			. " WHERE id=".$db->Quote($jsonRequest->fieldID)
			. " LIMIT 1";
			$db->setQuery($query);
			$obj = $db->loadObject();
				
			$user	= &JFactory::getUser();

			$regex = '/{user_id}/i';
			$obj->value  = preg_replace( $regex, $user->id, 		$obj->value );
				
			$regex = '/{user_email}/i';
			$obj->value  = preg_replace( $regex, $user->email, 	$obj->value );
				
			$regex = '/{username}/i';
			$obj->value  = preg_replace( $regex, $user->username,	$obj->value );

			$regex = '/{selectresult}/i';
			$obj->value  = preg_replace( $regex, $jsonRequest->selectedOption ,$obj->value );
				
			$db->setQuery($obj->value);
			$row = $db->loadAssocList();
				
			$obj->params = new JParameter($obj->params);
			$option	= array();
			$option[0]['value']	= '';
			$option[0]['text']	= $obj->params->get('chain_select-enabled-first_option', JText::_('Please select one'));
			$row	= array_merge($option,$row);
		}
		if ( isset($row) AND count($row) > 0 ) {
			$json	= array('action'=> 'success', 'value'=> $row);
			$this->jsonReturn($json);
		}else{
			$json	=array('action' =>'error');
			$this->jsonReturn($json);
		}
	}

	function getSubject($subject){
		global $mainframe;

		$params	=	new JParameter('');
		if(isset($this->customfields['subject'])){
			$params	= &$this->customfields['subject']->params;
		}
		if($params->get('prefix') == 'none'){
			return 	$subject;
		}else if($params->get('prefix') == 'text'){
			return $params->get('prefix-text-value'). ' '.$subject;
		}else{
			return htmlspecialchars_decode($mainframe->getCfg('sitename')). ': '.$subject;
		}

	}

	function getTemplateHTML($template,$templateType='email'){
		global $mainframe;

		if(file_exists(JPATH_COMPONENT.DS.'templates'.DS.$templateType.DS.$template.DS.'index.html')){
			$htmlFile	= JPATH_COMPONENT.DS.'templates'.DS.$templateType.DS.$template.DS.'index.html';
		}elseif(file_exists(JPATH_COMPONENT.DS.'templates'.DS.$templateType.DS.'default'.DS.'index.html')){
			$htmlFile	= JPATH_COMPONENT.DS.'templates'.DS.$templateType.DS.'default'.DS.'index.html';
			JError::raiseWarning( 0, JText::sprintf('Email template does not exists',$templateType.'/'.$template ) );
		}else{
			JError::raiseWarning( 0, JText::sprintf('Email template does not exists',$templateType.'/default' ) );
		}
		$html	= file_get_contents($htmlFile);

		//language replacements
		// expression to search for
		$regex = "#{txt(.*?)}#s";
		// find all instances of plugin and put in $matches
		preg_match_all( $regex, $html, $matches );
		$count	= count( $matches[0] );
		//testArray($matches[0]);
		if($count){
			for ( $i=0; $i < $count; $i++ )
			{
				$txt = str_replace( '{txt:'	, '', $matches[0][$i] );
				$txt = str_replace( '}'		, '', $txt );
				$html 	= str_replace($matches[0][$i], JText::_(trim( $txt )), $html);
			}
		}

		//POST replacements
		// expression to search for
		$regex = "#{post(.*?)}#s";
		// find all instances of plugin and put in $matches
		preg_match_all( $regex, $html, $matches );
		$count	= count( $matches[0] );
		//testArray($matches[0]);
		if($count){
			$db =& JFactory::getDBO();
			for ( $i=0; $i < $count; $i++ )
			{
				$post = str_ireplace( '{post:'	, '', $matches[0][$i] );
				$post = str_ireplace( '}'		, '', $post );
				$post =	JRequest::getVar($post,JRequest::getVar('cf_'.$post,'post' ),'post' );
				if(is_array($post))	$post = (isset($post[0]) ? $post[0] : (isset($post['value']) ? $post['value'][0] : '')  );
				$html 	= str_ireplace($matches[0][$i], $post, $html);
			}
		}

		$date			=& JFactory::getDate(time());
		$this->emailInfo->templateURI		= JURI::root().'components/com_contact_enhanced/templates/'.$templateType.'/'.$template.'/';
		$this->emailInfo->timestamp			= $date->toFormat(JText::_('DATE_FORMAT_LC2'));
		$this->emailInfo->DATE_FORMAT_LC	= $date->toFormat(JText::_('DATE_FORMAT_LC'));
		$this->emailInfo->DATE_FORMAT_LC1	= $date->toFormat(JText::_('DATE_FORMAT_LC1'));
		$this->emailInfo->DATE_FORMAT_LC2	= $date->toFormat(JText::_('DATE_FORMAT_LC2'));
		$this->emailInfo->DATE_FORMAT_LC3	= $date->toFormat(JText::_('DATE_FORMAT_LC3'));
		$this->emailInfo->DATE_FORMAT_LC4	= $date->toFormat(JText::_('DATE_FORMAT_LC4'));

		// replace tags
		$html	= ceHelper::replaceTags($html,$this->emailInfo);

		//SQL replacements
		// expression to search for
		$regex = "#{sql(.*?)}#s";
		// find all instances of plugin and put in $matches
		preg_match_all( $regex, $html, $matches );
		$count	= count( $matches[0] );
		//testArray($matches[0]);
		if($count){
			$db =& JFactory::getDBO();
			for ( $i=0; $i < $count; $i++ )
			{
				$sql = str_ireplace( '{sql:'	, '', $matches[0][$i] );
				$sql = str_ireplace( '}'		, '', $sql );
				$db->setQuery($sql);
				$html 	= str_ireplace($matches[0][$i], $db->loadResult(), $html);
			}
		}

		return $html;
			
	}

	function getEmailHTML($template,$templateType='email'){
		return '<html><body style="margin:0">'.$this->getTemplateHTML($template,$templateType).'</body></html>';
	}

	function getTemplateParams($tmpl='default',$templateType='email'){
		static $tmplParams = false;

		if(!$tmplParams){
			$tBaseDir	= JPATH_COMPONENT.DS.'templates'.DS.$templateType;
			$ini	= $tBaseDir.DS.$tmpl.DS.'params.ini';
			$xml	= $tBaseDir.DS.$tmpl.DS.'templateDetails.xml';
			jimport('joomla.filesystem.file');
			// Read the ini file
			if (JFile::exists($ini)) {
				$iniContent = JFile::read($ini);
			} else {
				$iniContent = null;
			}
			$tmplParams = new JParameter($iniContent, $xml, 'template');
		}
		return $tmplParams;
	}

	function file_upload_error_message($error_code) {
		switch ($error_code) {
			case UPLOAD_ERR_INI_SIZE:
				return JText::_('The uploaded file exceeds the upload_max_filesize directive'); // in php.ini
			case UPLOAD_ERR_FORM_SIZE:
				return JText::_('The uploaded file exceeds the MAX_FILE_SIZE directive'); // that was specified in the HTML form
			case UPLOAD_ERR_PARTIAL:
				return JText::_('The uploaded file was only partially uploaded');
			case UPLOAD_ERR_NO_FILE:
				return JText::_('No file was uploaded');
			case UPLOAD_ERR_NO_TMP_DIR:
				return JText::_('Missing a temporary folder');
			case UPLOAD_ERR_CANT_WRITE:
				return JText::_('Failed to write file to disk');
			case UPLOAD_ERR_EXTENSION:
				return JText::_('File upload stopped by extension');
			default:
				return JText::_('Unknown upload error');
		}
	}

	function sendDebugMessage($subject='') {
		// Initialize some variables
		jimport('joomla.mail.helper');
		$mainframe	= &JFactory::getApplication();
		$mail = JFactory::getMailer();
		//debug_mode
		$MailFrom 	= $mainframe->getCfg('mailfrom');
		$FromName 	= $mainframe->getCfg('fromname');

		$mail->addRecipient( $MailFrom);
		$mail->setSender( array( $MailFrom, $FromName ) );
		$mail->setSubject( JText::_('CE_DEBUG_MSG_SUBJECT').' '.$subject );
		$body	= '';
		$body	.= JText::_('CE_DEBUG_MSG_NOTE');

		$var	= "\n\n ------------- POST ------------\n";
		$key	= '';
		ceHelper::array2string($_POST,$var,$key);
		$body	.=	$var;

		$var	= "\n\n ------------- SESSION ------------\n";
		$key	= '';
		ceHelper::array2string($_SESSION,$var,$key);
		$body	.=	$var;


		$var	= "\n\n ------------- COOKIE ------------\n";
		$key	= '';
		ceHelper::array2string($_COOKIE,$var,$key);
		$body	.=	$var;

		$var	= "\n\n ------------- GET ------------\n";
		$key	= '';
		ceHelper::array2string($_GET,$var,$key);
		$body	.=	$var;

		/*	$var	= "\n\n ------------- GLOBALS ------------\n";
		 $key	= '';
		 ceHelper::array2string($GLOBALS,$var,$key);
		 $body	.=	$var;*/

		$var	= "\n\n ------------- SERVER ------------\n";
		$key	= '';
		ceHelper::array2string($_SERVER,$var,$key);
		$body	.=	$var;

		$var	= "\n\n ------------- ENV ------------\n";
		$key	= '';
		ceHelper::array2string($_ENV,$var,$key);
		$body	.=	$var;

		$body	.= "\n\n ------------- PHP VERSION ------------\n".phpversion();

		// Create the JConfig object
		$config = new JFrameworkConfig();

		//Remove all secret information
		$config->ftp_user= "**************";
		$config->ftp_pass= "**************";
		$config->ftp_root= "**************";
		$config->ftp_port= "**************";
		$config->smtppass= "**************";
		$config->smtpuser= "**************";
		$config->secret		= "**************";
		$config->ftp_pass 	= "**************";
		$config->user		= "**************";
		$config->db			= "**************";
		$config->user		= "**************";

		$var	= "\n\n ------------- JOOMLA CONFIG ------------\n";
		$var	.= "All top secret information from your config file have been removed and changed to **** \n\n";
		$key	= '';
		ceHelper::array2string($config,$var,$key);
		$body	.=	$var;

		if(JRequest::getVar('option')){
			$pparams = $mainframe->getParams(JRequest::getString('option'));
			$var	= "\n\n ------------- COMPONENT PARAMETERS ------------\n";
			$key	= '';
			ceHelper::array2string($pparams,$var,$key);
			$body	.=	$var;
		}
		$body	.= strip_tags(ceHelper::getSystemInfo(array()));

		$mail->setBody( $body );
		$mail->Send();
	}

}

function testArray($array, $exit=true){
	echo '<pre>';
	print_r($array);
	echo '</pre>';
	if($exit) exit;
}

