<?php
/**
* @version 1.0.0
* @package RSEvents! 1.0.0
* @copyright (C) 2009 www.rsjoomla.com
* @license GPL, http://www.gnu.org/copyleft/gpl.html
*/

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

require_once(JPATH_SITE.DS.'components'.DS.'com_rsevents'.DS.'models'.DS.'events.php');
require_once(JPATH_SITE.DS.'components'.DS.'com_rsevents'.DS.'models'.DS.'users.php');
require_once(JPATH_SITE.DS.'components'.DS.'com_rsevents'.DS.'helpers'.DS.'yahoo.class.php');
require_once(JPATH_SITE.DS.'components'.DS.'com_rsevents'.DS.'helpers'.DS.'gmail.class.php');

class rseventsHelper
{
	function fopen($url)
	{
		$url_info = parse_url($url);
		
		$data = false;

		// cURL
		if (extension_loaded('curl'))
		{
			// Init cURL
			$ch = @curl_init();
			
			// Set options
			@curl_setopt($ch, CURLOPT_URL, $url);
			@curl_setopt($ch, CURLOPT_HEADER, 0);
			@curl_setopt($ch, CURLOPT_FAILONERROR, 1);
			@curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
			
			// Set timeout
			@curl_setopt($ch, CURLOPT_TIMEOUT, 5);
			
			// Grab data
			$data = @curl_exec($ch);
			
			// Clean up
			@curl_close($ch);
			
			// Return data
			if ($data !== false)
				return $data;
		}

		// fsockopen
		if (function_exists('fsockopen'))
		{
			$errno = 0;
			$errstr = '';

			// Set timeout
			$fsock = @fsockopen($url_info['host'], 80, $errno, $errstr, 5);
		
			if ($fsock)
			{
				@fputs($fsock, 'GET '.$url_info['path'].(!empty($url_info['query']) ? '?'.$url_info['query'] : '').' HTTP/1.1'."\r\n");
				@fputs($fsock, 'HOST: '.$url_info['host']."\r\n");
				@fputs($fsock, 'Connection: close'."\r\n\r\n");
        
				// Set timeout
				@stream_set_blocking($fsock, 1);
				@stream_set_timeout($fsock, 5);
				
				$data = '';
				$passed_header = false;
				while (!@feof($fsock))
				{
					if ($passed_header)
						$data .= @fread($fsock, 1024);
					else
					{
						if (@fgets($fsock, 1024) == "\r\n")
							$passed_header = true;
					}
				}
				
				// Clean up
				@fclose($fsock);
				
				// Return data
				if ($data !== false)
					return $data;
			}
		}

	 	// fopen
		if (function_exists('fopen') && ini_get('allow_url_fopen'))
		{
			// Set timeout
			if (ini_get('default_socket_timeout') < 5)
				ini_set('default_socket_timeout', 5);
			@stream_set_blocking($handle, 1);
			@stream_set_timeout($handle, 5);
			
			$handle = @fopen ($url, 'r');
			
			$data = '';
			while (!feof($handle))
				$data .= @fread($handle, 8192);
			
			// Clean up
			@fclose($handle);
			
			// Return data
			if ($data !== false)
				return $data;
		}
						
		// file_get_contents
		if(function_exists('file_get_contents') && ini_get('allow_url_fopen'))
		{
			$data = @file_get_contents($url);
			
			// Return data
			if ($data !== false)
				return $data;
		}
		
		return $data;
	}
	
