<?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
*/

// No direct access
defined( '_JEXEC' ) or die( 'Restricted access' );

class rseventsControllerEvents extends rseventsController
{
	/**
	 * constructor (registers additional tasks to methods)
	 * @return void
	 */
	function __construct()
	{
		parent::__construct();
		$this->registerTask('apply' ,  'save');
	}

	/**
	 * save a record 
	 * @return void
	 */
	function save()
	{
		//get variables
		
		global $mainframe;
		$db= JFactory::getDBO();
		$model = $this->getModel('events');
		$post=JRequest::get('post',JREQUEST_ALLOWHTML);
		$config = new JConfig();
		$page = intval(JRequest::getVar('page','','request'));
		$files=JRequest::get('files');
		$icon = @$files['icon'];
		$pathToThumbs = JPATH_SITE.DS.'components'.DS.'com_rsevents'.DS.'images'.DS.'thumbs'.DS;
		
		//get the itemid
		$Itemid = intval(JRequest::getVar('Itemid','','request'));
		$itemId = ($Itemid == '') ? '' : '&Itemid='.$Itemid;
		
		if ($page == 2)
			$files=$files['files'];
		
		$cid = intval(JRequest::getVar('cid'));
		$rseventsConfig = $mainframe->getUserState('rseventsConfig');
		$user =& JFactory::getUser();
		$gid = $user->gid;
		
		$row= & JTable::getInstance('Rsevents_Events','Table');
		
		
		
		if($page == 1)
		{
		
			//verify if the default ticket exist
			$db->setQuery("SELECT COUNT(*) FROM #__rsevents_tickets WHERE IdEvent='".$cid."'");
			$res = $db->loadResult();
			
			if(!$row->bind($post)) 
			{
				return JError::raiseWarning(500, $row->getError());
			}
			
			if($row->EventURL == 'http://') $row->EventURL = '';
			
			//loads the default designDetails
			$db->setQuery("SELECT IdDesign FROM #__rsevents_designs WHERE DesignDefault = 1 AND published = 1 ");
			$row->IdDesign = $db->loadResult();
			
			//loads the time in unix timestamp
			if($rseventsConfig['enable.12format'] == 1)
			{
				if($row->EventAmPm1 == 0)
					$startH = $post['EventStartDateH'].':'.$post['EventStartDateM'].':00 am';
				else 
					$startH = $post['EventStartDateH'].':'.$post['EventStartDateM'].':00 pm';
				
				if($row->EventAmPm2 == 0)
					$endH = $post['EventEndDateH'].':'.$post['EventEndDateM'].':00 am';
				else 
					$endH = $post['EventEndDateH'].':'.$post['EventEndDateM'].':00 pm';
			} else 
			{
				$startH = $post['EventStartDateH'].':'.$post['EventStartDateM'].':00';
				$endH = $post['EventEndDateH'].':'.$post['EventEndDateM'].':00';
			}
			
			
			
			$row->EventStartDate=strtotime($post['EventStartDate'].' '.$startH);
			$row->EventEndDate=strtotime($post['EventEndDate'].' '.$endH);
			
			if($row->EventStartDate > $row->EventEndDate) $row->EventStartDate = $row->EventEndDate - 3600;
			
			$row->EventAlias = JFilterOutput::stringURLSafe($row->EventName);
			
			if($row->EventEndDate < $row->EventStartDate) 
			if(empty($row->IdEvent))
				$mainframe->redirect('index.php?option=com_rsevents&view=events&layout=addeditevent'.$itemId,JText::_('RSE_INVALID_DATE'));
			else
				$mainframe->redirect('index.php?option=com_rsevents&view=events&layout=addeditevent&cid='.$row->IdEvent.$itemId,JText::_('RSE_INVALID_DATE'));
			
			//verify if the event requires moderation
			$db->setQuery("SELECT gp.PermissionValue FROM #__rsevents_groups g LEFT JOIN #__rsevents_groups_acl ga ON g.IdGroup = ga.IdGroup "
						."LEFT JOIN #__rsevents_group_permissions gp ON g.IdGroup = gp.IdGroup WHERE ga.GroupAcl = '".$gid."' AND gp.PermissionName = 'enableModeration'");
			$permissionModeration = $db->loadResult();
			
			//set unpublished if the users group has event moderation on
			if($cid == 0)
			{
				if($permissionModeration == 1 && $user->usertype != "Super Administrator")
				{
					$row->published = 0;
					$from		= $config->mailfrom;
					$fromName	= $config->fromname;
					$to 		= $rseventsConfig['moderation.email'];
					$subject	= JText::sprintf('RSE_SUBJECT_REQUIRE_MODERATION',$user->name);
					$body		= JText::_('RSE_BODY_REQUIRE_MODERATION');

					
					if(!empty($to)) JUtility::sendMail($from , $fromName , $to , $subject , $body , 1 , null , null , null , null);
				}
				else 
				$row->published = 1;
				
			}
			
			//set the default registration form
			if(empty($row->EventRegistrationForm))
			$row->EventRegistrationForm = $rseventsConfig['event.registration.form'];
			
			//verify if the event requires registration
			$db->setQuery("SELECT gp.PermissionValue FROM #__rsevents_groups g LEFT JOIN #__rsevents_groups_acl ga ON g.IdGroup = ga.IdGroup "
							."LEFT JOIN #__rsevents_group_permissions gp ON g.IdGroup = gp.IdGroup WHERE ga.GroupAcl = '".$gid."' AND gp.PermissionName = 'allowRegistration'");
			$permissionRegistration = $db->loadResult();
			if($permissionRegistration == 0 && $user->usertype != "Super Administrator" )
			$row->EventEnableRegistration = 0;
			
			//creating the private Url
			if(empty($row->EventPrivateUrl))
			if($row->EventType == 0)
			{
				$row->EventPrivateUrl = uniqid('',FALSE);
			}
			
			//set the owner
			if($cid == 0)
			$row->IdUser = $user->id;
			
			if(empty($row->IdEvent) || $row->IdEvent == 0) $row->EventCreation = time();
			
			if($row->store())
			{
			
				//if the default ticket is not created , we create it
				if($res == '0')
				if($row->EventEnableRegistration) 
				{
					$db->setQuery("INSERT INTO #__rsevents_tickets (IdEvent,TicketName,TicketPrice,TicketMaxAudience,ordering) VALUES ('$row->IdEvent','".JText::_('RSE_TICKET_DEFAULT')."',0,'0','1')");
					$db->query();
				}
				if($rseventsConfig['enable.event.icon'] == 1)
				{
					$uniqid = uniqid('');
					rseventsControllerEvents::createThumbs($icon , $pathToThumbs , $rseventsConfig['event.icon.small'] , $row->IdEvent, $uniqid);
					rseventsControllerEvents::createThumbs($icon , $pathToThumbs , $rseventsConfig['event.icon.big'] , $row->IdEvent, $uniqid);
				}
				
				$db->setQuery("DELETE FROM #__rsevents_events_cat WHERE IdEvent = ".$row->IdEvent);
				$db->query();
				
				//insert categories
				foreach($post['IdCategory'] as $catid)
				{
					$db->setQuery("INSERT INTO #__rsevents_events_cat SET IdEvent = ".$row->IdEvent." , IdCategory = ".intval($catid));
					$db->query();
				}
				
				$task = JRequest::getVar('task');
				if($task == 'save')
					$mainframe->redirect(html_entity_decode(JRoute::_('index.php?option=com_rsevents&view=events&layout=addeditevent&cid='.$row->IdEvent.'&page=2'.$itemId)));
				if($task == 'apply')
					$mainframe->redirect(html_entity_decode(JRoute::_('index.php?option=com_rsevents&view=events&layout=addeditevent&cid='.$row->IdEvent.$itemId)));
			} else 
			{
				$mainframe->redirect(html_entity_decode(JRoute::_('index.php?option=com_rsevents&view=events&layout=addeditevent&cid='.$row->IdEvent.':'.JFilterOutput:: stringURLSafe($row->EventName).$itemId)),JText::_( 'RSE_EVENT_SAVE_ERROR' ));
			}
		}
		
		if($page == 2)
		{	
			$cid = JRequest::getVar('cid','','request');
			$cid = intval($cid);
			$row->load($cid);
			
			if(!$row->bind($post)) 
			{
				return JError::raiseWarning(500, $row->getError());
			}
		
			if ($row->store()) 
			{
				
				//start for inserting the files
				
				$allowedExtensions = str_replace(array("\r"," "),"",$rseventsConfig['event.files']);
				$allowedExtensions = explode("\n",$allowedExtensions);
				
				$target= JPATH_SITE.DS.'components'.DS.'com_rsevents'.DS.'files'.DS;
				$permissions =rseventsModelEvents::getPermissions();
				$uploadPermission = $permissions['allowUpload'];
				
				if($uploadPermission ==1 || $user->usertype == 'Super Administrator' || empty($files['name'][0]))
				{
					for($i=0;$i<10;$i++)
					{
						if(!empty($files['tmp_name'][$i]))
						{
							$extension = end(explode('.', $files['name'][$i]));
								if($extension != '' && array_search($extension,$allowedExtensions) !== false )
								{
									if($files['tmp_name'][$i]!='')
									{
										$fileLocation = uniqid('',FALSE)."_". basename( $files['name'][$i]);
										$file = $target . $fileLocation;
										move_uploaded_file($files['tmp_name'][$i] ,$file);
										$db->setQuery("INSERT INTO #__rsevents_files (IdEvent,FileName,FileLocation,FilePermission) VALUES ('".$db->getEscaped($row->IdEvent)."','".basename( $files['name'][$i])."','".$db->getEscaped($fileLocation)."','111111') "); 
										$db->query();
									}
								} else $mainframe->redirect(html_entity_decode(JRoute::_('index.php?option=com_rsevents&view=events&layout=addeditevent&cid='.$row->IdEvent.'&page=2'.$itemId)) , JText::_('RSE_FILE_INVALID'));
						}
					} $mainframe->redirect(html_entity_decode(JRoute::_('index.php?option=com_rsevents&view=events&layout=show&cid='.$row->IdEvent.':'.JFilterOutput:: stringURLSafe($row->EventName).$itemId)));
				} else $mainframe->redirect(html_entity_decode(JRoute::_('index.php?option=com_rsevents&view=events&layout=show&cid='.$row->IdEvent.':'.JFilterOutput:: stringURLSafe($row->EventName).$itemId)) , JText::_('RSE_FILE_CANNOT_UPLOAD'));
				
			} 
			else 
			{
				$mainframe->redirect(html_entity_decode(JRoute::_('index.php?option=com_rsevents&view=events&layout=show&cid='.$row->IdEvent.':'.JFilterOutput:: stringURLSafe($row->EventName).$itemId)),JText::_( 'RSE_EVENT_SAVE_ERROR' ));
			}
		}	
	}
	
