<?php
/**
 * @version $Id$
 * @package    Contact_Enhanced
 * @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.
 */

defined( '_JEXEC' ) or die( 'Restricted access' );

/**
 *
 * helper class.
 *
 */
class ceHelper extends JObject {
	function loadJavascriptFiles() {
		if(!defined('CONTACT_ENHANCED_JS_LOADED')){
			define('CONTACT_ENHANCED_JS_LOADED',1);
			JHTML::_('behavior.mootools');
			JHTML::_('behavior.tooltip');
			$doc =& JFactory::getDocument();
			
			/* Check whether MTupgrade is enabled */
			if(JFactory::getApplication()->get('MooToolsVersion') == '1.2.4 +Compat'){
				$doc->addScript( 	JURI::root(). 'components/com_contact_enhanced/assets/js/validate.js' );
			}else{
				$doc->addScript( 	JURI::root(). 'components/com_contact_enhanced/assets/js/validate-v1.11.js' );
			}
			ceHelper::loadCSSFiles();
		}
	}
	
	function loadCSSFiles() {
		$doc =& JFactory::getDocument();
		$doc->addStyleSheet(JURI::root(). 'components/com_contact_enhanced/assets/css/validate.css');
	}
	
	function loadJavascript(&$script,$suffix='') {
		ceHelper::loadJavascriptFiles();
		$doc 	=& JFactory::getDocument();
		$script	= '
		function validateForm( frm ) {
			var logObj	= $("ce-log'.$suffix.'");
			var	logFx	= document.celog_'.$suffix.';
			'.$script.'
			if (!document.formvalidator.isValid(frm)) {
				logObj.addClass("ce-error");
				logObj.setHTML("'. JText::_('CONTACT_ENHANCED INVALID FIELDS IN RED') .'");
				logFx.slideIn();
				return false;
			} else {
				logFx.slideOut();
				return true;
			}
		}
		
		window.addEvent(\'domready\', function() {
			$("screen_resolution'.$suffix.'").value=screen.width +"x"+ screen.height;
			document.celog_'.$suffix.'	= new Fx.Slide("ce-log'.$suffix.'"); 
			document.celog_'.$suffix.'.slideOut();
		});
			';
		$doc->addScriptDeclaration( $script );
	}
	
	
	function loadForm(&$obj,$formType='component') {
		
		$html	= '';
		$ce_cookie		= JRequest::getVar( 'ce_cookie',	'',	'cookie' );
		$show_sidebar	= $obj->contact->params->get( 'show_sidebar',false );
		$suffix			= JUtility::getHash(microtime());
		
		// Load Custom Fields
		$cf		= ceHelper::loadCustomFields($obj->customfields,$obj->params); 
		ceHelper::loadJavascript($cf['script'],$suffix);
		
		
			$html	.= '<a name="form" ></a>';
			$html	.= '<form  enctype="multipart/form-data" action="'.($obj->contact->params->get( 'advanced-integration-formaction' ,JRoute::_( 'index.php' ) ) ).'" method="post" name="emailForm" id="emailForm" class="form-validate">';
				$html	.= '<div class="contact_enhanced_email'.$obj->params->get( 'pageclass_sfx' ).'">';
					$html	.= '<small id="requiredsign">'.JText::_('REQUIRED_SIGN_DESC').'</small><br />';
					// Load Custom Fields
					$html	.= $cf['html'];  
					
					if ($obj->contact->params->get( 'show_email_copy',1 ) == 1){
						$html	.= '<div class="ce-contact-email-copy-container">';
							$html	.= '<input type="checkbox" name="email_copy" id="contact_email_copy" value="1"  />';
							$html	.= '<label for="contact_email_copy">';
								$html	.= JText::_( 'EMAIL_A_COPY' );
							$html	.= '</label>';
						$html	.= '</div>';
					}elseif($obj->contact->params->get( 'show_email_copy',1 ) == 2){
						$html	.= '<input type="hidden" name="email_copy" id="email_copy" value="1"  />';
					}

					// Get params and component configurations
					$pparams	= &$obj->params;
					
					if( ($pparams->get( 'enable_captcha', 2) > 0  AND !$obj->user->get('id') ) 
						OR $pparams->get( 'enable_captcha', 2) == 2)
					{
						// load plugin parameters
						/*$captchaPlugin = JPluginHelper::getPlugin( 'content', 'captcha' );
						if(!isset($captchaPlugin->params)){
							$captchaPlugin = new stdClass();
							$captchaPlugin->params	= '';
						}
						$captchaPluginParams = new JParameter( $captchaPlugin->params );*/
				        
						$dispatcher	=& JDispatcher::getInstance();
						// Process the content preparation plugins
						JPluginHelper::importPlugin('content');
						$results = $dispatcher->trigger('onAfterDisplayForm', array('params'=>'','returnType'=>'return'));
						if(isset($results[0])){
							$html	.= $results[0];
						} 
					} 
					
					$html	.= '<br />';
					$html	.= '<div class="ce-message-container"><div class="ce-message" id="ce-log'.$suffix.'" ></div></div>';
					
					$html	.= '<div class="ce-button-container">';
						//<!--  button class="button ce-button-submit validate" type="submit" >'.JText::_('Send').'</button -->';
						$html	.= ' <button class="button ce-button-submit" type="submit" onclick="return validateForm(this.form);">'.JText::_('Send').'</button>';
						$html	.= ' <button class="button ce-button-reset"  type="reset">'.JText::_('Reset').'</button>';
					$html	.= '</div>';
					
				$html	.= '</div>';
		
			$html	.= '<input type="hidden" name="option" value="com_contact_enhanced" />';
			$html	.= '<input type="hidden" name="view" value="contact" />';
			$html	.= '<input type="hidden" name="id" value="'.$obj->contact->id.'" />';
			$html	.= '<input type="hidden" name="category" value="'.$obj->contact->catid.'" />';
			$html	.= '<input type="hidden" name="task" value="submit" />';
			$html	.= '<input type="hidden" name="screen_resolution" id="screen_resolution'.$suffix.'" value="" />';
			$html	.= '<input type="hidden" name="formType" value="'.$formType.'" />';
			
			// In case weare loading the author layout
			if(isset($obj->author->id)){
				$html	.= '<input type="hidden" name="author_id" value="<?php echo $obj->author->id; ?>" />';
			}
			
			// Get template var if set. It is usually "component"
			if(JRequest::getVar('tmpl')){
				$html	.= '<input type="hidden" name="tmpl" value="'.JRequest::getVar('tmpl').'" />';
			}
			// Used in the loadcontact plugin
			if(trim($obj->params->get('return_url'))){
				$html	.= '<input type="hidden" name="return_url" value="'.trim($obj->params->get('return_url')).'" />';
			}
			// Used in all plugins
			if(JRequest::getVar('content_title')){
				$html	.= '<input type="hidden" name="content_title" value="'.JRequest::getVar('content_title').'" />';
			}
			if(JRequest::getVar('content_url')){
				$html	.= '<input type="hidden" name="content_url" value="'.JRequest::getVar('content_url').'" />';
			}
			$html	.= JHTML::_( 'form.token' );
			$html	.= '</form>';
			return $html;
	}
	
	function loadCustomFields(&$customfields, &$params, $isAdmin=false){
		require_once( JPATH_ROOT.DS.'components'.DS.'com_contact_enhanced'.DS."customFields.class.php" );
		$lang =& JFactory::getLanguage();
		$ret = array('html'=>'','script'=>'');
		$ret['html'] = '<div id="ce-custom-fields-container" class="ce-flt'.($lang->isRTL() ? 'rtl' : 'ltr').'">';
		foreach($customfields as $customfield){
			//@todo: I know I gotta do something cleverer here. This "if" is ugly
			if( ($isAdmin AND $customfield->type != 'multiplefiles') OR (!$isAdmin) ){
				$field = "ceFieldType_".$customfield->type;
				$customfield->params	= new JParameter($customfield->params);
				$customfield->params->set('isAdmin',$isAdmin);
				$customfield->params->merge($params);
				$cf = new $field($customfield, $customfield->params);
				$ret['html']	.= $cf->getFieldHTML();
				$ret['script']	.= $cf->getValidationScript();
			}
		}
		$ret['html'] .= '</div>';
		return $ret;
	}
	
	function getSubmitedFields(&$customFields, &$pparams){
		global $mainframe;
		jimport('joomla.filesystem.file');
		require_once( JPATH_ROOT.DS.'components'.DS.'com_contact_enhanced'.DS."customFields.class.php" );
		
		$fields = array();
		//testArray($customFields);
		// $customFields is a database objectList
		foreach($customFields as $cf){
				$fieldClass		= "ceFieldType_".$cf->type;
				$cf->params		= new JParameter($cf->params);
				$fieldObject	= new $fieldClass($cf, $cf->params);
				//$fieldObject->params	= new JParameter($fieldObject->params);
			if(JRequest::getVar( 'cf_'.$cf->id, false, 'post' )){
				if($cf->type == "wysiwyg"){
					//If it is a wysiwyg field, then allow HTML 
					$submittedField	= JRequest::getVar( 'cf_'.$cf->id, false, 'post', 'none',JREQUEST_ALLOWHTML );
					// Set email to HTML
					$pparams->set('emailOutputType', 'html');
				}else{
					$submittedField	= JRequest::getVar( 'cf_'.$cf->id, false, 'post' );
				}
				
				if(is_array($submittedField) AND isset($submittedField['value'][0])){
					if(empty($submittedField['value'][0])){
						continue;
					}
				}
				$fields[$cf->id]			= $fieldObject;
				$fields[$cf->id]->uservalue	= $submittedField;
				if($cf->type == 'text' OR $cf->type == 'multitext'){
					$fields[$cf->id]->uservalue	= stripslashes($fields[$cf->id]->uservalue);
				}
			}elseif($cf->published){
				$files	= JRequest::getVar( 'cf_'.$cf->id, false, 'files' );
				
				/**
				 * Added for in 1.5.8.1 for compatibility
				 * @todo remove from newer versions
				 */
				if($cf->type == 'selectrecipient'){
					$cf->type = 'recipient';
					$fieldObject->type = 'recipient';
				}
				
				if( $files AND $cf->type == 'file' ){ //$cf->type == 'multiplefiles'
					if($files['error'] == 0){
						$fields[$cf->id]				= $fieldObject;
						$fields[$cf->id]->uservalue		= $files ;	
					}
				}elseif( $files AND $cf->type == 'multiplefiles' ){ //$cf->type == 'multiplefiles'
					$fields[$cf->id]				= $fieldObject;
					$fields[$cf->id]->uservalue		= $files ;
				}elseif( $cf->type == 'surname' ){ //$cf->type == 'multiplefiles'
					$fields[$cf->id]				= $fieldObject;
					$fields[$cf->id]->uservalue		= JRequest::getVar( 'cf_surname', false, 'post' )  ;
				}elseif(JRequest::getVar( $cf->type, false, 'post' )){ 
					$fields[$cf->id]				= $fieldObject;
					$fields[$cf->id]->uservalue		= JRequest::getVar( $cf->type, false, 'post' )  ;
				}
			}
		}
		//testArray($fields);
		return $fields;
	}
	
	function getCustomFields($catid){
		$db			= & JFactory::getDBO();
		$query = "SELECT cf.id, cf.* "
		. "\n FROM #__contact_enhanced_cf AS cf"
		. "\n WHERE (cf.published > 0 OR (cf.published = 0 AND cf.iscore = 1) ) " //OR (cf.published = 0 AND cf.iscore = 1) 
			. "\n AND (cf.catid = ". (int) $catid . " OR  cf.catid = 0 )"
		. "\n ORDER BY cf.catid, cf.ordering ASC"
		;
		$db->setQuery($query);
		return $db->loadObjectList();

	}
	
	function timeDifference($date,$format = 'full')
	{
	    if(empty($date)) {
	        return JText::_("No date provided");
	    }

	    $date			=& JFactory::getDate($date);
	    $now			=& JFactory::getDate();
	   	
	    $periods		= array(JText::_("second"), JText::_("minute"), JText::_("hour"), JText::_("day"), JText::_("week"), JText::_("month"), JText::_("year"), JText::_("decade") );
	    $lengths		= array("60","60","24","7","4.35","12","10");
	   
		$now			= $now->toUnix();
	    $unix_date		= $date->toUnix();
	   
	       // check validity of date
	    if(empty($unix_date)) {   
	        return JText::_("Bad date");
	    }
	
	    // is it future date or past date
	    if($now > $unix_date) {   
        	$difference	= $now - $unix_date;
	        $tense		= JText::_("ago");
	       
	    } else {
	        $difference	= $unix_date - $now;
	        $tense		= JText::_("from now");
	    }
	   
	    for($j = 0; $difference >= $lengths[$j] && $j < count($lengths)-1; $j++) {
	        $difference /= $lengths[$j];
	    }
	   
	    $difference = round($difference);
	   
	    if($difference != 1) {
	        $periods[$j].= JText::_("s");
	    }
		
	    if($format == 'full'){
	    	if($j<3){
	    		return $date->toFormat(JText::_('HOUR_FORMAT')). " ($difference $periods[$j] {$tense})";	
	    	}else{
	    		return $date->toFormat(JText::_('MONTH_DAY_FORMAT'))." ($difference $periods[$j] {$tense})";
	    	}
	    	
	    }elseif($format == 'none'){
	    	//@todo: Add an option to show the difference in unix time format 
	    }else{
	    	return "$difference $periods[$j] {$tense}";
	    }
	    
	}
	
	function formatAttachmentList(&$attachmentsArray,$message_id){
		jimport('joomla.filesystem.file');
		
		$html 			= '';
		
		foreach($attachmentsArray as $attachments){
			$attachments	= explode('|',$attachments->value);
			foreach($attachments as $attachment){
				$html	.= ceHelper::formatAttachment($attachment,$message_id);
			}
		}
		return $html;
	}
	
	function formatAttachment($attachment,$message_id, $format="html"){
		jimport('joomla.filesystem.file');
		$viewableExt	= ceHelper::getViewableFileExtensions();
			$html	= '';
			$attachment	= trim($attachment);
			
			$attachment	= ceHelper::removePrefix($attachment,$message_id.'_');
			
			$link	= ceHelper::getAttachmentLink($message_id.'_'.$attachment,'download');
			
			if($format == 'html'){
				$filesize	= filesize(UPLOADED_FILE_PATH.$message_id.'_'.$attachment);
				$fileExt	= strtolower(JFile::getExt($attachment));
				if(JFile::exists(ICONSET_FOLDER_PATH.$fileExt.'.png')){
					$image = $fileExt.'.png';
				}else{
					$image = 'default.png';
				}
				//echo ICONSET_FOLDER_PATH.$fileExt.'.png'; exit;
				$image	= JURI::root().'components/'.COMPONENT_FOLDER.'/assets/images/file_ext/'.$image;
				$html	.= '<table class="attachment-container" width="99%">';
					$html	.= '<tr>';
					$html	.= '<td background="'.$image.'" width="32" height="32" rowspan="2"> </td>';
					$html	.= '<td style="font-weight:bolder;">'.$attachment.'</td>';
					$html	.= '</tr>';
					$html	.= '<tr>';
					$html	.= '<td>';
						$html	.= ' <span class="attachment-filesize">'.ceHelper::formatBytes($filesize,0).'</span>';
						$html	.= ' <span class="attachment-download">'.JHTML::_('link',$link,JText::_('Download')).'</span>';
						if(in_array($fileExt, $viewableExt)){
							$link	=  ceHelper::getAttachmentLink($message_id.'_'.$attachment,'view');
							$html	.= '<span class="attachment-view"  style="margin:0 5px 0 5px">'.JHTML::_('link',$link,JText::_('View'),' target="_blank" ').'</span>';
						}
					$html	.= '</td>';
					$html	.= '</tr>';

					
				$html	.= '</table>';
			}else{
				$html	.= "\n\t".$attachment.' < '.$link.' >';
			}
			
		return $html;
	}
	
	function getAttachmentLink($filename,$task='download'){
		return JURI::root().'index.php?option='.COMPONENT_FOLDER.'&task='.$task.'Attachment&file='.ceHelper::encode($filename);
	}
	
	function formatBytes($bytes, $precision = 2) {
		$units = array('B', 'KB', 'MB', 'GB', 'TB');

		$bytes = max($bytes, 0);
		$pow = floor(($bytes ? log($bytes) : 0) / log(1024));
		$pow = min($pow, count($units) - 1);
		$bytes /= pow(1024, $pow);
		
		return round($bytes, $precision) . ' ' . $units[$pow];
	}
	
	function getViewableFileExtensions(){
		$params = JComponentHelper::getParams(COMPONENT_FOLDER);

        // Get the other info about the attachment
        $viewableFileExtensions = $params->get('viewable_file_extensions', 'jpg,jpeg,gif,png,bmp,css,js,html,htm,xml,txt');
        return explode(',',$viewableFileExtensions);
	}
	/**
  	 * Provides an encoded string
 	 *
 	 * @param string Seed string
 	 * @return string
 	 */
	function encode( $string )
	{
		$secret = substr(JUtility::getHash($string),0,10);
		return base64_encode($secret.base64_encode( $string  ));
	}
	
	function decode( $string )
	{
		$secret = substr(JUtility::getHash($string),0,10);
		$string	= base64_decode( $string );
		$string	= ceHelper::removePrefix($string,$secret);
		return base64_decode( $string );
	}
	
	
	function removePrefix($string,$prefix){
		if(!is_numeric($prefix)){
			$prefix	= strlen($prefix);
		}
		return substr($string,$prefix );
	}
	
	function download($file, $download_mode='attachment')
    {
		jimport('joomla.filesystem.file');
		$filename_sys = UPLOADED_FILE_PATH.$file;
        
        $filename = $file;
        //$download_mode = $params->get('download_mode', 'attachment');
        
        // Make sure the file exists
        if ( !JFile::exists($filename_sys) ) {
             $errmsg = JText::_('ERROR FILE NOT FOUND ON SERVER') . " ($filename)";
             JError::raiseError(500, $errmsg);
             }
        $len = filesize($filename_sys);


        // Begin writing headers
        ob_clean(); // Clear any previously written headers in the output buffer
        header("Pragma: public");
        header('Cache-Control: no-store, no-cache, must-revalidate');
        header('Cache-Control: pre-check=0, post-check=0, max-age=0');
        header('Pragma: no-cache');
        header('Expires: 0');

        // Use the desired Content-Type
        $content_type = ceHelper::getMimeType(strtolower(JFile::getExt($file)));
        header("Content-Type: $content_type");
        
        if($download_mode != 'attachment' AND !in_array(strtolower(JFile::getExt($file)),ceHelper::getViewableFileExtensions()) ){
        	$download_mode = 'attachment';
        }

        // Force the download
        header("Content-Disposition: $download_mode; filename=\"".ceHelper::removePrefix($filename,(strpos($filename,'_')+1))."\"");
		header("Content-Transfer-Encoding: binary");
        header("Content-Length: ".$len);
        
		@readfile($filename_sys);
        
        
        exit;
    }
    
    function getMimeType($fileExtension){
    	/**
		 * Mapping of file extensions to their expected mime-type
		 *
		 * This mapping does not claim to be exhaustive, but is a good listing for a large amount
		 * of file types.
		 *
		 * Last updated: 2006-08-31
		 *
		 * @link 	http://www.duke.edu/websrv/file-extensions.html
		 * @var		array	$mime_map	key = file extension, value = mime-type
		 */
		$mime_map = array(
			'ai'	=>	'application/postscript',
			'aif'	=>	'audio/x-aiff',
			'aifc'	=>	'audio/x-aiff',
			'aiff'	=>	'audio/x-aiff',
			'asc'	=>	'text/plain',
			'au'	=>	'audio/basic',
			'avi'	=>	'video/x-msvideo',
			'bcpio'	=>	'application/x-bcpio',
			'bin'	=>	'application/octet-stream',
			'c'		=>	'text/plain',
			'cc'	=>	'text/plain',
			'ccad'	=>	'application/clariscad',
			'cdf'	=>	'application/x-netcdf',
			'class'	=>	'application/octet-stream',
			'cpio'	=>	'application/x-cpio',
			'cpt'	=>	'application/mac-compactpro',
			'csh'	=>	'application/x-csh',
			'css'	=>	'text/css',
			'dcr'	=>	'application/x-director',
			'dir'	=>	'application/x-director',
			'dms'	=>	'application/octet-stream',
			'doc'	=>	'application/msword',
			'drw'	=>	'application/drafting',
			'dvi'	=>	'application/x-dvi',
			'dwg'	=>	'application/acad',
			'dxf'	=>	'application/dxf',
			'dxr'	=>	'application/x-director',
			'eps'	=>	'application/postscript',
			'etx'	=>	'text/x-setext',
			'exe'	=>	'application/octet-stream',
			'ez'	=>	'application/andrew-inset',
			'f'		=>	'text/plain',
			'f90'	=>	'text/plain',
			'fli'	=>	'video/x-fli',
			'gif'	=>	'image/gif',
			'gtar'	=>	'application/x-gtar',
			'gz'	=>	'application/x-gzip',
			'h'		=>	'text/plain',
			'hdf'	=>	'application/x-hdf',
			'hh'	=>	'text/plain',
			'hqx'	=>	'application/mac-binhex40',
			'htm'	=>	'text/html',
			'html'	=>	'text/html',
			'ice'	=>	'x-conference/x-cooltalk',
			'ief'	=>	'image/ief',
			'iges'	=>	'model/iges',
			'igs'	=>	'model/iges',
			'ips'	=>	'application/x-ipscript',
			'ipx'	=>	'application/x-ipix',
			'jpe'	=>	'image/jpeg',
			'jpeg'	=>	'image/jpeg',
			'jpg'	=>	'image/jpeg',
			'js'	=>	'application/x-javascript',
			'kar'	=>	'audio/midi',
			'latex'	=>	'application/x-latex',
			'lha'	=>	'application/octet-stream',
			'lsp'	=>	'application/x-lisp',
			'lzh'	=>	'application/octet-stream',
			'm'		=>	'text/plain',
			'man'	=>	'application/x-troff-man',
			'me'	=>	'application/x-troff-me',
			'mesh'	=>	'model/mesh',
			'mid'	=>	'audio/midi',
			'midi'	=>	'audio/midi',
			'mif'	=>	'application/vnd.mif',
			'mime'	=>	'www/mime',
			'mov'	=>	'video/quicktime',
			'movie'	=>	'video/x-sgi-movie',
			'mp2'	=>	'audio/mpeg',
			'mp3'	=>	'audio/mpeg',
			'mpe'	=>	'video/mpeg',
			'mpeg'	=>	'video/mpeg',
			'mpg'	=>	'video/mpeg',
			'mpga'	=>	'audio/mpeg',
			'ms'	=>	'application/x-troff-ms',
			'msh'	=>	'model/mesh',
			'nc'	=>	'application/x-netcdf',
			'oda'	=>	'application/oda',
			'pbm'	=>	'image/x-portable-bitmap',
			'pdb'	=>	'chemical/x-pdb',
			'pdf'	=>	'application/pdf',
			'pgm'	=>	'image/x-portable-graymap',
			'pgn'	=>	'application/x-chess-pgn',
			'php'	=>	'text/plain',
			'php3'	=>	'text/plain',
			'png'	=>	'image/png',
			'pnm'	=>	'image/x-portable-anymap',
			'pot'	=>	'application/mspowerpoint',
			'ppm'	=>	'image/x-portable-pixmap',
			'pps'	=>	'application/mspowerpoint',
			'ppt'	=>	'application/mspowerpoint',
			'ppz'	=>	'application/mspowerpoint',
			'pre'	=>	'application/x-freelance',
			'prt'	=>	'application/pro_eng',
			'ps'	=>	'application/postscript',
			'qt'	=>	'video/quicktime',
			'ra'	=>	'audio/x-realaudio',
			'ram'	=>	'audio/x-pn-realaudio',
			'ras'	=>	'image/cmu-raster',
			'rgb'	=>	'image/x-rgb',
			'rm'	=>	'audio/x-pn-realaudio',
			'roff'	=>	'application/x-troff',
			'rpm'	=>	'audio/x-pn-realaudio-plugin',
			'rtf'	=>	'text/rtf',
			'rtx'	=>	'text/richtext',
			'scm'	=>	'application/x-lotusscreencam',
			'set'	=>	'application/set',
			'sgm'	=>	'text/sgml',
			'sgml'	=>	'text/sgml',
			'sh'	=>	'application/x-sh',
			'shar'	=>	'application/x-shar',
			'silo'	=>	'model/mesh',
			'sit'	=>	'application/x-stuffit',
			'skd'	=>	'application/x-koan',
			'skm'	=>	'application/x-koan',
			'skp'	=>	'application/x-koan',
			'skt'	=>	'application/x-koan',
			'smi'	=>	'application/smil',
			'smil'	=>	'application/smil',
			'snd'	=>	'audio/basic',
			'sol'	=>	'application/solids',
			'spl'	=>	'application/x-futuresplash',
			'src'	=>	'application/x-wais-source',
			'step'	=>	'application/STEP',
			'stl'	=>	'application/SLA',
			'stp'	=>	'application/STEP',
			'sv4cpio'	=>	'application/x-sv4cpio',
			'sv4crc'	=>	'application/x-sv4crc',
			'swf'	=>	'application/x-shockwave-flash',
			't'		=>	'application/x-troff',
			'tar'	=>	'application/x-tar',
			'tcl'	=>	'application/x-tcl',
			'tex'	=>	'application/x-tex',
			'texi'	=>	'application/x-texinfo',
			'texinfo'	=>	'application/x-texinfo',
			'tif'	=>	'image/tiff',
			'tiff'	=>	'image/tiff',
			'tr'	=>	'application/x-troff',
			'tsi'	=>	'audio/TSP-audio',
			'tsp'	=>	'application/dsptype',
			'tsv'	=>	'text/tab-separated-values',
			'txt'	=>	'text/plain',
			'unv'	=>	'application/i-deas',
			'ustar'	=>	'application/x-ustar',
			'vcd'	=>	'application/x-cdlink',
			'vda'	=>	'application/vda',
			'viv'	=>	'video/vnd.vivo',
			'vivo'	=>	'video/vnd.vivo',
			'vrml'	=>	'model/vrml',
			'wav'	=>	'audio/x-wav',
			'wrl'	=>	'model/vrml',
			'xbm'	=>	'image/x-xbitmap',
			'xlc'	=>	'application/vnd.ms-excel',
			'xll'	=>	'application/vnd.ms-excel',
			'xlm'	=>	'application/vnd.ms-excel',
			'xls'	=>	'application/vnd.ms-excel',
			'xlw'	=>	'application/vnd.ms-excel',
			'xml'	=>	'text/xml',
			'xpm'	=>	'image/x-xpixmap',
			'xwd'	=>	'image/x-xwindowdump',
			'xyz'	=>	'chemical/x-pdb',
			'zip'	=>	'application/zip'
		);
		
		if(array_key_exists($fileExtension,$mime_map)){
			return $mime_map[$fileExtension];
		}else{
			return 'application/octet-stream';
		}
    }
    
	function objectToArray($obj, $recursive=true) {
		$_arr = is_object($obj) ? get_object_vars($obj) : $obj;
		foreach ($_arr as $key => $val) {
			$val = (is_array($val) OR is_object($val) AND $recursive) ? ceHelper::objectToArray($val) : $val;
			$arr[$key] = $val;
		}
		return $_arr;
	}
	/**
	 * replace tags from 
	 */
	function replaceTags($content, $object,$prefix='', $startTag='{', $endTag='}'){
		foreach(get_object_vars($object) as $key => $value){

			if(is_array($value)){
				continue;
			}
			if(is_object($value)){
				if($key!='contact') continue;
				$content = ceHelper::replaceTags($content,$value, $key.'_');
			}else{
				 //echo $startTag.$prefix.strtolower($key).$endTag.' : '.$value.'<br>';
				$content = str_ireplace( $startTag.$prefix.$key.$endTag, $value, $content );
			}
		}
		return $content;
	}
	
	function getSystemInfo($param){
		$content_title	= JRequest::getVar( 'content_title',false,		'post' ); // This input is in CE plugin
		$session 		=& JFactory::getSession();
		require_once(SITE_COMPONENT_PATH.'browser.php');
		$suffix	= '';
		$suffix.= '<div class="userinfo">';
		$suffix.= "\n\n<h4>".JText::_('USER INFO').'</h4>';
		$suffix.= "\n\t<div><label>".JText::_('IP address').":</label>\t<span>". $_SERVER['REMOTE_ADDR'].'</span></div>'; 
		$suffix.= "\n\t<div><label>".JText::_('Web Browser').":</label>\t<span>". Browser_Detection::get_browser($_SERVER['HTTP_USER_AGENT']).'</span></div>'; 
		$suffix.= "\n\t<div><label>".JText::_('Operating System').":</label>\t<span>". Browser_Detection::get_os($_SERVER['HTTP_USER_AGENT']).'</span></div>';
		$suffix.= "\n\t<div><label>".JText::_('Screen resolution').":</label>\t	<span>". JRequest::getVar( 'screen_resolution','','post') .'</span></div>';
		$suffix.= '</div>'; 
		
		if($content_title){
			$suffix.= '<div class="last-visited-page">';
			$suffix.= "\n\n<h4>".JText::_('Last page visited').'</h4>';
			$suffix.= "\n\t<div><label>".JText::_('Page Tile').":</label>\t". $content_title.'</span></div>' ;
			$suffix.= "\n\t<div><label>".JText::_('Page URL').":</label>\t". JRequest::getVar( 'content_url',$_SERVER['HTTP_REFERER'],'post' ).'</span></div>' ;
			$suffix.= '</div>'; 
		} 

		//Get Referer from getReferer Plugin
		
		if( ($sitetracker = $session->get( 'sitetracker', null )) ){ //AND $param->get('useUserTracker',0)
			$suffix.= '<div class="user-tracker">';
			$suffix.= "\n\n<h4>".JText::_('Page Referers')."</h4>";
			foreach($sitetracker as $stKey => $stValue){
				$suffix.= "\n<br />".$stKey
						.":\n\t<div><label>". JText::_('Referer')."</label>\t => \t <span>".$stValue['referer'].'</span></div>'
						.":\n\t<div><label>". JText::_('Landing Page')	."</label>\t => \t <span>".$stValue['landingPage'].'</span></div>' ; 
			}
			$suffix.= '</div>'; 
		}
		return $suffix;
	}

	function array2string($myarray,&$output,&$parentkey){
		foreach($myarray as $key=>$value){
	    	if (is_array($value)) {
				$parentkey .= $key."^";
				ceHelper::array2string($value,$output,$parentkey);
				$parentkey = "";
	    	}else if(is_object($value)){
	    		$value	= ceHelper::objectToArray($value);
	    		ceHelper::array2string($value,$output,$parentkey);
	    	}else {
	    	   $output .= $parentkey.$key."^".$value."\n";
	    	}
		}
   }
   
	function findMenuItem($needles)
	{
		$component =& JComponentHelper::getComponent('com_contact_enhanced');

		$menus	= &JApplication::getMenu('site', array());
		$items	= $menus->getItems('componentid', $component->id);
		
		$match = null;
		if(!is_array($items) OR count($items)  < 1){
			return $match;
		}
		
		foreach($needles as $needle => $id)
		{
			foreach($items as $item)
			{
				if ((@$item->query['view'] == $needle) && (@$item->query['id'] == $id)) {
					$match = $item;
					break;
				}
			}

			if(isset($match)) {
				break;
			}
		}

		return $match;
	}
}