	function RSstripjavaVar($val)
	{
	   // remove all non-printable characters. CR(0a) and LF(0b) and TAB(9) are allowed
	   // this prevents some character re-spacing such as <java\0script>
	   // note that you have to handle splits with \n, \r, and \t later since they *are* allowed in some inputs
	   $val = preg_replace('/([\x00-\x08][\x0b-\x0c][\x0e-\x20])/', '', $val);

	   // straight replacements, the user should never need these since they're normal characters
	   // this prevents like <IMG SRC=&#X40&#X61&#X76&#X61&#X73&#X63&#X72&#X69&#X70&#X74&#X3A&#X61&#X6C&#X65&#X72&#X74&#X28&#X27&#X58&#X53&#X53&#X27&#X29>
	   $search = 'abcdefghijklmnopqrstuvwxyz';
	   $search .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
	   $search .= '1234567890!@#$%^&*()';
	   $search .= '~`";:?+/={}[]-_|\'\\';
	   for ($i = 0; $i < strlen($search); $i++) {
	      // ;? matches the ;, which is optional
	      // 0{0,7} matches any padded zeros, which are optional and go up to 8 chars

	      // &#x0040 @ search for the hex values
	      $val = preg_replace('/(&#[x|X]0{0,8}'.dechex(ord($search[$i])).';?)/i', $search[$i], $val); // with a ;
	      // &#00064 @ 0{0,7} matches '0' zero to seven times
	      $val = preg_replace('/(&#0{0,8}'.ord($search[$i]).';?)/', $search[$i], $val); // with a ;
	   }

	   // now the only remaining whitespace attacks are \t, \n, and \r
	   $ra1 = Array('javascript', 'vbscript', 'expression', 'applet', 'meta', 'blink', 'link',  'script', 'iframe', 'frame', 'frameset', 'ilayer', 'layer', 'bgsound');
	   $ra2 = Array('onabort', 'onactivate', 'onafterprint', 'onafterupdate', 'onbeforeactivate', 'onbeforecopy', 'onbeforecut', 'onbeforedeactivate', 'onbeforeeditfocus', 'onbeforepaste', 'onbeforeprint', 'onbeforeunload', 'onbeforeupdate', 'onblur', 'onbounce', 'oncellchange', 'onchange', 'onclick', 'oncontextmenu', 'oncontrolselect', 'oncopy', 'oncut', 'ondataavailable', 'ondatasetchanged', 'ondatasetcomplete', 'ondblclick', 'ondeactivate', 'ondrag', 'ondragend', 'ondragenter', 'ondragleave', 'ondragover', 'ondragstart', 'ondrop', 'onerror', 'onerrorupdate', 'onfilterchange', 'onfinish', 'onfocus', 'onfocusin', 'onfocusout', 'onhelp', 'onkeydown', 'onkeypress', 'onkeyup', 'onlayoutcomplete', 'onload', 'onlosecapture', 'onmousedown', 'onmouseenter', 'onmouseleave', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'onmousewheel', 'onmove', 'onmoveend', 'onmovestart', 'onpaste', 'onpropertychange', 'onreadystatechange', 'onreset', 'onresize', 'onresizeend', 'onresizestart', 'onrowenter', 'onrowexit', 'onrowsdelete', 'onrowsinserted', 'onscroll', 'onselect', 'onselectionchange', 'onselectstart', 'onstart', 'onstop', 'onsubmit', 'onunload');
	   $ra = array_merge($ra1, $ra2);

	   $found = true; // keep replacing as long as the previous round replaced something
	   while ($found == true) {
	      $val_before = $val;
	      for ($i = 0; $i < sizeof($ra); $i++) {
	         $pattern = '/';
	         for ($j = 0; $j < strlen($ra[$i]); $j++) {
	            if ($j > 0) {
	               $pattern .= '(';
	               $pattern .= '(&#[x|X]0{0,8}([9][a][b]);?)?';
	               $pattern .= '|(&#0{0,8}([9][10][13]);?)?';
	               $pattern .= ')?';
	            }
	            $pattern .= $ra[$i][$j];
	         }
	         $pattern .= '/i';
	         $replacement = substr($ra[$i], 0, 2).'<x>'.substr($ra[$i], 2); // add in <> to nerf the tag
	         $val = preg_replace($pattern, $replacement, $val); // filter out the hex tags
	         if ($val_before == $val) {
	            // no replacements were made, so exit the loop
	            $found = false;
	         }
	      }
	   }
	   return $val;
	}
	
	
	function showEvent($body = 'info')
	{
		//get variables
		global $mainframe;
		$db = JFactory::getDBO();
		$rseventsConfig = $mainframe->getUserState('rseventsConfig');
		$this->assignRef('rseventsConfig',$rseventsConfig);
		$cid=intval(JRequest::getVar('cid',0,'request'));
		
		//Load the event
		$event=$this->get('Event');
		$this->assignRef('data',$event);
		
		//get the Itemid
		$Itemid = intval(JRequest::getVar('Itemid','','request'));
		$itemId = ($Itemid == '') ? '' : '&Itemid='.$Itemid;
		
		$pathway 	= & $mainframe->getPathWay();
		$pathway->addItem($event->EventName, JRoute::_('index.php?option=com_rsevents&view=events&layout=show&cid='.$event->IdEvent.':'.$event->EventAlias));
				
		
		$document = & JFactory::getDocument();
		$document->addScript(JURI::root().'components/com_rsevents/rsevents.js'); 
		
		//Setting the title of the page
		$siteTitle = $document->getTitle();
		$document->setTitle($siteTitle.' - '.$event->EventName);
		
		if(trim($event->EventKeywords) !='')
			$document->setMetaData('keywords',$event->EventKeywords);
		if(trim($event->EventMetaDescription) !='')
			$document->setDescription($event->EventMetaDescription);
		
		$user =& JFactory::getUser();
		
		//get registered people
		$registeredUsers = $this->get('Registered');
		$this->assignRef('registeredUsers',$registeredUsers);
		
		//Private url
		$privateUrl = JRequest::getVar('privateUrl','','request');
		
		
		//Is event viewable (public=1 OR (private=0 AND (PrivateUrl == EventPrivateUrl OR I'm the event owner)) check)
		$EventPublicPrivate = ($event->EventType || (!$event->EventType && ($privateUrl == $event->EventPrivateUrl || $event->IdUser == $user->id))) ? 1:0;
		
		//If IdEvent exists AND (Event is published OR (Event is unpublished AND I am the owner)) AND Event is public/private viewable
		if($event->IdEvent != 0 && ($event->published || (!$event->published && ($event->IdUser == $user->id || $user->usertype =='Super Administrator') )) && $EventPublicPrivate)
		{
		
			if(!file_exists(JPATH_SITE.DS.'components'.DS.'com_rsevents'.DS.'designs'.DS.$event->DesignName.DS.$event->DesignName.'.html'))
				$event->DesignName = 'default';
			
			$layout = file_get_contents(JPATH_SITE.DS.'components'.DS.'com_rsevents'.DS.'designs'.DS.$event->DesignName.DS.$event->DesignName.'.html');
			$document->addStyleSheet(JURI::root().'components/com_rsevents/designs/'.$event->DesignName.'/'.$event->DesignName.'.css'); 
			
			
			//keep the unix time
			$event->EventStartDateToTime = $event->EventStartDate;
			$event->EventEndDateToTime = $event->EventEndDate;
			
			//change the event date to user's date format
			$event->EventStartDate = rseventsHelper::translateDate(date($rseventsConfig['global.dateformat'],$event->EventStartDate));
			$event->EventEndDate = rseventsHelper::translateDate(date($rseventsConfig['global.dateformat'],$event->EventEndDate));
			
			$categoryname = array();
			$db->setQuery("SELECT c.CategoryName , c.IdCategory FROM #__rsevents_categories c LEFT JOIN #__rsevents_events_cat ec ON ec.IdCategory = c.IdCategory WHERE ec.IdEvent =".$event->IdEvent);
			$categs = $db->loadObjectList();
			
			foreach($categs as $categ)
				$categoryname[] = '<a href="'.html_entity_decode(JRoute::_('index.php?option=com_rsevents&view=events&layout=listcategoryevents&cid='.$categ->IdCategory.':'.JFilterOutput::stringURLSafe($categ->CategoryName).$itemId)).'">'.$categ->CategoryName.'</a>';
			
			$categoryname = implode(',',$categoryname);
			
			//replace event properties
			$find = array('{EventName}' , '{EventSubtitle}' , '{EventHost}' ,'{EventStartDate}' , '{EventEndDate}' , '{LocationName}' , '{LocationAddress}' , '{LocationCity}' , '{LocationState}' , '{EventPhone}' , '{EventEmail}' , '{EventURL}' , '{EventOwner}' , '{EventDescription}' , '{EventIcon}' , '{LocationZip}' , '{LocationCountry}' , '{CategoryName}');
			
			//location url
			
			$link = html_entity_decode(JRoute::_('index.php?option=com_rsevents&view=locations&layout=show&cid='.$event->IdLocation.'&IdEvent='.$event->IdEvent.$itemId));
			$layout = str_replace('{locationUrl}' , $link , $layout);
			$eventLocationUrl = JText::_('RSE_AT_LOCATION').' <a href="'.$link.'">'.$event->LocationName.'</a>';
			
			if($rseventsConfig['enable.event.icon'] == 1 && $event->EventIcon != '')
				$eventIcon = '<img src="'.JURI::root().'components/com_rsevents/images/thumbs/'.str_replace('.jpg','_'.$rseventsConfig['event.icon.big'].'.jpg',$event->EventIcon).'" />';
			else
				$eventIcon = '';
			
			$replace =array($event->EventName , $event->EventSubtitle , JText::_('RSE_HOSTED_BY').' '.$event->EventHost , JText::_('RSE_START_EVENT').' '.$event->EventStartDate , JText::_('RSE_END_EVENT').' '.$event->EventEndDate , $eventLocationUrl , $event->LocationAddress , $event->LocationCity , $event->LocationState , $event->EventPhone , $event->EventEmail , $event->EventURL , JText::_('RSE_EVENT_POSTED').' '.$event->EventOwner , $event->EventDescription , $eventIcon,$event->LocationZip , $event->LocationCountry,$categoryname ); 
			
			$mainframe->triggerEvent('rse_onBeforeShowEvent',array(array('event'=>&$event,'layout'=>&$layout,'find'=>&$find,'replace'=>&$replace)));
			
			$layout = str_replace($find , $replace , $layout);

			if($user->usertype =='Super Administrator' || $event->IdUser == $user->id)
			{
				$host_module = rseventsHelper::createHostMenu($event);
				$layout = str_replace('{EventHostMenu}',$host_module , $layout);
			} else $layout = str_replace('{EventHostMenu}','', $layout);
			
			
			//replace guest menu			
			$guest_module = rseventsHelper::createGuestMenu($event);			
			$layout = str_replace('{EventGuestMenu}',$guest_module,$layout);

			
			/* Switch Body */
			switch($body)
			{
				case 'info':
					$layout = str_replace(array('{EventStartInfo}','{EventEndInfo}'),'',$layout);
					$layout = rseventsHelper::createExtras($event, $layout);
				break;
				
				case 'invite':
				case 'guestsendmessage':
				case 'subscribe':
				case 'photos':
				case 'importyahoo':
				case 'importgmail':
					$layout = rseventsHelper::splitLayout($event, $layout);
					$this->assignRef('data',$event);
				break;
				
			}
			
			$mainframe->triggerEvent('rse_onAfterShowEvent',array(array('event'=>&$event,'layout'=>&$layout)));
			
			$this->assignRef('layout',$layout);
		} else
		{
			$msg = JText::_('RSE_EVENT_INVALID');
			$link = html_entity_decode(JRoute::_('index.php?option=com_rsevents&view=events'.$itemId));
			$mainframe->redirect($link,$msg);
		}

	
	}
	