	//generate a new Private Url
	
	function generate()
	{
		//get the itemid
		$Itemid = intval(JRequest::getVar('Itemid','','request'));
		$itemId = ($Itemid == '') ? '' : '&Itemid='.$Itemid;
		
		$cid = intval(JRequest::getVar('cid',0,'request'));
		$model = $this->getModel('events');
		$row = & JTable::getInstance('Rsevents_Events','Table');
		$row->load($cid);
		$row->EventPrivateUrl = uniqid('',FALSE);
		$row->store();
		$this->setRedirect('index.php?option=com_rsevents&view=events&layout=addeditevent&cid='.$cid.'&page=1'.$itemId);
	}
	
	
	//invite code 
	
	function invite()
	{
		//get variables
		global $mainframe;
		$db = & JFactory::getDBO();
		$user = & JFactory::getUser();
		$privateUrl = JRequest::getVar('privateUrl','','request');
		if($privateUrl != '') $pUrl = '&privateUrl='.$privateUrl;
		else $pUrl='';
		$rseventsConfig = $mainframe->getUserState('rseventsConfig');
		$cid = intval(JRequest::getVar('cid',0));
		$model = $this->getModel('events');
		$row= & JTable::getInstance('Rsevents_Events','Table');
		$row->load($cid);
		$msg = JText::_('RSE_INVITE_SENT');
		$post = JRequest::get('post',JREQUEST_ALLOWRAW);
		$peoples = explode("\n",$post['emails']);
		
		//get the itemid
		$Itemid = intval(JRequest::getVar('Itemid','','request'));
		$itemId = ($Itemid == '') ? '' : '&Itemid='.$Itemid;
		
		//send a mail to the people invited
		
		$db->setQuery("SELECT e.EventName ,e.EventDescription ,e.EventStartDate , e.EventEndDate , e.EventHost , l.LocationName, l.LocationCity , l.LocationCountry ,l.LocationZip , 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='".$cid."'");
			$eventDetails = $db->loadObject();
			
			$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 =".$cid);
			$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);
			
