<?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();

		// Register Extra tasks
		$this->registerTask('apply' ,  'save');
		$this->registerTask( 'unpublish' , 'publish');

	}
	
	
	/**
	 * save a record (and redirect to main page)
	 * @return void
	 */
	function save()
	{
		global $mainframe;
		
		//get variables
		$db= JFactory::getDBO();
		$model = $this->getModel('events');
		$post=JRequest::get('post',JREQUEST_ALLOWHTML);
		$files=JRequest::get('files');
		$icon  = $files['icon'];
		$files = $files['files'];
		$cid = JRequest::getVar('cid');
		$rseventsConfig = $mainframe->getUserState('rseventsConfig');
		$pathToThumbs = JPATH_SITE.DS.'components'.DS.'com_rsevents'.DS.'images'.DS.'thumbs'.DS;
		
		//verify if the event has the default ticket
		$db->setQuery("SELECT COUNT(*) FROM #__rsevents_tickets WHERE IdEvent='".$cid."'");
		$res = $db->loadResult();
		
		
		$row= & JTable::getInstance('Rsevents_Events','Table');
		$row->load($cid);
		if(!$row->bind($post)) 
		{
			return JError::raiseWarning(500, $row->getError());
		}
		
		if($row->EventURL == 'http://') $row->EventURL = '';
		
		//preparing the date into the 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->EventEndDate < $row->EventStartDate) 
			if(empty($row->IdEvent))
				$mainframe->redirect('index.php?option=com_rsevents&task=editevent',JText::_('RSE_INVALID_DATE'));
			else
				$mainframe->redirect('index.php?option=com_rsevents&task=editevent&cid='.$row->IdEvent,JText::_('RSE_INVALID_DATE'));
		
		//creating the alias
		$alias = JFilterOutput:: stringURLSafe($row->EventName);
		if(empty($row->EventAlias)) $row->EventAlias = $alias;
		
		//creating the private Url
		if(empty($row->EventPrivateUrl))
		if($row->EventType == '0')
		{
			$row->EventPrivateUrl = uniqid('',FALSE);
		}
		
		if(empty($row->IdEvent)) $row->EventCreation = time();
		
		//saving the data
		if ($row->store()) {
		
		//insert the default ticket when enable registration is on
		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();
		}
		
		$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 = ".$catid);
			$db->query();
		}
		
		
		//code for inserting files
		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);
		}	
		
		$allowedExtensions = str_replace(array("\r"," "),"",$rseventsConfig['event.files']);
		$allowedExtensions = explode("\n",$allowedExtensions);
		
		
		$target= JPATH_SITE.DS.'components'.DS.'com_rsevents'.DS.'files'.DS;
		
		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 ('".$row->IdEvent."','".basename( $files['name'][$i])."','".$fileLocation."','111111') "); 
							$db->query();
						}
					} else $mainframe->redirect('index.php?option=com_rsevents&task=editevent&cid='.$row->IdEvent , JText::_('RSE_EVENT_INVALID_FILE'));
			}
		}
		
		//upload the event icon
		
		
		
		$msg = JText::_('RSE_EVENT_SAVE' );
		
		} else {
			$msg = JText::_('RSE_EVENT_SAVE_ERROR' );
		}
		
		switch(JRequest::getCmd('task'))
		{
			case 'apply' :
					$link = 'index.php?option=com_rsevents&task=editevent&cid='.$row->IdEvent;

			break;
			
			case 'save' :
					$link = 'index.php?option=com_rsevents&task=listevents';

			break;
		}
		$this->setRedirect($link, $msg);
	}

	//generate a new Private Url
	
	function generate()
	{
		$cid = 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&task=editevent&cid='.$cid);
	}
	
	function saveYoutube()
	{
		global $mainframe;
		$model = $this->getModel('extras');
		$post = JRequest::get('post');
		$url = $post['youtubeURL'];
		$idEvent = JRequest::getVar('IdEvent',0,'request');
		$cid = JRequest::getVar('cid',0,'request');
		$row = & JTable::getInstance('Rsevents_Extras','Table');
		
		$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('index.php?option=com_rsevents&task=editevent&cid='.$idEvent , $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);
		
		//loading the table
		$row = & JTable::getInstance('Rsevents_Extras','Table');
		$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('index.php?option=com_rsevents&task=editevent&cid='.$idEvent , $msg);
		} else $mainframe->redirect('index.php?option=com_rsevents&task=editevent&cid='.$idEvent , JText::_('RSE_EXTRA_FLICKR_INVALID_URL'));
	}
	
	function saveFlash()
	{
		global $mainframe;
		$model = $this->getModel('extras');
		$post = JRequest::get('post',JREQUEST_ALLOWRAW);
		$url = stripslashes($post['flashCode']);
		$idEvent = JRequest::getVar('IdEvent',0,'request');
		$cid = JRequest::getVar('cid',0,'request');
		$row = & JTable::getInstance('Rsevents_Extras','Table');
		
		$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('index.php?option=com_rsevents&task=editevent&cid='.$idEvent , $msg);
	}
	
	function saveMeebo()
	{
		global $mainframe;
		$model = $this->getModel('extras');
		$post = JRequest::get('post',JREQUEST_ALLOWRAW);
		$url = stripslashes($post['meeboCode']);
		$idEvent = JRequest::getVar('IdEvent',0,'request');
		$cid = JRequest::getVar('cid',0,'request');
		$row = & JTable::getInstance('Rsevents_Extras','Table');
		
		$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('index.php?option=com_rsevents&task=editevent&cid='.$idEvent , $msg);
	}
	
	function saveMp3()
	{
		global $mainframe;
		$model = $this->getModel('extras');
		$post = JRequest::get('post');
		$url = stripslashes(str_replace(array("\r","\n","\t"),"",$_POST['mp3Code']));
		$idEvent = JRequest::getVar('IdEvent',0,'request');
		$cid = JRequest::getVar('cid',0,'request');
		$row = & JTable::getInstance('Rsevents_Extras','Table');
		$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_INVALID_CODE');
			$mainframe->redirect('index.php?option=com_rsevents&task=editevent&cid='.$idEvent , $msg);
		}
		$row->ExtraValue=$matches[1];
		
		if($row->store())
		$msg=JText::_('RSE_EXTRA_MP3_SAVE');
		else
		$msg=JText::_('RSE_EXTRA_MP3_SAVE_ERROR');
		$mainframe->redirect('index.php?option=com_rsevents&task=editevent&cid='.$idEvent , $msg);
	}
	
	function deleteExtra()
	{
		global $mainframe;
		$model = $this->getModel('extras');
		$cid= JRequest::getVar('cid',0,'request');
		$idEvent = JRequest::getVar('IdEvent',0);
		$row = & JTable::getInstance('Rsevents_Extras','Table');
		if($row->delete($cid))
		$msg=JText::_('RSE_EXTRA_DELETE');
		else
		$msg=JText::_('RSE_EXTRA_DELETE_ERROR');
		$mainframe->redirect('index.php?option=com_rsevents&task=editevent&cid='.$idEvent , $msg);
 	}

	function remove()
	{
		$db= JFactory::getDBO();
		$model = $this->getModel('events');
		$cids=JRequest::getVar('cid',array(0),'post','array');
		$row =& JTable::getInstance('Rsevents_Events','Table');
		
		if(!empty($cids))
		{
		foreach($cids as $cid) 
		{
		
		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("DELETE FROM #__rsevents_events_cat 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();
			$row->reorder();
			$msg = JText::_( 'RSE_EVENT_DELETE' );
		}
		}
		} else
		{
			$msg = JText::_('RSE_EVENT_SELECT' );
		}
		$this->setRedirect( 'index.php?option=com_rsevents&task=listevents', $msg );
	}

	/**
	 * cancel editing a record
	 * @return void
	 */
	function cancel()
	{
		$msg = JText::_('RSE_CANCEL_OPERATION' );
		$this->setRedirect( 'index.php?option=com_rsevents&task=listevents', $msg );
	}
	
	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( 'index.php?option=com_rsevents&task=listevents' );
	}
 
     function copy()
     {
		$db = & JFactory::getDBO();
         global $mainframe;

 
         // Get some variables from the request
        $cid        = JRequest::getVar( 'cid', array(), 'post', 'array' );
		$db->setQuery("SELECT IdEvent FROM #__rsevents_events WHERE IdEvent IN ('".implode("','",$cid)."')");
		$arrayEvents       = $db->loadObjectList();

		 if(!empty($arrayEvents))
		 foreach($arrayEvents as $obj)
		 {
	        $model  =& $this->getModel( 'Events' );
	        $model->copy($obj->IdEvent);
		 }
		 else 
		 {
			$msg=JText::_('RSE_EVENT_COPY_ERROR');
			$this->setRedirect( 'index.php?option=com_rsevents&task=listevents', $msg );
		 }
			$msg=JText::_('RSE_EVENT_COPY');
			$this->setRedirect( 'index.php?option=com_rsevents&task=listevents', $msg );
		 
    }	
	
	//archive the events
	
	function archive()
	{
		global $mainframe;
		$db =& JFactory::getDBO();
		$cid = JRequest::getVar('cid',array(),'request','array');
		
		$cids = implode(',', $cid );
		
		$db->setQuery("UPDATE #__rsevents_events SET published = '-1' WHERE IdEvent IN (".$cids.") ");
		$db->query();
		
		$db->setQuery("UPDATE #__rsevents_events SET EventArchive = '0' WHERE IdEvent IN (".$cids.") ");
		$db->query();
		$total = count($cid);
		
		$msg = $total.' '.JText::_('RSE_EVENT_ARCHIVED');
		
		$mainframe->redirect('index.php?option=com_rsevents&task=listevents',$msg );
	}
	
function createThumbs( $file, $pathToThumbs, $thumbWidth , $IdEvent , $uniqid)
{
	global $mainframe;
	$db =& JFactory::getDBO();
	
    $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('index.php?option=com_rsevents&task=editevent&cid='.$IdEvent,JText::_('RSE_ICON_ERROR')); 

}

function deleteicon()
{
	global $mainframe;
	$db =& JFactory::getDBO();
	$rseventsConfig = $mainframe->getUserState('rseventsConfig');
	
	$cid = 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('index.php?option=com_rsevents&task=editevent&cid='.$cid , JText::_('RSE_ICON_DELETED'));
}
	
	
}