	function splitLayout($event, $layout)
	{
		$find = explode('{EventStartInfo}',$layout);
		$l[0] = $find[0];
		
		$end = explode('{EventEndInfo}',$find[1]);
		$l[1] = $end[1];
		
		return $l;
		
	}
	
	function createHostMenu($event)
	{
		global $mainframe;
		$rseventsConfig = $mainframe->getUserState('rseventsConfig');
		
		$user =& JFactory::getUser();
		
		//is everyone or registered(to the event)
		$isRegistered = $this->get('Subscriber');
		
		$Itemid = intval(JRequest::getVar('Itemid','','request'));
		$itemId = ($Itemid == '') ? '' : '&Itemid='.$Itemid;
		
		//Create the Host Menu
		$host_module = '<div id="rsevents_menu">';
		$host_module .= '<h3>'.JText::_('RSE_HOST_MENU').'</h3>';
		$host_module .= '<ul>';
		$host_module .= '<li><a href="'.html_entity_decode(JRoute::_('index.php?option=com_rsevents&view=events&layout=addeditevent&cid='.$event->IdEvent.':'.JFilterOutput::stringURLSafe($event->EventName).$itemId)).'">'.JText::_('RSE_MENU_EVENT_EDIT').'</a></li>';
		$host_module .= '<li><a href="'.html_entity_decode(JRoute::_('index.php?option=com_rsevents&view=events&layout=invite&cid='.$event->IdEvent.$itemId)).'">'.JText::_('RSE_MENU_EVENT_INVITE').'</a></li>';
		
		if($event->EventEnableRegistration == 1) $host_module .= '<li><a href="'.html_entity_decode(JRoute::_('index.php?option=com_rsevents&view=events&layout=guestssendmessage&cid='.$event->IdEvent.$itemId)).'">'.JText::_('RSE_MENU_EVENT_SEND_MESSAGES').'</a></li>';
		if($event->EventEnableRegistration == 1) $host_module .= '<li><a href="'.html_entity_decode(JRoute::_('index.php?option=com_rsevents&task=exportguests&controller=events&cid='.$event->IdEvent.':'.JFilterOutput::stringURLSafe($event->EventName).$itemId)).'">'.JText::_('RSE_MENU_EVENT_EXPORT').'</a></li>';
		if($event->EventEnableRegistration == 1) $host_module .= '<li><a href="'.html_entity_decode(JRoute::_('index.php?option=com_rsevents&view=subscriptions&IdEvent='.$event->IdEvent.':'.JFilterOutput::stringURLSafe($event->EventName).$itemId)).'">'.JText::_('RSE_MENU_EVENT_SUBSCRIBERS').'</a></li>';
		$host_module .= '<li><a href="'.html_entity_decode(JRoute::_('index.php?option=com_rsevents&task=duplicateevent&cid='.$event->IdEvent.':'.JFilterOutput::stringURLSafe($event->EventName).$itemId)).'">'.JText::_('RSE_MENU_EVENT_DUPLICATE').'</a></li>';
		if((time() > $event->EventEndDateToTime) && ($event->EventEnableRegistration == 1) ) $host_module .= '<li><a href="'.html_entity_decode(JRoute::_('index.php?option=com_rsevents&task=postreminder&controller=events&cid='.$event->IdEvent.':'.JFilterOutput::stringURLSafe($event->EventName).$itemId)).'" onclick="javascript:if(!confirm(\' '.JText::_('RSE_MENU_EVENT_PREMINDER_CONFIRM').' \')) return false;" >'.JText::_('RSE_MENU_EVENT_PREMINDER').'</a></li>';
		$host_module .= '<li><a href="'.html_entity_decode(JRoute::_('index.php?option=com_rsevents&task=reminder&controller=events&cid='.$event->IdEvent.':'.JFilterOutput::stringURLSafe($event->EventName).$itemId)).'" onclick="javascript:if(!confirm(\''.JText::_('RSE_MENU_EVENT_REMINDER_CONFIRM').'\')) return false;">'.JText::_('RSE_MENU_EVENT_REMINDER').'</a></li>';
		$host_module .= '<li><a href="'.html_entity_decode(JRoute::_('index.php?option=com_rsevents&task=cancelevent&controller=events&cid='.$event->IdEvent.':'.JFilterOutput::stringURLSafe($event->EventName).$itemId)).'"  onclick="javascript:if(!confirm(\' '.JText::_('RSE_MENU_EVENT_DELETE_CONFIRM').' \')) return false;">'.JText::_('RSE_MENU_EVENT_CANCEL').'</a></li>';
		$host_module .= '</ul>';
		$host_module .= '</div>';
		
		return $host_module;
	}
	