			$eventLink = '<a target="_blank" href="'.html_entity_decode(JRoute::_(JURI::root().'index.php?option=com_rsevents&view=events&layout=show&cid='.$cid.':'.JFilterOutput::stringURLSafe($row->EventName).$pUrl.$itemId)).'">'.$row->EventName.'</a>';
			$toChange = array('{EventName}','{EventDescription}','{EventStartDate}','{EventEndDate}','{EventHost}','{LocationName}','{LocationCity}','{CategoryName}','{username}','{message}','{EventLink}','{LocationCountry}','{LocationZip}');
			$with = array($eventDetails->EventName , $eventDetails->EventDescription , rseventsHelper::translateDate(date($rseventsConfig['global.dateformat'],$eventDetails->EventStartDate)) , rseventsHelper::translateDate(date($rseventsConfig['global.dateformat'],$eventDetails->EventEndDate)), $eventDetails->EventHost,$eventDetails->LocationName,$eventDetails->LocationCity,$categoryname, $eventDetails->username,$post['message'],$eventLink,$eventDetails->LocationCountry,$eventDetails->LocationZip);
			
			$from		= !empty($post['rse_from']) ? $post['rse_from'] : $rseventsConfig['emails.from'];
			$fromName	= $rseventsConfig['emails.from.name'];
			$subject	= $rseventsConfig['emails.invite.subject'];
			$subject	= str_replace($toChange , $with ,$subject);
			$body		= $rseventsConfig['emails.invite.content'];
			$body		= str_replace($toChange , $with ,$body);
			$mode		= $rseventsConfig['emails.invite.type'];
			$replyto	= $rseventsConfig['emails.reply'];			
			$cc			= !empty($rseventsConfig['emails.cc']) ? $rseventsConfig['emails.cc'] : null;
			$bcc		= !empty($rseventsConfig['emails.bcc']) ? $rseventsConfig['emails.bcc'] : null;
			
			foreach($peoples as $people)
			{
				$people = trim($people);
				$to = ($model->email($people)) ? $people : '';
				if($from!='') JUtility::sendMail($from , $fromName , $to , $subject , $body , $mode , $cc , $bcc , null , $replyto);
			}
		
