<?php

	/**
	 * Klasse die den Verkauf von individualisierten Videos ermöglicht
	 */
	class wpsg_mod_videodownload extends wpsg_mod_basic
	{
		
		var $lizenz = 2;
		var $id = 602;
		
		var $version = "3.0.0";
		var $free = false;
		
		var $valid_ending = array('avi', 'mp4');
		var $arMessage = array(); // Meldungen für die Bestallansicht
		var $arError = array(); // Fehlermeldungen für die Bestellansicht)

		/**
		 * Costructor
		 */
		public function __construct()
		{
			
			parent::__construct();
			
			$this->name = __('VideoDownload', 'wpsg');
			$this->group = __('Produkte', 'wpsg');
			$this->desc = __('Ermöglicht den Verkauf von individuellen Videos.', 'wpsg');
						
		} // public function __construct()
		
		public function install()
		{ 
			
			// Grundeinstellungen
			if ($this->shop->get_option('wpsg_mod_videodownload_command') === false || $this->shop->get_option('wpsg_mod_videodownload_command') == '') $this->shop->update_option('wpsg_mod_videodownload_command', 'ffmpeg -i %in% -acodec copy %filter% %out%');
			if ($this->shop->get_option('wpsg_mod_videodownload_infocommand') === false || $this->shop->get_option('wpsg_mod_videodownload_infocommand') == '') $this->shop->update_option('wpsg_mod_videodownload_infocommand', 'ffmpeg -i %in%');
			if ($this->shop->get_option('wpsg_mod_videodownload_filename') === false || $this->shop->get_option('wpsg_mod_videodownload_filename') == '') $this->shop->update_option('wpsg_mod_videodownload_filename', '%filename%');
			if ($this->shop->get_option('wpsg_mod_videodownload_indiv_mode') === false) $this->shop->update_option('wpsg_mod_videodownload_indiv_mode', '0');
						
			require_once(WPSG_PATH_WP.'/wp-admin/includes/upgrade.php');
			
			/**
			 * Tabelle für die Anpassungen der Videos
			 */
			$sql = "CREATE TABLE ".WPSG_TBL_VIDEOINDIV." (
				id INT(11) NOT NULL AUTO_INCREMENT,				
				o_id INT(11) NOT NULL,
				file VARCHAR(255) NOT NULL,
				out_file VARCHAR(255) NOT NULL,
				scheduled DATETIME NOT NULL,
				cron_start DATETIME NOT NULL,
				done DATETIME NOT NULL,		
				counter INT(11) NOT NULL,		
			  	PRIMARY KEY  (id),
			  	KEY o_id (o_id)
			) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;";
			
		   	dbDelta($sql);
			
		} // public function install()
		
		public function delOrder(&$order_id) 
		{ 
			
			$this->db->Query("DELETE FROM `".WPSG_TBL_VIDEOINDIV."` WHERE `o_id` = '".wpsg_q($order_id)."'");
			
			$path = $this->getVideoIndivPath($order_id); wpsg_rrmdir($order_id);
			
		} // public function delOrder(&$order_id)
		
		function wpsg_enqueue_scripts()
		{

			if (is_admin())
			{
				
				wp_enqueue_script('wpsg_ajaxupload', $this->shop->getRessourceURL('js/ajaxupload.js'));
				
			}
							
		} // function wpsg_enqueue_scripts()
		
		public function settings_edit()
		{

			$this->shop->view['arTexte'] = @unserialize($this->shop->get_option('wpsg_mod_videodownload_text'));			
			$this->shop->view['arFonts'] = $this->getFonts();
			
			$this->shop->render(WPSG_PATH_VIEW.'/mods/mod_videodownload/settings_edit.phtml');
						
		} // public function settings_edit()
		
		public function settings_save() 
		{
						
			$this->shop->update_option('wpsg_mod_videodownload_text', @serialize($_REQUEST['text']));
			$this->shop->update_option('wpsg_mod_videodownload_command', $_REQUEST['wpsg_mod_videodownload_command']);
			$this->shop->update_option('wpsg_mod_videodownload_infocommand', $_REQUEST['wpsg_mod_videodownload_infocommand']);
			$this->shop->update_option('wpsg_mod_videodownload_filename', $_REQUEST['wpsg_mod_videodownload_filename']); 
			$this->shop->update_option('wpsg_mod_videodownload_indiv_mode', $_REQUEST['wpsg_mod_videodownload_indiv_mode']);
			$this->shop->update_option('wpsg_mod_videodownload_autosend', $_REQUEST['wpsg_mod_videodownload_autosend']);
			$this->shop->update_option('wpsg_mod_videodownload_accepted', $_REQUEST['wpsg_mod_videodownload_accepted']);
			$this->shop->update_option('wpsg_mod_videodownload_days', $_REQUEST['wpsg_mod_videodownload_days']);
			$this->shop->update_option('wpsg_mod_videodownload_downloads', $_REQUEST['wpsg_mod_videodownload_downloads']);
			$this->shop->update_option('wpsg_mod_videodownload_videopath', $_REQUEST['wpsg_mod_videodownload_videopath']);
			$this->shop->update_option('wpsg_mod_videodownload_videoindivpath', $_REQUEST['wpsg_mod_videodownload_videoindivpath']);
			$this->shop->update_option('wpsg_mod_videodownload_fontpath', $_REQUEST['wpsg_mod_videodownload_fontpath']);
			$this->shop->update_option('wpsg_mod_videodownload_cleanolddownloads', $_REQUEST['wpsg_mod_videodownload_cleanolddownloads']);
			$this->shop->update_option('wpsg_mod_videodownload_cleanraiddownloads', $_REQUEST['wpsg_mod_videodownload_cleanraiddownloads']);
			$this->shop->update_option('wpsg_mod_videodownload_format', $_REQUEST['wpsg_mod_videodownload_format']);
			 
		} // public function settings_save()
		
		public function order_view_sidebar(&$order_id)
		{
			
			$bVideoProdukt = false;
			$arFiles = array();
			
			foreach ($this->shop->view['basket']['produkte'] as $k => $v)
			{
				
				if (preg_match('/vp_\d+\/\d+\_\d+/', $v['id']))
				{
					
					$produkt_id = preg_replace('/(vp_)|(\/(.*))/', '', $v['id']);
					
				}
				else
				{
					
					$produkt_id = $v['id'];
						
				}				
				
				if ($this->isVideoProdukt($produkt_id))
				{
					
					$bVideoProdukt = true;
					$arFiles = wpsg_array_merge($arFiles, $this->getFiles($produkt_id));
					
				}
				
			}
			
			if ($bVideoProdukt && wpsg_isSizedArray($arFiles))
			{
				 
				$arFiles = array_unique($arFiles);
				
				foreach ($arFiles as $k => $v)
				{
					
					$db_indiv = $this->db->fetchRow("
						SELECT 
							* 
						FROM 
							`".WPSG_TBL_VIDEOINDIV."` 
						WHERE 
							`file` = '".wpsg_q($v)."' AND
							`o_id` = '".wpsg_q($order_id)."' 
					");
					
					if ($db_indiv['id'] > 0)
					{
						$arFiles[$k] = array($v, $db_indiv);
					}
					else
					{
						$arFiles[$k] = array($v, false);
					}
					
				}
				
				$this->shop->view['arFiles'] = $arFiles;				
				$this->shop->view['order_id'] = $order_id;
				
				$this->shop->render(WPSG_PATH_VIEW.'/mods/mod_videodownload/order_view_sidebar.phtml');				
				
			}
			
		} // public function order_view_sidebar(&$order_id) 
		
		public function produkt_edit_sidebar(&$produkt_data) 
		{

			if (isset($_REQUEST['wpsg_lang'])) return;
			
			if ($produkt_data['id'] > 0)
			{
				
				$this->shop->view['data'] = $produkt_data;
				$this->shop->view['filesList'] = $this->renderFilesList($produkt_data['id']);
				$this->shop->render(WPSG_PATH_VIEW.'/mods/mod_videodownload/produkt_edit_sidebar.phtml');
				
			}
			
		} // public function produkt_edit_sidebar(&$produkt_data)
		
		public function produkt_ajax() 
		{
			
			if ($_REQUEST['cmd'] == 'upload_file')
			{
				
				$this->fileUpload(wpsg_q($_REQUEST['edit_id']));
				
			}
			else if ($_REQUEST['cmd'] == 'videofiles_list')
			{
				
				die($this->renderFilesList($_REQUEST['edit_id']));
				
			}
			else if ($_REQUEST['cmd'] == 'delete_file')
			{
				
				unlink($this->getVideoPath($_REQUEST['edit_id']).'/'.rawurldecode($_REQUEST['file']));
				die("1");
				
			}
			else if ($_REQUEST['cmd'] == 'download_file')
			{
				
				header('Content-Disposition: attachment; filename="'.rawurldecode($_REQUEST['file']).'"');
				
				die(file_get_contents($this->getVideoPath($_REQUEST['edit_id']).'/'.rawurldecode($_REQUEST['file'])));
				
			}
			
		} // public function produkt_ajax()
		 
		public function order_ajax() { 
			
			if ($_REQUEST['cmd'] == 'schedule_file')
			{
				
				$db_indiv = $this->db->fetchRow("
					SELECT 
						`id`
					FROM
						`".WPSG_TBL_VIDEOINDIV."`
					WHERE
						`file` = '".wpsg_q($_REQUEST['file'])."' AND
						`o_id` = '".wpsg_q($_REQUEST['edit_id'])."' 
				");
				
				$new_name = $this->getNewName($_REQUEST['file'], $_REQUEST['edit_id']);
				
				if ($db_indiv['id'] > 0)
				{
					
					$this->db->UpdateQuery(WPSG_TBL_VIDEOINDIV, array(
						"scheduled" => "NOW()",
						"out_file" => wpsg_q($new_name)
					), "`id` = '".wpsg_q($_REQUEST['edit_id'])."'");
					
				}
				else
				{
					
					$this->db->ImportQuery(WPSG_TBL_VIDEOINDIV, array(
						"o_id" => wpsg_q($_REQUEST['edit_id']),
						"file" => wpsg_q($_REQUEST['file']),
						"scheduled" => "NOW()",
						"out_file" => wpsg_q($new_name)
					));
					
				}
				
				$this->arMessage[] = __('Datei wurde geplant.', 'wpsg');
				
				die($this->order_view_sidebar_renderList($_REQUEST['edit_id']));
				
			}
			else if ($_REQUEST['cmd'] == 'reindiv')
			{
				
				$this->indivOrder($_REQUEST['edit_id']);
				
				$this->arMessage[] = __('Bestellung wurde geplant.', 'wpsg');
				
				die($this->order_view_sidebar_renderList($_REQUEST['edit_id']));
				
			}
			else if ($_REQUEST['cmd'] == 'reset')
			{
				
				$this->db->UpdateQuery(WPSG_TBL_VIDEOINDIV, array("counter" => "0"), "`o_id` = '".wpsg_q($_REQUEST['edit_id'])."'");
				
				$this->arMessage[] = __('Downloadzähler wurden zurückgesetzt.', 'wpsg');
				
				die($this->order_view_sidebar_renderList($_REQUEST['edit_id']));
				
			}
			else if ($_REQUEST['cmd'] == 'send_files')
			{
				
				$this->sendFiles($_REQUEST['edit_id']);
				
				die($this->order_view_sidebar_renderList($_REQUEST['edit_id']));
				
			}
			else if ($_REQUEST['cmd'] == 'cancelschedule_file')
			{
				
				$this->db->Query("
					DELETE FROM
						`".WPSG_TBL_VIDEOINDIV."`
					WHERE
						`file` = '".wpsg_q($_REQUEST['file'])."' AND
						`o_id` = '".wpsg_q($_REQUEST['edit_id'])."' 
				");
				
				$this->arMessage[] = __('Planung wurde storniert.', 'wpsg');
				 
				die($this->order_view_sidebar_renderList($_REQUEST['edit_id']));
				
			}
			else if ($_REQUEST['cmd'] == 'download_indivfile')
			{
				
				header('Content-Disposition: attachment; filename="'.rawurldecode($_REQUEST['file']).'"');
								
				die(file_get_contents($this->getPDFIndivPath($_REQUEST['edit_id']).'/'.rawurldecode($_REQUEST['file'])));
				
			}
			
		} // public function order_ajax()

		public function setOrderStatus($order_id, $status_id, $inform) { 
			
			if ($status_id == 100 && $this->shop->get_option('wpsg_mod_videodownload_indiv_mode') == '1')
			{
				
				$this->indivOrder($order_id);
				
			}
			
		} // public function setOrderStatus($order_id, $status_id, $inform)
		
		public function basket_save_done(&$order_id, &$kunden_id, &$oBasket) 
		{ 
			
			if ($this->shop->get_option('wpsg_mod_videodownload_indiv_mode') == '2')
			{

				$this->indivOrder($order_id);
				
			}
			
		} // public function basket_save_done($order_id, $kunden_id)
		
 		public function addShipping(&$arShipping) 
		{ 
			
			$arShipping[$this->id] = array(
				'id' 			=> $this->id,
				'name' 			=> __('Versand per Mail', 'wpsg'),
				'preis' 		=> 0,
				'preis_calc' 	=> 0,			
				'mwst' 			=> 0,
				'mwst_value' 	=> 0
			);
			 
		} // public function addShipping(&$arShipping)
		
		public function checkShippingAvailable(&$arShipping, &$arBasket) 
		{ 
			
			if (!array_key_exists($this->id, $arShipping)) return;
			
			$bVideo = false;
			
			foreach ((array)$arBasket['produkte'] as $p)
			{
								
				if ($this->isVideoProdukt($p['id']))
				{
					
					$bVideo = true;
					
				} 
				
			} 
			
			if (!$bVideo)
			{
				
				unset($arShipping[$this->id]);
				
			}
			else
			{
				
				// Wenn Videoprodukt dann alle anderen entfernen
				foreach ($arShipping as $k => $v) { if ($k != $this->id && $k != 601) { unset($arShipping[$k]); } }
			  
			}
			
		} // public function checkShippingAvailable(&$arShipping, &$arBasket)
		
		public function calcShipping(&$arBasket, $shipping_key) { 
			
			$bVideoProdukt = false;
			
			foreach ($arBasket['produkte'] as $p)
			{
				
				if ($this->isVideoProdukt($p['id']))
				{
					
					$bVideoProdukt = true;
					
				} 
				
			} 
			
			if ($bVideoProdukt)
			{
				 
				// Es ist ein Videoprodukt drin, also alle anderen Versandarten entfernen
				foreach ($this->shop->arShipping as $k => $v) { if ($v['id'] != $this->id) unset($this->shop->arShipping[$k]); }
				 
			}
			else
			{

				// Kein Videoprodukt in der Bestellung also diese Versandart entfernen
				unset($this->shop->arShipping[$this->id]);
				
			}
			
		} // public function calcShipping(&$arBasket)
		
		public function admin_emailconf() 
		{ 
			
			echo wpsg_drawEMailConfig(
				'videodownloadfiles',
				__('Videodownload E-Mail', 'wpsg'),
				__('E-Mail mit Links zu den Videos die an den Kunden geht.', 'wpsg'));
								
			echo wpsg_drawEMailConfig(
				'videodownloadcronmail', 
				__('Videodownload Cron E-Mail', 'wpsg'), 
				__('E-Mail mit Informationen zu der Videoindividualisierung die vom Cron verschickt wird. (An Admin!).', 'wpsg'),
				true);
						
		} // public function admin_emailconf()
		
		public function admin_emailconf_save()
		{
			
			wpsg_saveEMailConfig("videodownloadfiles");
			wpsg_saveEMailConfig("videodownloadcronmail");
			 
		} // public function admin_emailconf_save()
		
		private function isVideoProdukt($produkt_id)
		{
			
			if (is_numeric($produkt_id))
			{
				
				$arVideos = $this->getFiles($produkt_id);
				
				if (sizeof($arVideos) > 0) return true;
				
			}
			
			return false;
			
		} // private function isVideoProdukt($produkt_id)
		
		public function order_view_sidebar_renderList($order_id) {
			
			$bVideoProdukt = false;
			$arFiles = array();
			
			$arBasket = $this->shop->cache->loadBasketArray($order_id);
 						
			foreach ($arBasket['produkte'] as $k => $v)
			{
				
				if ($this->isVideoProdukt($v['id']))
				{
					
					$bVideoProdukt = true;
					$arFiles = wpsg_array_merge($arFiles, $this->getFiles($v['id']));
					
				}
				
			}
			
			$arIndivIDs = array();
			
			if ($bVideoProdukt && wpsg_isSizedArray($arFiles))
			{
				
				$arFiles = array_unique($arFiles);
				
				foreach ($arFiles as $k => $v)
				{
					
					$db_indiv = $this->db->fetchRow("
						SELECT 
							* 
						FROM 
							`".WPSG_TBL_VIDEOINDIV."` 
						WHERE 
							`file` = '".wpsg_q($v)."' AND
							`o_id` = '".wpsg_q($order_id)."' 
					");
										
					if ($db_indiv['id'] > 0)
					{
						
						$arIndivIDs[] = $db_indiv['id'];
						
						$db_indiv['raid'] = false;
						
						if ($this->shop->get_option('wpsg_mod_videodownload_accepted') == '1' && $db_indiv['counter'] >= $this->shop->get_option('wpsg_mod_videodownload_downloads'))
						{
							$db_indiv['raid'] = true;
						}
						
						if ($this->shop->get_option('wpsg_mod_videodownload_accepted') == '2' && time() > (strtotime($db_indiv['done']) + ($this->shop->get_option('wpsg_mod_videodownload_days') * 86400)))
						{
							$db_indiv['raid'] = true;
						}
						
						$arFiles[$k] = array($v, $db_indiv);
						
					}
					else
					{
						$arFiles[$k] = array($v, false);
					}
					
				}
				
				// Jetzt noch eventuell individualisierte Videos laden die in den Produkten gelöscht wurden
				if (wpsg_isSizedArray($arIndivIDs))
				{
				
					$arDbIndivDeleted = $this->db->fetchAssoc("SELECT * FROM `".WPSG_TBL_VIDEOINDIV."` WHERE `id` NOT IN (".implode(",", $arIndivIDs).") AND `o_id` = '".wpsg_q($order_id)."'");
					
					foreach ($arDbIndivDeleted as $v)
					{
						
						$arFiles[] = array($v['file'], $v);
						
					}
					
				}
				
				$this->shop->view['messages'] = $this->arMessage;
				$this->shop->view['errors'] = $this->arError;
				$this->shop->view['arFiles'] = $arFiles;
				$this->shop->render(WPSG_PATH_VIEW.'/mods/mod_videodownload/order_view_sidebar_renderlist.phtml');				
				
			}
			
		} // public function order_view_sidebar_renderList($order_id)

		public function wp_loaded()
		{
			
			if ($_REQUEST['wpsg_action'] == 'wpsg_mod_videodownload_download')
			{

				if (!isset($_REQUEST['hash']) || trim($_REQUEST['hash']) == '') die(__('Kein Kontrollhash!', 'wpsg'));
				
				$hash = $this->makeHash($_REQUEST['indi']);
				
				if ($_REQUEST['hash'] != $hash) die(__('Ungültiger Kontrollhash!', 'wpsg'));
				
				$indiv_db = $this->db->fetchRow("SELECT * FROM `".WPSG_TBL_VIDEOINDIV."` WHERE `id` = '".wpsg_q($_REQUEST['indi'])."'");
				
				if ($this->shop->get_option('wpsg_mod_videodownload_accepted') == '1' && $indiv_db['counter'] >= $this->shop->get_option('wpsg_mod_videodownload_downloads'))
				{
					die(__('Sie haben die maximale Anzahl an Downloads überschritten.', 'wpsg'));
				}
				
				if ($this->shop->get_option('wpsg_mod_videodownload_accepted') == '2' && time() > (strtotime($indiv_db['done']) + ($this->shop->get_option('wpsg_mod_videodownload_days') * 86400)))
				{
					die(__('Der Download der Datei ist nicht mehr gültig.', 'wpsg'));
				}

				$this->db->UpdateQuery(WPSG_TBL_VIDEOINDIV, array("counter" => wpsg_q($indiv_db['counter'] + 1)), "`id` = '".wpsg_q($_REQUEST['indi'])."'");
				
				header('Content-Disposition: attachment; filename="'.rawurldecode($indiv_db['out_file']).'"');				
				die(file_get_contents($this->getVideoIndivPath($indiv_db['o_id']).'/'.rawurldecode($indiv_db['out_file'])));
				
			}
			else if ($_REQUEST['wpsg_action'] == 'wpsg_mod_videodownload_send')
			{
				
				if (!isset($_REQUEST['hash']) || trim($_REQUEST['hash']) == '') die(__('Kein Kontrollhash!', 'wpsg'));
				
				$order = $this->shop->cache->loadOrder($_REQUEST['order']);
				
				$hash = md5($order['cdate'].'wpsg'.$order['id']);
				
				if ($hash != $_REQUEST['hash']) die(__('Ungültiger Kontrollhash!', 'wpsg'));
				
				$this->sendFiles($_REQUEST['order']);
				
				die(__('Mail mit Downloadlinks versendet!', 'wpsg'));
				
			}
			
		}
		
		public function cron() { 
			
			$arVideosUnindiv = $this->db->fetchAssoc("
				SELECT
					*
				FROM
					`".WPSG_TBL_VIDEOINDIV."`
				WHERE
					`scheduled` != '0000-00-00 00:00:00' AND
					`done` = '0000-00-00 00:00:00' AND
					`cron_start` = '0000-00-00 00:00:00'
			");
			
			$arLog = array();
			
			foreach ($arVideosUnindiv as $v)
			{
				
				$order_path = $this->getVideoIndivPath($v['o_id']);
				
				$arBasket = $this->shop->cache->loadBasketArray($v['o_id']);
			
				// Die Datei suchen, da ich das Produkt nicht mitspeichere
				foreach ($arBasket['produkte'] as $p)
				{
					
					if ($this->isVideoProdukt($p['id']) && in_array($v['file'], $this->getFiles($p['id'])))
					{
						
						$this->db->UpdateQuery(WPSG_TBL_VIDEOINDIV, array('cron_start' => 'NOW()'), "`id` = '".wpsg_q($v['id'])."'");
						
						$this->indivVideo(
							$this->getVideoPath($p['id']).'/'.$v['file'],
							$this->getVideoIndivPath($v['o_id']).'/'.$v['out_file'],
							$v['o_id']
						);

						$this->db->UpdateQuery(WPSG_TBL_VIDEOINDIV, array(
							"done" => "NOW()"
						), "`id` = '".wpsg_q($v['id'])."'");

						$arLog[$v['o_id']] ++;
						
						break;
						
					}
					
				}
				
			}
						
			$arClean = array();
			
			// Alte Downloads säubern
			if ($this->shop->get_option('wpsg_mod_videodownload_accepted') == '1' && $this->shop->get_option('wpsg_mod_videodownload_cleanraiddownloads') == '1')
			{
				
				$arClean = wpsg_array_merge($arClean, $this->db->fetchAssoc("
					SELECT
						*
					FROM
						`".WPSG_TBL_VIDEOINDIV."`
					WHERE
						`counter` > '".wpsg_q($this->shop->get_option('wpsg_mod_videodownload_downloads'))."'
				"));
				
			}
			else if ($this->shop->get_option('wpsg_mod_videodownload_accepted') == '2' && $this->shop->get_option('wpsg_mod_videodownload_cleanraiddownloads') == '1')
			{

				$arClean = wpsg_array_merge($arClean, $this->db->fetchAssoc("
					SELECT
						*
					FROM
						`".WPSG_TBL_VIDEOINDIV."`
					WHERE
						DATE_ADD(`done`, INTERVAL ".$this->shop->get_option('wpsg_mod_videodownload_days')." DAY) < NOW()
				"));
				
			}
			
			if (intval($this->shop->get_option('wpsg_mod_videodownload_cleanolddownloads')) > 0)
			{
				
				$arClean = wpsg_array_merge($arClean, $this->db->fetchAssoc("
					SELECT
						*
					FROM
						`".WPSG_TBL_VIDEOINDIV."`
					WHERE
						DATE_ADD(`done`, INTERVAL ".$this->shop->get_option('wpsg_mod_videodownload_cleanolddownloads')." DAY) < NOW()
				"));
				
			}
			
			if (wpsg_isSizedArray($arClean))
			{
				
				foreach ($arClean as $c)
				{
					
					$path = $this->getVideoIndivPath($c['o_id']);
					
					unlink($path.'/'.$c['out_file']);
					
					$this->db->Query("DELETE FROM `".WPSG_TBL_VIDEOINDIV."` WHERE `id` = '".wpsg_q($c['id'])."'");
					
				}
				
			}
			
			if (wpsg_isSizedArray($arLog))
			{
				
				$this->shop->view['arOrder'] = $arLog;
				
				foreach ($this->shop->view['arOrder'] as $k => $v)
				{
					
					$order = $this->shop->cache->loadOrder($k);
					
					$this->shop->view['arOrder'][$k] = array($v, $order, md5($order['cdate'].'wpsg'.$order['id']));
					
					if ($this->shop->get_option('wpsg_mod_videodownload_autosend') == '1')
					{
						
						$this->sendFiles($order['id']);
						
					}
					
				}
				
				$mail_text = $this->shop->render(WPSG_PATH_VIEW.'/mods/mod_videodownload/cronmail.phtml', false);
				
				if ($this->shop->htmlMail === true)
				{
					
					$mail_html = $this->shop->render(WPSG_PATH_VIEW.'/mods/mod_videodownload/cronmail_html.phtml', false);
					
				}
				else
				{
					
					$mail_html = false;
					
				}
				
				$this->shop->sendMail($mail_text, $this->shop->get_option('wpsg_videodownloadcronmail_empfaenger'), 'videodownloadcronmail', false, false, $mail_html);
				
			}
			
		} // public function cron()
		
		/**
		 * Sendet die Mail mit den Downloadlinks an den Kunden
		 */
		public function sendFiles($order_id)
		{
			
			$this->shop->view['arVideos'] = $this->db->fetchAssoc("
				SELECT
					*
				FROM
					`".WPSG_TBL_VIDEOINDIV."`
				WHERE
					`o_id` = '".wpsg_q($order_id)."' AND
					`done` != '0000-00-00 00:00:00'
			");
			
			foreach ($this->shop->view['arVideos'] as $k => $v)
			{
				
				// Download noch gültig
				if ($this->shop->get_option('wpsg_mod_videodownload_accepted') == '1' && $v['counter'] >= $this->shop->get_option('wpsg_mod_videodownload_downloads'))
				{
					unset($this->shop->view['arVideos'][$k]);
				}
				else if ($this->shop->get_option('wpsg_mod_videodownload_accepted') == '2' && time() > (strtotime($v['done']) + ($this->shop->get_option('wpsg_mod_videodownload_days') * 86400)))
				{
					unset($this->shop->view['arVideos'][$k]);
				}
				else 
				{
					$this->shop->view['arVideos'][$k]['hash'] = $this->makeHash($v['id']);
				}
				
			}
			
			if (sizeof($this->shop->view['arVideos']) > 0)
			{
						
				$this->shop->view['order'] = $this->shop->cache->loadOrder($order_id);
				$this->shop->view['kunde'] = $this->shop->cache->loadKunden($this->shop->view['order']['k_id']);
							
				$mail_text = $this->shop->render(WPSG_PATH_VIEW.'/mods/mod_videodownload/videodownloadmail.phtml', false);
				
				if ($this->shop->htmlMail === true)
				{
					
					$mail_html = $this->shop->render(WPSG_PATH_VIEW.'/mods/mod_videodownload/videodownloadmail_html.phtml', false);
					
				}
				else
				{
					
					$mail_html = false;
					
				}
				
				$this->shop->sendMail($mail_text, $this->shop->view['kunde']['email'], 'videodownloadfiles', array(), false, false, $mail_html);
				
				$this->db->ImportQuery(WPSG_TBL_OL, array(
					"o_id" => wpsg_q($order_id),
					"cdate" => "NOW()",
					"title" => wpsg_translate(__('Videodownloads an:#1#', 'wpsg'), $this->shop->view['kunde']['email']),
					"mailtext" => wpsg_q($mail_text)
				));

				$this->arMessage[] = __('E-Mail erfolgreich gesendet.', 'wpsg');
				
			}
			else 
			{
				
				$this->arError[] = __('Keine gültigen Downloads.', 'wpsg');
				
			}			
			
		} // public function sendFiles($order_id)
		
		/**
		 * Individualisiert die Videos für eine Bestellung
		 */
		public function indivOrder($order_id)
		{
			
			$arBasket = $this->shop->cache->loadBasketArray($order_id);
				
			$bVideoProdukt = false;
			$arVideos = array();
				
			foreach ($arBasket['produkte'] as $p)
			{
				
				if ($this->isVideoProdukt($p['id']))
				{
					
					$bVideoProdukt = true;
					$arVideos = wpsg_array_merge($arVideos, $this->getFiles($p['id']));						
					
				}
				
			}
			
			if ($bVideoProdukt === true && wpsg_isSizedArray($arVideos))
			{
				
				foreach ($arVideos as $v)
				{
					
					$this->db->Query("DELETE FROM `".WPSG_TBL_VIDEOINDIV."` WHERE `file` = '".wpsg_q($v)."' AND `o_id` = '".wpsg_q($order_id)."'");
					
					$this->db->ImportQuery(WPSG_TBL_VIDEOINDIV, array(
						"o_id" => wpsg_q($order_id),
						"file" => wpsg_q($v),
						"scheduled" => wpsg_q("NOW()"),
						"done" => wpsg_q("0000-00-00 00:00:00"),
						"out_file" => wpsg_q($this->getNewName($v, $order_id))
					));
					
				}
				
			}
			
		} // public function indivOrder($order_id)
		
		/** 
		 * Baut den Kontroll Hash
		 */
		private function makeHash($indiv_id)
		{
			
			$indiv_db = $this->db->fetchRow("SELECT * FROM `".WPSG_TBL_VIDEOINDIV."` WHERE `id` = '".wpsg_q($indiv_id)."'");
			if ($indiv_db['id'] <= 0) return false;
			
			$order = $this->shop->cache->loadOrder($indiv_db['o_id']);
			if ($order['id'] <= 0) return false;
			
			$strHash = md5($order['cdate'].'wpsg'.$indiv_db['cdate'].$indiv_db['file']);
			
			return $strHash;
			
		} // private function makeHash($indiv_id)
		
		/**
		 * Individualisiert das Video $src_file und speichert es unter $trg_file, Absolute Pfade
		 */
		private function indivVideo($src_file, $trg_file, $order_id)
		{
 
			ini_set('memory_limit', '2000M');			
			set_time_limit(0);
			
			$layer_img = $this->getOverlayImage($src_file, $order_id);
			
			//C:\Users\Daschmi\Desktop\ffmpeg-20120804-git-f857465-win64-shared\ffmpeg-20120804-git-f857465-win64-shared\bin\ffmpeg.exe -y -i %in% -strict -2 %filter% -vcodec libx264 %out%
			//ffmpeg -i 19542479.mp4 -strict -2 -vf "movie=alphatest.png [watermark]; [in][watermark] overlay=1:1 [out]" outputvideo.mp4
			$arReplace = array(
				'/%in%/' => $src_file,
				'/%filter%/' => '-vf "movie='.$layer_img.' [watermark]; [in][watermark] overlay=0:0 [out]"',
				'/%out%/' => $trg_file
			);
			
			unlink($trg_file);
			
			$cmd = $this->shop->get_option('wpsg_mod_videodownload_command');
			$cmd = preg_replace(array_keys($arReplace), array_values($arReplace), $cmd);	
			 
			$out = $this->shop->exec($cmd);
			
			$zipfile = preg_replace('/\.[^\.]*$/', '', $trg_file).'.zip';
			
			if ($this->shop->get_option('wpsg_mod_videodownload_format') == '1')
			{
				
				// Zip Intern
				$zip = new ZipArchive();
				$zip->open($zipfile, ZipArchive::CREATE);				
				$zip->addFile($file, basename($trg_file));				
				$zip->close();				
				
				// Original löschen
				unlink($trg_file);
				
			}
			else if ($this->shop->get_option('wpsg_mod_videodownload_format') == '2')
			{
				
				// Zip Extern
				$out = $this->shop->exec('zip '.$zipfile.' '.$trg_file);
				
				// Original löschen
				unlink($trg_file);
				
			}
			 			
		} // private function indivVideo($src_file, $trg_file)
		
		/**
		 * Generiert das Bild, welches über das Video gelegt wird 
		 */
		private function getOverlayImage($video_file, $order_id)
		{
			
			$image_file = $this->shop->getTempName('.png');
			
			list($width, $height) = $this->getVideoSize($video_file);
			
			$img = ImageCreateTruecolor($width, $height);
			
			imagealphablending($img, false);
			imagesavealpha($img, true);
			
			// Bild mit transparentem Hintergrund füllen
			$trans_color = imagecolorallocatealpha($img, 255, 255, 255, 127);
  			imagefill($img, 0, 0, $trans_color);
  			
  			$arTexte = @unserialize($this->shop->get_option('wpsg_mod_videodownload_text'));
  			
  			if (wpsg_isSizedArray($arTexte))
  			{
  				
  				foreach ($arTexte as $t)
  				{
  					
  					if ($t['aktiv'] == 1)
  					{
  						
  						$x = $t['x'];
  						$y = $t['y'];
  						$font = rawurldecode($t['font']);
  						$angle = $t['angle'];
  						$fontsize = $t['fontsize'];
  						$color = $t['color'];
  						$text = $t['text'];
  						
  						$text = $this->shop->replaceUniversalPlatzhalter($text, $order_id);
  						
  						if (file_exists($this->shop->get_option('wpsg_mod_videodownload_fontpath').'/'.$font)) $font = $this->shop->get_option('wpsg_mod_videodownload_fontpath').'/'.$font;
  						else if (file_exists(WPSG_PATH_USERVIEW_OLD.'/mods/mod_videodownload/fonts/'.$font)) $font = WPSG_PATH_USERVIEW_OLD.'/mods/mod_videodownload/fonts/'.$font;
  						else if (file_exists(WPSG_PATH_VIEW.'/mods/mod_videodownload/fonts/'.$font)) $font = WPSG_PATH_VIEW.'/mods/mod_videodownload/fonts/'.$font;
  						else continue;
  						 
						list($r, $g, $b) = wpsg_getColor($color);
						
  						$color = imagecolorallocatealpha($img, $r, $g, $b, 127 - wpsg_tf($t['alpha'] * 127));
  
  						if ($angle == '') $angle = 0;

  						$posInfo = imagettfbbox($fontsize, 0, $font, $text);
						
  						$text_width = $posInfo[2] - $posInfo[0];
  						$text_height = $posInfo[1] - $posInfo[7];
  						
  						if ($t['align'] == '1')
  						{
  							
  							$neg_offset_x = cos($angle * M_PI / 180) * ($text_width / 2);
  							$pos_offset_y = sin($angle * M_PI / 180) * ($text_width / 2);
  							  							
  						}
  						else 
  						{
  							
  							$pos_offset_y = $text_height;
  							
  						}
  						
  						$x -= $neg_offset_x;
  						$y += $pos_offset_y;
  						
  						ImageTTFText($img, $fontsize, $angle, $x, $y, $color, $font, $text);
  						
  					}
  					
  				}
  				
  			}
  			
  			imagepng($img, $image_file);
			
			return $image_file;
			
		} // private function getOverlayImage($video_file)
		
		/**
		 * Scant das Font Verzeichnis
		 */
		private function getFonts()
		{
			
			$arFonts = array();
			
			$handle = @opendir($this->shop->get_option('wpsg_mod_videodownload_fontpath').'/');
			if ($handle) { while ($file = readdir($handle))
			{
				if (is_file($this->shop->get_option('wpsg_mod_videodownload_fontpath').'/'.$file) && preg_match('/(.*).ttf$/i', $file))
				{
					
					$arFonts[] = $file;
					
				}
			} }
			@closedir($handle);
			
			$handle = @opendir(WPSG_PATH_USERVIEW_OLD.'/mods/mod_videodownload/fonts/');
			if ($handle) { while ($file = readdir($handle))
			{
				if (is_file(WPSG_PATH_USERVIEW_OLD.'/mods/mod_videodownload/fonts/'.$file) && preg_match('/(.*).ttf$/i', $file) && in_array($file, $arFonts))
				{
					
					$arFonts[] = $file;
					
				}
			} }
			@closedir($handle);
			
			$handle = @opendir(WPSG_PATH_VIEW.'/mods/mod_videodownload/fonts/');			
			if ($handle) { while ($file = readdir($handle))
			{
				if (is_file(WPSG_PATH_VIEW.'/mods/mod_videodownload/fonts/'.$file) && preg_match('/(.*).ttf$/i', $file) && !in_array($file, $arFonts))
				{
					
					$arFonts[] = $file;
					
				}
			} }
			@closedir($handle);
			
			return $arFonts;
			
		} // private function getFonts()
		
		/**
		 * Gibt die Auflösung eines Videofiles zurück
		 */
		private function getVideoSize($video_file)
		{
			
			$out = array();
			$cmd = $this->shop->get_option('wpsg_mod_videodownload_infocommand');
			
			$arReplace = array(
				'/%in%/' => $video_file
			);
			
			$cmd = preg_replace(array_keys($arReplace), array_values($arReplace), $cmd);
			
			$out = $this->shop->exec($cmd);
			
			preg_match('/\040\d+x\d+\040/', $out, $treffer);
			
			return explode('x', $treffer[0]);
			
		} // public function getVideoSize($video_file)
		
		/**
		 * Zeichnet die Dateiliste der Videos
		 */
		private function renderFilesList($produkt_id)
		{
			
			$this->shop->view['files'] = $this->getFiles($produkt_id);			
			return $this->shop->render(WPSG_PATH_VIEW.'/mods/mod_videodownload/filelist.phtml', false);
			
		} // private function renderFilesList($produkt_id)
		
		/**
		 * Gibt die Videodateien eines Produktes zurück
		 */
		private function getFiles($produkt_id)
		{

			$path = $this->getVideoPath($produkt_id);
			
			if (!file_exists($path)) return;

			$arrFiles = scandir($path);
			$arVideoFiles = array();
			
			foreach ($arrFiles as $file)
			{
				
				if (is_file($path.$file) && in_array(strtolower(preg_replace('/(.*)\./', '', $file)), $this->valid_ending))
				{
					
					$arVideoFiles[] = $file;
					
				}
				
			}
			
			return $arVideoFiles;
			
		} // private function getFiles($produkt_id)
		
		/** 
		 * lädt eine Datei in das entspr. upload Verzeichnis
		 */
		private function fileUpload($produkt_id)
		{
			
			if (file_exists($_FILES['videofiles']['tmp_name']))
			{
				
				$ending = strtolower(preg_replace('/(.*)\./', '', $_FILES['videofiles']['name']));
				
				if (!in_array($ending, $this->valid_ending))
				{

					die(__('Ungültige Dateiendung.', 'wpsg'));
					
				}
				else
				{
				
					$uploaddir = $this->getVideoPath($produkt_id);				
					if (!file_exists($uploaddir)) mkdir($uploaddir, 0777, true);
				
					$uploadfile = $uploaddir.basename($_FILES['videofiles']['name']);					
					move_uploaded_file($_FILES['videofiles']['tmp_name'], $uploadfile);
				
					die('1');
					
				}
				
			}
			else 
			{
			
				die(__('Fehler beim Upload.', 'wpsg'));
				
			}
			
		} // private function fileUpload($produkt_id)
				
		/**
		 * Gibt den Individualisierten Dateinamen für ein File und Bestellung zurück
		 */
		public function getNewName($oldFilename, $order_id)
		{
			
			$arReplace = array(
				'/%filename%/' => $oldFilename,
				'/%filename_clear%/' => preg_replace('/\.(.*)$/', '', $oldFilename)
			);
			
			$newFilename = $this->shop->replaceUniversalPlatzhalter($this->shop->get_option('wpsg_mod_videodownload_filename'), $order_id, false, false, false, $arReplace);
												
			return $newFilename;
			
		} // public function getNewName($oldFilename, $order_id)
		
		/**
		 * Gibt den Pfad zu dem Ordner zurück in dem die Videos abgelegt werden
		 */
		public function getVideoPath($produkt_id)
		{

			if ($this->shop->get_option('wpsg_mod_videodownload_videopath') !== false && trim($this->shop->get_option('wpsg_mod_videodownload_videopath')) != '')
			{

				$path = $this->shop->get_option('wpsg_mod_videodownload_videopath').'/'.$produkt_id.'/';
				
			}
			else
			{
			
				if ($this->shop->isMultiBlog())
				{
					
					$path = WP_CONTENT_DIR.'/'.WPSG_MB_UPLOADS.'/wpsg/wpsg_videoprodukte/'.$produkt_id.'/'; 
						
				}
				else
				{
						 
					$path = WP_CONTENT_DIR.'/uploads/wpsg_videoprodukte/'.$produkt_id.'/';
										
				}
				
			}
			
			if (!file_exists($path))
			{
				
				mkdir($path, 0777, true);
				
				$handle = fopen($path.'.htaccess', "w+");
				$content = "Deny from all";			
				fwrite($handle, $content, strlen($content));
				fclose($handle);
				
			}
					
			return $path;
			
		} // public function getVideoPath($produkt_id)
		
		/**
		 * Gibt den Pfad zurück wo die Individualisierten Videos einer Bestellung liegen
		 */
		public function getVideoIndivPath($order_id)
		{

			if ($this->shop->get_option('wpsg_mod_videodownload_videoindivpath') !== false && trim($this->shop->get_option('wpsg_mod_videodownload_videoindivpath')) != '')
			{

				$path = $this->shop->get_option('wpsg_mod_videodownload_videoindivpath').'/'.$order_id.'/';
				
			}
			else
			{
				
				if ($this->shop->isMultiBlog())
				{
					
					$path = WP_CONTENT_DIR.'/'.WPSG_MB_UPLOADS.'/wpsg/wpsg_videoprodukte_order/'.$order_id.'/'; 
										
				}
				else
				{
						 
					$path = WP_CONTENT_DIR.'/uploads/wpsg_videoprodukte_order/'.$order_id.'/';
									
				}
				
			}
			
			if (!file_exists($path))
			{
				
				mkdir($path, 0777, true);
				
				$handle = fopen($path.'.htaccess', "w+");
				$content = "Deny from all";			
				fwrite($handle, $content, strlen($content));
				fclose($handle);
				
			}
				
			return $path;
			
		} // public function getVideoIndivPath($order_id)
		
	} // class wpsg_mod_videodownload extends wpsg_mmod_basic

?>