	function createGuestMenu($event)
	{			
		global $mainframe;
		$rseventsConfig = $mainframe->getUserState('rseventsConfig');
		
		$user =& JFactory::getUser();
		
		//set the Itemid
		$Itemid = intval(JRequest::getVar('Itemid','','request'));
		$itemId = ($Itemid == '') ? '' : '&Itemid='.$Itemid;
		
		//is everyone or registered(to the event)
		$isRegistered = $this->get('Subscriber');
		
		//get and set the Private Url
		$privateUrl = JRequest::getVar('privateUrl','','request');
		if($privateUrl !='') $link = '&privateUrl='.$privateUrl;
		else $link='';
		
		//get the permissions
		$permissions = rseventsModelEvents::getPermissions();
		
		$guest_module = '<div id="rsevents_menu">';
		$guest_module .= '<h3>'.JText::_('RSE_GUEST_MENU').'</h3>';
		$guest_module .= '<ul>';
		
		if(@$permissions['canEdit'] == 1) $guest_module .= '<li><a href="'.html_entity_decode(JRoute::_('index.php?option=com_rsevents&view=events&layout=addeditevent&cid='.$event->IdEvent.':'.JFilterOutput::stringURLSafe($event->EventName).$itemId)).'">'.JText::_('RSE_MENU_EVENT_EDIT').'</a></li>';
		if(($event->EventEnableRegistration == 1 && !$isRegistered && $event->published != '-1') || $rseventsConfig['event.multiple.reg'] == 1) 
		$guest_module .= '<li><a href="'.html_entity_decode(JRoute::_('index.php?option=com_rsevents&view=events&layout=subscribe&cid='.$event->IdEvent.$link.$itemId)).'">'.JText::_('RSE_MENU_EVENT_SUBSCRIBE').'</a></li>';
		if($rseventsConfig['event.show.invite'] && $event->published != '-1') $guest_module .= '<li><a href="'.html_entity_decode(JRoute::_('index.php?option=com_rsevents&view=events&layout=invite&cid='.$event->IdEvent.$link.$itemId)).'">'.JText::_('RSE_MENU_EVENT_INVITE').'</a></li>';
		if($rseventsConfig['events.extras.flickr']) $guest_module .= '<li><a href="'.html_entity_decode(JRoute::_('index.php?option=com_rsevents&view=events&layout=photos&cid='.$event->IdEvent.$link.$itemId)).'">'.JText::_('RSE_MENU_EVENT_ADD_PHOTOS').'</a></li>';
		if ($rseventsConfig['event.show.outlook']) $guest_module .= '<li><a href="'.html_entity_decode(JRoute::_('index.php?option=com_rsevents&task=addoutlook&controller=events&cid='.$event->IdEvent.':'.JFilterOutput::stringURLSafe($event->EventName).$itemId)).'">'.JText::_('RSE_MENU_EVENT_ADD_OUTLOOK').'</a></li>';
		$guest_module .= '<li><a href="'.html_entity_decode(JRoute::_('index.php?option=com_rsevents&view=events&layout=printevent&cid='.$event->IdEvent.':'.JFilterOutput::stringURLSafe($event->EventName).'&tmpl=component'.$itemId)).'"  onclick="window.open(this.href,\'win2\',\'status=no,toolbar=no,scrollbars=yes,titlebar=no,menubar=no,resizable=yes,width=640,height=480,directories=no,location=no\'); return false;">'.JText::_('RSE_MENU_EVENT_PRINT').'</a></li>';
		if($isRegistered && $event->published != '-1') $guest_module .= '<li><a href="'.html_entity_decode(JRoute::_('index.php?option=com_rsevents&task=eventunsubscribe&controller=events&cid='.$event->IdEvent.':'.JFilterOutput::stringURLSafe($event->EventName).$itemId)).'" onclick="javascript:if(!confirm(\' '.JText::_('RSE_MENU_EVENT_UNSUBSCRIBE_CONFIRM').' \')) return false;">'.JText::_('RSE_MENU_EVENT_UNSUBSCRIBE').'</a></li>';
		$guest_module .= '</ul>';
		$guest_module .= '</div>';
		
		return $guest_module;
	}
	