		$link = html_entity_decode(JRoute::_('index.php?option=com_rsevents&view=events&layout=show&cid='.$cid.':'.JFilterOutput::stringURLSafe($row->EventName).$pUrl.$itemId));
		$this->setRedirect($link, $msg);
	}
	
	//add the event to Outlook
	
	function addOutlook()
	{
		global $mainframe;
		
		$db = & JFactory::getDBO();
		$rseventsConfig = $mainframe->getUserState('rseventsConfig');
		$model = $this->getModel('events');
		$cid = intval(JRequest::getVar('cid',0,'request'));
		$row= & JTable::getInstance('Rsevents_Events','Table');
		$row->load($cid);
		$db->setQuery("SELECT LocationName, LocationCity , LocationAddress FROM #__rsevents_locations WHERE IdLocation='".$row->IdLocation."'");
		$location = $db->loadObject();
	    $Filename = 'Event-'.$row->IdEvent.'.vcs';
	    header("Content-Type: text/x-vCalendar");
	    header("Content-Disposition: inline; filename=$Filename");

			$vCalStart = gmdate("Ymd\THis\Z", $row->EventStartDate);
			$vCalEnd = gmdate("Ymd\THis\Z", $row->EventEndDate);
			$row->EventDescription = str_replace(array("\r","\n"),'',strip_tags($row->EventDescription));
echo'
BEGIN:VCALENDAR
VERSION:1.0
BEGIN:VEVENT
SUMMARY:'.$row->EventName.'
DESCRIPTION;ENCODING=QUOTED-PRINTABLE:'.$row->EventDescription.'
LOCATION:'.$location->LocationCity.' - '.$location->LocationName.' - '.$location->LocationAddress.'
DTSTART:'.$vCalStart.'
DTEND:'.$vCalEnd.'
END:VEVENT
END:VCALENDAR
';
		exit();
	}
	
	//export the guests of the event
	
	function exportGuests()
	{
		//get variables
		global $mainframe;
		$db = & JFactory::getDBO();
		$user = &JFactory::getUser();
		$cid = intval(JRequest::getVar('cid',0,'request'));
		$model = $this->getModel('events');
		$row= & JTable::getInstance('Rsevents_Events','Table');
		$row->load($cid);
		
		//get the itemid
		$Itemid = intval(JRequest::getVar('Itemid','','request'));
		$itemId = ($Itemid == '') ? '' : '&Itemid='.$Itemid;
		
		if($user->usertype == 'Super Administrator' || $user->id == $row->IdUser)
		{
			$db->setQuery("SELECT FirstName , LastName , Email FROM #__rsevents_subscriptions WHERE IdEvent='".$cid."'");
			$results = $db->loadObjectList();
			$filename = 'Event'.$row->IdEvent.'.csv';
			header("Content-type: application/octet-stream");
			header("Content-Disposition: attachment; filename=$filename");
			$csv ="First Name,Last Name,E-mail \n";
			if(!empty($results))
			foreach($results as $objCsv)
			{
				$csv .= $objCsv->FirstName.",".$objCsv->LastName.",".$objCsv->Email."\n";
			}
			echo $csv;
			exit();
		} else $mainframe->redirect(html_entity_decode(JRoute::_('index.php?option=com_rsevents&view=events'.$itemId)),JText::_('RSE_ACCESS_DENIED'));
	}
	
	// code for sending message to  guests
	
	function guestsendmessage()
	{
		//get variables
		global $mainframe;
		$db = & JFactory::getDBO();
		$cid = intval(JRequest::getVar('cid',0,'request'));
		$rseventsConfig = $mainframe->getUserState('rseventsConfig');
		$model = $this->getModel('events');
		$row= & JTable::getInstance('Rsevents_Events','Table');
		$row->load($cid);
		$post = JRequest::get('post');
		
		//get the itemid
		$Itemid = intval(JRequest::getVar('Itemid','','request'));
		$itemId = ($Itemid == '') ? '' : '&Itemid='.$Itemid;
		
		//code for sending emails to guests
		if(!empty($post['SubscriptionState'])) 
		{
			$state = implode(',',$post['SubscriptionState']);
			$db->setQuery("SELECT e.EventName ,e.EventDescription ,e.EventStartDate , e.EventEndDate , e.EventHost , l.LocationName, l.LocationCity , u.username, s.Email FROM #__rsevents_events e LEFT JOIN #__rsevents_subscriptions s ON s.IdEvent = e.IdEvent LEFT JOIN #__users u ON u.id=s.IdUser LEFT JOIN #__rsevents_locations l ON e.IdLocation=l.IdLocation WHERE s.SubscriptionState IN (".$state.") AND e.IdEvent = '".$row->IdEvent."'");
			$subscriptionDetails = $db->loadObjectList();
			foreach($subscriptionDetails as $subscriptionDetailsObj)
			{					
				$from		= $rseventsConfig['emails.from'];
				$fromName	= $rseventsConfig['emails.from.name'];
				$to			= $subscriptionDetailsObj->Email;
				$subject	= $post['subject'];
				$body		= JRequest::getVar('message', '', 'post', 'none', JREQUEST_ALLOWRAW);
				$mode		= 1;
				$replyto	= $rseventsConfig['emails.reply'];
				$cc			= !empty($rseventsConfig['emails.cc']) ? $rseventsConfig['emails.cc'] : null;
				$bcc		= !empty($rseventsConfig['emails.bcc']) ? $rseventsConfig['emails.bcc'] : null;
				
				JUtility::sendMail($from , $fromName , $to , $subject , $body , $mode , $cc , $bcc , null , $replyto);
			}
			$msg = JText::_('RSE_MESSAGE_SENT');
			$link = html_entity_decode(JRoute::_('index.php?option=com_rsevents&view=events&layout=show&cid='.$cid.':'.JFilterOutput::stringURLSafe($row->EventName).$itemId));
		}
		else 
		{
			$state = '';
			$msg= JText::_('RSE_MESSAGE_RECIEVER_ERROR');
			$link = html_entity_decode(JRoute::_('index.php?option=com_rsevents&view=events&layout=guestssendmessage&cid='.$cid.':'.JFilterOutput::stringURLSafe($row->EventName).$itemId));
		}
		$this->setRedirect($link, $msg);
	}

	//cancel an event ( delete )
	
	function cancelEvent()
	{
		//get variables
		$db = & JFactory::getDBO();
		$my = & JFactory::getUser();
		$model = $this->getModel('events');
		$row =& JTable::getInstance('Rsevents_Events','Table');
		$cid = JRequest::getVar('cid',0,'request');
		$cid = intval($cid);
		
		//get the itemid
		$Itemid = intval(JRequest::getVar('Itemid','','request'));
		$itemId = ($Itemid == '') ? '' : '&Itemid='.$Itemid;
		
		
		$db->setQuery("SELECT IdUser FROM #__rsevents_events WHERE IdEvent='".$cid."'");
		$res = $db->loadResult();
		if($my->usertype == 'Super Administrator' || $my->id == $res )
		{
			if(!$row->delete($cid)) 
			{
				$msg = JText::_( 'RSE_EVENT_DELETE_ERROR' );
			} 
			else 
			{					
				$db->setQuery("SELECT FileLocation FROM #__rsevents_files WHERE IdEvent='".$cid."'");
				$arrayLocations=$db->loadObjectList();
				foreach ($arrayLocations as $obj)
				{
					@unlink(JPATH_SITE.DS.'components'.DS.'com_rsevents'.DS.'files'.DS.$obj->FileLocation);
				}
				$db->setQuery("DELETE FROM #__rsevents_files WHERE IdEvent=".$cid);
				$db->query();
				$db->setQuery("DELETE FROM #__rsevents_tickets WHERE IdEvent='".$cid."'");
				$db->query();
				$db->setQuery("SELECT IdSubscription FROM #__rsevents_subscriptions WHERE IdEvent='".$cid."'");
				$idSubscriptions = $db->loadObjectList();
				foreach($idSubscriptions as $i => $idSubscription)
				{
					$db->setQuery("DELETE FROM #__rsevents_subscription_tickets WHERE IdSubscription='".$idSubscription->IdSubscription."'");
					$db->query();
				}
				$db->setQuery("DELETE FROM #__rsevents_subscriptions WHERE IdEvent='".$cid."'");
				$db->query();
				
				$msg = JText::_( 'RSE_EVENT_DELETE' );
						
			}
		} else $msg = JText::_('RSE_ACCESS_DENIED');
		$this->setRedirect(html_entity_decode(JRoute::_('index.php?option=com_rsevents&view=events'.$itemId)), $msg );
	}

	/**
	 * cancel editing a record
	 * @return void
	 */
	function cancel()
	{
		//get the itemid
		$Itemid = intval(JRequest::getVar('Itemid','','request'));
		$itemId = ($Itemid == '') ? '' : '&Itemid='.$Itemid;
		
		$msg = JText::_( 'RSE_CANCELED_OPERATION' );
		$this->setRedirect(html_entity_decode(JRoute::_('index.php?option=com_rsevents&view=events'.$itemId)), $msg );
	}
	
	
	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;
	}
	
	
	//saving the youtube extra
	
	function saveYoutube()
	{
		//get variables
		
		global $mainframe;
		$db = & JFactory::getDBO();
		$model = $this->getModel('extras');
		$post = JRequest::get('post');
		$url = $post['youtubeURL'];
		$idEvent = JRequest::getVar('IdEvent',0,'request');
		$idEvent = intval($idEvent);
		$cid = JRequest::getVar('cid',0,'request');
		$cid = intval($cid);
		
		//get the itemid
		$Itemid = intval(JRequest::getVar('Itemid','','request'));
		$itemId = ($Itemid == '') ? '' : '&Itemid='.$Itemid;
		

		//loading the table
		$row = & JTable::getInstance('Rsevents_Extras','Table');
		$db->setQuery("SELECT EventName FROM #__rsevents_events WHERE IdEvent='".$idEvent."'");
		$res = $db->loadResult();
		$row->IdExtra=$cid;
		$row->IdEvent=$idEvent;
		$row->ExtraName='youtube';
		$row->ExtraValue=$url;
		
		if($row->store())
			$msg=JText::_('RSE_EXTRA_YOUTUBE_SAVE');
		else
		$msg=JText::_('RSE_EXTRA_YOUTUBE_SAVE_ERROR');
		$mainframe->redirect(html_entity_decode(JRoute::_('index.php?option=com_rsevents&view=events&layout=addeditevent&cid='.$idEvent.':'.JFilterOutput::stringURLSafe($res).'&page=2'.$itemId)) , $msg);
	}
	
	function saveFlickr()
	{
		//get variables
		
		global $mainframe;
		$db = & JFactory::getDBO();
		$model = $this->getModel('extras');
		$post = JRequest::get('post');
		$url = $post['flickr'];
		$idEvent = JRequest::getVar('IdEvent',0,'request');
		$idEvent = intval($idEvent);
		$cid = JRequest::getVar('cid',0,'request');
		$cid = intval($cid);
		
		//get the itemid
		$Itemid = intval(JRequest::getVar('Itemid','','request'));
		$itemId = ($Itemid == '') ? '' : '&Itemid='.$Itemid;
		
		//loading the table
		$row = & JTable::getInstance('Rsevents_Extras','Table');
		$db->setQuery("SELECT EventName FROM #__rsevents_events WHERE IdEvent='".$idEvent."'");
		$res = $db->loadResult();
		$row->IdExtra=$cid;
		$row->IdEvent=$idEvent;
		$row->ExtraName='flickr';
		$row->ExtraValue=$url;
		
		$pattern = '/http:\/\/www.flickr.com\/photos\/(.*)\/sets\/([0-9]+)/';
		preg_match($pattern, $post['flickr'], $matches);
		if(!empty($matches))
		{
			if($row->store())
			$msg=JText::_('RSE_EXTRA_FLICKR_SAVE');
			else
			$msg=JText::_('RSE_EXTRA_FLICKR_SAVE_ERROR');
			$mainframe->redirect(html_entity_decode(JRoute::_('index.php?option=com_rsevents&view=events&layout=addeditevent&cid='.$idEvent.':'.JFilterOutput::stringURLSafe($res).'&page=2'.$itemId)) , $msg);
		} else $mainframe->redirect(html_entity_decode(JRoute::_('index.php?option=com_rsevents&view=events&layout=addeditevent&cid='.$idEvent.':'.JFilterOutput::stringURLSafe($res).'&page=2'.$itemId)) , JText::_('RSE_EXTRA_FLICKR_INVALID_URL'));
	}
	
	//saving the meebo code
	
	function saveMeebo()
	{
		global $mainframe;
		$db = &JFactory::getDBO();
		$model = $this->getModel('extras');
		$post = JRequest::get('post',JREQUEST_ALLOWRAW);
		$url = stripslashes($this->RSstripjavaVar($post['meeboCode']));
		$idEvent = intval(JRequest::getVar('IdEvent',0,'request'));
		$cid = intval(JRequest::getVar('cid',0,'request'));
		$row = & JTable::getInstance('Rsevents_Extras','Table');
		$db->setQuery("SELECT EventName FROM #__rsevents_events WHERE IdEvent='".$idEvent."'");
		$res = $db->loadResult();
		
		//get the itemid
		$Itemid = intval(JRequest::getVar('Itemid','','request'));
		$itemId = ($Itemid == '') ? '' : '&Itemid='.$Itemid;
		
		$row->IdExtra=$cid;
		$row->IdEvent=$idEvent;
		$row->ExtraName='meebo';
		$row->ExtraValue=$url;
		
		if($row->store())
		$msg=JText::_('RSE_EXTRA_MEEBO_SAVE');
		else
		$msg=JText::_('RSE_EXTRA_MEEBO_SAVE_ERROR');
		$mainframe->redirect(html_entity_decode(JRoute::_('index.php?option=com_rsevents&view=events&layout=addeditevent&cid='.$idEvent.':'.JFilterOutput::stringURLSafe($res).'&page=2'.$itemId)) , $msg);
	}
	
	//saving the flash extra
	
	function saveFlash()
	{
		//get variables
		
		global $mainframe;
		$db = & JFactory::getDBO();
		$model = $this->getModel('extras');
		$post = JRequest::get('post',JREQUEST_ALLOWRAW);
		$url = stripslashes($this->RSstripjavaVar($post['flashCode']));
		$idEvent = intval(JRequest::getVar('IdEvent',0,'request'));
		$cid = intval(JRequest::getVar('cid',0,'request'));
		
		//get the itemid
		$Itemid = intval(JRequest::getVar('Itemid','','request'));
		$itemId = ($Itemid == '') ? '' : '&Itemid='.$Itemid;
		
		//loading the table
		$row = & JTable::getInstance('Rsevents_Extras','Table');
		$db->setQuery("SELECT EventName FROM #__rsevents_events WHERE IdEvent='".$idEvent."'");
		$res = $db->loadResult();
		
		$row->IdExtra=$cid;
		$row->IdEvent=$idEvent;
		$row->ExtraName='flash';
		$row->ExtraValue=$url;
		
		if($row->store())
		$msg=JText::_('RSE_EXTRA_FLASH_SAVE');
		else
		$msg=JText::_('RSE_EXTRA_FLASH_SAVE_ERROR');
		$mainframe->redirect(html_entity_decode(JRoute::_('index.php?option=com_rsevents&view=events&layout=addeditevent&cid='.$idEvent.':'.JFilterOutput::stringURLSafe($res).'&page=2'.$itemId)) , $msg);
	}
	
	//saving the mp3 Ieemem extra
	
	function saveMp3()
	{
		//get variables
		
		global $mainframe;
		$db = & JFactory::getDBO();
		$model = $this->getModel('extras');
		$post = JRequest::get('post');
		$url = stripslashes(str_replace(array("\r","\n","\t"),"",$_POST['mp3Code']));
		$idEvent = intval(JRequest::getVar('IdEvent',0,'request'));
		$cid = intval(JRequest::getVar('cid',0,'request'));
		
		//get the itemid
		$Itemid = intval(JRequest::getVar('Itemid','','request'));
		$itemId = ($Itemid == '') ? '' : '&Itemid='.$Itemid;
		
		//loadin the table
		$row = & JTable::getInstance('Rsevents_Extras','Table');
		$db->setQuery("SELECT EventName FROM #__rsevents_events WHERE IdEvent='".$idEvent."'");
		$res = $db->loadResult();
		$pattern = '/<param name="movie" value="(.*?)"/';
		$matches = array();
		preg_match($pattern,$url,$matches);
		$row->IdExtra=$cid;
		$row->IdEvent=$idEvent;
		$row->ExtraName='mp3';
		if(count($matches)<2) 
		{
			$msg = JText::_('RSE_EXTRA_MP3_NAME');
			$mainframe->redirect(html_entity_decode(JRoute::_('index.php?option=com_rsevents&view=events&layout=addeditevent&cid='.$idEvent.':'.JFilterOutput::stringURLSafe($res).'&page=2'.$itemId)) , $msg);
		}
		$row->ExtraValue=$matches[1];
		
		if($row->store())
		$msg=JText::_('RSE_EXTRA_MP3_SAVE');
		else
		$msg=JText::_('RSE_EXTRA_MP3_SAVE_ERROR');
		$mainframe->redirect(html_entity_decode(JRoute::_('index.php?option=com_rsevents&view=events&layout=addeditevent&cid='.$idEvent.':'.JFilterOutput::stringURLSafe($res).'&page=2'.$itemId)) , $msg);
	}
	
	//deleting  extras 
	
	function deleteExtra()
	{
		//get variables
		global $mainframe;
		$db = & JFactory::getDBO();
		$user = &JFactory::getUser();
		$model = $this->getModel('extras');
		$cid= intval(JRequest::getVar('cid',0,'request'));
		$idEvent = JRequest::getVar('IdEvent',0);
		
		//get the itemid
		$Itemid = intval(JRequest::getVar('Itemid','','request'));
		$itemId = ($Itemid == '') ? '' : '&Itemid='.$Itemid;
		
		//loading table
		$db->setQuery("SELECT EventName FROM #__rsevents_events WHERE IdEvent='".$idEvent."'");
		$res = $db->loadResult();
		$row = & JTable::getInstance('Rsevents_Extras','Table');
		$row1 = & JTable::getInstance('Rsevents_Events','Table');
		$row1->load($idEvent);
		
		
		if($user->usertype == 'Super Administrator' || $user->id == $row1->IdUser)
		{
			if($row->delete($cid))
				$msg=JText::_('RSE_EXTRA_DELETE');
			else
				$msg=JText::_('RSE_EXTRA_DELETE_ERROR');
			$mainframe->redirect(html_entity_decode(JRoute::_('index.php?option=com_rsevents&view=events&layout=addeditevent&cid='.$idEvent.':'.JFilterOutput::stringURLSafe($res).'&page=2'.$itemId)) , $msg);
		}
		$mainframe->redirect(html_entity_decode(JRoute::_('index.php?option=com_rsevents&view=events&layout=show&cid='.$idEvent.':'.JFilterOutput::stringURLSafe($res).$itemId)) , JText::_('RSE_ACCESS_DENIED'));
 	}
	
	
	
	//publish the event
	
	function publish()
	{
		global $mainframe;
		$db 	=& JFactory::getDBO();
		$cid		= JRequest::getVar( 'cid', array(), '', 'array' );
		$publish	= ( $this->getTask() == 'publish' ? 1 : 0 );

		JArrayHelper::toInteger($cid);

		if (count( $cid ) < 1)
		{
			$action = $publish ? 'publish' : 'unpublish';
			JError::raiseError(500, JText::_( 'RSE_PUBLISHED_ERROR' .$action, true ) );
		}

		$cids = implode( ',', $cid );
		
		$query = 'UPDATE #__rsevents_events'
		. ' SET published = ' . (int) $publish
		. ' WHERE IdEvent IN ( '. $cids .' )'
		;
		$db->setQuery( $query );
		if (!$db->query())
		{
			JError::raiseError(500, $db->getErrorMsg() );
		}
		$mainframe->redirect(html_entity_decode(JRoute::_('index.php?option=com_rsevents&view=events')));
	}
 

	//copy the event
    
	function copy()
    {
         // Get variables from the request
        global $mainframe;
		$db = & JFactory::getDBO();
        $cid        = JRequest::getVar( 'cid', array(), 'post', 'array' );
		if(is_array($cid)) $cid = $cid[0];
		$db->setQuery("SELECT IdEvent FROM #__rsevents_events WHERE IdEvent='".$cid."'");
		$arrayEvents       = $db->loadObjectList();
		
		//get the itemid
		$Itemid = intval(JRequest::getVar('Itemid','','request'));
		$itemId = ($Itemid == '') ? '' : '&Itemid='.$Itemid;

		if(!empty($arrayEvents))
		foreach($arrayEvents as $obj)
		{
	        $model  =& $this->getModel( 'Events' );
	        $model->copy($obj->IdEvent);
		}
		else 
		{
			$msg=JText::_('RSE_EVENT_ERROR1');
			$this->setRedirect(html_entity_decode(JRoute::_('index.php?option=com_rsevents&view=events'.$itemId)), $msg );
		}
			$msg=JText::_('RSE_EVENT_COPY');
			$this->setRedirect(html_entity_decode(JRoute::_('index.php?option=com_rsevents&view=events'.$itemId)), $msg );
		 
    }
	 
	function saveRegistration()
	{
		rseventsHelper::saveRegistration();
	}
	
	//unsubscribe the event
	function eventUnsubscribe()
	{
		global $mainframe;
		$my = & JFactory::getUser();
		$db = & JFactory::getDBO();
		$rseventsConfig = $mainframe->getUserState('rseventsConfig');
		$cid = JRequest::getVar('cid',0,'request');
		$cid = intval($cid);
		
		//get the itemid
		$Itemid = intval(JRequest::getVar('Itemid','','request'));
		$itemId = ($Itemid == '') ? '' : '&Itemid='.$Itemid;
		
		$model  =& $this->getModel( 'events' );
		$row = & JTable::getInstance('Rsevents_Events','Table');
		$row->load($cid);
		
		$mainframe->triggerEvent('rse_onBeforeUnsubscribe',array(array('data'=>&$row)));
		
		$db->setQuery("SELECT IdGroup FROM #__rsevents_groups_acl WHERE GroupAcl = ".$my->gid);
		$idg = $db->loadResult();
		
		$cancelation = $model->getCancelationPermission();
		
		if($cancelation == 1 || $my->usertype == "Super Administrator" || ($my->id > 0 && empty($idg)) )
		{
			if($row->EventEnableRegistration == '1')
			{
				$db->setQuery("SELECT IdSubscription FROM #__rsevents_subscriptions WHERE IdUser='".$my->id."' AND IdEvent='".$cid."'");
				$res = $db->loadResult();
				if($res != '')
				{
					$db->setQuery("DELETE FROM #__rsevents_subscription_tickets WHERE IdSubscription=".$res);
					$db->query();
					$db->setQuery("DELETE FROM #__rsevents_subscriptions WHERE IdUser='".$my->id."' AND IdEvent='".$cid."'");
					$db->query();
					$msg =  JText::_('RSE_SUBSCRIBER_UNSUBSCRIBE');					
					
				} else 	$msg =  JText::_('RSE_SUBSCRIBER_LOGIN_UNSUBSCRIBE');
			} else $msg =  JText::_('RSE_SUBSCRIBER_NO_REGISTRATION');
		} else $msg = JText::_('RSE_SUBSCRIBER_CANNOT_UNSUBSCRIBE');
		
		$mainframe->triggerEvent('rse_onAfterUnsubscribe',array(array('IdEvent'=>&$cid,'IdSubscription'=>&$res)));
		
		$this->setRedirect(html_entity_decode(JRoute::_('index.php?option=com_rsevents&view=events&layout=show&cid='.$cid.':'.JFilterOutput::stringURLSafe($row->EventName).$itemId)) , $msg);
	}
	
	//send post reminder emails 
	
	function postreminder()
	{
		global $mainframe;
		$db = &JFactory::getDBO();
		$user = &JFactory::getUser();
		$cid = JRequest::getVar('cid',0,'request');
		$cid = intval($cid);
		$model  =& $this->getModel( 'events' );
		$row = & JTable::getInstance('Rsevents_Events','Table');
		$row->load($cid);
		$rseventsConfig = $mainframe->getUserState('rseventsConfig');
		
		//get the itemid
		$Itemid = intval(JRequest::getVar('Itemid','','request'));
		$itemId = ($Itemid == '') ? '' : '&Itemid='.$Itemid;
		
		if($row->EventEndDate < time() && ($user->usertype == 'Super Administrator' || $row->IdUser == $user->id))
		{
			$db->setQuery("SELECT e.EventName ,e.EventDescription ,e.EventStartDate , e.EventEndDate , e.EventHost , l.LocationName, l.LocationCity , l.LocationCountry ,l.LocationZip , u.username ,s.Email FROM #__rsevents_events e LEFT JOIN #__rsevents_subscriptions s ON s.IdEvent = e.IdEvent LEFT JOIN #__users u ON u.id=s.IdUser LEFT JOIN #__rsevents_locations l ON e.IdLocation=l.IdLocation LEFT JOIN #__rsevents_categories c ON e.IdCategory=c.IdCategory WHERE s.IdEvent ='".$row->IdEvent."'");
				$reminderDetails = $db->loadObjectList();
		
				$eventLink = '<a target="_blank" href="'.html_entity_decode(JRoute::_(JURI::root().'index.php?option=com_rsevents&view=events&layout=show&cid='.$cid.':'.JFilterOutput::stringURLSafe($row->EventName).$itemId)).'">'.$row->EventName.'</a>';
				
				$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 =".$row->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);
				
				foreach($reminderDetails as $reminderDetailsObj)
				{
					$toChange = array('{EventName}','{EventDescription}','{EventStartDate}','{EventEndDate}','{EventHost}','{LocationName}','{LocationCity}','{CategoryName}','{username}','{EventLink}','{LocationCountry}','{LocationZip}');
					$with = array($reminderDetailsObj->EventName , $reminderDetailsObj->EventDescription , date($rseventsConfig['global.dateformat'],$reminderDetailsObj->EventStartDate) , date($rseventsConfig['global.dateformat'],$reminderDetailsObj->EventEndDate), $reminderDetailsObj->EventHost,$reminderDetailsObj->LocationName,$reminderDetailsObj->LocationCity,$categoryname, $reminderDetailsObj->username,$eventLink,$reminderDetailsObj->LocationCountry,$reminderDetailsObj->LocationZip);
					
					
					$from		= $rseventsConfig['emails.from'];
					$fromName	= $rseventsConfig['emails.from.name'];
					$to			= $reminderDetailsObj->Email;
					$subject	= $rseventsConfig['emails.reminder.subject'];
					$subject	= str_replace($toChange , $with , $subject);
					$body		= $rseventsConfig['emails.reminder.content'];
					$body		= str_replace($toChange , $with ,$body);
					$mode		= $rseventsConfig['emails.reminder.type'];
					$replyto	= $rseventsConfig['emails.reply'];
					$cc			= !empty($rseventsConfig['emails.cc']) ? $rseventsConfig['emails.cc'] : null;
					$bcc		= !empty($rseventsConfig['emails.bcc']) ? $rseventsConfig['emails.bcc'] : null;
					
					
					if($from != '') JUtility::sendMail($from , $fromName , $to , $subject , $body , $mode , $cc , $bcc , null , $replyto);
				}
				$msg = JText::_('RSE_POST_REMINDER_SENT');
		} else $msg = JText::_('RSE_ACCESS_DENIED');
		$mainframe->redirect(html_entity_decode(JRoute::_('index.php?option=com_rsevents&view=events&layout=show&cid='.$row->IdEvent.$idEvent.$itemId)) , $msg);
		
	}
	
	//send reminder email
	function reminder()
	{
		global $mainframe;
		$db = &JFactory::getDBO();
		$user = &JFactory::getUser();
		$cid = intval(JRequest::getVar('cid',0,'request'));
		$model  =& $this->getModel( 'events' );
		$row = & JTable::getInstance('Rsevents_Events','Table');
		$row->load($cid);
		$rseventsConfig = $mainframe->getUserState('rseventsConfig');
		
		//get the itemid
		$Itemid = intval(JRequest::getVar('Itemid','','request'));
		$itemId = ($Itemid == '') ? '' : '&Itemid='.$Itemid;
		
		if($user->usertype == 'Super Administrator' || $row->IdUser == $user->id)
		{
			$db->setQuery("SELECT e.EventName ,e.EventDescription ,e.EventStartDate , e.EventEndDate , e.EventHost , l.LocationName, l.LocationCity , l.LocationCountry ,l.LocationZip , u.username ,s.Email FROM #__rsevents_events e LEFT JOIN #__rsevents_subscriptions s ON s.IdEvent = e.IdEvent LEFT JOIN #__users u ON u.id=s.IdUser LEFT JOIN #__rsevents_locations l ON e.IdLocation=l.IdLocation WHERE s.IdEvent ='".$row->IdEvent."' AND s.SubscriptionState IN (0,1)");
				$reminderDetails = $db->loadObjectList();
		
				$eventLink = '<a target="_blank" href="'.html_entity_decode(JRoute::_(JURI::root().'index.php?option=com_rsevents&view=events&layout=show&cid='.$cid.':'.JFilterOutput::stringURLSafe($row->EventName).$itemId)).'">'.$row->EventName.'</a>';
				
				$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 =".$cid);
				$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);
				
				foreach($reminderDetails as $reminderDetailsObj)
				{
					$toChange = array('{EventName}','{EventDescription}','{EventStartDate}','{EventEndDate}','{EventHost}','{LocationName}','{LocationCity}','{CategoryName}','{username}','{EventLink}','{LocationCountry}','{LocationZip}');
					$with = array($reminderDetailsObj->EventName , $reminderDetailsObj->EventDescription , date($rseventsConfig['global.dateformat'],$reminderDetailsObj->EventStartDate) , date($rseventsConfig['global.dateformat'],$reminderDetailsObj->EventEndDate), $reminderDetailsObj->EventHost,$reminderDetailsObj->LocationName,$reminderDetailsObj->LocationCity,$categoryname, $reminderDetailsObj->username,$eventLink,$reminderDetailsObj->LocationCountry,$reminderDetailsObj->LocationZip);
					
					
					$from		= $rseventsConfig['emails.from'];
					$fromName	= $rseventsConfig['emails.from.name'];
					$to			= $reminderDetailsObj->Email;
					$subject	= $rseventsConfig['emails.rem.subject'];
					$subject	= str_replace($toChange , $with , $subject);
					$body		= $rseventsConfig['emails.rem.content'];
					$body		= str_replace($toChange , $with ,$body);
					$mode		= $rseventsConfig['emails.rem.type'];
					$replyto	= $rseventsConfig['emails.reply'];
					$cc			= !empty($rseventsConfig['emails.cc']) ? $rseventsConfig['emails.cc'] : null;
					$bcc		= !empty($rseventsConfig['emails.bcc']) ? $rseventsConfig['emails.bcc'] : null;
					
					if($from != '') JUtility::sendMail($from , $fromName , $to , $subject , $body , $mode , $cc , $bcc , null , $replyto);
				}
				$msg = JText::_('RSE_REMINDER_SENT');
		} else $msg = JText::_('RSE_ACCESS_DENIED');
		$mainframe->redirect(html_entity_decode(JRoute::_('index.php?option=com_rsevents&view=events&layout=show&cid='.$row->IdEvent.$idEvent.$itemId)) , $msg);
	}
	
	function savePhotos()
	{
		global $mainframe;
		$model = $this->getModel('extras');
		$post = JRequest::get('post');
		$privateUrl = JRequest::getVar('privateUrl','','request');
		if($privateUrl != '') $pUrl = '&privateUrl='.$privateUrl;
		else $pUrl='';
		//get the itemid
		$Itemid = intval(JRequest::getVar('Itemid','','request'));
		$itemId = ($Itemid == '') ? '' : '&Itemid='.$Itemid;
		
		$cid = JRequest::getVar('cid',0,'request');
		$cid = intval($cid);
		$row = & JTable::getInstance('Rsevents_Extras','Table');
		
		$row->IdEvent=$cid;
		if(strpos($post['photos'],'flickr')) $row->ExtraName='flickr';
		$row->ExtraValue=$post['photos'];
		
		$pattern = '/http:\/\/www.flickr.com\/photos\/(.*)\/sets\/([0-9]+)/';
		preg_match($pattern, $post['photos'], $matches);

		if(!empty($matches))
		{
			if($row->store())
			$msg=JText::_('RSE_PHOTOS_SAVED');
			else
			$msg=JText::_('RSE_PHOTOS_SAVED_ERROR');
			$mainframe->redirect(html_entity_decode(JRoute::_('index.php?option=com_rsevents&view=events&layout=album&cid='.$row->IdExtra.$pUrl.$itemId)) , $msg);
		} else $mainframe->redirect(html_entity_decode(JRoute::_('index.php?option=com_rsevents&view=events&layout=photos&cid='.$cid.$pUrl.$itemId)) , JText::_('RSE_EXTRA_FLICKR_INVALID_URL'));
	}

	
