<?php

	/**
	 * Klasse für die individualisierung von PDF Dokumenten
	 */
	class wpsg_mod_downloadplus extends wpsg_mod_basic
	{
		
		var $lizenz = 1;
		var $id = 101;
		var $version = "9.9.9";
		var $hilfeURL = 'http://wpshopgermany.de/?p=1426';

		var $valid_ending = array('pdf');
		var $barCodeFonts = array('EAN13', 'Code128', 'UPC_A');
		
		/**
		 * Costructor
		 */
		public function __construct()
		{
			
			parent::__construct();
			
			$this->name = __('DownloadPlus', 'wpsg');
			$this->group = __('Produkte', 'wpsg');
			$this->desc = __('Ermöglicht den Verkauf von angepassten PDF Dokumenten.', 'wpsg');
						
		} // public function __construct()
		
		public function install()
		{
			
			require_once(WPSG_PATH_WP.'/wp-admin/includes/upgrade.php');
			
			/**
			 * Tabelle für die Anpassungen der PDF Dokumente
			 */
			$sql = "CREATE TABLE ".WPSG_TBL_PDFINDIV." (
				id INT(11) NOT NULL AUTO_INCREMENT,				
				o_id INT(11) NOT NULL,
				p_key VARCHAR(255) NOT NULL,
				product_index INT(11) NOT NULL,
				file VARCHAR(255) NOT NULL,
				out_file VARCHAR(255) NOT NULL,
				downloadnr VARCHAR(500) NOT NULL,
				scheduled DATETIME NOT NULL,
				done DATETIME NOT NULL,		
				counter INT(11) NOT NULL,		
				fielddata TEXT NOT NULL,
			  	PRIMARY KEY  (id)
			) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;";
			
		   	dbDelta($sql);
		   	
		   	// Abwärtskombatibilität mit DLPlus
			if ($this->shop->isMultiBlog())
			{
				
				$path = WP_CONTENT_DIR.'/'.WPSG_MB_UPLOADS.'/wpsg/wpsg_dlplus/'; 
				$new_path = WP_CONTENT_DIR.'/'.WPSG_MB_UPLOADS.'/wpsg/wpsg_pdfprodukte/'.$produkt_id.'/';
				
			}
			else
			{
					 
				$path = WP_CONTENT_DIR.'/uploads/wpsg_dlplus/';
				$new_path = WP_CONTENT_DIR.'/uploads/wpsg_pdfprodukte/'.$produkt_id.'/';					
				
			}
			
			if (file_exists($path))
			{
				
				rename($path, $new_path);
				
			}
		   	
			// Standardwerte
			$this->shop->checkDefault('wpsg_mod_downloadplus_filename', '%order_id%-%filename%');
			$this->shop->checkDefault('wpsg_mod_downloadplus_shipping', '1');
			$this->shop->checkDefault('wpsg_mod_downloadplus_memorylimit', '1');	
			$this->shop->checkDefault('wpsg_mod_downloadplus_timelimit', '1');
			$this->shop->checkDefault('wpsg_mod_downloadplus_numberformat', '%download_nr%');
			$this->shop->checkDefault('wpsg_mod_downloadplus_startnumber', '1');
			
		} // public function install()
		
		public function delOrder(&$order_id) 
		{ 
			
			$this->db->Query("DELETE FROM `".WPSG_TBL_PDFINDIV."` WHERE `o_id` = '".wpsg_q($order_id)."'");
			
			// Individualisierte Dateien löschen
			$path = $this->getPDFIndivPath($order_id); wpsg_rrmdir($path);
			
		} // public function delOrder(&$order_id)
		
		public function wpsg_enqueue_scripts()
		{
			
			if (is_admin())
			{
			
				wp_enqueue_script('wpsg_ajaxupload', $this->shop->getRessourceURL('js/ajaxupload.js'));
				
			}
			
		} // function wpsg_enqueue_scripts()
		
		public function admin_emailconf() 
		{ 
			
			echo wpsg_drawEMailConfig(
				'pdfdownloadfiles',
				__('PDFdownload E-Mail', 'wpsg'),
				__('E-Mail mit Links zu den PDFs die an den Kunden geht.', 'wpsg')); 
			
			echo wpsg_drawEMailConfig(
				'pdfdownloadcronmail',
				__('PDFdownload Cron E-Mail', 'wpsg'),
				__('E-Mail mit Informationen zu der PDF Individualisierung die vom Cron verschickt wird. (An Admin!).', 'wpsg'),
				true);
						
		} // public function admin_emailconf()
		
		public function admin_emailconf_save()
		{
			
			wpsg_saveEMailConfig("pdfdownloadfiles");
			wpsg_saveEMailConfig("pdfdownloadcronmail");
			 
		} // public function admin_emailconf_save()
		
		public function settings_save()
		{
			
			$this->shop->update_option('wpsg_mod_downloadplus_text', $_REQUEST['text']);
			$this->shop->update_option('wpsg_mod_downloadplus_filename', $_REQUEST['wpsg_mod_downloadplus_filename']);
			$this->shop->update_option('wpsg_mod_downloadplus_indiv_mode', $_REQUEST['wpsg_mod_downloadplus_indiv_mode']);
			$this->shop->update_option('wpsg_mod_downloadplus_autosend', $_REQUEST['wpsg_mod_downloadplus_autosend']);
			$this->shop->update_option('wpsg_mod_downloadplus_shipping', $_REQUEST['wpsg_mod_downloadplus_shipping']);		
			$this->shop->update_option('wpsg_mod_downloadplus_einsplusx', $_REQUEST['wpsg_mod_downloadplus_einsplusx']);	
			$this->shop->update_option('wpsg_mod_downloadplus_accepted', $_REQUEST['wpsg_mod_downloadplus_accepted']);
			$this->shop->update_option('wpsg_mod_downloadplus_days', $_REQUEST['wpsg_mod_downloadplus_days']);
			$this->shop->update_option('wpsg_mod_downloadplus_downloads', $_REQUEST['wpsg_mod_downloadplus_downloads']);
			$this->shop->update_option('wpsg_mod_downloadplus_cleanraiddownloads', $_REQUEST['wpsg_mod_downloadplus_cleanraiddownloads']);
			$this->shop->update_option('wpsg_mod_downloadplus_cleanolddownloads', $_REQUEST['wpsg_mod_downloadplus_cleanolddownloads']);			
			$this->shop->update_option('wpsg_mod_downloadplus_pdfpath', $_REQUEST['wpsg_mod_downloadplus_pdfpath']);
			$this->shop->update_option('wpsg_mod_downloadplus_pdfindivpath', $_REQUEST['wpsg_mod_downloadplus_pdfindivpath']);
			$this->shop->update_option('wpsg_mod_downloadplus_range', $_REQUEST['wpsg_mod_downloadplus_range']);
			$this->shop->update_option('wpsg_mod_downloadplus_range_von', $_REQUEST['wpsg_mod_downloadplus_range_von']);
			$this->shop->update_option('wpsg_mod_downloadplus_range_bis', $_REQUEST['wpsg_mod_downloadplus_range_bis']);
			$this->shop->update_option('wpsg_mod_downloadplus_masterpass', $_REQUEST['wpsg_mod_downloadplus_masterpass']);
			$this->shop->update_option('wpsg_mod_downloadplus_openpass', $_REQUEST['wpsg_mod_downloadplus_openpass']);
			$this->shop->update_option('wpsg_mod_downloadplus_securitysave', $_REQUEST['wpsg_mod_downloadplus_securitysave']);
			$this->shop->update_option('wpsg_mod_downloadplus_securityprint', $_REQUEST['wpsg_mod_downloadplus_securityprint']);
			$this->shop->update_option('wpsg_mod_downloadplus_securitymod', $_REQUEST['wpsg_mod_downloadplus_securitymod']);
			$this->shop->update_option('wpsg_mod_downloadplus_securitynote', $_REQUEST['wpsg_mod_downloadplus_securitynote']);
			$this->shop->update_option('wpsg_mod_downloadplus_format', $_REQUEST['wpsg_mod_downloadplus_format']);			
			$this->shop->update_option('wpsg_mod_downloadplus_memorylimit', $_REQUEST['wpsg_mod_downloadplus_memorylimit']);
			$this->shop->update_option('wpsg_mod_downloadplus_timelimit', $_REQUEST['wpsg_mod_downloadplus_timelimit']);
			$this->shop->update_option('wpsg_mod_downloadplus_numberformat', $_REQUEST['wpsg_mod_downloadplus_numberformat']);
			$this->shop->update_option('wpsg_mod_downloadplus_startnumber', $_REQUEST['wpsg_mod_downloadplus_startnumber']);
			$this->shop->update_option('wpsg_mod_downloadplus_attachement', $_REQUEST['wpsg_mod_downloadplus_attachement']);
			
		} // public function settings_save()
		
		public function settings_edit()
		{
			
			$font_path = WPSG_PATH_LIB.'fpdf/font/';
			
			$arFontFiles = scandir($font_path);
			
			foreach ($arFontFiles as $k => $v)
			{
								
				$file = $font_path.$v;
				
				if (is_file($file) && file_exists($file) && preg_match('/(.*)\.php$/i', $v))
				{
					
					$this->shop->view['wpsg_mod_downloadplus']['arFonts'][$v] = ucfirst(preg_replace('/\.php$/i', '', $v)); 
					
				}
				
				
			}
			
			$this->shop->view['wpsg_mod_downloadplus']['barCodeFonts'] = $this->barCodeFonts;
			
			// Barcode
			$this->shop->view['wpsg_mod_downloadplus']['arFonts']['EAN13'] = 'EAN 13';
			$this->shop->view['wpsg_mod_downloadplus']['arFonts']['Code128'] = 'Code 128';
			$this->shop->view['wpsg_mod_downloadplus']['arFonts']['UPC_A'] = 'UPC-A';
			 
			$this->shop->view['arTexte'] = $this->shop->get_option('wpsg_mod_downloadplus_text');
			
			$this->shop->render(WPSG_PATH_VIEW.'/mods/mod_downloadplus/settings_edit.phtml');
						
		} // public function settings_edit()
		
		public function produkt_ajax() 
		{
			
			if ($_REQUEST['cmd'] == 'upload_file')
			{
				
				$this->fileUpload(wpsg_q($_REQUEST['edit_id']));
				
			}
			else if ($_REQUEST['cmd'] == 'pdffiles_list')
			{
				
				die($this->renderFilesList($_REQUEST['edit_id']));
				
			}
			else if ($_REQUEST['cmd'] == 'delete_file')
			{
				
				unlink($this->getPDFPath($_REQUEST['edit_id']).'/'.rawurldecode($_REQUEST['file']));
				die("1");
				
			}
			else if ($_REQUEST['cmd'] == 'download_file')
			{
				
				wpsg_ob_end_clean();
				
				header('Content-Type: application/pdf');
				header('Content-Disposition: inline; filename="'.rawurldecode($indiv_db['out_file']).'"');
				header('Cache-Control: private, max-age=0, must-revalidate');
				header('Pragma: public'); 
								
				die(file_get_contents($this->getPDFPath($_REQUEST['edit_id']).'/'.rawurldecode($_REQUEST['file'])));
				
			}
			
		} // public function produkt_ajax()
		
		public function produkt_save(&$produkt_id) 
		{ 

			if (wpsg_isSizedArray($_FILES['wpsg_mod_downloadplus_file']) && file_exists($_FILES['wpsg_mod_downloadplus_file']['tmp_name']))
			{
		 
				$bReturn = $this->fileUpload($produkt_id, false);
				
				if ($bReturn !== '1')
				{
					
					$this->shop->addBackendError($bReturn);
					
				}
				else
				{
					
					$this->shop->addBackendMessage(__('Datei für das Downloadplus Modul erfolgreich hochgeladen.', 'wpsg'));
					
				}
				
			}
			
		} // public function produkt_save(&$produkt_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_downloadplus/produkt_edit_sidebar.phtml');
				
			}
			
		} // public function produkt_edit_sidebar(&$produkt_data)
		 
		public function setOrderStatus($order_id, $status_id, $inform)
		{
			
			if ($this->shop->get_option('wpsg_mod_downloadplus_indiv_mode') == '1' && $status_id == 100) // Nach Zahlung planen
			{
				
				$this->indivOrder($order_id);
				
			}
			
		} // public function setOrderStatus($order_id, $status_id, $inform)
		
		public function basket_save_done(&$order_id, &$kunde_id, &$oBasket)
		{

			if ($this->shop->get_option('wpsg_mod_downloadplus_indiv_mode') != '2') return;
			
			$this->indivOrder($order_id);

		} // public function basket_save_done(&$order_id, &$kunde_id, &$oBasket)
		
		/**
		 * Zeichnet die Dateiliste der PDFs
		 */
		private function renderFilesList($produkt_id)
		{
			
			$this->shop->view['files'] = $this->getFiles($produkt_id);			
			return $this->shop->render(WPSG_PATH_VIEW.'/mods/mod_downloadplus/filelist.phtml', false);
			
		} // private function renderFilesList($produkt_id)
		
		public function basket_toArray(&$produkt, $backend = false, $noMwSt = false)
		{
		
			if ($this->shop->get_option('wpsg_mod_downloadplus_einsplusx') != '1')
			{
		 
				if ($this->isPDFProdukt($produkt['id']))
				{
		
					if ($produkt['menge'] != 1)
					{
							
						// Datei ist ein Downloadprodukt
						$produkt['menge'] = '1';
		
						// In der Session auch korrigieren
						foreach ($_SESSION['wpsg']['basket'] as $k => $v) { { if ($v['id'] == $produkt['id']) $_SESSION['wpsg']['basket'][$k]['menge'] = 1; } }
							
					}
						
					$produkt['oneOnly'] = true;
						
				}
		
			}
				
		} // public function basket_toArray(&$produkt, $backend = false, $noMwSt = false)
		
		public function order_ajax() { 
						
			if ($_REQUEST['cmd'] == 'schedule_file')
			{
								
				$db_indiv = $this->db->fetchRow("
					SELECT 
						`id`
					FROM
						`".WPSG_TBL_PDFINDIV."`
					WHERE
						`file` = '".wpsg_q($_REQUEST['file'])."' AND
						`o_id` = '".wpsg_q($_REQUEST['edit_id'])."' AND
						`product_index` = '".wpsg_q($_REQUEST['product_index'])."' 
				");
								
				if ($db_indiv['id'] > 0)
				{
					
					$new_name = $this->getNewName($_REQUEST['file'], $_REQUEST['edit_id'], $_REQUEST['product_key'], $db_indiv['downloadnr'], $_REQUEST['product_index']);
					
					$this->db->UpdateQuery(WPSG_TBL_PDFINDIV, array(
						"scheduled" => "NOW()",
						"out_file" => wpsg_q($new_name)
					), "`id` = '".wpsg_q($db_indiv['id'])."'");
					
				}
				else
				{
					
					$download_nr = $this->getDownloadNr($_REQUEST['edit_id'], $_REQUEST['product_key'], $_REQUEST['product_index']);
					
					$new_name = $this->getNewName($_REQUEST['file'], $_REQUEST['edit_id'], $_REQUEST['product_key'], $download_nr, $_REQUEST['product_index']);
					
					$this->db->ImportQuery(WPSG_TBL_PDFINDIV, array(
						"o_id" => wpsg_q($_REQUEST['edit_id']),
						"p_key" => wpsg_q($_REQUEST['product_key']),
						'product_index' => wpsg_q($_REQUEST['product_index']),
						"downloadnr" => wpsg_q($download_nr),
						"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_PDFINDIV, 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_PDFINDIV."`
					WHERE
						`file` = '".wpsg_q($_REQUEST['file'])."' AND
						`o_id` = '".wpsg_q($_REQUEST['edit_id'])."' AND
						`p_key` = '".wpsg_q($_REQUEST['product_key'])."'
				");
				
				$this->arMessage[] = __('Planung wurde storniert.', 'wpsg');
				 
				die($this->order_view_sidebar_renderList($_REQUEST['edit_id']));
				
			}
			else if ($_REQUEST['cmd'] == 'download_indivfile')
			{
				
				wpsg_ob_end_clean();
				
				header('Content-Type: application/pdf');
				header('Content-Disposition: inline; filename="'.rawurldecode($indiv_db['out_file']).'"');
				header('Cache-Control: private, max-age=0, must-revalidate');
				header('Pragma: public'); 
								
				die(file_get_contents($this->getPDFIndivPath($_REQUEST['edit_id']).'/'.rawurldecode($_REQUEST['file'])));
				
			}
			
		} // public function order_ajax()
		
		public function order_view_sidebar(&$order_id)
		{
			
			$bPDFProdukt = false;
			$arFiles = array();
			
			// Die arFiles brauch ich um zu bestimmen ob Produkte gekauft wurden, die Downloads enthalten
			foreach ($this->shop->view['basket']['produkte'] as $k => $v)
			{
				
				$this->shop->view['arProducts'][$k] = $v;
				
				if ($this->isPDFProdukt($v['id']))
				{
					
					$bPDFProdukt = true;
					
					$product_id = $this->shop->getProduktID($v['id']);
					
					// Hier darf das wpsg_array_merge nicht verwendet werden, da der Index nicht überschrieben werden darf
					//$arFiles = array_merge($arFiles, $this->getFiles($v['id']));
					$arFiles_product = $this->getfiles($v['id']);
					
					foreach ($arFiles_product as $file_product)
					{
						
						$arFiles[] = array($product_id, $file_product);
						
					}
					
				}
				
			}
			
			if ($bPDFProdukt && sizeof($arFiles) > 0)
			{
				 											
				$this->shop->view['order_id'] = $order_id;
				
				$this->shop->render(WPSG_PATH_VIEW.'/mods/mod_downloadplus/order_view_sidebar.phtml');				
				
			}
			
		} // public function order_view_sidebar($order_id) 
		
		public function order_view_sidebar_renderList($order_id) {
			
			$bPDFProdukt = false;
			$arFiles = array();
			
			$arBasket = $this->shop->cache->loadBasketArray($order_id);
 						
			foreach ($arBasket['produkte'] as $k => $v)
			{
 
				if ($this->isPDFProdukt($v['id']))
				{
					 
					$bPDFProdukt = true;
					
					if (wpsg_isSizedString($v['mod_vp_varkey'])) $product_key = $v['mod_vp_varkey']; else $product_key = $v['productkey'];
					
					//$product_id = $this->shop->getProduktID($v['id']);
					
					// Hier darf das wpsg_array_merge nicht verwendet werden, da der Index nicht überschrieben werden darf 
					//$arFiles = array_merge($arFiles, $this->getFiles($v['id']));
					
					$product_files = $this->getFiles($v['id']);
					
					foreach ($product_files as $file)
					{
										
						$arFiles[] = array($product_key, $file, $v['product_index']);
					
					}
						
				}
				
			}
			
			$arIndivIDs = array();
			
			if ($bPDFProdukt && wpsg_isSizedArray($arFiles))
			{
				
				$arFiles = wpsg_array_unique($arFiles);
				
				foreach ($arFiles as $k => $v)
				{
					
					$db_indiv = $this->db->fetchRow("
						SELECT 
							* 
						FROM 
							`".WPSG_TBL_PDFINDIV."` 
						WHERE 
							`file` = '".wpsg_q($v[1])."' AND
							`p_key` = '".wpsg_q($v[0])."' AND
							`o_id` = '".wpsg_q($order_id)."' AND
							`product_index` = '".wpsg_q($v[2])."'
					");
										
					if ($db_indiv['id'] > 0)
					{
						
						$arIndivIDs[] = $db_indiv['id'];
						
						$db_indiv['raid'] = false;
						
						if ($this->shop->get_option('wpsg_mod_downloadplus_accepted') == '1' && $db_indiv['counter'] >= $this->shop->get_option('wpsg_mod_downloadplus_downloads'))
						{
							$db_indiv['raid'] = true;
						}
						
						if ($this->shop->get_option('wpsg_mod_downloadplus_accepted') == '2' && strtotime($db_indiv['done']) > 0 && time() > (strtotime($db_indiv['done']) + ($this->shop->get_option('wpsg_mod_downloadplus_days') * 86400)))
						{
							$db_indiv['raid'] = true;
						}
						
						//$arFiles[$k] = array($v, $db_indiv);
						$arFiles[$k][3] = $db_indiv;
						
					}
					else
					{
						
						//$arFiles[$k] = array($v, false);
						$arFiles[$k][3] = false;
						
					}
					
				}
				
				// Jetzt noch eventuell individualisierte Dokumente laden die in den Produkten gelöscht wurden
				if (wpsg_isSizedArray($arIndivIDs))
				{
				
					$arDbIndivDeleted = $this->db->fetchAssoc("SELECT * FROM `".WPSG_TBL_PDFINDIV."` WHERE `id` NOT IN (".implode(",", $arIndivIDs).") AND `o_id` = '".wpsg_q($order_id)."'");
					
					foreach ($arDbIndivDeleted as $v)
					{
						
						//$arFiles[] = array($v['file'], $v);
						$arFiles[] = array($v['p_id'], $v['file'], false, $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_downloadplus/order_view_sidebar_renderlist.phtml');				
				
			}
			
		} // public function order_view_sidebar_renderList($order_id)
		 
		public function addShipping(&$arShipping) 
		{ 
			
			if ($this->shop->get_option('wpsg_mod_downloadplus_shipping') != '1') return;
			
			$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;
			
			$bPDF = false; $bOther = false;
			
			foreach ((array)$arBasket['produkte'] as $p)
			{
								
				if ($this->isPDFProdukt($p['id']))
				{
					
					$bPDF = true;
					
				}
				else
				{
					
					$bOther = true;
					
				} 
				
			} 
			
			if (!$bPDF || $bOther)
			{
				
				unset($arShipping[$this->id]);
				
			}
			else
			{
				
				// Wenn Downloadprodukt dann alle anderen entfernen
				foreach ($arShipping as $k => $v) { if ($k != $this->id) { unset($arShipping[$k]); } }
			  
			}
			
		} // public function checkShippingAvailable(&$arShipping, &$arBasket)
		
		/** 
		 * lädt eine Datei in das entspr. upload Verzeichnis
		 */
		private function fileUpload($produkt_id, $die = true)
		{
			
			if (file_exists($_FILES['wpsg_mod_downloadplus_file']['tmp_name']))
			{
				
				$ending = strtolower(preg_replace('/(.*)\./', '', $_FILES['wpsg_mod_downloadplus_file']['name']));
				
				if (!in_array($ending, $this->valid_ending))
				{

					if (!$die) return __('Ungültige Dateiendung.', 'wpsg');
					else die(__('Ungültige Dateiendung.', 'wpsg'));
					
				}
				else
				{
				
					$uploaddir = $this->getPDFPath($produkt_id);				
					if (!file_exists($uploaddir)) mkdir($uploaddir, 0777, true);
				
					$uploadfile = $uploaddir.basename($_FILES['wpsg_mod_downloadplus_file']['name']);					
					move_uploaded_file($_FILES['wpsg_mod_downloadplus_file']['tmp_name'], $uploadfile);
				
					if (!$die) return '1';
					else die('1');
					
					
				}
				
			}
			else 
			{
			
				if (!$die) return __('Fehler beim Upload.', 'wpsg');
				else die(__('Fehler beim Upload.', 'wpsg'));
				
			}
			
		} // private function fileUpload($produkt_id)
		
		/**
		 * Individualisiert das PDF $src_file und speichert es unter $trg_file, Absolute Pfade
		 */
		private function indivPDF($p_key, $src_file, $trg_file, $order_id, $download_nr, $indiv_id, $product_index)
		{
			
			if (preg_match('/^vp_(.*)/', $p_key))
			{
				
				$p_id = preg_replace('/(^vp_)|(\/(.*))/', '', $p_key);
				
			}
			else 
			{
				
				$p_id = $p_key;
				
			}
					
			$arProduct = $this->db->fetchRow("SELECT * FROM `".WPSG_TBL_PRODUCTS."` WHERE `id` = '".$p_id."'");
			
			if (preg_match('/^vp_(.*)/', $p_key))
			{
				
				$variInfo = $this->shop->callMod('wpsg_mod_varianten', 'getVariantenInfoArray', array($p_key));
				
				if (wpsg_isSizedArray($variInfo))
				{
				
					foreach ($variInfo as $k => $v)
					{
						
						if (is_numeric($k)) $arProduct['preis'] += $v['preis'];
						
					}
					
				}
				
			}
			
			if (wpsg_isSizedString($arProduct['mod_varianten']))
			{
				
				$arPkeys = $this->db->fetchAssoc("SELECT `p_key` FROM `".WPSG_TBL_PDFINDIV."` WHERE `o_id` = '".$order_id."'");
				
				$arVarianten = $this->shop->callMod('wpsg_mod_varianten', 'loadVarianten', array($p_id));
				
				$strVarKey = preg_replace('/(^vp_\d+\/)/', '', $p_key);

				if (strpos($strVarKey, ':'))
				{
					
					$arVar = explode(':', $strVarKey);
					
					$varName = '';
					
					foreach ($arVar as $vars)
					{
						
						$arPvar = explode('_', $vars);
						
						if ($arPvar[1] == 1 && $arVarianten[$arPvar[0]]['typ'] == 'checkbox')
						{
							
							$varName .= $this->shop->callMod('wpsg_mod_varianten', 'getVariantenName', array($arVarianten, $arPvar[0]));
							$varName .= " / ";
							
						}
						else if ($arVarianten[$arPvar[0]]['typ'] != 'checkbox')
						{
							
							$varName .= $this->shop->callMod('wpsg_mod_varianten', 'getVariantenName', array($arVarianten, $arPvar[0]));
							$varName .= ': ';
							$varName .= $this->shop->callMod('wpsg_mod_varianten', 'getVariName', array($arVarianten, $arPvar[0], $arPvar[1]));
							$varName .= " / ";
							
						}
												
					}
					
				}
				else 
				{
					
					$varName = '';
					
					$arPvar = explode('_', $strVarKey);
					
					if ($arPvar[1] == 1 && $arVarianten[$arPvar[0]]['typ'] == 'checkbox')
					{
							
						$varName .= $this->shop->callMod('wpsg_mod_varianten', 'getVariantenName', array($arVarianten, $arPvar[0]));
						$varName .= " / ";
							
					}
					else if ($arVarianten[$arPvar[0]]['typ'] != 'checkbox')
					{
							
						$varName .= $this->shop->callMod('wpsg_mod_varianten', 'getVariantenName', array($arVarianten, $arPvar[0]));
						$varName .= ': ';
						$varName .= $this->shop->callMod('wpsg_mod_varianten', 'getVariName', array($arVarianten, $arPvar[0], $arPvar[1]));
						$varName .= " / ";
							
					}
						
				}
				
				$varName = preg_replace('/\040*\/\040*$/', '',  $varName);
					
			}
			
			if ($this->shop->get_option('wpsg_mod_downloadplus_memorylimit') == '1') ini_set('memory_limit', '2000M');			
			if ($this->shop->get_option('wpsg_mod_downloadplus_timelimit') == '1') set_time_limit(3600);
			
			require_once (WPSG_PATH_LIB."fpdf/fpdf.php");
			require_once (WPSG_PATH_LIB."fpdf/fpdi.php");
			require_once (WPSG_PATH_LIB."fpdf/FPDI_Protection.php");
			require_once (WPSG_PATH_MOD."mod_downloadplus/wpsg_fpdf.php");
				 
			$pi = pathinfo($src_file); 
		 
   			if (in_array(strtolower($pi['extension']), $this->valid_ending))
   			{ 
   				   		 
   				$pdf = new wpsg_dl_fpdf();
 
   				$pdf->setSourceFile($src_file);

   				$tplidx = $pdf->importPage(1, '/MediaBox');					
   				$size = $pdf->getTemplateSize($tplidx); 
				$orientation = (($size['h'] > $size['w'])?'P':'L');
   				
   				$pdf = new wpsg_dl_fpdf($orientation, "mm", array($size['w'], $size['h']));
   				
   				$arRights = array();	
   							
				if ($this->shop->get_option("wpsg_mod_downloadplus_securitysave") == "1") $arRights[] = "copy";
				if ($this->shop->get_option("wpsg_mod_downloadplus_securityprint") == "1") $arRights[] = "print";
				if ($this->shop->get_option("wpsg_mod_downloadplus_securitymod") == "1") $arRights[] = "modify";
				if ($this->shop->get_option("wpsg_mod_downloadplus_securitynote") == "1") $arRights[] = "annot-forms";
				
				$pdf->SetProtection($arRights, $this->shop->get_option("wpsg_mod_downloadplus_openpass"), $this->shop->get_option("wpsg_mod_downloadplus_masterpass"));									
   				
				$pagecount = $pdf->setSourceFile($src_file);
				 
				$arCustomReplace = array(
					'/%filename%/' 				=> basename($src_file),
					'/%filename_clear%/' 			=> preg_replace('/\.(.*)$/', '', $src_file),
					'/%filename_ohneext%/' 		=> preg_replace('/\.(.*)$/', '', basename($src_file)),
					'/%product_detailname%/' 			=> $arProduct['detailname'],
					'/%product_name%/' 			=> $arProduct['name'],
					'/%product_anr%/' 			=> $arProduct['anr'],
					'/%product_preis%/' 			=> wpsg_ff($arProduct['preis']),
					'/%product_netto_preis%/' 	=> wpsg_ff($arProduct['netto_preis']),
					'/%product_beschreibung%/' 	=> $arProduct['beschreibung'],
					'/%product_varianten_name%/' 	=> $varName,
					'/%download_nr%/' 			=> $download_nr
				);
				
				$arTexte = $this->shop->get_option('wpsg_mod_downloadplus_text');
				
				$fielddata = array();
				
				for ($pagei = 1; $pagei <= $pagecount; $pagei ++)
				{
					
					$tplidx = $pdf->importPage($pagei, '/BleedBox');	 					
					
					$pdf->addPage();
					
					if ($this->shop->get_option("wpsg_mod_downloadplus_range") != "1" || ($pagei >= $this->shop->get_option("wpsg_mod_downloadplus_range_von") && $pagei <= $this->shop->get_option("wpsg_mod_downloadplus_range_bis")))
					{
						
						foreach ($arTexte as $text_key => $t)
						{
							
							if ($t['bg'] == '1' && $t['aktiv'] == '1')
							{
								
								$t['text'] = $this->shop->replaceUniversalPlatzhalter($t['text'], $order_id, false, false, $p_id, $arCustomReplace, $product_index);
								$fielddata['texte'][$text_key] = $t['text'];
								
								if ($t['alpha'] > 0) $pdf->setAlpha($t['alpha']);
								
								$bSetFont = false;
								 
								if (wpsg_isSizedString($t['font']) && !in_array($t['font'], $this->barCodeFonts))
								{
									 
									$font_file = WPSG_PATH_LIB.'fpdf/font/'.$t['font'];
									 
									if (file_exists($font_file))
									{
										 
										include $font_file;
										 
										$bSetFont = true;
										$pdf->SetFont($name, '', $t['fontsize']);
										
									}
									
								}
																
								if (!$bSetFont) $pdf->SetFont('Arial', 'B', $t['fontsize']);								
								
								if (in_array($t['font'], $this->barCodeFonts))
								{
									 
									$pdf->SetDrawColor(0, 0, 0);
									$pdf->$t['font']($t['x'], $t['y'], $t['text'], $t['fontsize']); 
									
								}
								else 
								{
									
									list($r, $g, $b) = wpsg_getColor($t["color"]);
									$pdf->SetTextColor($r, $g, $b);
	
							    	$pdf->RotatedText(
								    	$t['x'], $t['y'], 
								    	$t['text'], 
								    	$t['angle'],
								    	$t['align']
								    );
							    
									$pdf->setAlpha(1);
									
								}
								
							}
							
						}
												
					}
					 
					$pdf->useTemplate($tplidx, 0, 0, $size['w'], $size['h']);

					if ($this->shop->get_option("wpsg_mod_downloadplus_range") != "1" || ($pagei >= $this->shop->get_option("wpsg_mod_downloadplus_range_von") && $pagei <= $this->shop->get_option("wpsg_mod_downloadplus_range_bis")))
					{
						 
						foreach ($arTexte as $text_key => $t)
						{
							
							if ($t['bg'] != '1' && $t['aktiv'] == '1')
							{
								
								$t['text'] = $this->shop->replaceUniversalPlatzhalter($t['text'], $order_id, false, false, $p_id, $arCustomReplace, $product_index);
								$fielddata['texte'][$text_key] = $t['text'];
								
								if ($t['alpha'] > 0) $pdf->setAlpha($t['alpha']);
																
								$bSetFont = false;
									
								if (wpsg_isSizedString($t['font']) && !in_array($t['font'], $this->barCodeFonts))
								{
								
									$font_file = WPSG_PATH_LIB.'fpdf/font/'.$t['font'];
								
									if (file_exists($font_file))
									{
											
										include $font_file;
									 
										$pdf->AddFont($name, '', $t['font']);
										
										$bSetFont = true;
										$pdf->SetFont($name, '', $t['fontsize']);
								
									}
										
								}
								
								if (!$bSetFont) $pdf->SetFont('Arial', 'B', $t['fontsize']);

								if (in_array($t['font'], $this->barCodeFonts))
								{
									 
									$pdf->SetDrawColor(0, 0, 0);
									$pdf->$t['font']($t['x'], $t['y'], $t['text'], $t['fontsize']); 
										
								}
								else
								{
										
									list($r, $g, $b) = wpsg_getColor($t["color"]);
									$pdf->SetTextColor($r, $g, $b);
								
									$pdf->RotatedText(
											$t['x'], $t['y'],
											$t['text'],
											$t['angle'],
											$t['align']
									);
										
									$pdf->setAlpha(1);
										
								}
								 
								
							}
							
						}
												
					}
					
				}
				
				// Daten in die Individualisierung eintragen
				$this->db->UpdateQuery(WPSG_TBL_PDFINDIV, array(
					'fielddata' => wpsg_q(serialize($fielddata))
				), " `id` = '".wpsg_q($indiv_id)."' ");
				
				$pdf->Output($trg_file, 'f'); 
				
				chmod($trg_file, 0777);
								
   			}
   			else
   			{
   				
   				return false;
   				
   			}
			 			
		} // private function indivPDF($src_file, $trg_file)
		
		public function wp_loaded()
		{
			
			if (wpsg_isSizedString($_REQUEST['wpsg_action'], 'wpsg_mod_downloadplus_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_PDFINDIV."` WHERE `id` = '".wpsg_q($_REQUEST['indi'])."'");
				
				if ($this->shop->get_option('wpsg_mod_downloadplus_accepted') == '1' && $indiv_db['counter'] >= $this->shop->get_option('wpsg_mod_downloadplus_downloads'))
				{
					die(__('Sie haben die maximale Anzahl an Downloads überschritten.', 'wpsg'));
				}
				
				if ($this->shop->get_option('wpsg_mod_downloadplus_accepted') == '2' && time() > (strtotime($indiv_db['done']) + ($this->shop->get_option('wpsg_mod_downloadplus_days') * 86400)))
				{
					die(__('Der Download der Datei ist nicht mehr gültig.', 'wpsg'));
				}

				$this->db->UpdateQuery(WPSG_TBL_PDFINDIV, array("counter" => wpsg_q($indiv_db['counter'] + 1)), "`id` = '".wpsg_q($_REQUEST['indi'])."'");
				
				if ($this->shop->get_option('wpsg_mod_downloadplus_format') == '1') 
				{ 

					if ($this->shop->get_option('wpsg_mod_downloadplus_memorylimit') == '1') ini_set('memory_limit', '2000M');			
					if ($this->shop->get_option('wpsg_mod_downloadplus_timelimit') == '1') set_time_limit(3600);
					
					// Gezippt intern
					$zipfile = tempnam("tmp", "zip");
					$zip = new ZipArchive();
					$zip->open($zipfile, ZipArchive::CREATE);				
					$zip->addFile($this->getPDFIndivPath($indiv_db['o_id']).'/'.rawurldecode($indiv_db['out_file']), $indiv_db['out_file']);					
					$zip->close();
					
					$pi_file = pathinfo($this->getPDFIndivPath($indiv_db['o_id']).'/'.rawurldecode($indiv_db['out_file']));
					$zip_name = $pi_file['filename'].".zip";
					
					wpsg_ob_end_clean();
					
					header('Content-Type: application/zip');
					header('Content-Length: '.filesize($zipfile));
					header('Content-Disposition: attachment; filename="'.$zip_name.'"');
					header('Expires: 0');
					header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
					header('Pragma: public');
					
					readfile($zipfile);
					unlink($zipfile);
					die();
					  				
				} 
				/*else if ($this->shop->get_option('wpsg_mod_downloadplus_format') == '1') 
				{ 
					
					// Eventuell TODO					
					
				}*/
				else
				{
				
					wpsg_ob_end_clean();
					
					header('Content-Type: application/pdf');
					header('Content-Disposition: inline; filename="'.rawurldecode($indiv_db['out_file']).'"');
					header('Cache-Control: private, max-age=0, must-revalidate');
					header('Pragma: public');
					
					//header('Content-Disposition: attachment; filename="'.rawurldecode($indiv_db['out_file']).'"');				
					die(file_get_contents($this->getPDFIndivPath($indiv_db['o_id']).'/'.rawurldecode($indiv_db['out_file'])));
					
				}
				
			}
			else if (wpsg_isSizedString($_REQUEST['wpsg_action'], 'wpsg_mod_downloadplus_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() { 
			
			$arPDFsUnindiv = $this->db->fetchAssoc("
				SELECT
					*
				FROM
					`".WPSG_TBL_PDFINDIV."`
				WHERE
					`scheduled` != '0000-00-00 00:00:00' AND
					`done` = '0000-00-00 00:00:00'
			");
			
			$arLog = array();
			
			foreach ($arPDFsUnindiv as $v)
			{
				 
				$order_path = $this->getPDFIndivPath($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 ($p['id'] != $v['p_key']) continue;

					$product_key = $p['id'];
					
					if (preg_match('/^vp_(.*)/', $p['id']))
					{
						$p['id'] = preg_replace('/(^vp_)|(\/(.*))/', '', $p['id']);
					} 
					
					if ($this->isPDFProdukt($p['id']) && in_array($v['file'], $this->getFiles($p['id'])))
					{
						 
						$this->indivPDF(
							$product_key,
							$this->getPDFPath($p['id']).'/'.$v['file'],
							$this->getPDFIndivPath($v['o_id']).'/'.$v['out_file'],
							$v['o_id'],
							$v['downloadnr'],
							$v['id'],
							$v['product_index']
						);

						$this->db->UpdateQuery(WPSG_TBL_PDFINDIV, 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_downloadplus_accepted') == '1' && $this->shop->get_option('wpsg_mod_downloadplus_cleanraiddownloads') == '1')
			{
				
				$arClean = array_merge($arClean, $this->db->fetchAssoc("
					SELECT
						*
					FROM
						`".WPSG_TBL_PDFINDIV."`
					WHERE
						`counter` > '".wpsg_q($this->shop->get_option('wpsg_mod_downloadplus_downloads'))."'
				"));
				
			}
			else if ($this->shop->get_option('wpsg_mod_downloadplus_accepted') == '2' && $this->shop->get_option('wpsg_mod_downloadplus_cleanraiddownloads') == '1')
			{

				$arClean = array_merge($arClean, $this->db->fetchAssoc("
					SELECT
						*
					FROM
						`".WPSG_TBL_PDFINDIV."`
					WHERE
						DATE_ADD(`done`, INTERVAL ".$this->shop->get_option('wpsg_mod_downloadplus_days')." DAY) < NOW()
				"));
				
			}
			
			if (intval($this->shop->get_option('wpsg_mod_downloadplus_cleanolddownloads')) > 0)
			{
				
				$arClean = array_merge($arClean, $this->db->fetchAssoc("
					SELECT
						*
					FROM
						`".WPSG_TBL_PDFINDIV."`
					WHERE
						DATE_ADD(`done`, INTERVAL ".$this->shop->get_option('wpsg_mod_downloadplus_cleanolddownloads')." DAY) < NOW()
				"));
				
			}
			
			if (wpsg_isSizedArray($arClean))
			{
				
				foreach ($arClean as $c)
				{
					
					$path = $this->getPDFIndivPath($c['o_id']);
					
					unlink($path.'/'.$c['out_file']);
					
					$this->db->Query("DELETE FROM `".WPSG_TBL_PDFINDIV."` 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_downloadplus_autosend') == '1')
					{
						
						$this->sendFiles($order['id']);
						
					}
					
				}
								
				$mail_text = $this->shop->render(WPSG_PATH_VIEW.'/mods/mod_downloadplus/cronmail.phtml', false);
				
				if ($this->shop->get_option('wpsg_htmlmail') === '1')
				{
					
					$mail_html = $this->shop->render(WPSG_PATH_VIEW.'/mods/mod_downloadplus/cronmail_html.phtml', false);
					
				}
				else
				{
					
					$mail_html = false;
					
				}
				
				$this->shop->sendMail($mail_text, $this->shop->get_option('wpsg_pdfdownloadcronmail_empfaenger'), 'pdfdownloadcronmail', array(), false, false, $mail_html);
				
			}
			
		} // public function cron()
		
		public function wpsg_mod_export_loadFields(&$arFields) 
		{ 
			
			$arDPFields = array(
				'name' => __('Downloadplus', 'wpsg'),
				'fields' => array()				
			);
			
			for ($i = 1; $i <= 10; $i ++)
			{
			
				$arDPFields['fields']['text'.$i] = wpsg_translate(__('Text in Textfeld #1#', 'wpsg'), $i);

			}
			
			$arDPFields['fields']['dnr'] = __('Downloadnummer', 'wpsg');
			
			$arFields[] = $arDPFields;
			
		} // public function wpsg_mod_export_loadFields(&$arFields)
		
		public function wpsg_mod_export_getValue(&$return, $field_value, $o_id, $p_id, $productkey, $product_index, $profil_separator) 
		{ 

			// Individualisierung heraussuchen
			$db_indiv = $this->db->fetchRow("SELECT * FROM `".WPSG_TBL_PDFINDIV."` WHERE `o_id` = '".wpsg_q($o_id)."' AND `p_key` = '".wpsg_q($p_id)."' AND `product_index` = '".wpsg_q($product_index)."' ORDER BY `id` DESC LIMIT 1 ");
			
			switch ($field_value)
			{
				
				case 'dnr':
					if (!wpsg_isSizedInt($db_indiv['id'])) $return = ''; else $return = $db_indiv['downloadnr'];
					break;
					
				default:
					
					if (preg_match('/^text\d+$/', $field_value))
					{
						
						$return = '';
						
						if (wpsg_isSizedInt($db_indiv['id'])) 
						{
						
							$arTexte = unserialize($db_indiv['fielddata']);

							if (wpsg_isSizedArray($arTexte))
							{					

								$txt_nr = substr($field_value, 4); 
								
								$return = $arTexte['texte'][$txt_nr - 1];
								
							}
							
						}
						
					}
									
			} // switch
			
		} // public function wpsg_mod_export_getValue(&$return, $field_value, $o_id, $p_id, $product_index, $profil_separator)
		
		/** 
		 * Baut den Kontroll Hash
		 */
		private function makeHash($indiv_id)
		{
			
			$indiv_db = $this->db->fetchRow("SELECT * FROM `".WPSG_TBL_PDFINDIV."` 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)
		
		/**
		 * Sendet die Mail mit den Downloadlinks an den Kunden
		 */
		public function sendFiles($order_id)
		{
			
			$this->shop->view['arPDFs'] = $this->db->fetchAssoc("
				SELECT
					*
				FROM
					`".WPSG_TBL_PDFINDIV."`
				WHERE
					`o_id` = '".wpsg_q($order_id)."' AND
					`done` != '0000-00-00 00:00:00'
			");
			
			foreach ($this->shop->view['arPDFs'] as $k => $v)
			{
				
				// Download noch gültig
				if ($this->shop->get_option('wpsg_mod_downloadplus_accepted') == '1' && $v['counter'] >= $this->shop->get_option('wpsg_mod_downloadplus_downloads'))
				{
					unset($this->shop->view['arPDFs'][$k]);
				}
				else if ($this->shop->get_option('wpsg_mod_downloadplus_accepted') == '2' && time() > (strtotime($v['done']) + ($this->shop->get_option('wpsg_mod_downloadplus_days') * 86400)))
				{
					unset($this->shop->view['arPDFs'][$k]);
				}
				else 
				{
					$this->shop->view['arPDFs'][$k]['hash'] = $this->makeHash($v['id']);
				}
				
			}
			
			if (sizeof($this->shop->view['arPDFs']) > 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']);

				// Andere Sprache setzten wenn die Bestellung in einer anderen Sprache durchgeführt wurde
				if (trim($this->shop->view['order']['language']) != '') $this->shop->setTempLocale($this->shop->view['order']['language']);
				
				$mail_text = $this->shop->render(WPSG_PATH_VIEW.'/mods/mod_downloadplus/pdfdownloadmail.phtml', false);
				
				if ($this->shop->get_option('wpsg_htmlmail') === '1')
				{
					
					$mail_html = $this->shop->render(WPSG_PATH_VIEW.'/mods/mod_downloadplus/pdfdownloadmail_html.phtml', false);
					
				}
				else
				{
					
					$mail_html = false;
					
				}
				
				$attachment = array();
				
				if ($this->shop->get_option('wpsg_mod_downloadplus_attachement') == '1')
				{
				
					foreach ($this->shop->view['arPDFs'] as $k => $v)
					{
					
						$attachment[] = $this->getPDFIndivPath($order_id).'/'.$v['out_file'];
						
					}
					
				}
				
				$this->shop->sendMail($mail_text, $this->shop->view['kunde']['email'], 'pdfdownloadfiles', $attachment, $order_id, false, $mail_html);
				
				$this->shop->restoreTempLocale();
				
				$this->db->ImportQuery(WPSG_TBL_OL, array(
					"o_id" => wpsg_q($order_id),
					"cdate" => "NOW()",
					"title" => wpsg_translate(__('Pdf Downloads 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 PDFs für eine Bestellung
		 */
		public function indivOrder($order_id)
		{

			$arBasket = $this->shop->cache->loadBasketArray($order_id);
				
			$bPDFProdukt = false;
			$arPDF = array();
				
			foreach ($arBasket['produkte'] as $p)
			{
				 
				if ($this->isPDFProdukt($p['id']))
				{
 					
					$bPDFProdukt = true;
					
					// Hier darf nicht wpsg_array_merge verwendet werden, da sonst Index=0 überschrieben wird
					//$arPDF = array_merge($arPDF, $this->getFiles($p['id']));						
					
					if (wpsg_isSizedString($p['mod_vp_varkey'])) $product_key = $p['mod_vp_varkey']; else $product_key = $p['productkey'];
									
					$product_files = $this->getFiles($p['id']);

					foreach ($product_files as $file)
					{
						
						$arPDF[] = array(
							$product_key, $file, $p['product_index']
						);
						
					}
					
				}
				
			}
 
			if ($bPDFProdukt === true && wpsg_isSizedArray($arPDF))
			{
				
				foreach ($arPDF as $v)
				{
			
					$this->db->Query("DELETE FROM `".WPSG_TBL_PDFINDIV."` WHERE `file` = '".wpsg_q($v)."' AND `o_id` = '".wpsg_q($order_id)."'");
					
					$download_nr = $this->getDownloadNr($order_id, $v[0], $v[2]);
					
					$this->db->ImportQuery(WPSG_TBL_PDFINDIV, array(
						"o_id" => wpsg_q($order_id),
						"downloadnr" => wpsg_q($download_nr),
						"p_key" => wpsg_q($v[0]),
						'product_index' => wpsg_q($v[2]),
						"downloadnr" => wpsg_q($download_nr),
						"file" => wpsg_q($v[1]),
						"scheduled" => wpsg_q("NOW()"),
						"done" => wpsg_q("0000-00-00 00:00:00"),
						"out_file" => wpsg_q($this->getNewName($v[1], $order_id, $v[0], $download_nr, $v[2]))
					));
					
				}
				
			}
			
		} // public function indivOrder($order_id)
		
		/**
		 * Gibt den Individualisierten Dateinamen für ein File und Bestellung zurück
		 */
		public function getNewName($oldFilename, $order_id, $product_key, $download_nr, $product_index)
		{
			
			$product_id = $this->shop->getProduktId($product_key);
			
			$arReplace = array(
				'/%filename%/' => $oldFilename,
				'/%filename_clear%/' => preg_replace('/\.(.*)$/', '', $oldFilename),
				'/%filename_ohneext%/' => preg_replace('/\.(.*)$/', '', $oldFilename),
				'/%download_nr%/' => $download_nr
			);
			
			$newFilename = $this->shop->replaceUniversalPlatzhalter($this->shop->get_option('wpsg_mod_downloadplus_filename'), $order_id, false, false, $product_id, $arReplace, $product_index);
				
			return $newFilename;
			
		} // public function getNewName($oldFilename, $order_id, $product_key, $download_nr, $product_index)
		
		/**
		 * Gibt die PDFdateien eines Produktes zurück
		 */
		public function getFiles($produkt_id)
		{

			if (preg_match('/^vp_(.*)/', $produkt_id))
			{
				$produkt_id = preg_replace('/(^vp_)|(\/(.*))/', '', $produkt_id);
			} 
			
			$path = $this->getPDFPath($produkt_id);
			
			if (!file_exists($path)) return;

			$arrFiles = scandir($path);
			$arPDFFiles = array();
			
			foreach ($arrFiles as $file)
			{
				
				if (is_file($path.$file) && in_array(strtolower(preg_replace('/(.*)\./', '', $file)), $this->valid_ending))
				{
					
					$arPDFFiles[] = $file;
					
				}
				
			}
			
			return $arPDFFiles;
			
		} // private function getFiles($produkt_id)
		
		/**
		 * Gibt alle Dokumente zurück, die zu einer Bestellung individualisiert wurden
		 */
		public function getIndivFiles($produkt_id, $order_id)
		{
			
			if (preg_match('/^vp_(.*)/', $produkt_id))
			{
				$produkt_id = preg_replace('/(^vp_)|(\/(.*))/', '', $produkt_id);
			}

			$arFilesProdukt = $this->getFiles($produkt_id);			
			$arFilesReturn = array();
			
			foreach ($arFilesProdukt as $k => $v)
			{
				
				$indiv = $this->db->fetchRow("SELECT * FROM `".WPSG_TBL_PDFINDIV."` WHERE `o_id` = '".wpsg_q($order_id)."' AND `file` = '".wpsg_q($v)."'");
				
				$infoArray = array(
					'done' => '0000-00-00 00:00:00',
					'scheduled' => '0000-00-00 00:00:00',
					'counter' => -1,
					'status' => 0
				);

				if ($indiv['id'] > 0) 
				{
					
					$infoArray['status'] = 1;
					$infoArray['done'] = $indiv['done'];
					$infoArray['scheduled'] = $indiv['scheduled'];
					$infoArray['counter'] = $indiv['counter'];
					$infoArray['indiv_id'] = $indiv['id'];
					$infoArray['hash'] = $this->makeHash($indiv['id']);
					
				}
				
				if (@strtotime($indiv['done']) > 0) $infoArray['status'] = 2;				
				
				$infoArray['file'] = $v;
				$infoArray['file_out'] = @$indiv['out_file'];
				$infoArray['path'] = $this->getPDFIndivPath($order_id);

				$arFilesReturn[] = $infoArray;
				
			}
			
			return $arFilesReturn;
			
		} // public function getIndivFiles($produkt_id, $order_id)
		
		/**
		 * Überprüft ein Produkt ob es ein PDFDownloadProdukt ist
		 */
		public function isPDFProdukt($produkt_key)
		{

			$produkt_id = $this->shop->getProduktId($produkt_key);
			 	
			$arPDFs = $this->getFiles($produkt_id);
				
			if (sizeof($arPDFs) > 0) return true;
			
			return false;
			
		} // private function isPDFProdukt($produkt_key)
		
		/**
		 * Gibt den Pfad zu dem Ordner zurück in dem die PDFs abgelegt werden
		 */
		public function getPDFPath($produkt_id)
		{

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

				$path = $this->shop->get_option('wpsg_mod_downloadplus_pdfpath').'/'.$produkt_id.'/';
				
			}
			else
			{
			
				if ($this->shop->isMultiBlog())
				{
					
					$path = WP_CONTENT_DIR.'/'.WPSG_MB_UPLOADS.'/wpsg/wpsg_pdfprodukte/'.$produkt_id.'/'; 
						
				}
				else
				{
						 
					$path = WP_CONTENT_DIR.'/uploads/wpsg_pdfprodukte/'.$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 getPDFPath($produkt_id)
		
		/**
		 * Gibt den Pfad zurück wo die Individualisierten PDFs einer Bestellung liegen
		 */
		public function getPDFIndivPath($order_id)
		{

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

				$path = $this->shop->get_option('wpsg_mod_downloadplus_pdfindivpath').'/'.$order_id.'/';
				
			}
			else
			{
				
				if ($this->shop->isMultiBlog())
				{
					
					$path = WP_CONTENT_DIR.'/'.WPSG_MB_UPLOADS.'/wpsg/wpsg_pdfprodukte_order/'.$order_id.'/'; 
										
				}
				else
				{
						 
					$path = WP_CONTENT_DIR.'/uploads/wpsg_pdfprodukte_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 getPDFIndivPath($order_id)
		
		/**
		 * Gibt die DownloadNr zurück
		 * @param int $order_id BestellID
		 * @param varchar $product_key Produktkey
		 */
		private function getDownloadNr($order_id, $product_key, $product_index)
		{
			
			$product_id = $this->shop->getProduktID($product_key);
			
			$format = $this->shop->get_option('wpsg_mod_downloadplus_numberformat');
			if (!wpsg_isSizedString($format)) $format = "%download_nr%";
			
			$download_nr = $this->shop->get_option('wpsg_mod_downloadplus_startnumber');
			if (!wpsg_isSizedInt($download_nr)) $download_nr = 1;
			
			$arCustomReplace = array(
				'/\%download_nr\%/' => $download_nr			
			);
			
			$format = $this->shop->replaceUniversalPlatzhalter($format, $order_id, false, false, $product_id, $arCustomReplace, $product_index);		

			$this->shop->update_option('wpsg_mod_downloadplus_startnumber', $download_nr + 1);
			
			return $format;
			
		} // private function getDownloadNr($order_id, $product_key)
		
	} // class wpsg_mod_downloadplus extends wpsg_mod_basic

?>