	function createExtras($event, $layout)
	{
		global $mainframe;
		$rseventsConfig = $mainframe->getUserState('rseventsConfig');
		
		$user =& JFactory::getUser();
		
		//loading the files
		$fileList=$this->get('Files');
		
		//is everyone or registered(to the event)
		$isRegistered = $this->get('Subscriber');
		
		//loading the extras
		$extras=$this->get('Extras');
		
		//The {googleMap} Placeholder
		if($rseventsConfig['locations.gmaps'])
			$map = rseventsModelEvents::getMap($event->IdLocation);
		else $map = '';
		
		$find[] = '{googleMap}';
		$replace[] = $map;
		
		
		//The {EventFiles} Placeholder
		$permissions = $this->get('Permissions');
		$allowDownload = (@$permissions['allowDownload'] || $user->usertype =='Super Administrator') ? 1 : 0 ;
		
		//Determine the interval you are in (before/during/after)
		if(time() < $event->EventStartDateToTime) $interval = 'before';
		if(time() >= $event->EventStartDateToTime && time() < $event->EventEndDateToTime) $interval = 'during';
		if(time() >= $event->EventEndDateToTime) $interval = 'after';

		//Show files
		$files = array();
		if(!empty($fileList))
		{
			foreach($fileList as $i => $file)
			{
					if((!$isRegistered && $allowDownload &&  (($interval == 'before' && $file->FilePermission[0]==1) || ($interval == 'during' && $file->FilePermission[1]==1) || ($interval == 'after' && $file->FilePermission[2]==1)))||($isRegistered && $allowDownload &&  (($interval == 'before' && $file->FilePermission[3]==1) || ($interval == 'during' && $file->FilePermission[4]==1) || ($interval == 'after' && $file->FilePermission[5]==1)))) 
					$files[] = '<li><a href="'.JURI::root().'components/com_rsevents/files/'.$file->FileLocation.'" target="_blank">'.$file->FileName.'</a></li>';
			}
		}
		$find[] = '{EventFiles}';
		$replace[] = implode('',$files);


		//The {youtubeURL} Placeholder
		$youtubeURL=array();
		foreach($extras as $i => $objExtra)
		{ 
			if($extras[$i]->ExtraName=='youtube')
			{
				$yURL = str_replace('watch?v=','v/',$objExtra->ExtraValue);
				$youtubeURL[]='<object width="480" height="295"><param name="movie" value="'.$yURL.'&hl=en&fs=1"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="'.$yURL.'&hl=en&fs=1" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="480" height="295"></embed></object>';
			}
		}
		$find[] = '{youtubeURL}';
		$replace[] = implode("",$youtubeURL);
		
		
		//The {meeboCode} Placeholder
		$meeboCode = array();
		foreach($extras as $i => $objExtra)
		{
			if($extras[$i]->ExtraName == 'meebo')
			{
				$meeboCode[] = $objExtra->ExtraValue;
			}
		}
		$find[] = '{meeboCode}';
		$replace[] = implode("",$meeboCode);
		
		
		//The {EventPhotos} Placeholder
		$photos = array();
		foreach($extras as $i => $objExtra)
		{
			if($extras[$i]->ExtraName == 'flickr')
			{
				$photos[] = $this->getPhotos($objExtra->IdExtra, $objExtra->ExtraValue);
			}
		}
		
		if(count($photos) > 0 && !empty($photos)) 
			$photos = '<p>'.JText::_('RSE_EVENT_PHOTOS').'</p>'.
			'<ul class="rsevents-extra-photos">'.implode('',$photos).'</ul>';
		else $photos = '';
		$find[] = '{EventPhotos}';
		$replace[] = $photos;
		
		
		//The {mp3URL} Placeholder
		$mp3URL=array();
		foreach($extras as $i => $objExtra)
		{ 
			if($extras[$i]->ExtraName=='mp3')
			{
				$mp3URL[]='<object width="300" height="110"><param name="movie" value="'.$objExtra->ExtraValue.'"></param><param name="wmode" value="transparent"></param><embed src="'.$objExtra->ExtraValue.'" type="application/x-shockwave-flash" width="300" height="110" wmode="transparent"></embed></object>';
			}
		}
		$find[] = '{mp3URL}';
		$replace[] = implode("",$mp3URL);
		
		
		//The {flashURL} Placeholder
		$flashURL=array();
		foreach($extras as $i => $objExtra)
		{ 
			if($extras[$i]->ExtraName=='flash')
			{
				$flashURL[]=$objExtra->ExtraValue;
			}
		}
		$find[] = '{flashURL}';
		$replace[] = implode("",$flashURL);
		
		//Replace the placeholders in the layout
		$layout = str_replace($find,$replace,$layout);
		
		return $layout;
	}	
	
	function importyahoo()
	{			
		$cid = intval(JRequest::getVar('cid','','request'));
			
		$username = JRequest::getVar('username','','post');
		$password = JRequest::getVar('password','','post');
	
		$showContacts = false;
			if(isset($username) && isset($password) && $username != '' && $password != '') 
			{
				$this->assignRef('contacts',yahoo::import($username,$password));
				$showContacts = true;
			}
		
		
		
		$location = "";
		$cookiearr = array();
		
		$addopt = true;
		
		
		$this->assignRef('cid',$cid);
		$this->assignRef('showContacts',$showContacts);
	}
	