function createThumbs( $file, $pathToThumbs, $thumbWidth , $IdEvent , $uniqid)
{
	global $mainframe;
	$db =& JFactory::getDBO();
	
	//get the itemid
	$Itemid = intval(JRequest::getVar('Itemid','','request'));
	$itemId = ($Itemid == '') ? '' : '&Itemid='.$Itemid;
	
    $info = pathinfo($file['name']);
    $fname = $file['tmp_name'];
	
	$nameOfFile = $uniqid.'_'.$file['name'];
	// continue only if this is a JPEG image
	if($file['name'] != '')
    if ( strtolower($info['extension']) == 'jpg' )
    {
		// load image and get image size
		$img = imagecreatefromjpeg( $fname );
		$width = imagesx( $img );
		$height = imagesy( $img );

		// calculate thumbnail size
		$new_width = $thumbWidth;
		$new_height = floor( $height * ( $thumbWidth / $width ) );

		// create a new temporary image
		$tmp_img = imagecreatetruecolor( $new_width, $new_height );

		// copy and resize old image into new image
		imagecopyresized( $tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height );

		$thumb_name = str_replace('.jpg','_'.$thumbWidth.'.jpg',$nameOfFile);

		$db->setQuery("UPDATE #__rsevents_events SET EventIcon = '".$nameOfFile."' WHERE IdEvent = '".$IdEvent."'");
		$db->query();

		// save thumbnail into a file
		imagejpeg( $tmp_img, "{$pathToThumbs}{$thumb_name}" );
    } 
	else $mainframe->redirect(html_entity_decode(JRoute::_('index.php?option=com_rsevents&view=events&layout=addeditevent&cid='.$IdEvent.$itemId)),JText::_('RSE_ICON_ERROR')); 

}
	