	function importgmail()
	{
		$cid = intval(JRequest::getVar('cid','','request'));
		$username = JRequest::getVar('username','','post');
		$password = JRequest::getVar('password','','post');

		$showContacts = false;
		if(isset($username) && isset($password) && $username != '' && $password != '') 
		{
			$this->assignRef('contacts',g_import($username,$password));
			$showContacts = true;
		}
		$location = "";
		$cookiearr = array();
		$csv_source_encoding='utf-8';
		$this->assignRef('showContacts',$showContacts);
		$this->assignRef('cid',$cid);
	
	}
	
	
	function strip_html_tags( $text )
	{
		$text = preg_replace(
			array(
			  // Remove invisible content
				'@<head[^>]*?>.*?</head>@siu',
				'@<style[^>]*?>.*?</style>@siu',
				'@<script[^>]*?.*?</script>@siu',
				'@<object[^>]*?.*?</object>@siu',
				'@<embed[^>]*?.*?</embed>@siu',
				'@<applet[^>]*?.*?</applet>@siu',
				'@<noframes[^>]*?.*?</noframes>@siu',
				'@<noscript[^>]*?.*?</noscript>@siu',
				'@<noembed[^>]*?.*?</noembed>@siu',
			  // Add line breaks before and after blocks
				'@</?((address)|(blockquote)|(center)|(del))@iu',
				'@</?((div)|(h[1-9])|(ins)|(isindex)|(p)|(pre))@iu',
				'@</?((dir)|(dl)|(dt)|(dd)|(li)|(menu)|(ol)|(ul))@iu',
				'@</?((table)|(th)|(td)|(caption))@iu',
				'@</?((form)|(button)|(fieldset)|(legend)|(input))@iu',
				'@</?((label)|(select)|(optgroup)|(option)|(textarea))@iu',
				'@</?((frameset)|(frame)|(iframe))@iu',
			),
			array(
				' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
				"\n\$0", "\n\$0", "\n\$0", "\n\$0", "\n\$0", "\n\$0",
				"\n\$0", "\n\$0",
			),
			$text );
		return strip_tags( $text );
	}
	
	function saveRegistration($subscriptionId = null)
	{
		global $mainframe;
		
		$db			= & JFactory::getDBO();
		$user		= & JFactory::getUser();
		$idEvent	= intval(JRequest::getVar('cid',0,'request'));
		$info		= $mainframe->getUserState('rseventsConfig');
		$post		= JRequest::get('post');
		$fName		= @($post['form']['RSEventsFirstName'] == '') ? $post['FirstName'] : $post['form']['RSEventsFirstName'];
		$lName		= @($post['form']['RSEventsLastName'] == '') ? $post['LastName'] : $post['form']['RSEventsLastName'];
		$email		= @($post['form']['RSEventsEmail'] == '') ? $post['Email'] : $post['form']['RSEventsEmail'];
		$ticket		= @($post['form']['RSEventsTickets'][0] == '') ? $post['IdTicket'] : $post['form']['RSEventsTickets'][0];
		$numTickets = @($post['form']['RSEventsNumTickets'][0] == '') ? @$post['rse_numtickets'] : $post['form']['RSEventsNumTickets'][0] ;
		$payment	= @($post['form']['RSEventsPayment'] == '') ? @$post['payment'] : $post['form']['RSEventsPayment'];
		$userip		= $_SERVER['REMOTE_ADDR'];
		
		$numTickets = !isset($numTickets) ? 1 : $numTickets;		
		
		if(!isset($post['payment'])) $post['payment'] = 'none';
		if(!isset($post['form']['RSEventsPayment'])) $post['form']['RSEventsPayment'] = 'none';
		
		$Itemid = intval(JRequest::getVar('Itemid','','request'));
		$itemId = ($Itemid == '') ? '' : '&Itemid='.$Itemid;
		
		//Get event name
		$db->setQuery("SELECT EventName FROM #__rsevents_events WHERE IdEvent = '".$idEvent."'");
		$EventName = $db->loadResult();
		
		$db->setQuery("SELECT id FROM #__users WHERE email = '".$email."'");
		$uid = $db->loadResult();
		
		//Check if user exists(if not, we create it)
		if($fName != '' && $email != '' && rseventsModelEvents::email($email))
		{
			if ($info['event.enable.guests'] == 0)
				$userId = rseventsModelUsers::returnUser($db->getEscaped($email),$db->getEscaped($fName)." ".$db->getEscaped($lName));
			elseif (empty($user->id) && empty($uid)) $userId = 0;
			else $userId = $uid;
		}
		else 
			$mainframe->redirect(html_entity_decode(JRoute::_('index.php?option=com_rsevents&view=events&layout=subscribe&cid='.$idEvent.$itemId)),JText::_('RSE_SUBSCRIBER_NAME_EMAIL_ERROR'));
		
		//check if user is already subscribed
		$db->setQuery("SELECT COUNT(IdSubscription) FROM jos_rsevents_subscriptions WHERE IdEvent='".$idEvent."' AND Email='".$db->getEscaped($email)."'");
		$row = $db->loadResult();
		if($info['event.multiple.reg'] == 1) $row = 0;
		
		if($row)
		{
			$mainframe->redirect(html_entity_decode(JRoute::_('index.php?option=com_rsevents&view=events&layout=show&cid='.$idEvent.$itemId)),JText::_('RSE_SUBSCRIBER_ALLREADY_REGISTERED'));
		}
		else
		{
			
			
			//Get ticket details
			$db->setQuery("SELECT TicketName, TicketPrice FROM #__rsevents_tickets WHERE IdTicket = '".$db->getEscaped($ticket)."'");
			$ticketDetails = $db->loadObject();
			
			$db->setQuery("SELECT EventAutoApprove FROM #__rsevents_events WHERE IdEvent='".$idEvent."'");
			$autoApprove = $db->loadResult();
			
			$SubscriptionState = ($autoApprove == 1 && $ticketDetails->TicketPrice == 0) ? 1 : 0;
			
			$SubscriptionVerification = md5(uniqid(''));
			$SubscriptionDate = time();
			$SubscriptionGateway = $payment;
			
			//get the subscription id  
			$subscriptionId = ($subscriptionId != null) ? $subscriptionId : ''; 
			
			$mainframe->triggerEvent('rse_onBeforeStoreSubmission',array(array('idEvent'=>&$idEvent,'userId'=>&$userId,'fName'=>&$fName,'lName'=>&$lName,'email'=>&$email,'subscriptionId'=>&$subscriptionId,'SubscriptionState'=>&$SubscriptionState)));

			//Add to Subscriptions
			$db->setQuery("INSERT INTO #__rsevents_subscriptions (IdEvent , IdUser , FirstName , LastName , Email , SubscriptionDate, SubscriptionVerification , TransactionGateway , SubscriptionFormId , UserIp , SubscriptionState) "
						 ." VALUES ('".$idEvent."' , '".$userId."' , '".$db->getEscaped($fName)."' , '".$db->getEscaped($lName)."' , '".$db->getEscaped($email)."' , '".$SubscriptionDate."','".$SubscriptionVerification."' , '".$SubscriptionGateway."' , '".$subscriptionId."' , '".$userip."' , '".$SubscriptionState."') ");
			$db->query();
			
			$IdSubscription = $db->insertid();
			
			//Add to Subscription Tickets
			$db->setQuery("INSERT INTO #__rsevents_subscription_tickets (IdSubscription , IdTicket , TicketsSubscribed) VALUES ('".$IdSubscription."' , '".$db->getEscaped($ticket)."' , ".$numTickets.")");
			$db->query();
			
			$mainframe->triggerEvent('rse_onAfterStoreSubmission',array(array('idEvent'=>&$idEvent,'userId'=>&$userId,'fName'=>&$fName,'lName'=>&$lName,'email'=>&$email,'IdSubscription'=>&$IdSubscription,'SubscriptionState'=>&$SubscriptionState)));

			//START Send email to registered
			$db->setQuery("SELECT e.EventName ,e.EventDescription ,e.EventStartDate , e.EventEndDate , e.EventHost , l.LocationName, l.LocationCity , u.username FROM #__rsevents_events e LEFT JOIN #__users u ON u.id='".$user->id."' LEFT JOIN #__rsevents_locations l ON e.IdLocation=l.IdLocation WHERE e.IdEvent='".$idEvent."'");
			$eventDetails = $db->loadObject();
			
			$eventLink = '<a target="_blank" href="'.html_entity_decode(JRoute::_(JURI::root().'index.php?option=com_rsevents&view=events&layout=show&cid='.$idEvent.':'.JFilterOutput::stringURLSafe($eventDetails->EventName).$itemId)).'">'.$eventDetails->EventName.'</a>';
			
			//category names
			$categoryname = array();
			$db->setQuery("SELECT c.CategoryName , c.IdCategory FROM #__rsevents_categories c LEFT JOIN #__rsevents_events_cat ec ON ec.IdCategory = c.IdCategory WHERE ec.IdEvent =".$idEvent);
			$categs = $db->loadObjectList();
			
			foreach($categs as $categ)
				$categoryname[] = '<a href="'.html_entity_decode(JRoute::_('index.php?option=com_rsevents&view=events&layout=listcategoryevents&cid='.$categ->IdCategory.':'.JFilterOutput::stringURLSafe($categ->CategoryName).$itemId)).'">'.$categ->CategoryName.'</a>';
			
			$categoryname = implode(',',$categoryname);
			
			//ticket details 
			$ticketInfo = $numTickets . ' '.JText::_('RSE_TICKET_SEPARATOR').' '.$ticketDetails->TicketName;
			
			$toChange = array('{EventName}','{EventDescription}','{EventStartDate}','{EventEndDate}','{EventHost}','{LocationName}','{LocationCity}','{CategoryName}','{username}','{EventLink}','{TicketInfo}');
			$with = array($eventDetails->EventName , $eventDetails->EventDescription , rseventsHelper::translateDate(date($info['global.dateformat'],$eventDetails->EventStartDate)) , rseventsHelper::translateDate(date($info['global.dateformat'],$eventDetails->EventEndDate)), $eventDetails->EventHost,$eventDetails->LocationName,$eventDetails->LocationCity,$categoryname, empty($eventDetails->username) ? $email : $eventDetails->username ,$eventLink,$ticketInfo);
			
			$from		= $info['emails.from'];
			$fromName	= $info['emails.from.name'];
			$to			= $email;
			$subject	= $info['emails.registration.subject'];
			$body		= $info['emails.registration.content'];
			$body		= str_replace($toChange , $with ,$body);
			$mode		= $info['emails.registration.type'];
			$replyto	= $info['emails.reply'];
			$cc			= !empty($info['emails.cc']) ? $info['emails.cc'] : null;
			$bcc		= !empty($info['emails.bcc']) ? $info['emails.bcc'] : null;
			
			if ($info['emails.registration.enable'] == 1) JUtility::sendMail($from , $fromName , $to , $subject , $body , $mode , $cc , $bcc , null , $replyto);
			
			//END Send email to registered
			
			//Send activation email if the user has purchased a free ticket
			if($SubscriptionState == 1)
			{
				$db->setQuery("SELECT e.EventName ,e.EventDescription ,e.EventStartDate , e.EventEndDate , e.EventHost , l.LocationName, l.LocationCity , u.username FROM #__rsevents_events e LEFT JOIN #__users u ON u.id='".$user->id."' LEFT JOIN #__rsevents_locations l ON e.IdLocation=l.IdLocation WHERE IdEvent='".$idEvent."'");
				$eventDetails = $db->loadObject();
					
				$eventLink = '<a target="_blank" href="'.html_entity_decode(JRoute::_(JURI::root().'index.php?option=com_rsevents&view=events&layout=show&cid='.$idEvent.':'.JFilterOutput::stringURLSafe($eventDetails->EventName).$itemId)).'">'.$eventDetails->EventName.'</a>';
				$toChange = array('{EventName}','{EventDescription}','{EventStartDate}','{EventEndDate}','{EventHost}','{LocationName}','{LocationCity}','{CategoryName}','{username}','{EventLink}','{TicketInfo}');
				$with = array($eventDetails->EventName , $eventDetails->EventDescription , rseventsHelper::translateDate(date($info['global.dateformat'],$eventDetails->EventStartDate)) , rseventsHelper::translateDate(date($info['global.dateformat'],$eventDetails->EventEndDate)), $eventDetails->EventHost,$eventDetails->LocationName,$eventDetails->LocationCity,$categoryname, empty($eventDetails->username) ? $email : $eventDetails->username,$eventLink,$ticketInfo);
				
				
				$from		= $info['emails.from'];
				$fromName	= $info['emails.from.name'];
				$to			= $email;
				$subject	= $info['emails.activation.subject'];
				$body		= $info['emails.activation.content'];
				$body		= str_replace($toChange , $with ,$body);
				$mode		= $info['emails.activation.type'];
				$replyto	= $info['emails.reply'];
				$cc			= !empty($info['emails.cc']) ? $info['emails.cc'] : null;
				$bcc		= !empty($info['emails.bcc']) ? $info['emails.bcc'] : null;
				
				if($info['emails.activation.enable'] == 1) JUtility::sendMail($from , $fromName , $to , $subject , $body , $mode , $cc , $bcc , null , $replyto);
			}
			
			if($ticketDetails->TicketPrice > 0)
			{
				if(defined('RSEVENTS_PAYPAL') && $payment == 'paypal')
				{
					$plugin =& JPluginHelper::getPlugin( 'system', 'rseventspaypal' ); 	//Get a reference to this plugin
					$params = new JParameter( $plugin->params );
					
					$db->setQuery("SELECT EventPaypalEmail FROM #__rsevents_events WHERE IdEvent='".$idEvent."'");
					$paypal_user_email = $db->loadResult();
					
					if($info['paypal.for.users'] == 1 && $paypal_user_email != '')
					$payment_email = $paypal_user_email;
					else
					$payment_email = $params->get('paypal_email','');
					
					$payment_mode = $params->get('paypal_mode',0);
					
					$ticket_price = $numTickets * $ticketDetails->TicketPrice;
					
					//Paypal Control is md5(IdEvent.SubscriptionVerification.IdSubscription)
					
					$paypal_link = $payment_mode ? 'https://www.paypal.com/cgi-bin/webscr' : 'https://www.sandbox.paypal.com/';
					$link = $paypal_link . '?cmd=_xclick&business=' . urlencode($payment_email) . '&item_name=' . urlencode($EventName.' - '.$ticketDetails->TicketName) . '&currency_code=' . urlencode($info['payment.currency'] ). '&amount=' . urlencode($ticket_price) . '&notify_url='.JURI::root().'?paypal&custom='.md5($idEvent.$SubscriptionVerification.$IdSubscription);
					
					// Get event return url
					$db->setQuery("SELECT EventReturnUrl FROM #__rsevents_events WHERE IdEvent = '".$idEvent."'");
					$return_url = $db->loadResult();
					if (!empty($return_url))
						$link .= '&return='.urlencode($return_url);
					
					$mainframe->redirect($link);
				}
				
				if(defined('RSEVENTS_2CO') && $payment == '2co')
				{
					$ticket_price = $numTickets * $ticketDetails->TicketPrice;
					
					$mainframe->redirect(JRoute::_('index.php?option=com_rsevents&task=twoco&coi='.htmlentities($EventName.' - '.$ticketDetails->TicketName).'&price='.htmlentities($ticket_price).'&custom='.htmlentities(md5($idEvent.$SubscriptionVerification.$IdSubscription)).'&idevent='.$idEvent));

				}
				
				if(defined('RSEVENTS_WIRE') && $payment == 'wire')
				{
					$mainframe->redirect(html_entity_decode(JRoute::_('index.php?option=com_rsevents&view=events&layout=wire&cid='.$idEvent.$itemId)));
				}
			}
		
			
			$msg=JText::_('RSE_SUBSCRIBER_SUCCESS');
			if(!isset($post['form']['formId']))
				$mainframe->redirect(html_entity_decode(JRoute::_('index.php?option=com_rsevents&view=events&layout=show&cid='.$idEvent.':'.JFilterOutput::stringURLSafe($EventName).$itemId)),$msg);

		}
	}
	