function deleteicon()
{
	global $mainframe;
	$db =& JFactory::getDBO();
	$rseventsConfig = $mainframe->getUserState('rseventsConfig');

	//get the itemid
	$Itemid = intval(JRequest::getVar('Itemid','','request'));
	$itemId = ($Itemid == '') ? '' : '&Itemid='.$Itemid;

	$cid = intval(JRequest::getVar('cid','','request'));

	$db->setQuery("SELECT EventIcon FROM #__rsevents_events WHERE IdEvent = '".$cid."'");
	$iconName = $db->loadResult();
	
	$small_icon = str_replace('.jpg','_'.$rseventsConfig['event.icon.small'].'.jpg',$iconName);
	$big_icon = str_replace('.jpg','_'.$rseventsConfig['event.icon.big'].'.jpg',$iconName);
	
	@unlink(JPATH_SITE.DS.'components'.DS.'com_rsevents'.DS.'images'.DS.'thumbs'.DS.$small_icon);
	@unlink(JPATH_SITE.DS.'components'.DS.'com_rsevents'.DS.'images'.DS.'thumbs'.DS.$big_icon);
	
	$db->setQuery("UPDATE #__rsevents_events SET EventIcon = '' WHERE IdEvent = '".$cid."'");
	$db->query();
	
	$mainframe->redirect(html_entity_decode(JRoute::_('index.php?option=com_rsevents&view=events&layout=addeditevent&cid='.$cid.$itemId)) , JText::_('RSE_ICON_DELETED'));
}

	
}