	function translateDate($date)
	{
		$replace = array('Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday','January','February','March','April','May','June','July','August','September','October','November','December','Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec');
		$with	 = array(JText::_('RSE_MONTH_MONDAY'),JText::_('RSE_MONTH_TUESDAY'),JText::_('RSE_MONTH_WEDNESDAY'),JText::_('RSE_MONTH_THURSDAY'),JText::_('RSE_MONTH_FRIDAY'),JText::_('RSE_MONTH_SATURDAY'),JText::_('RSE_MONTH_SUNDAY'),JText::_('RSE_JANUARY'),JText::_('RSE_FEBRUARY'),JText::_('RSE_MARCH'),JText::_('RSE_APRIL'),JText::_('RSE_MAY'),JText::_('RSE_JUNE'),JText::_('RSE_JULY'),JText::_('RSE_AUGUST'),JText::_('RSE_SEPTEMBER'),JText::_('RSE_OCTOBER'),JText::_('RSE_NOVEMBER'),JText::_('RSE_DECEMBER'),JText::_('RSE_JAN'),JText::_('RSE_FEB'),JText::_('RSE_MAR'),JText::_('RSE_APR'),JText::_('RSE_MAY'),JText::_('RSE_JUN'),JText::_('RSE_JUL'),JText::_('RSE_AUG'),JText::_('RSE_SEP'),JText::_('RSE_OCT'),JText::_('RSE_NOV'),JText::_('RSE_DEC'));
		
		return str_replace($replace, $with, $date);
	}
	
}