<?php
class Shop
{
	var $Limit = 15;
	var $ArticleLimit = 15;
	var $separator = ";";
	var $enclosed = "\"";
	var $cutter = "\r\n";
	var $_field_width = "400px";
	var $_textarea_width = "98%";
	var $_textarea_height = "400px";
	var $_allowed = array('image/pjpeg','image/jpeg','image/x-png','image/png','image/gif');
	var $_upload_path = 'uploads/shop/icons_thumbnails/'; // Nicht aendern!
	
	function showMoney()
	{
		if(perm('shop_settings')) 
		{
			if(isset($_REQUEST['search']) && $_REQUEST['search'] == 1)
			{
				$ZeitStart = mktime(0,0,1,$_REQUEST['start_Month'],$_REQUEST['start_Day'],$_REQUEST['start_Year']);
				$ZeitEnde  = mktime(23,59,59,$_REQUEST['end_Month'],$_REQUEST['end_Day'],$_REQUEST['end_Year']);
			} else {
				$ZeitStart = mktime(0,0,1,date("m"),date("d")-(date("d")-1),date("Y"));
				$ZeitEnde  = mktime(23,59,59,date("m"),date("d"),date("Y"));
			}
			
			$ZahlungsId = (isset($_REQUEST['ZahlungsId']) && $_REQUEST['ZahlungsId'] != 'egal') ? "AND ZahlungsId = '$_REQUEST[ZahlungsId]'" : "";
			$VersandId = (isset($_REQUEST['VersandId']) && $_REQUEST['VersandId'] != 'egal') ? "AND VersandId = '$_REQUEST[VersandId]'" : "";
			$Benutzer = (isset($_REQUEST['Benutzer']) && $_REQUEST['Benutzer'] != '') ? "AND Benutzer = '$_REQUEST[Benutzer]'"  : "";
			
			$row = $GLOBALS['db']->RowQuery("SELECT SUM(Betrag) AS GesamtUmsatz FROM " . PREFIX . "_shop_bestellungen WHERE (Status = 'ok' || Status = 'oksend') AND (Datum BETWEEN $ZeitStart AND $ZeitEnde) $ZahlungsId $VersandId $Benutzer");
			$row2 = $GLOBALS['db']->RowQuery("SELECT SUM(Betrag) AS GesamtUmsatz FROM " . PREFIX . "_shop_bestellungen WHERE Datum BETWEEN $ZeitStart AND $ZeitEnde $ZahlungsId $VersandId $Benutzer");
			$row3 = $GLOBALS['db']->RowQuery("SELECT SUM(Betrag) AS GesamtUmsatz FROM " . PREFIX . "_shop_bestellungen WHERE (Status = 'wait') AND (Datum BETWEEN $ZeitStart AND $ZeitEnde) $ZahlungsId $VersandId $Benutzer");
			$row4 = $GLOBALS['db']->RowQuery("SELECT SUM(Betrag) AS GesamtUmsatz FROM " . PREFIX . "_shop_bestellungen WHERE (Status = 'progress') AND (Datum BETWEEN $ZeitStart AND $ZeitEnde) $ZahlungsId $VersandId $Benutzer");
			$row5 = $GLOBALS['db']->RowQuery("SELECT SUM(Betrag) AS GesamtUmsatz FROM " . PREFIX . "_shop_bestellungen WHERE (Status = 'failed') AND (Datum BETWEEN $ZeitStart AND $ZeitEnde) $ZahlungsId $VersandId $Benutzer");
			
			$row->GesamtUmsatz = number_format($row->GesamtUmsatz,'2',',','.'); 
			$row->GesamtUmsatzAlle = number_format($row2->GesamtUmsatz,'2',',','.'); 
			$row->GesamtUmsatzWartend = number_format($row3->GesamtUmsatz,'2',',','.'); 
			$row->GesamtUmsatzBearbeitung = number_format($row4->GesamtUmsatz,'2',',','.'); 
			$row->GesamtFehlgeschlagen = number_format($row5->GesamtUmsatz,'2',',','.'); 
			
			$GLOBALS['tmpl']->assign('paymentMethods', $this->listPayments());
			$GLOBALS['tmpl']->assign('shippingMethods', $this->listShipper());
			$GLOBALS['tmpl']->assign('row', $row);
			$GLOBALS['tmpl']->assign('ZeitStart', $ZeitStart);
			$GLOBALS['tmpl']->assign('ZeitEnde', $ZeitEnde);
			$GLOBALS['tmpl']->assign('currency', $this->getShopSettings('WaehrungSymbol_1'));
			$GLOBALS['tmpl']->assign('title', $GLOBALS['config_vars']['Shop_showmoney_title']); 
			$GLOBALS['tmpl']->assign('content', $GLOBALS['tmpl']->fetch($GLOBALS['config']['source'] . '/shop/showmoney.tpl'));
		}
	}
	
	//=================================================================
	// Kategorien-Zubehoer Prueffunktion fuer Aktualisierung
	//=================================================================
	function categAddons_CheckEmpty($field_id,$id,$field_name,$name_old,$lc)
	{
		$error = '';
		switch($field_id)
		{
			case 1: $zubWhere = 'a'; break;
			case 2: $zubWhere = 'b'; break;
			case 3: $zubWhere = 'c'; break;
		}
		
		if(empty($_POST['Teile_' . $field_id . '_Name_1'][$id]))
		{
			$r = $GLOBALS['db']->RowQuery("SELECT Zub_{$zubWhere} AS DA FROM " . PREFIX . "_shop_produkte WHERE Kategorie = '" . $_POST['id'][$id] . "'");
			if(is_object($r) && $r->DA && $name_old!='') 
			{
				$e_text = $GLOBALS['config_vars']['Shop_CategoriesNoEmpty'];
				$e_text = str_replace('__FIELD__', stripslashes($field_name), $e_text);
				$e_text = str_replace('__VAL__', $name_old, $e_text);
				$error = $e_text;
				$q1 = '';
			} else {
				$q1 = "Teile_" . $field_id . "_Name_1 = '',";
				$q1 .= "Teile_" . $field_id . "_Name_2 = '',";
				$q1 .= "Teile_" . $field_id . "_Name_3 = '',";
			} 
		} else {
			$q1 = "Teile_" . $field_id . "_Name_$lc = '" . $_POST['Teile_' . $field_id . '_Name_1'][$id] . "',";
		}
		
		return $q1 . '|' . $error;
	}
	
	//=================================================================
	// Kategorien-Zubehoer
	//=================================================================
	function categAddons() 
	{
	
		if(perm('shop_addons')) 
		{
			$categs_used = '';
			if(isset($_GET['del']) && $_GET['del']==1)
			{
				$GLOBALS['db']->Query("DELETE FROM " . PREFIX . "_shop_kategorie_zubehoer WHERE Id = '" . $_GET['categ'] . "'");
				$GLOBALS['db']->Query("UPDATE " . PREFIX . "_shop_produkte SET Zub_a = 'NULL',Zub_b = 'NULL',Zub_c = 'NULL' WHERE Kategorie = '" . $_GET['shop_categ'] . "'");
				Logger('User ' . $_SESSION['user_name'] . ' delete Shop-Addon-Category', '3', $_SESSION['benutzer_id']);
			}
			
			$error   = '';
			$scategs = array();
			
			if(isset($_POST['new']) && $_POST['new'] == 1)
			{
				$GLOBALS['db']->Query("INSERT INTO " . PREFIX . "_shop_kategorie_zubehoer
				(
					Id,
					Kategorie,
					Teile_1_Name_1,
					Teile_1_Name_2,
					Teile_1_Name_3,
					Teile_2_Name_1,
					Teile_2_Name_2,
					Teile_2_Name_3,
					Teile_3_Name_1,
					Teile_3_Name_2,
					Teile_3_Name_3
				) VALUES (
					'',
					'" . $_POST['Categ'] . "',
					'" . $_POST['Teile_1_Name_1'] . "',
					'" . $_POST['Teile_1_Name_1'] . "',
					'" . $_POST['Teile_1_Name_1'] . "',
					'" . @$_POST['Teile_2_Name_1'] . "',
					'" . @$_POST['Teile_2_Name_1'] . "',
					'" . @$_POST['Teile_2_Name_1'] . "',
					'" . @$_POST['Teile_3_Name_1'] . "',
					'" . @$_POST['Teile_3_Name_1'] . "',
					'" . @$_POST['Teile_3_Name_1'] . "'
				)");
				Logger('User ' . $_SESSION['user_name'] . ' create new Shop-Addon-Category', '3', $_SESSION['benutzer_id']);
			}
			
			if(isset($_POST['save']) && $_POST['save'] == 1 )
			{
				foreach($_POST['id'] as $id => $val)
				{
					//=================================================================
					// Zubehoerfelder pruefen
					//=================================================================
					$c1      = explode('|', $this->categAddons_CheckEmpty(1,$id,$_POST['name'][$id],$_POST['name_old'][$id],$_REQUEST['lc']));
					$q1      = $c1[0];
					if($c1[1]!='') $error[] = $c1[1];
					
					$c2      = explode('|', $this->categAddons_CheckEmpty(2,$id,$_POST['name'][$id],$_POST['name_old_2'][$id],$_REQUEST['lc']));
					$q2      = $c2[0];
					if($c2[1]!='') $error[] = $c2[1];
					
					$c3      = explode('|', $this->categAddons_CheckEmpty(3,$id,$_POST['name'][$id],$_POST['name_old_3'][$id],$_REQUEST['lc']));
					$q3      = $c3[0];
					if($c3[1]!='') $error[] = $c3[1];
					
					$GLOBALS['db']->Query("UPDATE " . PREFIX . "_shop_kategorie_zubehoer 
					SET 
						$q1 
						$q2 
						$q3 
						Kategorie = '" . $_POST['id'][$id] . "' 
					WHERE 
						Id = '$id'
					");
					Logger('User ' . $_SESSION['user_name'] . ' update Shop-Addon-Category', '3', $_SESSION['benutzer_id']);
				}
			}
			
			$addons = array();
			
			$LC = (isset($_REQUEST['lc']) && !empty($_REQUEST['lc'])) ? $_REQUEST['lc'] : 1;
			
			$sql = $GLOBALS['db']->Query("SELECT 
				Id,
				Kategorie,
				Teile_1_name_{$LC} AS Teile_1_Name_1,
				Teile_2_name_{$LC} AS Teile_2_Name_1,
				Teile_3_name_{$LC} AS Teile_3_Name_1 
			 FROM " . PREFIX . "_shop_kategorie_zubehoer ORDER BY Id DESC");
			while($row = $sql->fetchrow())
			{
				$row->CategInfo = $this->getCategInfo($row->Kategorie);
				$categs_used[] = $row->CategInfo->Id;
				array_push($addons, $row);
			}
			
			$GLOBALS['tmpl']->assign('title', $GLOBALS['config_vars']['Shop_CategoriesAddons']); 
			$GLOBALS['tmpl']->assign('error', ((count($error) > 0 && !empty($error)) ? $error : '')); 
			$GLOBALS['tmpl']->assign('categ_addons', $addons);
			$GLOBALS['tmpl']->assign('categs_used', $categs_used);
			$GLOBALS['tmpl']->assign('lc',$LC);
			$GLOBALS['tmpl']->assign('shop_search_small_categs', $this->get_shop_categs_simple(0, '', $scategs, $area, 0, 1));
			$GLOBALS['tmpl']->assign('content', $GLOBALS['tmpl']->fetch($GLOBALS['config']['source'] . '/shop/categories_addons.tpl'));
		} else {
			no_perm();
		}
	}
	
	function getCategInfo($id)
	{
		$res = $GLOBALS['db']->RowQuery("SELECT Name_1 AS Name,Id FROM " . PREFIX . "_shop_kategorie WHERE Id = '$id'");
		return $res;
	}
	
	function getUstELements()
	{
		$items = array();
		$sql = $GLOBALS['db']->Query("SELECT * FROM " . PREFIX . "_shop_ustzone ORDER BY Id ASC");
		while($row = $sql->fetchrow())
		{
			array_push($items, $row);
		}
		return $items;
	}
	
	
	//=================================================================
	// Staffelpreise
	//=================================================================
	function getStprices($id)
	{
		if(!perm('shop_stprices'))
		{
			no_perm();
		} else {
			//=================================================================
			// Speichern (Aktualisieren)
			//=================================================================
			if(isset($_REQUEST['save']) && $_REQUEST['save'] == 1)
			{
				$count = 1;
				if(isset($_POST['Id']) && $_POST['Id'] >= 1)
				{
					foreach($_POST['Id'] as $sid => $key)
					{
						$Von = ($_POST['Von'][$sid] == 1 || $_POST['Von'][$sid] < 2 || $_POST['Von'][$sid] == '') ? 2 : $_POST['Von'][$sid];
						$Bis = ($_POST['Bis'][$sid] <= $Von) ? $Von + 1 : $_POST['Bis'][$sid];
						$Prozent = $_POST['Prozent'][$sid];
						$GLOBALS['db']->Query("UPDATE " . PREFIX . "_shop_staffelpreise SET Von = '{$Von}', Bis = '{$Bis}', Prozent = '{$Prozent}' WHERE Id = '{$sid}'");
						$count++;
					}
				}
				//=================================================================
				// Neuer Staffelpreis
				//=================================================================
				if(!empty($_POST['VonNeu']) && !empty($_POST['BisNeu']) && !empty($_POST['ProzentNeu']))
				{
					$von = $_POST['VonNeu'];
					$bis = $_POST['BisNeu'];
					$prozent = $_POST['ProzentNeu'];
					$GLOBALS['db']->Query("INSERT INTO " . PREFIX . "_shop_staffelpreise (Id,ArtikelId,Von,Bis,Prozent) VALUES ('','$id','$von','$bis','$prozent')");
				}
				
				//=================================================================
				// Loeschen
				//=================================================================
				if(isset($_POST['Del']) && $_POST['Del'] >= 1)
				{	
					foreach($_POST['Del'] as $did => $key)
					{
						$GLOBALS['db']->Query("DELETE FROM " . PREFIX . "_shop_staffelpreise WHERE Id = '{$did}'");
						Logger('User ' . $_SESSION['user_name'] . ' delete Relay price', '3', $_SESSION['benutzer_id']);
					}
				}
				Logger($_SESSION['user_name'] . ' update Relay price', '3', $_SESSION['benutzer_id']);
			}
			
			$stprices = array();
			$sql = $GLOBALS['db']->Query("SELECT * FROM " . PREFIX . "_shop_staffelpreise WHERE ArtikelId = '{$id}' ORDER BY Von ASC");
			while($row = $sql->fetcharray())
			{
				array_push($stprices, $row);
			}
			$GLOBALS['tmpl']->assign('stprices', $stprices);
			$GLOBALS['tmpl']->assign('title', $GLOBALS['config_vars']['Shop_articles_stprices']); 
			$GLOBALS['tmpl']->assign('content', $GLOBALS['tmpl']->fetch($GLOBALS['config']['source'] . '/shop/article_strprices.tpl'));
		}
	}
	
	//=================================================================
	// Bestellungen listen
	//=================================================================
	function listOrders()
	{
		$GLOBALS['tmpl']->assign('orders', $this->getOrders());
		$GLOBALS['tmpl']->assign('StartDate', mktime(0,0,1,date('m')-1,date('d'), date('Y')) ); 
		$GLOBALS['tmpl']->assign('title', $GLOBALS['config_vars']['Shop_title_orders']); 
		$GLOBALS['tmpl']->assign('content', $GLOBALS['tmpl']->fetch($GLOBALS['config']['source'] . '/shop/orders.tpl'));
	}
	
	//=================================================================
	// Artikel anzeigen
	//=================================================================
	function listArticles()
	{
		$GLOBALS['tmpl']->assign('articles', $this->getArticles());
		$GLOBALS['tmpl']->assign('title', $GLOBALS['config_vars']['Shop_title_articles']); 
		$GLOBALS['tmpl']->assign('content', $GLOBALS['tmpl']->fetch($GLOBALS['config']['source'] . '/shop/articles.tpl'));
	}
	
	//=================================================================
	// Varianten fuer einen Artikel
	//=================================================================
	function getVariants($id,$categ)
	{
		if(!perm('shop_variants'))
		{
			no_perm();
		} else {
			//=================================================================
			// Speichern
			//=================================================================
		
			if(isset($_REQUEST['save']) && $_REQUEST['save'] == 1 /*&& isset($_POST['Id']) && $_POST['Id']>0*/)
			{
				
				if(isset($_POST['Del']) && $_POST['Del'] >= 1)
				{
					foreach($_POST['Del'] as $del => $key)
					{
						$GLOBALS['db']->Query("DELETE FROM " . PREFIX ."_shop_varianten WHERE Id = '{$del}'");
						Logger($_SESSION['user_name'] . ' delete Article-Variant', '3', $_SESSION['benutzer_id']);
					}
				}
				
				//=================================================================
				// Vorhandene speichern
				//=================================================================
				if(isset($_POST['Id']))
				{
					foreach($_POST['Id'] as $vid => $key)
					{
						if(!empty($_POST['Name_1'][$vid]))
						{
							$sql = "UPDATE " . PREFIX ."_shop_varianten SET 
								Vorselektiert = '0',
								Name_1 = '" . koobispecialchars($_POST['Name_1'][$vid]) . "',
								Name_2 = '" . ((!empty($_POST['Name_2'][$vid])) ? koobispecialchars($_POST['Name_2'][$vid]) : koobispecialchars($_POST['Name_1'][$vid])) . "',
								Name_3 = '" . ((!empty($_POST['Name_3'][$vid])) ? koobispecialchars($_POST['Name_3'][$vid]) : koobispecialchars($_POST['Name_1'][$vid])) . "',
								Operant = '" . $_POST['Operant'][$vid] . "',
								Wert = '" . $this->priceClean($_POST['Wert'][$vid]) . "',
								Position = '" . $_POST['Position'][$vid] . "',
								Gewicht = '" . $_POST['Gewicht'][$vid] . "'
							WHERE Id = '" . $vid. "'";
							$GLOBALS['db']->Query($sql);
						}
					}
				}
				
				
				//=================================================================
				// Vorselektion speichern
				//=================================================================
				if(isset($_POST['Vor']))
				{
					foreach(@$_POST['Vor'] as $vor => $key)
					{
						$sql = "UPDATE " . PREFIX ."_shop_varianten SET Vorselektiert = '1' WHERE Id = '" . $key . "'";
						$GLOBALS['db']->Query($sql);
					}
				}
				//=================================================================
				// Neue Varianten
				//=================================================================
				foreach(@$_POST['NewName'] as $neu => $key)
				{
					if(!empty($key))
					{
						$key = koobispecialchars($key);
						$sql = "INSERT INTO " . PREFIX ."_shop_varianten (Id,KatId,ArtId,Name_1,Name_2,Name_3,Operant,Wert,Gewicht,Position) VALUES ('','$neu','$_REQUEST[id]','$key','$key','$key','" . $_POST['NewOperant'][$neu] . "','" . $this->priceClean($_POST['WertNeu'][$neu]) . "','" . $_POST['GewichtNeu'][$neu] . "','" . $_POST['PositionNeu'][$neu] . "')";
						$GLOBALS['db']->Query($sql);
						Logger($_SESSION['user_name'] . ' add a new Article-Variant: ' . $key , '3', $_SESSION['benutzer_id']);
					}
				}
			}
			
			//=================================================================
			// Auslesen
			//=================================================================
			$GLOBALS['tmpl']->assign('variant_categs', $this->listVariantCategs($id,$categ));
			$GLOBALS['tmpl']->assign('title', $GLOBALS['config_vars']['Shop_variants']); 
			$GLOBALS['tmpl']->assign('content', $GLOBALS['tmpl']->fetch($GLOBALS['config']['source'] . '/shop/article_variants.tpl'));
		}
	}
	
	//=================================================================
	// Varianten-Array
	//=================================================================
	function listVariantCategs($id,$categ)
	{
		$Lc = $_SESSION['AdminLangcode'];
		$variants = array();
		$sql = $GLOBALS['db']->Query("SELECT Id,KatId,Name_1,Name_2,Name_3, Beschreibung_{$Lc} AS Beschreibung FROM " . PREFIX ."_shop_varianten_kategorien WHERE KatId = '{$categ}' ORDER BY Position ASC"); 
		while($row = $sql->fetcharray())
		{
			$vars = array();
			$sql_v = $GLOBALS['db']->Query("SELECT Id,KatId,Name_1,Name_2,Name_3,Wert,Position,Vorselektiert,Gewicht,Operant FROM " . PREFIX ."_shop_varianten WHERE ArtId = '{$id}' AND KatId = '" . $row['Id'] . "' ORDER BY Position ASC"); 
			while($row_v = $sql_v->fetcharray())
			{
				array_push($vars,$row_v);
			}
			$row['vars'] = $vars;
			array_push($variants,$row);
		}
		return $variants;
	}
	
	//=================================================================
	// Artikel loeschen
	//=================================================================
	function deleteArticle($id)
	{
		if(perm('shop_delete') && KOOBIDEMO!=1)
		{
			
			$GLOBALS['db']->Query("DELETE FROM " . PREFIX . "_shop_varianten WHERE ArtId = '$id'");
			$GLOBALS['db']->Query("DELETE FROM " . PREFIX . "_shop_preisalarm WHERE ProdId = '$id'");
			$GLOBALS['db']->Query("DELETE FROM " . PREFIX . "_shop_downloads WHERE ArtId = '$id'");
			$GLOBALS['db']->Query("DELETE FROM " . PREFIX . "_shop_bewertung WHERE Produkt = '$id'");
			$GLOBALS['db']->Query("DELETE FROM " . PREFIX . "_shop_produkte WHERE Id='$id'");
			Logger('User ' . $_SESSION['user_name'] . ' delete Shop-Product', '3', $_SESSION['benutzer_id']);	
		}
		echo '<script language="javascript">window.opener.location.reload();window.close()</script>';
	}
	
	//=================================================================
	// Artikel kopieren
	//=================================================================
	function copyArticle($id)
	{
		if(perm('shop_copyarticle'))
		{
			$error = '';
			
			if(isset($_POST['copy']) && $_POST['copy']==1)
			{
				if(empty($_POST['Artikelnummer'])) 
				{
					$error[] = $GLOBALS['config_vars']['Shop_articles_copyEN'];
				} else {
					$_POST['Artikelnummer'] = trim(eregi_replace('[^-A-Za-zÀ-ÖØ-öø-ÿ0-9_]', '', $_REQUEST['Artikelnummer']));
				
					$row = $GLOBALS['db']->RowQuery("SELECT Id FROM " . PREFIX . "_shop_produkte WHERE Artikelnummer='" . $_POST['Artikelnummer'] . "'");
					if(is_object($row)) 
					{
						$error[] = $GLOBALS['config_vars']['Shop_articles_copyEE'];
					} else {
						$qsql = $GLOBALS['db']->Query("SELECT * FROM " . PREFIX . "_shop_produkte WHERE Id='$id'");
						$erg = $qsql->fetchrow();
						$serg = '';
						foreach($erg as $i => $fid)
						{
							$fid = addslashes($fid);
							switch($i)
							{
								case 'Artikelnummer':$fid=$_POST['Artikelnummer']; break;
								case 'Titel_1':$fid=$_POST['Titel_1']; break;
								case 'Titel_2':$fid=$_POST['Titel_1']; break;
								case 'Titel_3':$fid=$_POST['Titel_1']; break;
							}
							$serg .= "". ($i=='Id') ? "''" :",'$fid'"; 
						}
						
						$query = $GLOBALS['db']->Query("INSERT INTO " . PREFIX . "_shop_produkte VALUES (" . $serg . ")");
						$Iid   = $GLOBALS['db']->InsertId();
						Logger($_SESSION['user_name'] . ' copy Article: ' . $erg->Titel_1 , '3', $_SESSION['benutzer_id']);
						
						if(isset($_POST['edit_new']) && $_POST['edit_new']==1)
						{
							echo "<script language='javascript'>var Fenster = null;
								function popup(meineSeite,meinName,w,h,scroll)
								{
									LeftPosition = (screen.width) ? (screen.width-w)/2 : 0;
									TopPosition = (screen.height) ? (screen.height-h)/2 : 0;
									settings =
									'height='+h+',width='+w+',top='+TopPosition+',left='+LeftPosition+',scrollbars='+scroll+',resizable'
									Fenster = window.open(meineSeite,meinName,settings)
								}</script>";
							echo "<script language='javascript'>popup('?do=shop&sub=edit_article&id=" . $Iid . "&noframes=1&langcode=1&closeafter=1', 'edit_new','800','600','yes');</script>";
							echo '<script language="javascript">window.opener.location.reload();window.close()</script>';
						} else {
							echo '<script language="javascript">window.opener.location.reload();window.close()</script>';
						}
                       
					}
				}
				$GLOBALS['tmpl']->assign('error', $error);
				
			}
			
			$row = $GLOBALS['db']->RowQuery("SELECT Titel_1, Id FROM " . PREFIX . "_shop_produkte WHERE Id='$id'");
			
			
			$GLOBALS['tmpl']->assign('row', $row);
			$GLOBALS['tmpl']->assign('title', $GLOBALS['config_vars']['Shop_articles_copy']); 
			$GLOBALS['tmpl']->assign('content', $GLOBALS['tmpl']->fetch($GLOBALS['config']['source'] . '/shop/article_copy.tpl'));
		}
	}
	
	
	//=================================================================
	// Artikel bearbeiten
	//=================================================================
	function editArticle($id)
	{
		$Bild = '';
		$scategs = array();
		if(!perm('shop_articleedit'))
		{
			no_perm();
		} else {
			$base = substr($_SERVER['PHP_SELF'],0,-15);
			$Lc = (isset($_REQUEST['langcode']) && !empty($_REQUEST['langcode'])) ? $_REQUEST['langcode'] : 1;
			
			// Speichern
			if(isset($_REQUEST['save']) && $_REQUEST['save'] == 1)
			{
				if(perm('shop_images'))
				{
					$Bild = (isset($_POST['newImg_1']) && !empty($_POST['newImg_1'])) ? $_POST['newImg_1'] : '';
				}
				
				
				$text = $_REQUEST['Beschreibung'];
				$text = str_replace('src=\"' . $base, 'src=\"%%ECRUOS_GMI_IBOOK%%', $text);
				
				$text2 = $_REQUEST['Beschreibung2'];
				$text2 = str_replace('src=\"' . $base, 'src=\"%%ECRUOS_GMI_IBOOK%%', $text2);
				
				
				$Preis_Liste = str_replace(',','.', @$_POST['Preis_Liste']);
				$Preis = str_replace(',','.',@ $_POST['Preis']);
				$Preis = ($Preis >= $Preis_Liste) ? 0 : $Preis;
				$Preis_Liste = ($Preis_Liste < '0.01') ? '0.99' : $Preis_Liste;
				$plg   = explode('.', @$_POST['Preis_Liste_Gueltig']);
				$Preis_Liste_Gueltig = ($Preis < '0.01' || $Preis >= $Preis_Liste) ? '0' :  mktime(23,49,59,$plg[1],$plg[0],$plg[2]);
				$Kategorie_Multi = @implode(',', $_POST['Kategorie_Multi']);
				$Artikelnummer = (isset($_POST['Artikelnummer']) && !empty($_POST['Artikelnummer']) && $this->notExists($_POST['Artikelnummer'])) ? "Artikelnummer = '" . $this->cleanArtNr($_POST['Artikelnummer']) . "',"  : "";
				$Titel = (isset($_POST['Titel']) && !empty($_POST['Titel'])) ? "Titel_{$Lc} = '" . koobispecialchars($_POST['Titel']) . "'," : "";
				$ProdBild = (!empty($Bild)) ? "Bild = '$Bild'," : "";
				$BilderMulti = $this->upload_multi();
				$Bilder = (!empty($BilderMulti)) ? "Bilder = '" . $BilderMulti . "',": "";
				
				//=================================================================
				// Selektierte Bilder loeschen...
				//=================================================================
				if(isset($_POST['Loeschen']) && !empty($_POST['Loeschen']))
				{
					$MultiArray = explode('|',$BilderMulti);
					foreach($_POST['Loeschen'] as $bid)
					{
						if (false !== ($key = array_search($bid,$MultiArray)))
						{
							unset($MultiArray[$key]);
						}
						
						@unlink(BASE_DIR . '/uploads/shop/icons/' . $bid);
						@unlink(BASE_DIR . '/uploads/shop/icons_thumbnails/xsmall/' . $bid);
						@unlink(BASE_DIR . '/uploads/shop/icons_thumbnails/small/' . $bid);
						@unlink(BASE_DIR . '/uploads/shop/icons_thumbnails/medium/' . $bid);
						@unlink(BASE_DIR . '/uploads/shop/icons_thumbnails/normal/' . $bid);
						@unlink(BASE_DIR . '/uploads/shop/icons_thumbnails/big/' . $bid);
					}
					$BilderMulti = implode('|', $MultiArray);
					$Bilder =  "Bilder = '" . $BilderMulti . "',";
				}
				
				$DB_Spez = '';
				$SetAll = '';
				//=================================================================
				// Spezifikationen speichern
				//=================================================================
				for($i=1;$i<=15;$i++) 
				{
					$DB_Spez .= "Spez_{$i} = '" . @$_POST['Spez_' . $i] . "',";
				}
				
				$Zub_a = "Zub_a = '',";
				$Zub_b = "Zub_b = '',";
				$Zub_c = "Zub_c = '',";
				
				// Zubehoer
				if(isset($_POST['prods']) && !empty($_POST['prods']))
				{
					$p = $_POST['prods'];
					$x = array_unique($p);
					$x = implode(',',$x);
					$Zub_a = "Zub_a = '$x',";
				}
				
				// Ersatzteile
				if(isset($_POST['ersatzteile']) && !empty($_POST['ersatzteile']))
				{
					$p = $_POST['ersatzteile'];
					$x = array_unique($p);
					$x = implode(',',$x);
					$Zub_b = "Zub_b = '$x',";
				}
				
				// Tuningteile
				if(isset($_POST['tuningteile']) && !empty($_POST['tuningteile']))
				{
					$p = $_POST['tuningteile'];
					$x = array_unique($p);
					$x = implode(',',$x);
					$Zub_c = "Zub_c = '$x',";
				}
				
				//=================================================================
				// Datensatz aktualisieren
				//=================================================================
				if($_REQUEST['langcode'] > 1)
				{
					// Spez
					$DB_Spez = '';
					$DB_Spez2 = '';
					$DB_Spez3 = '';
					
					$Lc = $_REQUEST['langcode'];
					for($i=1;$i<=15;$i++) 
					{
						$DB_Spez .= "Spez_{$i}_{$Lc} = '" . @$_POST['Spez_' . $i] . "',";
					}
					$GLOBALS['db']->Query("UPDATE " . PREFIX ."_shop_produkte SET 
								$DB_Spez
								$Titel 
								Beschreibung_{$Lc} = '{$text}',
								Beschreibung_lang_{$Lc} = '{$text2}'
						WHERE Id = '$_REQUEST[id]'");	
				} else {
					if(isset($_POST['saveAllLang']) && $_POST['saveAllLang']==1)
					{
						for($i=1;$i<=15;$i++) 
						{
							$DB_Spez2 .= ",Spez_{$i}_2 = '" . @$_POST['Spez_' . $i] . "'";
							$DB_Spez3 .= ",Spez_{$i}_3 = '" . @$_POST['Spez_' . $i] . "'";
						}
					
						$SetAll = "
							{$DB_Spez2} 
							{$DB_Spez3} 
							,Titel_2 = '" . koobispecialchars($_POST['Titel']) . "'
							,Beschreibung_2 = '{$text}'
							,Beschreibung_lang_2 = '{$text2}'
							,Titel_3 = '" . koobispecialchars($_POST['Titel']) . "'
							,Beschreibung_3 = '{$text}'
							,Beschreibung_lang_3 = '{$text2}'
							";
					}
					
					$Bestellt = (isset($_POST['Bestellt']) && $_POST['Bestellt']==1) ? 1 : 0;
					$GLOBALS['db']->Query("UPDATE " . PREFIX ."_shop_produkte SET 
							$Zub_a 
							$Zub_b 
							$Zub_c 
							$DB_Spez 
							$Artikelnummer 
							$Titel 
							$ProdBild 
							$Bilder 
							Lieferzeit = '" . $_POST['Lieferzeit'] . "', 
							Bestellt = '$Bestellt',
							Beschreibung_{$Lc} = '{$text}',
							Beschreibung_lang_{$Lc} = '{$text2}',
							Aktiv = '$_POST[Aktiv]',
							Preis_Liste_Gueltig = '{$Preis_Liste_Gueltig}',
							Preis_Liste = '{$Preis_Liste}',
							Preis = '{$Preis}',
							Hersteller = '$_REQUEST[Hersteller]',
							Kategorie = '$_REQUEST[Kategorie]',
							Kategorie_Multi = '{$Kategorie_Multi}',
							Gewicht = '" . $this->cleanNum($_POST['Gewicht']) . "',
							Gewicht_Ohne = '" . $this->cleanNum($_POST['Gewicht_Ohne']) . "',
							Abmessungen = '" . @$_POST['Abmessungen'] . "',
							Schlagwoerter = '" . trim($_POST['Schlagwoerter']) . "',
							EinheitCount = '" . str_replace(',','.', $_POST['EinheitCount']) . "',
							EinheitId = '$_POST[EinheitId]',
							Lagerbestand = '" . $this->cleanNum($_POST['Lagerbestand']) . "',
							Verfuegbar = '$_POST[Verfuegbar]',
							EinzelBestellung = '$_POST[EinzelBestellung]',
							MinBestellung = '" . trim($_POST['MinBestellung']) . "',
							MaxBestellung = '" . trim($_POST['MaxBestellung']) . "',
							Startseite = '" . $_POST['Startseite'] . "',
							Fsk18 = '" . $_POST['Fsk18'] . "' 
							{$SetAll} 
					WHERE Id = '$_REQUEST[id]'");
					
					//=================================================================
					// Preisalarm
					//=================================================================
					$Preis_Alt   = str_replace(',','.', @$_POST['Preis_Alt']);
					$Preis_Neu   = $Preis_Liste;
					$Angebot_Alt = str_replace(',','.', @$_POST['Angebot_Alt']);
					$Angebot_Neu = $Preis;
					
					if( ($Preis_Neu < $Preis_Alt) || ($Angebot_Neu < $Angebot_Alt) || ($Angebot_Alt<'0.01' && $Angebot_Neu>'0.01') )
					{
						$p_lim = '';
						if($Preis_Neu < $Preis_Alt) $p_lim = $Preis_Neu;
						if($Angebot_Neu < $Angebot_Alt && $Angebot_Neu > '0.01') $p_lim = $Angebot_Neu;
						if($Angebot_Alt<'0.01' && $Angebot_Neu>'0.01') $p_lim = $Angebot_Neu;
						
						if($p_lim>'0.0.1') 
						{
							$Koobi = new Koobi;
							$subject_text = $GLOBALS['config_vars']['Shop_Settings_AlertSubject'];
							
							$link = explode('admin/', redir());
							$link = $link[0] . 'index.php?p=shop&action=showproduct&id=' . $_REQUEST['id'] . '&cid=' . $_REQUEST['Kategorie'];
			
							$sql = $GLOBALS['db']->Query("SELECT * FROM " . PREFIX . "_shop_preisalarm WHERE ProdId='$_REQUEST[id]' AND Preis>='$p_lim'");
							while($row=$sql->fetchrow())
							{
								$text = $GLOBALS['config_vars']['Shop_settings_AlertText'];
								$text = str_replace('__PRODUCT__', koobispecialchars($_POST['Titel']), $text);
								$text = str_replace('__OLD__', number_format($Preis_Alt,2,'.',''), $text);
								$text = str_replace('__NEW__', number_format($p_lim,2,'.',''), $text);
								$text = str_replace('__LINK__', $link, $text);
								$text = str_replace('__CURRENCY__', $GLOBALS['shop_settings']['Waehrung_1'], $text);
								$Koobi->koobi_mail($row->Email, $text, $subject_text, $GLOBALS['shop_settings']['Email_Abs'], $GLOBALS['shop_settings']['Name_Abs'], 'text', '');	
								
								$GLOBALS['db']->Query("DELETE FROM " . PREFIX . "_shop_preisalarm WHERE ProdId='$_REQUEST[id]' AND Email='$row->Email'");	
							}
						}
					}
					// Preialarm Ende
					
					
				}
				
				Logger($_SESSION['user_name'] . ' save Article: ' . koobispecialchars($_POST['Titel']) , '3', $_SESSION['benutzer_id']);
				if(isset($_REQUEST['closeafter']) && $_REQUEST['closeafter']==1)
				{
					echo '<script language="javascript">window.close()</script>';
				} else {
					echo '<script language="javascript">window.opener.location.reload();</script>';
				}
			}
			
			$db_f = '';
			if($_REQUEST['langcode']>1)
			{
				$Lc = $_REQUEST['langcode'];
				for($i=1;$i<=15;$i++) 
				{
					$db_f .= "Spez_{$i}_{$Lc} AS Spez_{$i},
					";
				}
			}
			$row = $GLOBALS['db']->ArrQuery("SELECT 
				*, 
				$db_f 
				Titel_{$Lc} AS Titel, 
				Beschreibung_{$Lc} AS Beschreibung, 
				Beschreibung_lang_{$Lc} AS BeschreibungLang 
			FROM " . PREFIX ."_shop_produkte WHERE Id = '{$id}'");
			
			$row['Beschreibung'] = str_replace('%%ECRUOS_GMI_IBOOK%%', $base, $row['Beschreibung']);
			$row['BeschreibungLang'] = str_replace('%%ECRUOS_GMI_IBOOK%%', $base, $row['BeschreibungLang']);
			$row['Kategorie_Multi'] = explode(',', $row['Kategorie_Multi']);
			$row['Bild_Norm'] = (is_file(BASE_DIR . '/' . $this->_upload_path . 'normal/' . $row['Bild'])) ? "<img src='../" . $this->_upload_path . "normal/" . $row['Bild'] . "' alt=''  />" : "<img src='../system/shopthumb.php?smode=2&amp;img=" . $row['Bild'] . "' alt='' />";
			$row['Bild_Alt'] = $row['Bild'];
			
			if($row['Bilder'] != '')
			{
				$Bilder_Klein = array();
				$bilder = explode('|', $row['Bilder']);
				foreach($bilder as $bild)
				{
					$arr['BildId'] = $bild;
					$arr['Bild'] = (is_file(BASE_DIR . '/' . $this->_upload_path . 'normal/' . $bild)) ? '<img src="../' . $this->_upload_path . 'normal/' . $bild . '" alt="" />' : '<img src="../system/shopthumb.php?smode=2&amp;img=' . $bild . '" alt="" />';
					if(!empty($bild)) array_push($Bilder_Klein, $arr);
				}
				$GLOBALS['tmpl']->assign('Bilder',$Bilder_Klein);
			} else {
				$row['Bilder'] = '';
			}
			
			$spez = $GLOBALS['db']->ArrQuery("SELECT * FROM " . PREFIX . "_shop_kategorie_spezifikation WHERE Kategorie = '" . $row['Kategorie'] . "'");
			if(is_array($spez))
			{
				for($i=1;$i<=15;$i++) 
				{
					$GLOBALS['tmpl']->assign('Spez_Def_' . $i, $spez['Spez_' . $i]);
					$GLOBALS['tmpl']->assign('Spez_' . $i, stripslashes($row['Spez_' . $i]));
				}
			} else {
				$GLOBALS['tmpl']->assign('nospez', 1);
			}
			
			$categs_shop = array();
			
			
			$Tabs = $GLOBALS['db']->RowQuery("
			SELECT 
				Teile_1_Name_{$Lc} AS TAB1,
				Teile_2_Name_{$Lc} AS TAB2,
				Teile_3_Name_{$Lc} AS TAB3 
			FROM " . PREFIX . "_shop_kategorie_zubehoer WHERE Kategorie = '" . $row['Kategorie'] ."'");

			$GLOBALS['tmpl']->assign('tabs',$Tabs);
			
			
			$GLOBALS['tmpl']->assign('text', fckInit($row['Beschreibung'], 'Beschreibung', 150, 'Basic'));
			$GLOBALS['tmpl']->assign('text2', fckInit($row['BeschreibungLang'], 'Beschreibung2', 350, 'Shop'));
			$GLOBALS['tmpl']->assign('shipping_time', $this->TimeTillShipping());
			$GLOBALS['tmpl']->assign('row', $row);
			$GLOBALS['tmpl']->assign('ass', explode(',',$row['Zub_a']));
			$GLOBALS['tmpl']->assign('units', $this->getUnits());
			$GLOBALS['tmpl']->assign('categs_ass', $this->get_all_categs(0,$categs_shop));
			$GLOBALS['tmpl']->assign('manufaturer', $this->listManufaturer());
			$GLOBALS['tmpl']->assign('available', $this->getAvailabilities());
			$GLOBALS['tmpl']->assign('zub', $this->getProdsByZub($row['Zub_a']));
			$GLOBALS['tmpl']->assign('ers', $this->getProdsByZub($row['Zub_b']));
			$GLOBALS['tmpl']->assign('tun', $this->getProdsByZub($row['Zub_c']));
			$GLOBALS['tmpl']->assign('shop_search_small_categs', $this->get_shop_categs_simple(0, '', $scategs, $area, 0, 1));
			$GLOBALS['tmpl']->assign('content', $GLOBALS['tmpl']->fetch($GLOBALS['config']['source'] . '/shop/article_edit.tpl'));
		}
	}
	
	//=================================================================
	// Artikel neu
	//=================================================================
	function addArticle()
	{
		if(perm('shop_articlenew'))
		{
			if(isset($_POST['new']) && $_POST['new']==1)
			{
				// Artikelnummer-Pruefung
				$an    = strtolower(trim($_POST['Artikelnummer']));
				$check = $GLOBALS['db']->RowQuery("SELECT Artikelnummer FROM " . PREFIX . "_shop_produkte WHERE Artikelnummer = '$an'");
				$an    = (is_object($check) && $an == strtolower($check->Artikelnummer)) ? $this->DigitRandom(8) : $this->cleanArtNr(trim($_POST['Artikelnummer']));
				
				$plg   = explode('.', $_POST['Preis_Liste_Gueltig']);
				$base  = substr($_SERVER['PHP_SELF'],0,-15);
				$text  = str_replace('src=\"' . $base, 'src=\"%%ECRUOS_GMI_IBOOK%%', $_REQUEST['Beschreibung']);
				$text2 = str_replace('src=\"' . $base, 'src=\"%%ECRUOS_GMI_IBOOK%%', $_REQUEST['Beschreibung2']);
				$Preis_Liste = str_replace(',','.', $_POST['Preis_Liste']);
				$Preis = str_replace(',','.', $_POST['Preis']);
				$Preis = ($Preis >= $Preis_Liste) ? 0 : $Preis;
				$Preis_Liste = ($Preis_Liste < '0.01') ? '0.99' : $Preis_Liste;
				$Preis_Liste_Gueltig = ($Preis < '0.01' || $Preis >= $Preis_Liste) ? '0' :  mktime(23,49,59,$plg[1],$plg[0],$plg[2]);
				$Bild        = (!empty($_POST['newImg_1'])) ? $_POST['newImg_1'] : '';
				
				
				$q = "INSERT INTO " . PREFIX . "_shop_produkte 
				(
					Id,
					Kategorie,
					Kategorie_Multi,
					Schlagwoerter,
					Artikelnummer,
					Preis,
					Preis_Liste,
					Preis_Liste_Gueltig,
					Titel_1,
					Titel_2,
					Titel_3,
					Beschreibung_1,
					Beschreibung_2,
					Beschreibung_3,
					Beschreibung_lang_1,
					Beschreibung_lang_2,
					Beschreibung_lang_3,
					Aktiv,
					Erstellt,
					Bild,
					Gewicht,
					Hersteller,
					EinheitCount,
					EinheitId,
					Startseite,
					Lagerbestand,
					Bestellt,
					Verfuegbar,
					EinzelBestellung,
					MaxBestellung,
					MinBestellung,
					Lieferzeit,
					Gewicht_Ohne,
					Abmessungen,
					Fsk18
				) VALUES (
					'',
					'" . $_POST['Kategorie'] . "',
					'" . @implode(',',$_POST['Kategorie_Multi']) . "',
					'" . $_POST['Schlagwoerter'] . "',
					'$an',
					'" . $Preis . "',
					'" . $Preis_Liste . "',
					'" . $Preis_Liste_Gueltig . "',
					'" . trim($_POST['Titel']) . "',
					'" . trim($_POST['Titel']) . "',
					'" . trim($_POST['Titel']) . "',
					'" . $text . "',
					'" . $text . "',
					'" . $text . "',
					'" . $text2 . "',
					'" . $text2 . "',
					'" . $text2 . "',
					'" . $_POST['Aktiv'] . "',
					'" . stime() . "',
					'" . $Bild . "',
					'" . $_POST['Gewicht'] . "',
					'" . $_POST['Hersteller'] . "',
					'" . str_replace(',','.',$_POST['EinheitCount']) . "',
					'" . $_POST['EinheitId'] . "',
					'" . $_POST['Startseite'] . "',
					'" . $_POST['Lagerbestand'] . "',
					'" . @$_POST['Bestellt'] . "',
					'" . $_POST['Verfuegbar'] . "',
					'" . @$_POST['EinzelBestellung'] . "',
					'" . $_POST['MaxBestellung'] . "',
					'" . $_POST['MinBestellung'] . "',
					'" . $_POST['Lieferzeit'] . "',
					'" . $_POST['Gewicht_Ohne'] . "',
					'" . $_POST['Abmessungen'] . "',
					'" . $_POST['Fsk18'] . "' 
				)";
				$res = $GLOBALS['db']->Query($q);
				$iid = $GLOBALS['db']->InsertId();
				
				Logger($_SESSION['user_name'] . ' add new Article: ' . koobispecialchars($_POST['Titel']) , '3', $_SESSION['benutzer_id']);
				
				$BilderMulti = $this->upload_multi($iid);
				$GLOBALS['db']->Query("UPDATE " . PREFIX . "_shop_produkte SET Bilder = '" . $BilderMulti . "' WHERE Id = '" . $iid . "'");
				
				echo '<script type="text/javascript">
				Check = confirm("'.$GLOBALS['config_vars']['Shop_confirmed_editafter'].'");
				if (Check == false)
				{
					window.opener.location.reload();
					window.close();
				} else {
					window.opener.location.reload();
					location.href=\'index.php?do=shop&sub=edit_article&id=' . $iid . '&noframes=1&langcode=1&pop=1\';
				};
				</script>';
				exit;
				
				// Eintrag
			}
			
			$base = substr($_SERVER['PHP_SELF'],0,-15);
			$Lc = (isset($_REQUEST['langcode']) && !empty($_REQUEST['langcode'])) ? $_REQUEST['langcode'] : 1;
			$_REQUEST['langcode'] = $Lc;
			$scategs = array();
			$categs_shop = array();
			
			
			$GLOBALS['tmpl']->assign('artnumber', $this->DigitRandom(8));
			$GLOBALS['tmpl']->assign('text', fckInit('', 'Beschreibung', 200, 'Basic'));
			$GLOBALS['tmpl']->assign('text2', fckInit('', 'Beschreibung2', 300, 'Shop'));
			$GLOBALS['tmpl']->assign('units', $this->getUnits());
			$GLOBALS['tmpl']->assign('shipping_time', $this->TimeTillShipping());
			$GLOBALS['tmpl']->assign('categs_ass', $this->get_all_categs(0,$categs_shop));
			$GLOBALS['tmpl']->assign('manufaturer', $this->listManufaturer());
			$GLOBALS['tmpl']->assign('available', $this->getAvailabilities());
			$GLOBALS['tmpl']->assign('shop_search_small_categs', $this->get_shop_categs_simple(0, '', $scategs, $area, 0, 1));
			$GLOBALS['tmpl']->assign('title', $GLOBALS['config_vars']['Shop_articles_addnew']);
			$GLOBALS['tmpl']->assign('content', $GLOBALS['tmpl']->fetch($GLOBALS['config']['source'] . '/shop/article_new.tpl'));
		}
	}
	
	//=================================================================
	// Produktbewertungen zaehlen
	//=================================================================
	function getVotes($prod)
	{
		$v = $GLOBALS['db']->RowQuery("SELECT COUNT(Id) AS Summe FROM " . PREFIX . "_shop_bewertung WHERE Produkt='$prod'");
		return $v->Summe;
	}
	
	//=================================================================
	// Produktbewertungen zaehlen
	//=================================================================
	function getProdVotes($prod)
	{
		if(perm('shop_votes'))
		{
			if(isset($_POST['save']) && $_POST['save']=='1')
			{
				if(isset($_POST['Bewertung']))
				{
					foreach($_POST['Bewertung'] as $id => $key)
					{
						$GLOBALS['db']->Query("UPDATE " . PREFIX . "_shop_bewertung SET 
							Bewertung = '" . $_POST['Bewertung'][$id] . "',
							Bewertung_Punkte = '" . $_POST['Bewertung_Punkte'][$id] . "',
							Offen = '" . $_POST['Offen'][$id] . "' 
						WHERE Id='$id'");
						if(isset($_POST['Del']) && $_POST['Del']>=1) $GLOBALS['db']->Query("DELETE FROM " . PREFIX . "_shop_bewertung WHERE Id = '$id'");
					}
				}
			}
			
			$votes = array();	
			$sql = $GLOBALS['db']->Query("SELECT * FROM " . PREFIX . "_shop_bewertung WHERE Produkt='$prod' ORDER BY Id DESC");
			while($row = $sql->fetchrow())
			{
				$row->BenutzerName = $this->getUser($row->Benutzer);
				array_push($votes,$row);
			}
			
			$GLOBALS['tmpl']->assign('votes', $votes);
			$GLOBALS['tmpl']->assign('title', $GLOBALS['config_vars']['Shop_prodvotes']);
			$GLOBALS['tmpl']->assign('content', $GLOBALS['tmpl']->fetch($GLOBALS['config']['source'] . '/shop/article_votes.tpl'));
		}
	}
	
	function getUser($user)
	{
		$res = $GLOBALS['db']->RowQuery("SELECT Benutzername FROM " . PREFIX . "_benutzer WHERE Id = '$user'");
		return $res->Benutzername;
	}
	
	//=================================================================
	// Artikel listen
	//=================================================================
	function getArticles()
	{
		$search_nav = '';
		$search_lager = '';
		$search_lager_nav = '';
		$search_status = '';
		$search_status_nav = '';
		$search_kategorie = '';
		$search_kategorie_nav = '';
		$search_verkauft_nav = '';
		$search_verkauft = '';
		$search_hersteller_nav = '';
		$search_hersteller = '';
		$search_preis_nav = '';
		$search_preis = '';
		$Lc = $_SESSION['AdminLangcode'];
		$xoutput = '';
		$filename = $GLOBALS['config_vars']['Shop_articles_exportname'];
		$format = 'csv';
		$articles = array();
		
		
		if(isset($_POST['multiaction']) && $_POST['multiaction']==1)
		{
			switch($_POST['Aktion'])
			{
				case 'updateamount':    $GLOBALS['db']->Query("UPDATE " . PREFIX . "_shop_produkte SET Lagerbestand = Lagerbestand+$_REQUEST[updatenewamount] $_SESSION[query_user]");break;
				case 'lagernull':   $GLOBALS['db']->Query("UPDATE " . PREFIX . "_shop_produkte SET Lagerbestand = '0' $_SESSION[query_user]");break;
				case 'setoffline':  $GLOBALS['db']->Query("UPDATE " . PREFIX . "_shop_produkte SET Aktiv= '0' $_SESSION[query_user]");break;
				case 'setonline':   $GLOBALS['db']->Query("UPDATE " . PREFIX . "_shop_produkte SET Aktiv= '1' $_SESSION[query_user]");break;
				case 'move':   $GLOBALS['db']->Query("UPDATE " . PREFIX . "_shop_produkte SET Kategorie= '$_REQUEST[Kategorie]' $_SESSION[query_user]");break;
				case '4':   $GLOBALS['db']->Query("UPDATE " . PREFIX . "_shop_produkte SET Verfuegbar = '4' $_SESSION[query_user]");break;
				case '3':   $GLOBALS['db']->Query("UPDATE " . PREFIX . "_shop_produkte SET Verfuegbar = '3',Lagerbestand = '0',Bestellt='0' $_SESSION[query_user]");break;
				case '2':   $GLOBALS['db']->Query("UPDATE " . PREFIX . "_shop_produkte SET Verfuegbar = '2',Lagerbestand = '0',Bestellt='1' $_SESSION[query_user]");break;
				case '1':   $GLOBALS['db']->Query("UPDATE " . PREFIX . "_shop_produkte SET Verfuegbar = '1',Lagerbestand = '99', Bestellt='0' $_SESSION[query_user]");break;
				
				case 'settoall':
					if(perm('shop_articleedit'))
					{
						$k = '';
						$sql = $GLOBALS['db']->Query("SELECT Spez_1,Spez_2,Spez_3,Spez_4,Spez_5,Spez_6,Spez_7,Spez_8,Spez_9,Spez_10,Spez_11,Spez_12,Spez_13,Spez_14,Spez_15,Id,Kategorie,Titel_1,Beschreibung_1,Beschreibung_lang_1 FROM " . PREFIX . "_shop_produkte $_SESSION[query_user]");
						while($row = $sql->fetchrow())
						{
							// Spezifikationen der Artikel aktualisieren
							$sp1 = '';
							$sp2 = '';
							for($i=1;$i<=15;$i++) $sp1  .= "Spez_{$i}_2 = Spez_{$i},";
							for($j=1;$j<=15;$j++) $sp2  .= "Spez_{$j}_3 = Spez_{$j},";
							
							// Artikel aktualisieren
							$q = "UPDATE " . PREFIX . "_shop_produkte 
							SET 
								$sp1 
								$sp2 
								Titel_2 = '$row->Titel_1', 
								Titel_3 = '$row->Titel_1',
								Beschreibung_2 = '$row->Beschreibung_1',
								Beschreibung_3 = '$row->Beschreibung_1',
								Beschreibung_lang_2 = '$row->Beschreibung_lang_1',
								Beschreibung_lang_3 = '$row->Beschreibung_lang_1' 
							WHERE Id = '$row->Id<br>'";
							$GLOBALS['db']->Query($q);
							$k[] = $row->Kategorie;
						}
						
						// Spezifikationen-Kategorien aktualisieren
						$k = array_unique($k);
						if(count($k) >= 1)
						{
							$cat_or = '';
							foreach($k as $id => $key)
							{
								if($id == '0') 
									$cat_or = " WHERE  Kategorie = '$key' ";
								else
									$cat_or .= "OR Kategorie = '$key' ";
							}
							
							$sf = '';
							$sff = '';
							for($i=1;$i<=15;$i++)
							{
								$sf  .= "Spez_$i,";
							}
							
							$g_temp = "SELECT $sf Id FROM " . PREFIX . "_shop_kategorie_spezifikation $cat_or";
							$sql_s = $GLOBALS['db']->Query($g_temp);
							while($row_s = $sql_s->fetcharray())
							{
								for($i=1;$i<=15;$i++)
								{
									$sff  .= "Spez_{$i}_2 = '" . $row_s['Spez_' . $i] . "',";
								}
								
								for($i2=1;$i2<=15;$i2++)
								{
									$sff  .= "Spez_{$i2}_3 = '" . $row_s['Spez_' . $i2] . "',";
								}
								
								$g_f = "UPDATE " . PREFIX . "_shop_kategorie_spezifikation 
								SET 
									$sff Id = $row_s[Id] 
								WHERE Id = '" . $row_s['Id'] . "'";
								$sff = '';
								$GLOBALS['db']->Query($g_f);
							}
						}
					}
				break;
				
				case 'delete': 
				if(defined('KOOBIDEMO')) $GLOBALS['tmpl']->assign('emsg', $GLOBALS['config_vars']['notindemo']);
				if(perm('shop_delete') && KOOBIDEMO!=1)
				{ 
					$q = $GLOBALS['db']->Query("SELECT * FROM " . PREFIX . "_shop_produkte $_SESSION[query_user]");
					while($r = $q->fetchrow())
					{
						$GLOBALS['db']->Query("DELETE FROM " . PREFIX . "_shop_produkte WHERE Id = '$r->Id'");
						$GLOBALS['db']->Query("DELETE FROM " . PREFIX . "_shop_varianten WHERE ArtId = '$r->Id'");
						$GLOBALS['db']->Query("DELETE FROM " . PREFIX . "_shop_preisalarm WHERE ProdId = '$r->Id'");
						$GLOBALS['db']->Query("DELETE FROM " . PREFIX . "_shop_downloads WHERE ArtId = '$r->Id'");
						$GLOBALS['db']->Query("DELETE FROM " . PREFIX . "_shop_bewertung WHERE Produkt = '$r->Id'");
					}
					$GLOBALS['db']->Query("DELETE FROM " . PREFIX . "_shop_produkte $_SESSION[query_user]");
				}
				break;
			}
		}
		
		// Artikelschnellspeicherung aus Uebersicht
		if(isset($_POST['action']) && $_POST['action']=='save')
		{
			foreach($_POST['Id'] as $id => $key)
			{
				$update_title = (!empty($_POST['Titel'][$id])) ? "Titel_1 = '" . koobispecialchars($_POST['Titel'][$id]) . "'," : "";
				$update_price = (!empty($_POST['Preis_Liste'][$id]) && $_POST['Preis_Liste'][$id]>0) ? "Preis_Liste = '" . str_replace(',','.', $_POST['Preis_Liste'][$id]) . "'," : "";
				$update_store = ($_POST['Lagerbestand'][$id]!='') ? "Lagerbestand = '" . $_POST['Lagerbestand'][$id] . "'," : "";
				$update_selled = ($_POST['Verkauft'][$id]!='') ? "Verkauft = '" . $_POST['Verkauft'][$id] . "'," : "";
				$update_hits = ($_POST['Klicks'][$id]!='') ? "Klicks = '" . $_POST['Klicks'][$id] . "'," : "";
				$update_categs = ($_POST['Kategorie'][$id]!='') ? "Kategorie = '" . $_POST['Kategorie'][$id] . "'," : "";
				$GLOBALS['db']->Query("UPDATE " . PREFIX . "_shop_produkte SET " . $update_title . $update_price . $update_hits . $update_store . $update_selled . $update_categs . " Aktiv = Aktiv WHERE Id = '{$id}'");
			}
		}
		
		// Sortierung
		$db_order = "ORDER BY Titel_{$Lc} ASC";
		$db_order_nav = '';
		$offers_search = '';
		
		if(isset($_REQUEST['order']) && !empty($_REQUEST['order']))
		{
			switch($_REQUEST['order'])
			{
				case 'title_asc':$db_order = "ORDER BY Titel_{$Lc} ASC"; $db_order_nav = '&amp;order=ordernum_asc'; $GLOBALS['tmpl']->assign('title_sort', 'title_desc');break;
				case 'title_desc':$db_order = "ORDER BY Titel_{$Lc} DESC"; $db_order_nav = '&amp;order=ordernum_desc'; $GLOBALS['tmpl']->assign('title_sort', 'title_asc');break;
				case 'artnr_asc':$db_order = 'ORDER BY Artikelnummer ASC'; $db_order_nav = '&amp;order=artnr_asc'; $GLOBALS['tmpl']->assign('artnr_sort', 'artnr_desc');break;
				case 'artnr_desc':$db_order = 'ORDER BY Artikelnummer DESC'; $db_order_nav = '&amp;order=artnr_desc'; $GLOBALS['tmpl']->assign('artnr_sort', 'artnr_asc');break;
				case 'price_asc':$db_order = 'ORDER BY Preis_Liste ASC'; $db_order_nav = '&amp;order=price_asc'; $GLOBALS['tmpl']->assign('price_sort', 'price_desc');break;
				case 'price_desc':$db_order = 'ORDER BY Preis_Liste DESC'; $db_order_nav = '&amp;order=price_desc'; $GLOBALS['tmpl']->assign('price_sort', 'price_asc');break;
				case 'store_asc':$db_order = 'ORDER BY Lagerbestand ASC'; $db_order_nav = '&amp;order=store_asc'; $GLOBALS['tmpl']->assign('store_sort', 'store_desc');break;
				case 'store_desc':$db_order = 'ORDER BY Lagerbestand DESC'; $db_order_nav = '&amp;order=store_desc'; $GLOBALS['tmpl']->assign('store_sort', 'store_asc');break;
				case 'ordered_asc':$db_order = 'ORDER BY Verkauft ASC'; $db_order_nav = '&amp;order=ordered_asc'; $GLOBALS['tmpl']->assign('ordered_sort', 'ordered_desc');break;
				case 'hits_asc':$db_order = 'ORDER BY Klicks ASC'; $db_order_nav = '&amp;order=hits_asc'; $GLOBALS['tmpl']->assign('hits_sort', 'hits_desc');break;
				case 'hits_desc':$db_order = 'ORDER BY Klicks DESC'; $db_order_nav = '&amp;order=hits_desc'; $GLOBALS['tmpl']->assign('hits_sort', 'hits_asc');break;
				case 'ordered_desc':$db_order = 'ORDER BY Verkauft DESC'; $db_order_nav = '&amp;order=ordered_desc'; $GLOBALS['tmpl']->assign('ordered_sort', 'ordered_asc');break;
				case 'categ_asc':$db_order = 'ORDER BY Kategorie ASC'; $db_order_nav = '&amp;order=categ_asc'; $GLOBALS['tmpl']->assign('categ_sort', 'categ_desc');break;
				case 'categ_desc':$db_order = 'ORDER BY Kategorie DESC'; $db_order_nav = '&amp;order=categ_desc'; $GLOBALS['tmpl']->assign('categ_sort', 'categ_asc');break;
			}
		}
		
		if(isset($_REQUEST['query']) && !empty($_REQUEST['query']))
		{
			$q = trim(addslashes($_REQUEST['query']));
			$t_search = (isset($_REQUEST['b_search']) && $_REQUEST['b_search']==1) ? " OR Beschreibung_1 LIKE '%$q%' OR Beschreibung_2 LIKE '%$q%' OR Beschreibung_3 LIKE '%$q%' " : "";
			$search = " WHERE (Id = '$q' OR Artikelnummer = '$q' OR Titel_1 LIKE '%$q%' OR Titel_2 LIKE '%$q%' OR Titel_3 LIKE '%$q%' {$t_search})";
			$search_nav = "&amp;query=$q" . ((isset($_REQUEST['b_search']) && $_REQUEST['b_search']==1) ? "&amp;b_search=$_REQUEST[b_search]" : "");
		} else {
			$search = "WHERE Id != 0";
		}
		
		if(isset($_REQUEST['aktiv']) && $_REQUEST['aktiv'] != '')
		{
			$search_status = " AND (Aktiv = '" . $_REQUEST['aktiv'] . "') ";
			$search_status_nav = "&amp;aktiv=$_REQUEST[aktiv]";
		}
		
		if(isset($_REQUEST['b_offers']) && $_REQUEST['b_offers']==1)
		{
			$offers_search = " AND (Preis != '0.00' AND Preis_Liste > Preis AND Preis_Liste_Gueltig >= " . stime() . ") ";
		}
		
		
		if(isset($_REQUEST['lagerv']) && $_REQUEST['lagerv'] != '')
		{
			$v = eregi_replace('[^0-9]', '', $_REQUEST['lagerv']);
			$b = eregi_replace('[^0-9]', '', $_REQUEST['lagerb']);
			$_REQUEST['lagerv'] = $v;
			$_REQUEST['lagerb'] = $b;
			if($v!='' && $b!='') $search_lager = " AND (Lagerbestand BETWEEN $v AND $b) ";
			if($v!='' && $b!='') $search_lager_nav = "&amp;lagerv=$v&amp;lagerb=$b";
		}
		
		if(isset($_REQUEST['kategorie']) && $_REQUEST['kategorie'] != '')
		{
			$search_kategorie = " AND (Kategorie = '" . $_REQUEST['kategorie'] . "') ";
			$search_kategorie_nav = "&amp;kategorie=$_REQUEST[kategorie]";
		}
		
		// Es wird nach dem Hersteller gesucht
		if(isset($_REQUEST['hersteller']) && $_REQUEST['hersteller'] != '')
		{
			$search_hersteller = " AND (Hersteller = '" . $_REQUEST['hersteller'] . "') ";
			$search_hersteller_nav = "&amp;hersteller=$_REQUEST[hersteller]";
		}
		
		// Es wird nach einem Preis gesucht
		if(isset($_REQUEST['preis_von']) && $_REQUEST['preis_von'] > 0 && $_REQUEST['preis_bis'] && $_REQUEST['preis_bis'] > 0)
		{
			$v = $this->priceClean($_REQUEST['preis_von']);
			$b = $this->priceClean($_REQUEST['preis_bis']);
			$search_preis = " AND (Preis_Liste  BETWEEN $v AND $b) ";
			$search_preis_nav = "&amp;preis_von=$v&amp;preis_bis=$b";
		}
		
		// Es wird nach Verkaufszahlen gesucht
		if(isset($_REQUEST['verkauft_von']) && $_REQUEST['verkauft_von'] >= 0 && $_REQUEST['verkauft_bis'] && $_REQUEST['verkauft_bis'] > 0)
		{
			$_REQUEST['verkauft_von'] = $this->cleanNum($_REQUEST['verkauft_von']);
			$_REQUEST['verkauft_bis'] = $this->cleanNum($_REQUEST['verkauft_bis']);
			$search_verkauft = " AND (Verkauft  BETWEEN $_REQUEST[verkauft_von] AND $_REQUEST[verkauft_bis]) ";
			$search_verkauft_nav = "&amp;verkauft_von=$_REQUEST[verkauft_von]&amp;verkauft_bis=$_REQUEST[verkauft_bis]";
		}
		
		$_SESSION['query_user'] = "{$search} AND Id != '' {$search_status} {$search_kategorie} {$search_preis} {$search_verkauft} {$search_hersteller}" ;
		
		
		$q = "SELECT Id FROM " . PREFIX ."_shop_produkte {$search} AND Id != '' {$search_lager} {$offers_search} {$search_status} {$search_kategorie} {$search_preis} {$search_verkauft} {$search_hersteller}";
		$sql = $GLOBALS['db']->Query($q);
		$num = $sql->numrows();
		
		$limit = (isset($_REQUEST['limit']) && $_REQUEST['limit'] >= 1) ? $this->cleanNum($_REQUEST['limit']) : $this->ArticleLimit;
		$seiten = ceil($num / $limit);
		$a = prepage() * $limit - $limit;
		
		$cutter = $this->cutter();
		$db_export_lang_sel = (isset($_REQUEST['export']) && $_REQUEST['export']==1) ? "" : ",Titel_" . $_SESSION['AdminLangcode'] . " AS Titel";
		
		$q = "SELECT * {$db_export_lang_sel} FROM " . PREFIX ."_shop_produkte {$search} AND Id != '' {$search_lager} {$offers_search} {$search_status} {$search_kategorie} {$search_preis} {$search_verkauft} {$search_hersteller} {$db_order} LIMIT $a,$limit";
		$sql = $GLOBALS['db']->Query($q);
		
		$fieldcount = $sql->NumFields();
		for ($i = 0; $i < $fieldcount; $i++) $xoutput .= $this->enclosed . $sql->FieldName($i) . $this->enclosed . $this->separator;
		$xoutput .=  $cutter;
		
		while($row = $sql->fetchrow())
		{
			//=================================================================
			// Export-String
			//=================================================================
			foreach($row as $key=>$val)
			{
				if(@$_REQUEST['export']==1)
				{
					#if($key == 'Artikel') $val = base64_encode($val);
					#if($key == 'Bestellung') $val = base64_encode($val);
					#if($key == 'Betrag') $val = number_format($val,'2',',','.');
					$val = str_replace("\r\n","\n",$val);
					$xoutput .= ($val=='') ? $this->separator : $this->enclosed . $this->escape($val) . $this->enclosed . $this->separator;
				}
			}
			$xoutput .= $cutter;
			//=================================================================
			// Export-String Ende
			//=================================================================
			
			$row->IsOffer = ($row->Preis != '0.00' && ($row->Preis_Liste > $row->Preis) && ($row->Preis_Liste_Gueltig >=  stime())) ? 1 : 0;
			$row->Votes = $this->getVotes($row->Id);
			$row->CatName = $this->getCategName($row->Kategorie);
			$row->Bild_Orig = $row->Bild;
			$row->Bild_Klein = (is_file(BASE_DIR . '/' . $this->_upload_path . 'xsmall/' . $row->Bild)) ? $this->_upload_path . 'xsmall/' . $row->Bild : 'system/shopthumb.php?shopadmin=1&amp;smode=xsmall&amp;img=' . $row->Bild;
			$row->Bild_Norm = (is_file(BASE_DIR . '/' . $this->_upload_path . 'normal/' . $row->Bild)) ? "<img src='../" . $this->_upload_path . "normal/" . $row->Bild . "' alt=''  />" : "<img src='../system/shopthumb.php?smode=2&amp;img=" . $row->Bild . "' alt='' />";
			array_push($articles,$row);
		}
		
		//=================================================================
		// Exportaufruf
		//=================================================================
		if(@$_REQUEST['export']==1 && perm('export_articles'))
		{
			$format = (@$_REQUEST['export_format']=='text') ? 'txt' : 'csv';
			$xoutput = str_replace(array("\";\r\n","\";\n"),"\"\r\n",$xoutput);
			$header = (@$_REQUEST['export_format']=='text') ? 'text/plain' : 'text/csv';
			$this->DataExportDownload($xoutput, ''.$filename.'.'.$format.'', $header, 1);	
		}
		$scategs = array();
		$order_page = (isset($_REQUEST['page']) && !empty($_REQUEST['page'])) ? $_REQUEST['page'] : 1;
		$nav_string = "index.php?do=shop&amp;sub=articles&amp;b_offers=" . @abs((int)$_REQUEST['b_offers']) . "&amp;b_search=" . @abs((int)$_REQUEST['b_search']) . "&amp;page={s}{$search_lager_nav}{$search_nav}{$search_status_nav}{$search_kategorie_nav}{$search_preis_nav}{$search_verkauft_nav}{$search_hersteller_nav}&amp;limit={$limit}";
		
		$GLOBALS['tmpl']->assign('available', $this->getAvailabilities());
		$GLOBALS['tmpl']->assign('nav_string', "index.php?do=shop&amp;sub=articles&amp;SID=" . SESSION . "&amp;page={$order_page}{$search_lager_nav}{$search_nav}{$search_status_nav}{$search_kategorie_nav}{$search_preis_nav}{$search_verkauft_nav}{$search_hersteller_nav}&amp;limit={$limit}");
		$GLOBALS['tmpl']->assign('pages', pagenav($seiten, '', "<a class=\"page_navigation\" href=\"{$nav_string}{$db_order_nav}\">{t}</a> "));
		$GLOBALS['tmpl']->assign('shop_search_small_categs', $this->get_shop_categs_simple(0, '', $scategs, $area, 0, 1));
		$GLOBALS['tmpl']->assign('limit', $limit);
		$GLOBALS['tmpl']->assign('shop_manufaturer', $this->getManufacturer());
		return $articles;
	}

	//=================================================================
	// Kategorie(n) loeschen
	//=================================================================
	function delCateg($id) 
	{
		if(perm('shop_catdeletenew'))
		{
			$query = $GLOBALS['db']->Query("SELECT * FROM " . PREFIX . "_shop_kategorie WHERE Parent_Id='$id'");
			while ($item = $query->fetchrow())
			{
				$GLOBALS['db']->Query("DELETE FROM " . PREFIX . "_shop_kategorie WHERE catid='" . $item->Id . "'");	
				$GLOBALS['db']->Query("UPDATE " . PREFIX . "_shop_produkte SET Aktiv='0' WHERE Kategorie='" . $item->Id . "'");		
				$this->delCateg($item->Id);
				$GLOBALS['db']->Query("DELETE FROM " . PREFIX . "_shop_kategorie WHERE  catid = '$item->Id'");
				$GLOBALS['db']->Query("DELETE FROM " . PREFIX . "_shop_kategorie WHERE  catid = '$item->Parent_Id'");
				$GLOBALS['db']->Query("UPDATE " . PREFIX . "_shop_produkte SET Aktiv='0' WHERE Kategorie='" . $item->Id . "'");		
				$GLOBALS['db']->Query("UPDATE " . PREFIX . "_shop_produkte SET Aktiv='0' WHERE Kategorie='" . $item->Parent_Id . "'");		
			}
			$GLOBALS['db']->Query("DELETE FROM " . PREFIX . "_shop_kategorie WHERE Id='$id'");
			$GLOBALS['db']->Query("UPDATE " . PREFIX . "_shop_produkte SET Aktiv='0' WHERE Kategorie='$id'");		
			echo "<script>window.opener.location.reload();window.close();</script>";
			
			
			
		} else {
			no_perm();
		}
	}

	//=================================================================
	// Neue Kategorie anlegen
	//=================================================================
	function newCateg($id)
	{
		if(perm('shop_catdeletenew'))
		{
			$error = '';
			if(isset($_POST['save']) && $_POST['save']==1)
			{
				$q = "INSERT INTO " . PREFIX . "_shop_kategorie 
				(
					Id, 
					Parent_Id, 
					Name_1,
					Name_2,
					Name_3,
					Beschreibung_1,
					Beschreibung_2,
					Beschreibung_3,
					posi,
					UstId,
					Bild_Navi,
					Bild_Kategorie
				) VALUES (
					'',
					'" . $_POST['Parent'] . "',
					'" . $_POST['Name_1'] . "',
					'" . $_POST['Name_1'] . "',
					'" . $_POST['Name_1'] . "',
					'" . $_POST['Beschreibung_1'] . "',
					'" . $_POST['Beschreibung_1'] . "',
					'" . $_POST['Beschreibung_1'] . "',
					'" . $_POST['Position'] . "',
					'" . $_POST['UstId'] . "',
					'" . @$_POST['newImg_2']. "',
					'" . @$_POST['newImg_1']. "'
				)";
				$GLOBALS['db']->Query($q);
				Logger('User ' . $_SESSION['user_name'] . ' create new Shop-Category - ' . $_POST['Name_1'], '3', $_SESSION['benutzer_id']);
				echo "<script>window.opener.location.reload();window.close();</script>";
			}
			
			
			$parent = ($id=='no_sub') ? '0' : $id;
			$scategs = array();
			$GLOBALS['tmpl']->assign('title', $GLOBALS['config_vars']['Global_NewCateg']);
			$GLOBALS['tmpl']->assign('ust_elements', $this->getUstELements());
			$GLOBALS['tmpl']->assign('shop_search_small_categs', $this->get_shop_categs_simple(0, '', $scategs, $area, 0, 1));
			$GLOBALS['tmpl']->assign('Editor', fckInit('', 'Beschreibung_1', 200, 'Basic'));
			$GLOBALS['tmpl']->assign('content', $GLOBALS['tmpl']->fetch($GLOBALS['config']['source'] . '/shop/categ_new.tpl'));
		} else {
			no_perm();
		}
	}
	
	//=================================================================
	// Kategorie bearbeiten
	//=================================================================
	function editCateg($id)
	{
		if(perm('shop_catdeletenew'))
		{
			$scategs = array();
			if(isset($_POST['save']) && $_POST['save']==1)
			{
				if($_POST['Name_1']!='')
				{
					$up_icon_categ = (isset($_POST['noImg_1']) && $_POST['noImg_1']==1) ? ",Bild_kategorie=''" : ((!empty($_POST['newImg_1'])) ? ",Bild_Kategorie='" . $_POST['newImg_1'] . "'" : "");
					$up_navi_categ = (isset($_POST['noImg_2']) && $_POST['noImg_2']==1) ? ",Bild_Navi=''" : ((!empty($_POST['newImg_2'])) ? ",Bild_Navi='" . $_POST['newImg_2'] . "'" : "");
					
					$q = "UPDATE " . PREFIX . "_shop_kategorie 
						SET 
						Name_1 = '" . $_POST['Name_1'] . "',
						Beschreibung_1 = '" . @$_POST['Beschreibung_1'] . "' ,
						UstId = '" . $_POST['UstId'] . "' 
						{$up_icon_categ} 
						{$up_navi_categ}
						
						WHERE Id = '" . $_POST['id'] . "'
						";
					$GLOBALS['db']->Query($q);
					Logger('User ' . $_SESSION['user_name'] . ' update Shop-Category - ' . $_POST['Name_1'], '3', $_SESSION['benutzer_id']);
				}
				
				if(isset($_POST['noImg_1']) && $_POST['noImg_1']==1) @unlink(BASE_DIR . 'uploads/shop/icons_categs/' . $_POST['categ_del_img']);
				if(isset($_POST['noImg_2']) && $_POST['noImg_2']==1) @unlink(BASE_DIR . 'uploads/shop/navi_categs/' . $_POST['navi_del_img']);
				echo "<script>window.opener.location.reload();</script>";
			}
			
			$row = $GLOBALS['db']->RowQuery("SELECT *, Name_1 AS Name, Beschreibung_1 AS Beschreibung FROM " . PREFIX . "_shop_kategorie WHERE Id = '$id'");
			
			$row->Bild_Kategorie_Del = $row->Bild_Kategorie;
			$row->Bild_Navi_Del = $row->Bild_Navi;
			$row->Bild_Kategorie = ($row->Bild_Kategorie!='' && file_exists(BASE_DIR . '/uploads/shop/icons_categs/' . $row->Bild_Kategorie)) ? '<img src="../uploads/shop/icons_categs/' . $row->Bild_Kategorie . '" alt="" />' : '';
			$row->Bild_Navi      = ($row->Bild_Navi!='' && file_exists(BASE_DIR . '/uploads/shop/navi_categs/' . $row->Bild_Navi)) ? '<img src="../uploads/shop/navi_categs/' . $row->Bild_Navi . '" alt="" />' : '';
		
			$GLOBALS['tmpl']->assign('shop_search_small_categs', $this->get_shop_categs_simple(0, '', $scategs, $area, 0, 1));
			$GLOBALS['tmpl']->assign('title', $GLOBALS['config_vars']['Shop_cat_edit']);
			$GLOBALS['tmpl']->assign('ust_elements', $this->getUstELements());
			$GLOBALS['tmpl']->assign('row', $row);
			$GLOBALS['tmpl']->assign('Editor', fckInit($row->Beschreibung, 'Beschreibung_1', 200, 'Basic'));
			$GLOBALS['tmpl']->assign('content', $GLOBALS['tmpl']->fetch($GLOBALS['config']['source'] . '/shop/categ_edit.tpl'));
		} else {
			no_perm();
		}
	}
	
	//=================================================================
	// Kategorie bearbeiten (Name und Beschreibung)
	//=================================================================
	function editCategNameText($langcode,$id)
	{
		if(perm('shop_catdeletenew'))
		{
			$LC = $_REQUEST['langcode'];
			
			if(isset($_POST['save']) && $_POST['save']==1)
			{
				$GLOBALS['db']->Query("UPDATE " . PREFIX . "_shop_kategorie SET Name_{$LC}='" . $_POST['Name_' . $LC] . "', Beschreibung_{$LC} = '" . $_POST['Beschreibung_' . $LC] . "' WHERE Id = '" . $_POST['id']. "'");
				Logger('User ' . $_SESSION['user_name'] . ' update Shop-Category - ' . $_POST['Name_' . $LC], '3', $_SESSION['benutzer_id']);
				/*
				sleep(1);
				echo "<script>window.close();</script>";
				*/
			}
			
			$row = $GLOBALS['db']->RowQuery("SELECT Name_{$LC} AS Name, Beschreibung_{$LC} AS Beschreibung FROM " . PREFIX . "_shop_kategorie WHERE Id = '$id'");
			$GLOBALS['tmpl']->assign('title', $GLOBALS['config_vars']['Shop_cat_edit_normal']);
			$GLOBALS['tmpl']->assign('row', $row);
			$GLOBALS['tmpl']->assign('Editor', fckInit($row->Beschreibung, 'Beschreibung_' . $_REQUEST['langcode'], 200, 'Basic'));
			$GLOBALS['tmpl']->assign('content', $GLOBALS['tmpl']->fetch($GLOBALS['config']['source'] . '/shop/categ_name_edit.tpl'));
		} else {
			no_perm();
		}
	}

	//=================================================================
	// Kategorien anzeigen
	//=================================================================
	function displayCategories()
	{
		if(isset($_POST['save']) && $_POST['save']==1 && perm('shop_catdeletenew'))
		{
			if(@$_POST['name']>=1)
			{
				foreach ($_POST['name'] as $id => $name)
				{
					if(!empty($_POST['name'][$id]))
					{
						$GLOBALS['db']->Query("UPDATE " . PREFIX . "_shop_kategorie SET Name_1='".$_POST['name'][$id]."', posi='".(int)$_POST['posi'][$id]."' WHERE Id = '$id'");
						Logger('User ' . $_SESSION['user_name'] . ' update Shop-Category - ' . $_POST['name'][$id], '3', $_SESSION['benutzer_id']);
					}
				}
			}
		}
		
		$categs_shop = array();
		
		$GLOBALS['tmpl']->assign('title', $GLOBALS['config_vars']['Global_ShopCategs']);
		$GLOBALS['tmpl']->assign('categs', $this->get_all_categs(0,$categs_shop,''));
		$GLOBALS['tmpl']->assign('content', $GLOBALS['tmpl']->fetch($GLOBALS['config']['source'] . '/shop/shopcategs.tpl'));
	}
	
	//=================================================================
	// Funktion zur Anzeige der Kategorien fier Dropdown
	//=================================================================
	function get_prods_categs()
	{
		$categs_shop = array();
		$GLOBALS['tmpl']->assign('categs_ass', $this->get_all_categs(0,$categs_shop,@$_REQUEST['c']));
		if(isset($_REQUEST['c']) && !empty($_REQUEST['c'])) $GLOBALS['tmpl']->assign('prods_all', $this->getProdsByCat(@$_REQUEST['c']));
		
		$GLOBALS['tmpl']->display(TPL_FOLDER . 'shop/browse_categs_products.tpl');
	}
	
	function get_prods_parts()
	{
		$categs_shop = array();
		$GLOBALS['tmpl']->assign('categs_ass', $this->get_all_categs(0,$categs_shop,@$_REQUEST['c']));
		if(isset($_REQUEST['c']) && !empty($_REQUEST['c'])) $GLOBALS['tmpl']->assign('prods_all', $this->getProdsByCat(@$_REQUEST['c']));
		$GLOBALS['tmpl']->display(TPL_FOLDER . 'shop/browse_parts_products.tpl');
	}
	
	function get_prods_tuning()
	{
		$categs_shop = array();
		$GLOBALS['tmpl']->assign('categs_ass', $this->get_all_categs(0,$categs_shop,@$_REQUEST['c']));
		if(isset($_REQUEST['c']) && !empty($_REQUEST['c'])) $GLOBALS['tmpl']->assign('prods_all', $this->getProdsByCat(@$_REQUEST['c']));
		$GLOBALS['tmpl']->display(TPL_FOLDER . 'shop/browse_tuning_products.tpl');
	}
	
	//=================================================================
	// Produkte nach Kategorie fuer Dropdown
	//=================================================================
	function getProdsByCat($cat=0)
	{
		$Lc = $_SESSION['AdminLangcode'];
		$prods = array();
		$sql_prod = $GLOBALS['db']->Query("SELECT Id, Titel_{$Lc} AS Titel FROM " . PREFIX ."_shop_produkte WHERE Kategorie = '" . $cat . "'");
		while($prod = $sql_prod->fetchrow())
		{
			array_push($prods,$prod);
		}
		return $prods;
	}
	
	//=================================================================
	// Produkte nach Zubehoer fuer Artikel-Zubehoer
	//=================================================================
	function getProdsByZub($string)
	{
		$Lc = $_SESSION['AdminLangcode'];
		$Prods = explode(',', $string);
		$string = implode(',', $Prods);
		if(!empty($string))
		{
			$Zubehoer = array();
			$sql_prod = $GLOBALS['db']->Query("SELECT Id, Titel_{$Lc} AS Titel FROM " . PREFIX ."_shop_produkte WHERE Id IN ($string)");
			while($prod = $sql_prod->fetchrow())
			{
				array_push($Zubehoer,$prod);
			}
			return $Zubehoer;
		}
	}
	
	//=================================================================
	//
	//=================================================================
	function get_all_categs($id,&$categs_shop,$categ='',$prefix='',$subcount=0,$subs='0')
	{
		$Lc = $_SESSION['AdminLangcode'];
		$query = $GLOBALS['db']->Query("SELECT *,Id as catid, Name_1 as catname, Name_1 as Name FROM " . PREFIX . "_shop_kategorie WHERE Parent_Id = '$id' ORDER BY posi ASC");
		if (!$query->numrows()) return;
		while ($item = $query->fetchrow())
		{
			$item->Expander = $prefix;
			$item->Subcount = strlen($prefix);
			$item->Bold = ($item->Parent_Id == 0) ? 1 : 0;
			
			$sql_prod = $GLOBALS['db']->Query("SELECT Id, Titel_1 AS Titel FROM " . PREFIX ."_shop_produkte WHERE Kategorie = '" . $categ . "'");
			$prods = array();
			while($prod = $sql_prod->fetchrow())
			{
				array_push($prods,$prod);
			}
			$item->prods = $prods;
			array_push($categs_shop,$item);
			
			$this->get_all_categs($item->catid, $categs_shop,$categ, $prefix  .'&nbsp;- ',$subcount,'|');
		}
		unset($prods);
		return $categs_shop;
	}
	

	

	
	//=================================================================
	// Bestellungen listen
	//=================================================================
	function getOrders()
	{
		$orders = array();
		$filename = 'export';
		$format = 'csv';
		$search = '';
		$search_nav = '';
		$status = '';
		$status_nav = '';
		$query_date = '';
		$date_nav = '';
		$zid = '';
		$zid_nav = '';
		$vid = '';
		$vid_nav = '';
		$s_search = '';
		$s_search_nav = '';
		
		if(isset($_REQUEST['StartDate']))
		{
			$st = explode('.',$_REQUEST['StartDate']);
			$en = explode('.',$_REQUEST['EndDate']);
			
			$zs = @mktime(0,0,1,$st[1],$st[0],$st[2]);
			$ze = @mktime(23,59,59,$en[1],$en[0],$en[2]);
			
			if($zs<10) $zs = stime();
			if($ze<10) $ze = stime();
			
			$query_date = " AND (Datum BETWEEN $zs AND $ze)";
			$date_nav = "&StartDate=" .  preg_replace('/([^0-9.]*)/', '',$_REQUEST['StartDate']);
			$date_nav .= "&EndDate=" . preg_replace('/([^0-9.]*)/', '',$_REQUEST['EndDate']);
			$GLOBALS['tmpl']->assign('ZeitStart', $zs);
			$GLOBALS['tmpl']->assign('ZeitEnde', $ze);
		} else {
			$zs = mktime(0,0,1,date('m')-1,date('d'),date('Y'));
			$ze = mktime(0,0,1,date('m'),date('d'),date('Y'));
			$GLOBALS['tmpl']->assign('ZeitStart', $zs);
			$GLOBALS['tmpl']->assign('ZeitEnde', $ze);
		}
		
		if(isset($_REQUEST['query']) && !empty($_REQUEST['query'])){$q = trim(addslashes($_REQUEST['query']));$search = " WHERE (Id = '$q' OR TransaktionsNummer = '$q' OR Rng_Nachname LIKE '$q%' OR Benutzer = '$q')";$search_nav = "&amp;query=" . $q;} else {$search = "WHERE Id != 0";}
		if(isset($_REQUEST['status']) && !empty($_REQUEST['status'])){$status = " AND (Status = '" . escs($_REQUEST['status']). "')";$status_nav = "&amp;status=" . $_REQUEST['status'];}
		if(isset($_REQUEST['ZahlungsId']) && !empty($_REQUEST['ZahlungsId'])){$zid = " AND (ZahlungsId = '" . escs($_REQUEST['ZahlungsId']). "')";$zid_nav = "&amp;ZahlungsId=" . $_REQUEST['ZahlungsId'];}
		if(isset($_REQUEST['VersandId']) && !empty($_REQUEST['VersandId'])){$vid = " AND (VersandId = '" . escs($_REQUEST['VersandId']). "')";$vid_nav = "&amp;VersandId=" . $_REQUEST['VersandId'];}
		if(isset($_REQUEST['BetragVon']) && !empty($_REQUEST['BetragVon']) && isset($_REQUEST['BetragBis']) && !empty($_REQUEST['BetragBis'])){$s_from = $this->eng_num($_REQUEST['BetragVon']);$s_to = $this->eng_num($_REQUEST['BetragBis']);$_REQUEST['BetragVon'] = $s_from;$_REQUEST['BetragBis'] = $s_to;$s_search = " AND (Betrag BETWEEN $s_from AND $s_to)";$s_search_nav = "&amp;BetragVon={$s_from}&amp;BetragBis={$s_to}";}
		
		$db_order = 'ORDER BY Id DESC';
		$db_order_nav = '';
		
		if(isset($_REQUEST['order']) && !empty($_REQUEST['order']))
		{
			switch($_REQUEST['order'])
			{
				case 'ordernum_asc':$db_order = 'ORDER BY TransaktionsNummer ASC';$db_order_nav = '&amp;order=ordernum_asc';$GLOBALS['tmpl']->assign('ordernum_sort', 'ordernum_desc');break;
				case 'ordernum_asc':$db_order = 'ORDER BY TransaktionsNummer DESC';$db_order_nav = '&amp;order=ordernum_asc';$GLOBALS['tmpl']->assign('ordernum_sort', 'ordernum_asc');break;
				case 'summ_asc':$db_order = 'ORDER BY Betrag ASC';$db_order_nav = '&amp;order=summ_asc';$GLOBALS['tmpl']->assign('summ_sort', 'summ_desc');break;
				case 'summ_desc':$db_order = 'ORDER BY Betrag DESC';$db_order_nav = '&amp;order=summ_desc';$GLOBALS['tmpl']->assign('summ_sort', 'summ_asc');break;
				case 'date_asc':$db_order = 'ORDER BY Datum ASC';$db_order_nav = '&amp;order=date_asc';$GLOBALS['tmpl']->assign('date_sort', 'date_desc');break;
				case 'date_desc':$db_order = 'ORDER BY Datum DESC';$db_order_nav = '&amp;order=date_desc';$GLOBALS['tmpl']->assign('date_sort', 'date_asc');break;
				case 'customer_asc':$db_order = 'ORDER BY Rng_Nachname ASC';$db_order_nav = '&amp;order=customer_asc';$GLOBALS['tmpl']->assign('customer_sort', 'customer_desc');break;
				case 'customer_desc':$db_order = 'ORDER BY Rng_Nachname DESC';$db_order_nav = '&amp;order=customer_desc';$GLOBALS['tmpl']->assign('customer_sort', 'customer_asc');break;
				case 'customerid_asc':$db_order = 'ORDER BY Benutzer ASC';$db_order_nav = '&amp;order=customerid_asc';$GLOBALS['tmpl']->assign('customerid_sort', 'customerid_desc');break;
				case 'customerid_desc':$db_order = 'ORDER BY Benutzer DESC';$db_order_nav = '&amp;order=customerid_desc';$GLOBALS['tmpl']->assign('customerid_sort', 'customerid_asc');break;
				case 'payment_asc':$db_order = 'ORDER BY ZahlungsId ASC';$db_order_nav = '&amp;order=payment_asc';$GLOBALS['tmpl']->assign('payment_sort', 'payment_desc');break;
				case 'payment_desc':$db_order = 'ORDER BY ZahlungsId DESC';$db_order_nav = '&amp;order=payment_desc';$GLOBALS['tmpl']->assign('payment_sort', 'payment_asc');break;
				case 'shipper_asc':$db_order = 'ORDER BY VersandId ASC';$db_order_nav = '&amp;order=shipper_asc';$GLOBALS['tmpl']->assign('shipper_sort', 'shipper_desc');break;
				case 'shipper_desc':$db_order = 'ORDER BY VersandId DESC';$db_order_nav = '&amp;order=shipper_desc';$GLOBALS['tmpl']->assign('shipper_sort', 'shipper_asc');break;
				case 'status_asc':$db_order = 'ORDER BY Status ASC';$db_order_nav = '&amp;order=status_asc';$GLOBALS['tmpl']->assign('status_sort', 'status_desc');break;
				case 'status_desc':$db_order = 'ORDER BY Status DESC';$db_order_nav = '&amp;order=status_desc';$GLOBALS['tmpl']->assign('status_sort', 'status_asc');break;
			}
		}
	
		
		$q = "SELECT Id FROM " . PREFIX ."_shop_bestellungen {$search} AND Id != '' {$status} {$query_date} {$zid} {$vid} {$s_search}";
		$sql = $GLOBALS['db']->Query($q);
		$num = $sql->numrows();
		
		$limit = (isset($_REQUEST['limit']) && $_REQUEST['limit'] >= 1) ? $this->cleanNum($_REQUEST['limit']) : $this->Limit;
		$seiten = ceil($num / $limit);
		$a = prepage() * $limit - $limit;
		
		$cutter = $this->cutter();
		
		$q = "SELECT * FROM " . PREFIX ."_shop_bestellungen {$search} AND Id != '' {$status} {$query_date} {$zid} {$vid} {$s_search} {$db_order} LIMIT $a,$limit";
		$sql = $GLOBALS['db']->Query($q);
		$fieldcount = $sql->NumFields();
		
		$xoutput = '';
		if(isset($_POST['export_format']) && $_POST['export_format'] == 'html')
		{
			//
		} else {
			for ($i = 0; $i < $fieldcount; $i++)
			{
				$xoutput .= $this->enclosed . $sql->FieldName($i) . $this->enclosed . $this->separator;
			}
			$xoutput .=  $cutter;
		}
		
		while($row = $sql->fetchrow())
		{
			foreach($row as $key=>$val)
			{
				if(@$_REQUEST['export']==1)
				{
					
					if(isset($_POST['export_format']) && $_POST['export_format'] == 'html')
					{
						if($key == 'Bestellung') 
						{
							$val = base64_decode($val);
							$val = str_replace("\r\n","\n",$val);
							$xoutput .= "<p>&nbsp;</p><hr noshade=\"noshade\">";
							$xoutput .=  $this->escape($val);
						}
					} else {
						if($key == 'Artikel') $val = base64_encode($val);
						if($key == 'Bestellung' && isset($_POST['order_html']) && $_POST['order_html']==1) $val = base64_decode($val);
						if($key == 'Betrag') $val = number_format($val,'2',',','.');
						$val = str_replace("\r\n","\n",$val);
						$xoutput .= ($val=='') ? $this->separator : $this->enclosed . $this->escape($val) . $this->enclosed . $this->separator;
					}
				}
			}
			$xoutput .= $cutter;
			$row->payment = stripslashes($this->getPaymentName($row->ZahlungsId));
			$row->shipper = stripslashes($this->getShipperName($row->VersandId));
			$row->hasESD = $this->hasUserDownloads($row->Benutzer);
			array_push($orders, $row);
			
		}
		$filename= $GLOBALS['config_vars']['Shop_orders_exportname'];
		//=================================================================
		// Exportaufruf
		//=================================================================
		if(@$_REQUEST['export']==1 && perm('export_orders'))
		{
			if(isset($_POST['export_format']) && $_POST['export_format'] == 'html')
			{
				$format = 'html';
				$xoutput = str_replace(array("\";\r\n","\";\n"),"\"\r\n",$xoutput);
				$header = 'text/html';
			} else {
				$format = ($_REQUEST['export_format']=='text') ? 'txt' : 'csv';
				$xoutput = str_replace(array("\";\r\n","\";\n"),"\"\r\n",$xoutput);
				$header = ($_REQUEST['export_format']=='text') ? 'text/plain' : 'text/csv';
			}
			$this->DataExportDownload($xoutput, ''.$filename.'.'.$format.'', $header, 1);	
		}
		
		$GLOBALS['tmpl']->assign('payments', $this->listPayments());
		$GLOBALS['tmpl']->assign('shipper', $this->listShipper());
		
		$order_page = (isset($_REQUEST['page']) && !empty($_REQUEST['page'])) ? $_REQUEST['page'] : 1;
		$noframes_page = (isset($_REQUEST['noframes']) && $_REQUEST['noframes']==1) ? '&amp;noframes=1' : '';
		$nav_string = "index.php?do=shop&amp;sub=orders&amp;page={s}{$search_nav}{$status_nav}{$date_nav}{$zid_nav}{$vid_nav}{$s_search_nav}{$db_order_nav}&amp;limit={$limit}{$noframes_page}";
		
		$GLOBALS['tmpl']->assign('nav_string', "index.php?do=shop&amp;sub=orders{$search_nav}{$status_nav}{$date_nav}{$zid_nav}{$vid_nav}{$s_search_nav}&amp;page={$order_page}&amp;limit={$limit}{$noframes_page}");
		$GLOBALS['tmpl']->assign('pages', pagenav($seiten, '', "<a class=\"page_navigation\" href=\"{$nav_string}\">{t}</a> "));
		$GLOBALS['tmpl']->assign('limit', $limit);		
		return $orders;
	}
	
	function hasUserDownloads($user)
	{
		$res = $GLOBALS['db']->RowQuery("SELECT COUNT(Id) AS Numcount FROM " . PREFIX . "_shop_downloads_user WHERE Benutzer = '$user'");
		if($res->Numcount>=1)
			return true;
		else
			return false;
	}
	//=================================================================
	// Bestellung stornieren
	//=================================================================
	function cancelOrder($id)
	{
		if(perm('edit_order')) $GLOBALS['db']->Query("UPDATE " . PREFIX ."_shop_bestellungen SET Status = 'failed' WHERE Id = '{$id}' ");	
		echo "<script>window.opener.location.reload();window.close();</script>";
		exit;
	}
	
	//=================================================================
	// Bestellung bearbeiten
	//=================================================================
	function editOrder($id)
	{
		$path = $this->getHomeLink();
		
		if(!perm('edit_order')) 
		{
			$this->noperm();
		} else {
			if(isset($_REQUEST['save']) && $_REQUEST['save'] == '1')
			{
				$q = "UPDATE " . PREFIX ."_shop_bestellungen SET 
					Status = '$_POST[Status]',
					KundenNachricht = '$_POST[KundenNachricht]',
					Bemerkung = '$_POST[Bemerkung]'
				WHERE Id = '$_REQUEST[id]' ";
				$GLOBALS['db']->Query($q);
				
				//=================================================================
				// E-Mail senden?
				//=================================================================
				if(isset($_POST['SendEmail']) && $_POST['SendEmail']==1)
				{
					$Koobi = new Koobi;
					$subject_text = stripslashes($_POST['BetreffKunde']);
					$html_text = stripslashes($_POST['MailKunde']);
					$html_text = str_replace("\n", "<br />", $html_text);
					$html_order = stripslashes($_POST['OHTML']);
					$html_order = str_replace("src=\"uploads/", "src=\"{$path}/uploads/", $html_order);
					$att_ext = ''; 
					$Koobi->koobi_mail($_POST['OEmail'], $GLOBALS['settings']['Mail_Header'] . $html_text . '<hr noshade="noshade" size="1" />' . $html_order, $subject_text, $GLOBALS['shop_settings']['Email_Abs'], $GLOBALS['shop_settings']['Name_Abs'], "text", $att_ext, 1);		
				}
				echo "<script>window.opener.location.reload();window.close();</script>";
				exit;
			}
			
			$path = $this->getHomeLink();
			
			$q = "SELECT * FROM " . PREFIX ."_shop_bestellungen WHERE Id = '{$id}' ";
			$Order = $GLOBALS['db']->ArrQuery($q);
			$Order['Datum'] = date("d-m-Y, H:i",$Order['Datum']);
			$Order['Bestellung'] = base64_decode($Order['Bestellung']);
			$Order['Bestellung'] = str_replace("src=\"uploads/", "src=\"{$path}/uploads/", $Order['Bestellung']);
			
			$GLOBALS['tmpl']->assign('order', $Order);
			$GLOBALS['tmpl']->assign('content', $GLOBALS['tmpl']->fetch($GLOBALS['config']['source'] . '/shop/order_edit.tpl'));
		}
	}
	
	//=================================================================
	//=================================================================
	function  DataExportDownload($datstring, $datname, $dattype, $extra = "0")
	{
		$filetype = 'application/octet-stream';
		header('Content-Type: ' . $dattype);
		header('Expires: ' . gmdate('D, d M Y H:i:s') . ' GMT');
		header('Content-Disposition: attachment; filename="' . $datname . '"');
		if ($extra != 1) header('Content-Length: ' . strlen($datstring));
		header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
		header('Pragma: public');
		echo $datstring;
		exit;
	}

	//=================================================================
	//=================================================================
	function get_shop_categs_simple($id, $prefix, &$categs, &$area, $admin=0, $select=0, $cid=0)
	{
		$Lc = $_SESSION['AdminLangcode'];
		$row_nav_opt = $GLOBALS['db']->ArrQuery("SELECT a.Parent_Id as Parent FROM " . PREFIX . "_shop_kategorie as a," . PREFIX . "_shop_produkte as b WHERE a.Id = '0' ");
		$query =       $GLOBALS['db']->Query("SELECT *,Id as catid, Name_{$Lc} as catname, Name_{$Lc} as Name FROM " . PREFIX . "_shop_kategorie WHERE Parent_Id = '$id' ORDER BY NAME ASC");
		
		if (!$query->numrows()) return;
		
		while ($item = $query->fetchrow())
		{
			$item->visible_title = (($item->Parent_Id==0) ? '' : ' ') . $prefix . $item->Name;
			$item->bold = ($item->Parent_Id==0) ? 1 : 0;
			$item->expander = $prefix . " ";
			$item->sub = ($item->Parent_Id==0) ? 0 : 1;
			$item->Subcount = strlen($prefix);
			
			array_push($categs,$item);
			if($admin == 1)
				$this->get_shop_categs_simple($item->catid, $prefix . "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;", $categs, $area, $admin,0,0,0);
			else
				$this->get_shop_categs_simple($item->catid, $prefix . (($select==1) ? "-&nbsp;" : "&nbsp;&nbsp;&nbsp;"), $categs, $area, 0, $select,0);
		} 
		return $categs;
	} 
	
	//=================================================================
	//=================================================================
	function get_parent_shopcateg($param)
	{
		$id = (is_array($param)) ? $param['id'] : $param ;
		
		$Parent_Id = $id;
		$id = 0;
		if($Parent_Id != 0)
		{
			$sql = $GLOBALS['db']->Query("SELECT Parent_Id,Id as catid FROM ".PREFIX."_shop_kategorie WHERE Id = '".$Parent_Id."'");
			$row = $sql->fetchrow();
			$Parent_Id = $row->Parent_Id;
			$id = $Parent_Id;
		}
		return($id);
		
	}
	
	//=================================================================
	// Funktion zum hochladen von Bildern aus dem Produkt heraus
	//=================================================================
	function upload_multi($rid='')
	{
		$_REQUEST['id'] = ($rid!='') ? $rid : $_REQUEST['id'];
		$images = '';
		$db_images = '';
		$allowed = $this->_allowed;
		if(isset($_FILES['files']))
		{
			for($i=0;$i<count($_FILES['files']['tmp_name']);$i++)
			{
				if(!empty($_FILES['files']['tmp_name'][$i]))
				{
					switch($_FILES['files']['type'][$i])
					{
						case 'image/pjpeg' :
						case 'image/jpeg' :
						case '' :
							$new_name = md5(time() . mt_rand(10001, 19999) . $_FILES['files']['tmp_name'][$i]) . '.jpg';
						break;
						
						case 'image/x-png' :
						case 'image/png' :
							$new_name = md5(time() . mt_rand(10001, 19999) . $_FILES['files']['tmp_name'][$i]) . '.png';
						break;
						
						case 'image/gif' :
							$new_name = md5(time() . mt_rand(10001, 19999) . $_FILES['files']['tmp_name'][$i]) . '.gif';
						break;
					}
					
					@move_uploaded_file($_FILES['files']['tmp_name'][$i], BASE_DIR . '/uploads/shop/icons/' . $new_name);
					@chmod(BASE_DIR . '/uploads/shop/icons/' . $new_name,0777);
					$images[] = $new_name;
				}
			}
			if(!empty($images)) $db_images = @implode("|", $images);
			
			// Alte Bilder entfernen?
			if(isset($_REQUEST['del_old']) && $_REQUEST['del_old'] == 1)
			{
				$row_o = $GLOBALS['db']->RowQuery("SELECT Bilder FROM " . PREFIX . "_shop_produkte WHERE Id = '" . $_REQUEST['id'] . "'");
				$old = explode('|', $row_o->Bilder);
				foreach($old as $del)
				{
					@unlink(BASE_DIR . '/uploads/shop/icons/' . $del);
					@unlink(BASE_DIR . '/uploads/shop/icons_thumbnails/xsmall/' . $del);
					@unlink(BASE_DIR . '/uploads/shop/icons_thumbnails/small/' . $del);
					@unlink(BASE_DIR . '/uploads/shop/icons_thumbnails/medium/' . $del);
					@unlink(BASE_DIR . '/uploads/shop/icons_thumbnails/normal/' . $del);
					@unlink(BASE_DIR . '/uploads/shop/icons_thumbnails/big/' . $del);
				}
				$images = '';
			} else {
				$row_o = $GLOBALS['db']->RowQuery("SELECT Bilder FROM " . PREFIX . "_shop_produkte WHERE Id = '" . $_REQUEST['id'] . "'");
				if(!empty($row_o->Bilder)) 
				{
					$images = $row_o->Bilder . (!empty($db_images) ? '|' : '');
				} else {
					$images = '';
				}
			}
			return "{$images}{$db_images}";
			//$GLOBALS['db']->Query("UPDATE " . PREFIX . "_shop_produkte SET Bilder = '{$images}{$db_images}' WHERE Id = '" . $_REQUEST['id'] . "'");
		}
	}


	//=================================================================
	//=================================================================
	function listShipper()
	{
		$shipper = array();
		$sql = $GLOBALS['db']->Query("SELECT Id,Name_1 AS Name FROM " . PREFIX . "_shop_versandarten ORDER BY Name ASC");
		while($row = $sql->fetcharray())
		{
			array_push($shipper,$row);
		}
		return $shipper;
	}
	
	//=================================================================
	//=================================================================
	function listPayments()
	{
		$payments = array();
		$sql = $GLOBALS['db']->Query("SELECT Id,Name_1 AS Name FROM " . PREFIX . "_shop_zahlungsmethoden ORDER BY Name ASC");
		while($row = $sql->fetcharray())
		{
			array_push($payments,$row);
		}
		return $payments;
	}
	
	//=================================================================
	//=================================================================
	function getHtmlOrder($id)
	{
		$path = $this->getHomeLink();
		$pdf = $GLOBALS['db']->RowQuery("SELECT Bestellung FROM " . PREFIX ."_shop_bestellungen WHERE Id = '{$id}' ");
		$pdf->Bestellung = base64_decode($pdf->Bestellung);
		$pdf->Bestellung = str_replace("src=\"uploads/", "src=\"{$path}/uploads/", $pdf->Bestellung);
		echo $pdf->Bestellung;
		exit;
	}
	
	//=================================================================
	//=================================================================
	function getHomeLink()
	{
		$path = explode('/admin/',redir());
		$path = $path[0];
		return $path;
	}
	
	//=================================================================
	//=================================================================
	function eng_num($string)
	{
		$string = trim(str_replace(',','.',$string));
		return eregi_replace('[^0-9.]', '', $string);
	}
	
	//=================================================================
	//=================================================================
	function escape($s)
	{ 
		return ($s);
		//return( function_exists('mysql_real_escape_string') ? mysql_real_escape_string($s) : mysql_escape_string($s) ); 
	} 
	
		
	//=================================================================
	//=================================================================
	function getHome()
	{
		$GLOBALS['tmpl']->assign('content', 'Shop-Startseite');
	}
	
	function switchPostedCurr($data)
	{
		switch($data)
		{
			case 'EUR': $symbol='&euro;'; break;
			case 'GBP': $symbol='&pound;'; break;
			case 'USD': $symbol='\$'; break;
			default: $symbol = $data ;break;
		}
		return $symbol;
	}
	
	//=================================================================
	// SHop-Einstellungen
	//=================================================================
	function shopSettings()
	{
		if(perm('shop_settings'))
		{
			if(isset($_POST['save']) && $_POST['save']==1)
			{
				// Neues Wasserzeichen?
				$db_wasserzeichen = (isset($_POST['newImg_1']) && !empty($_POST['newImg_1'])) ? "Wasserzeichen_Bild='" . $_POST['newImg_1'] . "'," : '';
				
				
				$WaehrungSymbol_1 = $this->switchPostedCurr($_POST['Waehrung_1']);
				$WaehrungSymbol_2 = $this->switchPostedCurr($_POST['Waehrung_2']);
				$WaehrungSymbol_3 = $this->switchPostedCurr($_POST['Waehrung_3']);
				$m1 = str_replace(',','.',$_POST['Multiplikator_2']);
				$m2 = str_replace(',','.',$_POST['Multiplikator_3']);
				
				$query = "UPDATE " . PREFIX . "_shop_einstellungen 
				SET 
					$db_wasserzeichen 
					Waehrung_1 = '" . @$_POST['Waehrung_1'] . "',
					WaehrungSymbol_1 = '" . $WaehrungSymbol_1 . "',
					Waehrung_2 = '" . @$_POST['Waehrung_2'] . "',
					WaehrungSymbol_2 = '" . $WaehrungSymbol_2 . "',
					Waehrung_3 = '" . @$_POST['Waehrung_3'] . "',
					WaehrungSymbol_3 = '" . $WaehrungSymbol_3 . "',
					Multiplikator_2 = '" . ($m1<'0.0001' ? 1 : $m1) . "',
					Multiplikator_3 = '" . ($m2<'0.0001' ? 1 : $m2)  . "',
					NettoPreise = '" . $_POST['NettoPreise'] . "',
					ShopLand = '" . $_POST['ShopLand'] . "',
					Email_Abs = '" . $_POST['Email_Abs'] . "',
					Email_Antwort = '" . $_POST['Email_Abs'] . "',
					Email_Wertung = '" . $_POST['Email_Abs'] . "',
					Email_Produktanfrage = '" . $_POST['Email_Abs'] . "',
					Email_Bestellung = '" . $_POST['Email_Bestellung'] . "',
					Name_Abs = '" . $_POST['Name_Abs'] . "',
					Subjekt_Bestellung = '" . $_POST['Subjekt_Bestellung'] . "',
					Subjekt_Best_Kopie = '" . $_POST['Subjekt_Best_Kopie'] . "',
					Gastbestellung = '" . $_POST['Gastbestellung'] . "',
					RechnungsLogo = '" . $_POST['RechnungsLogo'] . "',
					thumb_width_norm = '" . $_POST['thumb_width_norm'] . "',
					thumb_width_middle = '" . $_POST['thumb_width_middle'] . "',
					thumb_width_small = '" . $_POST['thumb_width_small'] . "',
					thumb_width_big = '" . $_POST['thumb_width_big'] . "',
					thumb_quality = '" . $_POST['thumb_quality'] . "',
					Wasserzeichen = '" . $_POST['Wasserzeichen'] . "',
					WasserzeichenKomp = '" . $_POST['WasserzeichenKomp'] . "',
					Wasserzeichen_Position = '" . $_POST['Wasserzeichen_Position'] . "',
					Gutscheine = '" . $_POST['Gutscheine'] . "',
					BestMax = '" . $_POST['BestMax'] . "',
					BestMin = '" . $_POST['BestMin'] . "',
					Bestand_Zaehlen = '" . $_POST['Bestand_Zaehlen'] . "',
					Template_Produkte = '" . $_POST['Template_Produkte'] . "',
					Versandfreibetrag = '" . $_POST['Versandfreibetrag'] . "',
					Start_Limit = '" . $_POST['Start_Limit'] . "',
					Topseller_Limit = '" . $_POST['Topseller_Limit'] . "',
					Angebote_Limit = '" . $_POST['Angebote_Limit'] . "',
					Spalten_Neueste = '" . $_POST['Spalten_Neueste'] . "',
					Spalten_Topseller = '" . $_POST['Spalten_Topseller'] . "',
					Spalten_Angebote = '" . $_POST['Spalten_Angebote'] . "',
					Produkt_Limit_Seite = '" . $_POST['Produkt_Limit_Seite'] . "',
					Topseller_Navi_Limit = '" . $_POST['Topseller_Navi_Limit'] . "',
					Zubehoer_Limit = '" . $_POST['Zubehoer_Limit'] . "',
					Lager_Gering = '" . $_POST['Lager_Gering'] . "',
					Tab_Limit = '" . $_POST['Tab_Limit'] . "',
					Prodtext_Laenge = '" . $_POST['Prodtext_Laenge'] . "',
					LimitExternNeu = '" . $_POST['LimitExternNeu'] . "',
					TplExternNeu = 'page_extern_products_new.tpl'
					
				";
				
				if($_POST['ThumbRenew']==1 || $db_wasserzeichen!='')
				{
					$this->delThumbs(BASE_DIR . '/uploads/shop/icons_thumbnails/big/');
					$this->delThumbs(BASE_DIR . '/uploads/shop/icons_thumbnails/medium/');
					$this->delThumbs(BASE_DIR . '/uploads/shop/icons_thumbnails/normal/');
					$this->delThumbs(BASE_DIR . '/uploads/shop/icons_thumbnails/small/');
					
					if(isset($_POST['watermark_old']) && $_POST['watermark_old']=='')
					{
						@unlink(BASE_DIR . '/uploads/shop/' . $_POST['watermark_old']);
					}
				}
				
				Logger('User ' . $_SESSION['user_name'] . ' update Shop-Settings', '3', $_SESSION['benutzer_id']);
				$GLOBALS['db']->Query($query);
			}
			
			$row = $GLOBALS['db']->RowQuery("SELECT * FROM " . PREFIX . "_shop_einstellungen");
			$row->WasserzeichenBild = (file_exists(BASE_DIR . '/uploads/shop/' . $row->Wasserzeichen_Bild) && $row->Wasserzeichen_Bild!='') ? '<img src="../uploads/shop/' . $row->Wasserzeichen_Bild . '" alt="" border="" />' : '';
			
			
			$GLOBALS['tmpl']->assign('row', $row);
			$GLOBALS['tmpl']->assign('content', $GLOBALS['tmpl']->fetch($GLOBALS['config']['source'] . '/shop/settings.tpl'));
		} else {
			no_perm();
		}
	}
	
	
	function delThumbs($dir)
	{
		$handle = opendir($dir); 
		while ($file = readdir ($handle)) 
		{ 
			if($file != '.' && $file != '..' && $file != '.htaccess') @unlink($dir . $file);
		} 
	}
	
	//=================================================================
	// Shop-Informationen
	//=================================================================
	function shopInfos()
	{
		if(perm('shop_settings'))
		{
			$error = '';
			if(isset($_POST['save']) && $_POST['save']==1)
			{
				if(empty($_POST['ShopAdresse'])) $error[] = $GLOBALS['config_vars']['Shop_error_company'];
				if(empty($_POST['ShopAGB'])) $error[] = $GLOBALS['config_vars']['Shop_error_agb'];
				if(empty($_POST['Widerruf'])) $error[] = $GLOBALS['config_vars']['Shop_error_cancel'];
				
				if($error)
				{
					$GLOBALS['tmpl']->assign('error', $error);
				} else {
					$GLOBALS['db']->Query("UPDATE " . PREFIX . "_shop_einstellungen 
					SET 
						Fsk18 = '" . $_POST['Fsk18'] . "',
						ShopInfo_1='" . @$_POST['ShopInfo_1']. "', 
						ShopInfo_2='" . @$_POST['ShopInfo_2']. "', 
						ShopInfo_3='" . @$_POST['ShopInfo_3']. "',
						ShopAGB = '" . $_POST['ShopAGB'] . "',
						ShopDatenschutz = '" . $_POST['ShopDatenschutz'] . "',
						ShopAdresse = '" . $_POST['ShopAdresse'] . "',
						Widerruf = '" . $_POST['Widerruf'] . "',
						VersandInfo_Footer = '" . $_POST['VersandInfo_Footer'] . "'
					");
					Logger('User ' . $_SESSION['user_name'] . ' update Shop-Infos', '3', $_SESSION['benutzer_id']);
					echo '<script>window.close();</script>';
				}
			}
			
			$row = $GLOBALS['db']->RowQuery("SELECT Fsk18,ShopDatenschutz,ShopAdresse,Widerruf,ShopAGB,ShopInfo_1,ShopInfo_2,ShopInfo_3,VersandInfo_Footer FROM " . PREFIX . "_shop_einstellungen");
			
			$GLOBALS['tmpl']->assign('VersandInfo_Footer', fckInit((isset($_POST['VersandInfo_Footer']) ? $_POST['VersandInfo_Footer'] : $row->VersandInfo_Footer), 'VersandInfo_Footer', 200, 'ShopSettings'));
			$GLOBALS['tmpl']->assign('ShopAdresse', fckInit((isset($_POST['ShopAdresse']) ? $_POST['ShopAdresse'] : $row->ShopAdresse), 'ShopAdresse', 150, 'ShopSettings'));
			$GLOBALS['tmpl']->assign('ShopAGB', fckInit((isset($_POST['ShopAGB']) ? $_POST['ShopAGB'] : $row->ShopAGB), 'ShopAGB', 200, 'ShopSettings'));
			$GLOBALS['tmpl']->assign('ShopDatenschutz', fckInit((isset($_POST['ShopDatenschutz']) ? $_POST['ShopDatenschutz'] : $row->ShopDatenschutz), 'ShopDatenschutz', 200, 'ShopSettings'));
			$GLOBALS['tmpl']->assign('Widerruf', fckInit((isset($_POST['Widerruf']) ? $_POST['Widerruf'] : $row->Widerruf), 'Widerruf', 200, 'ShopSettings'));
			$GLOBALS['tmpl']->assign('ShopInfo_1', fckInit((isset($_POST['ShopInfo_1']) ? $_POST['ShopInfo_1'] : $row->ShopInfo_1), 'ShopInfo_1', 200, 'ShopSettings'));
			$GLOBALS['tmpl']->assign('ShopInfo_2', fckInit((isset($_POST['ShopInfo_2']) ? $_POST['ShopInfo_2'] : $row->ShopInfo_2), 'ShopInfo_2', 200, 'ShopSettings'));
			$GLOBALS['tmpl']->assign('ShopInfo_3', fckInit((isset($_POST['ShopInfo_3']) ? $_POST['ShopInfo_3'] : $row->ShopInfo_3), 'ShopInfo_3', 200, 'ShopSettings'));
			$GLOBALS['tmpl']->assign('Fsk18', fckInit((isset($_POST['Fsk18']) ? $_POST['Fsk18'] : $row->Fsk18), 'Fsk18', 200, 'ShopSettings'));
			$GLOBALS['tmpl']->assign('content', $GLOBALS['tmpl']->fetch($GLOBALS['config']['source'] . '/shop/shopinfos.tpl'));
		} else {
			no_perm();
		}
	}
	
	function userDownloads($user)
	{
		if(perm('shop_downloads'))
		{
			if(isset($_REQUEST['save']) && $_REQUEST['save']==1)
			{
				$user  = abs((int)$_REQUEST['user']);
				foreach($_POST['Userfile'] as $uf => $val)
				{
					$dltill = explode('.', $_POST['DownloadBis'][$uf]);
					
					// Lizenz = '" . @$_POST['Lizenz'][$uf] . "',
					$query = "UPDATE " . PREFIX . "_shop_downloads_user 
					SET
						DownloadBis = '" . mktime(23,59,59,$dltill[1],$dltill[0],$dltill[2]) . "',
						UrlLizenz = '" . $_POST['UrlLizenz'][$uf] . "',
						KommentarBenutzer = '" . @$_POST['KommentarBenutzer'][$uf] . "',
						KommentarAdmin = '" . @$_POST['KommentarAdmin'][$uf] . "',
						Gesperrt = '" . $_POST['Gesperrt'][$uf] . "',
						GesperrtGrund = '" . @$_POST['GesperrtGrund'][$uf] . "',
						UrlLizenz_Pflicht= '" . @$_POST['UrlLizenz_Pflicht'][$uf] . "' 
					WHERE
						Benutzer = '$user' AND Id = '$uf'
					";
					$GLOBALS['db']->Query($query);
					if(isset($_POST['del'][$uf]) && $_POST['del'][$uf]==1)
					{
						$GLOBALS['db']->Query("DELETE FROM " . PREFIX . "_shop_downloads_user  WHERE Id = '$uf'");
					}
				}
			}
			
	
			if(isset($_POST['newfile']) && $_POST['newfile']==1)
			{
				$user  = abs((int)$_REQUEST['user']);
				$art_arr = explode('||', $_REQUEST['ArtikelId']);
				$time_arr = explode('.', $_REQUEST['DownloadBis']);
				$artid = $art_arr[0];
				$dltill = mktime(23,59,59,$time_arr[1],$time_arr[0],$time_arr[2]);
				$pname = $art_arr[1];
				$license = $this->newKey();
				
				
				$dbres = $GLOBALS['db']->Query("INSERT INTO " . PREFIX . "_shop_lizenzen VALUES 
				(
					'',
					'$user',
					'$license',
					'".time()."',
					'".date('Y-m-d H:i:s')."',
					'".$pname."',
					'".$dltill."',
					'".$artid."'
				)");
				
				if(!$dbres)
				{
					$license = $this->newKey();
					$GLOBALS['db']->Query("INSERT INTO " . PREFIX . "_shop_lizenzen VALUES 
					(
						'',
						'$user',
						'$license',
						'".time()."',
						'".date('Y-m-d H:i:s')."',
						'".$pname."',
						'".$dltill."',
						'".$artid."'
					)");
				}
				
				$GLOBALS['db']->Query("INSERT INTO " . PREFIX . "_shop_downloads_user 
				(
					Id,
					Benutzer,
					PName,
					ArtikelId,
					DownloadBis,
					Lizenz
				) VALUES (
					'',
					'$user',
					'$pname',
					'$artid',
					'$dltill',
					'$license'
				)");
				
				
				
			}
			
			$userfiles = array();
			$res_c = $GLOBALS['db']->RowQuery("SELECT Id FROM " . PREFIX . "_shop_downloads_user WHERE Benutzer = '$user'");
			
			$sql = $GLOBALS['db']->Query("SELECT * FROM " . PREFIX . "_shop_downloads_user WHERE Benutzer = '$user' ORDER BY PName 	 ASC");
			if(is_object($res_c))
			{
				while($row = $sql->fetchrow())
				{
					$sql_2 = $GLOBALS['db']->Query("SELECT * FROM " . PREFIX . "_shop_produkte WHERE Id='$row->ArtikelId'");
					$row_2 = $sql_2->fetchrow();
					
					$row->article = $row_2->Titel_1;
					$row->date_day = date("d",$row->DownloadBis);
					$row->date_month = date("m",$row->DownloadBis);
					$row->date_year = date("Y",$row->DownloadBis);
					array_push($userfiles, $row);
				}
				$GLOBALS['tmpl']->assign('userfiles', $userfiles);
				$GLOBALS['tmpl']->assign('row', $row);
			}
			
			// Alle Produkte listen, die downloadbare Artikel enthalten koennen
			$produkte = array();
			$sql = $GLOBALS['db']->Query("SELECT Titel_1,Id FROM " . PREFIX . "_shop_produkte WHERE Hat_ESD = '1'");
			while($row = $sql->fetchrow())
			{
				array_push($produkte, $row);
			}
			
			// Lizenz erzeugen
			$ld = $this->licdata();
			
			$GLOBALS['tmpl']->assign('lizenz', $ld);
			$GLOBALS['tmpl']->assign('produkte', $produkte);
			$GLOBALS['tmpl']->assign('selmon', date("m"));
			$GLOBALS['tmpl']->assign('selday', date("d"));
			$GLOBALS['tmpl']->assign('selyear', date("Y"));
			$GLOBALS['tmpl']->assign('content', $GLOBALS['tmpl']->fetch($GLOBALS['config']['source'] . '/shop/userfiles.tpl'));
		} else {
			no_perm();
		}
	}
	
	function licdata()
	{
		$licdata = mt_rand(100000000,199999999);
		$data = "";
		
		for ($i = 0; $i < strlen($licdata); $i++) {
			$data .= substr($licdata, $i, 1);
			if (( ($i+1) % 3) == 0 && $i != 0) {
				$data .= "-";
			}
		}
		$lic = substr($data, 0,11);
		$ld_c = $GLOBALS['db']->RowQuery("SELECT Lizenz FROM " . PREFIX . "_shop_downloads_user Lizenz = '$lic'");
		if(is_object($ld_c) && $ld_c->Lizenz == $lic)
		{
			$this->licdata();
		} else {
			return $lic;
		}
	}
	
	//=======================================================
	// Datei - Downloads für einen Artikel
	//=======================================================
	function esdDownloads($aid)
	{
		if(perm('shop_downloads'))
		{
			// Neu anlegen
			if(isset($_REQUEST['subaction']) && $_REQUEST['subaction'] == 'new')
			{
				$GLOBALS['db']->Query("INSERT INTO " . PREFIX . "_shop_downloads
				(
					Id,
					ArtId,
					Datei,
					DateiTyp,
					TageNachKauf,
					Bild,
					Titel,
					Beschreibung,
					Position
				) VALUES (
					'',
					'" . $aid . "',
					'" . ((isset($_POST['newFile_1']) && !empty($_POST['newFile_1'])) ? $_POST['newFile_1'] : @$_POST['Datei']) . "',
					'" . @$_POST['DateiTyp'] . "',
					'" . @$_POST['TageNachKauf'] . "',
					'" . @$_POST['Bild'] . "',
					'" . @$_POST['Titel'] . "',
					'" . @koobispecialchars($_POST['Beschreibung']) . "',
					'" . @$_POST['Position'] . "')
				");
				$GLOBALS['db']->Query("UPDATE " . PREFIX . "_shop_produkte SET Hat_ESD = '1' WHERE Id = '$aid'");
			}
		
			
			if(isset($_REQUEST['subaction']) && $_REQUEST['subaction'] == 'save')
			{
			// Speichern
				if(isset($_POST['Del']) && $_POST['Del'] >= 1)
				{
					foreach($_POST['Del'] as $id => $Datei) $GLOBALS['db']->Query("DELETE FROM " . PREFIX . "_shop_downloads WHERE Id = '$id'");
				}
				
				if(isset($_POST['Datei']))
				{
					foreach($_POST['Datei'] as $id => $Datei)
					{
						$GLOBALS['db']->Query("UPDATE " . PREFIX . "_shop_downloads 
						SET 
							Datei = '" . @$_POST['Datei'][$id] . "',
							DateiTyp = '" . @$_POST['DateiTyp'][$id] . "',
							TageNachKauf = '" . @$_POST['TageNachKauf'][$id] . "',
							Bild = '" . @$_POST['Bild'][$id] . "',
							Titel = '" . @$_POST['Titel'][$id] . "',
							Beschreibung = '" . @koobispecialchars($_POST['Beschreibung'][$id]) . "',
							Position = '" . @$_POST['Position'][$id] . "'
						WHERE Id = '$id'");
					}
				}
			}
			
			$downloads_full = array();
			$downloads_updates = array();
			$downloads_bugfixes = array();
			$downloads_other = array();
			
			$sql_full = $GLOBALS['db']->Query("SELECT * FROM " . PREFIX . "_shop_downloads WHERE  DateiTyp='full' AND ArtId='$aid' ORDER BY Position ASC");
			$sql_updates = $GLOBALS['db']->Query("SELECT * FROM " . PREFIX . "_shop_downloads WHERE  DateiTyp='update' AND ArtId='$aid' ORDER BY Position ASC");
			$sql_bugfixes = $GLOBALS['db']->Query("SELECT * FROM " . PREFIX . "_shop_downloads WHERE  DateiTyp='bugfix' AND ArtId='$aid' ORDER BY Position ASC");
			$sql_other = $GLOBALS['db']->Query("SELECT * FROM " . PREFIX . "_shop_downloads WHERE  DateiTyp='other' AND ArtId='$aid' ORDER BY Position ASC");
			
			while($row_full = $sql_full->fetchrow()) array_push($downloads_full, $row_full);
			while($row_updates = $sql_updates->fetchrow()) array_push($downloads_updates, $row_updates);
			while($row_bugfixes = $sql_bugfixes->fetchrow()) array_push($downloads_bugfixes, $row_bugfixes);
			while($row_other = $sql_other->fetchrow()) array_push($downloads_other, $row_other);
			
			$GLOBALS['tmpl']->assign('can_upload', ((is_writable(BASE_DIR . 'uploads/shop/files/')) ? 1 : 0) );
			$GLOBALS['tmpl']->assign('downloads_full', $downloads_full);
			$GLOBALS['tmpl']->assign('downloads_updates', $downloads_updates);
			$GLOBALS['tmpl']->assign('downloads_bugfixes', $downloads_bugfixes);
			$GLOBALS['tmpl']->assign('downloads_other', $downloads_other);
			$GLOBALS['tmpl']->assign('esds', $this->fetchEsdFiles());
			$GLOBALS['tmpl']->assign('content', $GLOBALS['tmpl']->fetch($GLOBALS['config']['source'] . '/shop/article_downloads.tpl'));
		} else {
			no_perm();
		}
	}
	
	
	function EditShippingVolumes($id)
	{
		if(perm('shop_shipper'))
		{
			// Neu
			if(isset($_POST['new']) && $_POST['new']==1 && !empty($_POST['Bis']) && !empty($_POST['Gebuehr']))
			{
				$_POST['Gebuehr'] = trim(str_replace(',','.',$_POST['Gebuehr']));
				$_POST['Bis']     = trim(str_replace(',','.',$_POST['Bis']));
				$_POST['Bis']     = ($_POST['Bis'] <= $_POST['Von']) ? ($_POST['Von'] + 10.00) : $_POST['Bis'];
				
				$Gebuehr = ($_POST['Gebuehr'] < $_POST['GebuehrCheck']) ? ($_POST['GebuehrCheck'] + 10.00) : $_POST['Gebuehr'];
				
				$GLOBALS['db']->Query("INSERT INTO " . PREFIX . "_shop_versandarten_volumen
				(
					Id, 
					VersandId,
					Von,
					Bis,
					Gebuehr
				) VALUES (
					'',
					'$id',
					'" . $_POST['Von'] . "',
					'" . $_POST['Bis'] . "',
					'$Gebuehr'
				)");
				Logger('User ' . $_SESSION['user_name'] . ' add new Shipping-Volume', '3', $_SESSION['benutzer_id']);
				header('Location:index.php?do=shop&sub=editshippingvolumes&Id=' . $id . '&noframes=1');
				exit;
			}
			
			// Speichern
			if(isset($_POST['save']) && $_POST['save']==1)
			{
				foreach($_POST['Von'] as $vid => $var)
				{
					$_POST['Bis'][$vid] = ($_POST['Bis'][$vid] <= $_POST['Von'][$vid]) ? $_POST['Von'][$vid] + 1 : $_POST['Bis'][$vid];
					$GLOBALS['db']->Query("UPDATE " . PREFIX . "_shop_versandarten_volumen 
					SET
						Von = '" . $_POST['Von'][$vid] . "',
						Bis = '" . $_POST['Bis'][$vid] . "',
						Gebuehr = '" . $_POST['Gebuehr'][$vid] . "' 
					WHERE 
						Id = '$vid'");
					
					if(isset($_POST['Del'][$vid]) && $_POST['Del'][$vid]==1)
					{
						$GLOBALS['db']->Query("DELETE FROM " . PREFIX . "_shop_versandarten_volumen WHERE Id='$vid'");
					}
				}
			}
			
			// Auslesen
			$volumes = array();
			$sql = $GLOBALS['db']->Query("SELECT * FROM " . PREFIX . "_shop_versandarten_volumen WHERE VersandId = '$id' ORDER BY Von ASC");
			while($row = $sql->fetchrow()) array_push($volumes, $row);
			
			$last = $GLOBALS['db']->RowQuery("SELECT * FROM " . PREFIX . "_shop_versandarten_volumen WHERE VersandId = '$id' ORDER BY Von DESC");
			$row  = $GLOBALS['db']->RowQuery("SELECT Name_1 AS Name FROM " . PREFIX . "_shop_versandarten WHERE Id = '$_REQUEST[Id]'");
			
			$GLOBALS['tmpl']->assign('new_f', ($last->Bis + '0.01'));
			$GLOBALS['tmpl']->assign('new_t', ($last->Bis + '10.00'));
			$GLOBALS['tmpl']->assign('new_g', ($last->Gebuehr + '5.00'));
			$GLOBALS['tmpl']->assign('volumes', $volumes);
			$GLOBALS['tmpl']->assign('title', $GLOBALS['config_vars']['Shop_shipper_w_edit'] . ': ' . koobispecialchars($row->Name) );
			$GLOBALS['tmpl']->assign('row', $row);
			$GLOBALS['tmpl']->assign('content', $GLOBALS['tmpl']->fetch($GLOBALS['config']['source'] . '/shop/shipper_volumes.tpl'));
		}
	}
	
	//=======================================================
	// Versandart bearbeiten
	//=======================================================
	function EditShipper($id,$lc=1,$IconDel='')
	{
		if(perm('shop_shipper'))
		{
			// Speichern
			$SetAll = '';
			if(isset($_POST['save']) && $_POST['save']==1)
			{
				if(isset($_POST['IconDel']) && $_POST['IconDel']==1 && !empty($_POST['IconDelOld']))
				{
					$IconDel = "Icon = '',";
					@unlink(BASE_DIR . 'uploads/shop/shipper_icons/' . $_POST['IconDelOld']);
				}
				
				if($_REQUEST['lc']<2)
				{
					if(isset($_POST['saveAllLang']) && $_POST['saveAllLang']==1)
					{
						$SetAll = "
							,Name_2 = '" . $_POST['Name'] . "'
							,Beschreibung_2 = '" . @$_POST['Beschreibung_1'] . "'
							,Name_3 = '" . $_POST['Name'] . "'
							,Beschreibung_3 = '" . @$_POST['Beschreibung_1'] . "'
							";
					}
					
					$GLOBALS['db']->Query("UPDATE " . PREFIX . "_shop_versandarten
					SET
						Name_{$lc} = '" . $_POST['Name'] . "',
						$IconDel 
						" . ((isset($_POST['newImg_1']) && !empty($_POST['newImg_1'])) ? "Icon = '" . $_POST['newImg_1'] . "'," : "" ). "
						Beschreibung_{$lc} = '" . $_POST['Beschreibung_' . $lc] . "',
						Laender = '" . implode($_POST['Laender'],',') . "',
						Gruppen = '" . implode($_POST['Gruppen'],',') . "',
						GewichtNull = '" . $_POST['GewichtNull'] . "',
						Versanddauer = '" . $_POST['Versanddauer'] . "',
						Gebuehr_Pauschal = '" . str_replace(',','.',$_POST['Gebuehr_Pauschal']) . "' 
						{$SetAll} 
					WHERE Id='$id'");
				} else {
					$GLOBALS['db']->Query("UPDATE " . PREFIX . "_shop_versandarten
					SET
						Name_{$lc} = '" . $_POST['Name'] . "',
						Beschreibung_{$lc} = '" . $_POST['Beschreibung_' . $lc] . "' 
					WHERE Id='$id'");
				}
				Logger('User ' . $_SESSION['user_name'] . ' save Shipping-Method (' . $_POST['Name'] . ')', '3', $_SESSION['benutzer_id']);
				echo '<script language="javascript">window.opener.location.reload();</script>';	
			}
			// Auslesen
			$row = $GLOBALS['db']->RowQuery("SELECT 
				*, 
				Name_{$lc} AS Name, 
				Beschreibung_{$lc} AS Beschreibung 
			FROM " . PREFIX . "_shop_versandarten WHERE Id = '$id'");
			
			$GLOBALS['tmpl']->assign('row', $row);
			$GLOBALS['tmpl']->assign('writable', ((is_writable(BASE_DIR . 'uploads/shop/shipper_icons/')) ? 1 : 0));
			$GLOBALS['tmpl']->assign('countries_in', (explode(',',$row->Laender)) );
			$GLOBALS['tmpl']->assign('groups_in', (explode(',',$row->Gruppen)) );
			$GLOBALS['tmpl']->assign('countries', $this->Countries());
			$GLOBALS['tmpl']->assign('groups', $this->Groups());
			$GLOBALS['tmpl']->assign('intro', fckInit($row->Beschreibung, "Beschreibung_{$lc}", 150, 'Basic'));
			$GLOBALS['tmpl']->assign('title', $GLOBALS['config_vars']['Shop_shipper_edit']);
			$GLOBALS['tmpl']->assign('content', $GLOBALS['tmpl']->fetch($GLOBALS['config']['source'] . '/shop/shipper_edit.tpl'));
		}
	}
	
	//=======================================================
	// Versandarten
	//=======================================================
	function ShippingMethods()
	{
		if(perm('shop_shipper'))
		{
		// Speichern
			if(isset($_POST['save']) && $_POST['save']==1)
			{
				foreach ($_POST['Aktiv'] as $id => $var)
				{
					$GLOBALS['db']->Query("UPDATE " . PREFIX . "_shop_versandarten
					SET 
						Aktiv = '" . $_POST['Aktiv'][$id] . "',
						Position = '" . @$_POST['Position'][$id] . "' 
					WHERE Id='$id'");
				}
				Logger('User ' . $_SESSION['user_name'] . ' save Shipping-Method (Position)', '3', $_SESSION['benutzer_id']);
				header('Location:index.php?do=shop&sub=shipper');
				exit;
			}
			
			$Lc = $_SESSION['AdminLangcode'];
			$methods = array();
			$sql = $GLOBALS['db']->Query("SELECT * FROM " . PREFIX . "_shop_versandarten ORDER BY Position ASC");
			while($row = $sql->fetchrow()) array_push($methods, $row);
			
			$GLOBALS['tmpl']->assign('methods', $methods);
			$GLOBALS['tmpl']->assign('title', $GLOBALS['config_vars']['Shop_shipper_title']);
			$GLOBALS['tmpl']->assign('content', $GLOBALS['tmpl']->fetch($GLOBALS['config']['source'] . '/shop/shippingmethods.tpl'));
		}
	}
	
	//=======================================================
	// Zahlungsmethode bearbeiten
	//=======================================================
	function EditPaymentMethod($id,$lc=1,$IconDel='')
	{
		if(perm('shop_paymentmethods'))
		{
			// Speichern
			$SetAll = '';
			if(isset($_POST['save']) && $_POST['save']==1)
			{
				if(isset($_POST['IconDel']) && $_POST['IconDel']==1 && !empty($_POST['IconDelOld']))
				{
					$IconDel = "Icon = '',";
					@unlink(BASE_DIR . 'uploads/shop/payment_icons/' . $_POST['IconDelOld']);
				}
				
				if($_REQUEST['lc']<2)
				{
					$Betreff    = (isset($_POST['Betreff'])) ? "Betreff = '" . $_POST['Betreff'] . "'," : "";
					$Testmodus  = (isset($_POST['Testmodus'])) ? "Testmodus = '" . $_POST['Testmodus'] . "'," : "";
					$Install_Id = (isset($_POST['Install_Id'])) ? "Install_Id = '" . $_POST['Install_Id'] . "'," : "";
					$Kosten     = str_replace(',','.',@$_POST['Kosten']);
					$Kosten     = ($_POST['KostenTyp']=='pro' && $Kosten>100) ? 100 : $Kosten;
					
					if(isset($_POST['saveAllLang']) && $_POST['saveAllLang']==1)
					{
						$SetAll = "
							,Name_2 = '" . $_POST['Name'] . "'
							,Beschreibung_2 = '" . @$_POST['Beschreibung_1'] . "'
							,BeschreibungLang_2 = '" . @$_POST['BeschreibungLang_1'] . "'
							,Name_3 = '" . $_POST['Name'] . "'
							,Beschreibung_3 = '" . @$_POST['Beschreibung_1'] . "'
							,BeschreibungLang_3 = '" . @$_POST['BeschreibungLang_1'] . "'
							";
					}
					
					$GLOBALS['db']->Query("UPDATE " . PREFIX . "_shop_zahlungsmethoden 
					SET
						Name_{$lc} = '" . $_POST['Name'] . "',
						$IconDel 
						$Betreff 
						$Testmodus 
						$Install_Id 
						" . ((isset($_POST['newImg_1']) && !empty($_POST['newImg_1'])) ? "Icon = '" . $_POST['newImg_1'] . "'," : "" ). "
						Beschreibung_{$lc} = '" . $_POST['Beschreibung_' . $lc] . "',
						BeschreibungLang_{$lc} = '" . $_POST['BeschreibungLang_' . $lc] . "',
						Laender = '" . implode($_POST['Laender'],',') . "',
						Gruppen = '" . implode($_POST['Gruppen'],',') . "',
						Versandarten = '" . implode($_POST['Versandarten'],',') . "',
						KostenOperant = '" . $_POST['KostenOperant'] . "',
						Kosten = '" . $Kosten . "',
						KostenTyp = '" . $_POST['KostenTyp'] . "',
						DetailInfo = '" . $_POST['DetailInfo'] . "' 
						{$SetAll} 
					WHERE Id='$id'");
				} else {
					$GLOBALS['db']->Query("UPDATE " . PREFIX . "_shop_zahlungsmethoden 
					SET
						Name_{$lc} = '" . $_POST['Name'] . "',
						Beschreibung_{$lc} = '" . $_POST['Beschreibung_' . $lc] . "',
						BeschreibungLang_{$lc} = '" . $_POST['BeschreibungLang_' . $lc] . "' 
					WHERE Id='$id'");
				}
				Logger('User ' . $_SESSION['user_name'] . ' edit Payment-Method (' . $_POST['Name'] . ')', '3', $_SESSION['benutzer_id']);
				echo '<script language="javascript">window.opener.location.reload();</script>';
				
			}
			
			// Auslesen
			$row = $GLOBALS['db']->RowQuery("SELECT 
				*, 
				Name_{$lc} AS Name, 
				Beschreibung_{$lc} AS Beschreibung,  
				BeschreibungLang_{$lc} AS BeschreibungLang
			FROM " . PREFIX . "_shop_zahlungsmethoden WHERE Id = '$id'");
			
			$GLOBALS['tmpl']->assign('row', $row);
			$GLOBALS['tmpl']->assign('writable', ((is_writable(BASE_DIR . 'uploads/shop/payment_icons/')) ? 1 : 0));
			$GLOBALS['tmpl']->assign('countries_in', (explode(',',$row->Laender)) );
			$GLOBALS['tmpl']->assign('groups_in', (explode(',',$row->Gruppen)) );
			$GLOBALS['tmpl']->assign('shipper_in', (explode(',',$row->Versandarten)) );
			$GLOBALS['tmpl']->assign('countries', $this->Countries());
			$GLOBALS['tmpl']->assign('groups', $this->Groups());
			$GLOBALS['tmpl']->assign('shipper', $this->Shipper());
			$GLOBALS['tmpl']->assign('intro', fckInit($row->Beschreibung, "Beschreibung_{$lc}", 250, 'ShopSettings'));
			$GLOBALS['tmpl']->assign('text', fckInit($row->BeschreibungLang, "BeschreibungLang_{$lc}", 300, 'ShopSettings'));
			$GLOBALS['tmpl']->assign('payinf', fckInit($row->DetailInfo, "DetailInfo", 300, 'ShopSettings'));
			$GLOBALS['tmpl']->assign('title', $GLOBALS['config_vars']['Shop_payment_edit']);
			$GLOBALS['tmpl']->assign('content', $GLOBALS['tmpl']->fetch($GLOBALS['config']['source'] . '/shop/paymentmethod_edit.tpl'));
			
		}
		
	}
	
	//=======================================================
	// Zahlungs-Methoden
	//=======================================================
	function PaymentMethods()
	{
		if(perm('shop_paymentmethods'))
		{
			// Speichern
			if(isset($_POST['save']) && $_POST['save']==1)
			{
				foreach ($_POST['Aktiv'] as $id => $var)
				{
					$GLOBALS['db']->Query("UPDATE " . PREFIX . "_shop_zahlungsmethoden 
					SET 
						Aktiv = '" . $_POST['Aktiv'][$id] . "',
						Position = '" . @$_POST['Position'][$id] . "' 
					WHERE Id='$id'");
				}
				Logger('User ' . $_SESSION['user_name'] . ' saved Payment-Methods (Position)', '3', $_SESSION['benutzer_id']);
				header('Location:index.php?do=shop&sub=paymentmethods');
				exit;
			}
			
			$Lc = $_SESSION['AdminLangcode'];
			$methods = array();
			$sql = $GLOBALS['db']->Query("SELECT * FROM " . PREFIX . "_shop_zahlungsmethoden ORDER BY Position ASC");
			while($row = $sql->fetchrow()) array_push($methods, $row);
			
			$GLOBALS['tmpl']->assign('methods', $methods);
			$GLOBALS['tmpl']->assign('title', $GLOBALS['config_vars']['Shop_payment_title']);
			$GLOBALS['tmpl']->assign('content', $GLOBALS['tmpl']->fetch($GLOBALS['config']['source'] . '/shop/paymentmethods.tpl'));
		}
	}
	
	//=======================================================
	// Gutscheine
	//=======================================================
	function CouponCodes()
	{
		if(perm('shop_couponcodes'))
		{
			
			if(isset($_POST['new']) && $_POST['new']==1 && $_POST['Code']>=1)
			{
				foreach ($_POST['Code'] as $id => $couponcode)
				{
					if( !empty($_POST['Code'][$id]) && !empty($_POST['Wert'][$id]))
					{
						$min_amount = str_replace(",", ".", $_POST['MinBestellwert'][$id]);
						$ex = @explode(".", $_POST['GueltigBis'][$id]);
						$expires_on = (!empty($ex[0]) && !empty($ex[1]) && !empty($ex[2])) ? mktime(23,23,59,$ex[1],$ex[0],$ex[2]) : mktime(23,23,59,date('m'),date('d'),date('Y')+1);
						$amount = ($_POST['Typ'][$id] == 'pro') ? ( ($_POST['Wert'][$id]>99) ? 99 : str_replace(',','.',$_POST['Wert'][$id]) ) : ( str_replace(',','.',$_POST['Wert'][$id])  );
						
						
						$query = "INSERT INTO ".PREFIX."_shop_gutscheine
						(
							Id,
							Code,
							Wert,
							Erstellt,
							Typ,
							Endlos,
							GueltigBis,
							MinBestellwert,
							Gastbestellung
						) VALUES (
							'',
							'" . $_POST['Code'][$id] . "',
							'" . $amount . "',
							'" . stime() . "',
							'" . $_POST['Typ'][$id] . "',
							'" . $_POST['Endlos'][$id] . "',
							'" . $expires_on . "',
							'" . $min_amount . "',
							'" . $_POST['Gastbestellung'][$id] . "'
						)";
						$GLOBALS['db']->Query($query);
					}
				}
			}
			// Speichern
			if(isset($_POST['save']) && $_POST['save']==1)
			{
				foreach ($_POST['Code'] as $id => $couponcode)
				{
					if(!empty($_POST['Code'][$id]) && !empty($_POST['Wert'][$id]))
					{
						
						$min_amount = str_replace(",", ".", $_POST['MinBestellwert'][$id]);
						$ex = @explode(".", $_POST['GueltigBis'][$id]);
						$expires_on = (!empty($ex[0]) && !empty($ex[1]) && !empty($ex[2])) ? mktime(23,23,59,$ex[1],$ex[0],$ex[2]) : mktime(23,23,59,date('m'),date('d'),date('Y')+1);
						$amount = ($_POST['Typ'][$id] == 'pro') ? ( ($_POST['Wert'][$id]>99) ? 99 : str_replace(',','.',$_POST['Wert'][$id]) ) : ( str_replace(',','.',$_POST['Wert'][$id])  );
						
						$query = "UPDATE  ".PREFIX."_shop_gutscheine 
						SET 
							Code = '" . trim($_POST['Code'][$id]) . "',
							Wert = '" . $amount . "',
							Typ = '" . $_POST['Typ'][$id] . "',
							Endlos = '" . $_POST['Endlos'][$id] . "',
							GueltigBis = '" . $expires_on . "',
							MinBestellwert = '" . $min_amount . "'
						WHERE
							Id = '$id'";
						$GLOBALS['db']->Query($query);
					}
					
					if(!empty($_POST['Del'][$id]) && $_POST['Del'][$id]==1)
					{
						$GLOBALS['db']->Query("DELETE FROM ".PREFIX."_shop_gutscheine WHERE Id = '$id'");
					}
				}
			}
			
			// Auslesen
			$_REQUEST['show'] = (isset($_REQUEST['show']) && !empty($_REQUEST['show'])) ? $_REQUEST['show'] : 'all';
			switch($_REQUEST['show'])
			{
				case 'all':$dbsort = "ORDER BY Erstellt DESC";break;
				case 'red':$dbsort = " WHERE Eingeloest > 1 ORDER BY Erstellt DESC";break;
				case 'free':$dbsort = " WHERE Eingeloest < 1 ORDER BY Erstellt DESC";break;
			}
			
			
			$sql = $GLOBALS['db']->Query("SELECT Id FROM " . PREFIX . "_shop_gutscheine $dbsort");
			$limit = (isset($_REQUEST['limit']) && !empty($_REQUEST['limit'])) ? (int)$_REQUEST['limit'] : 10;
			$num = $sql->numrows();
			$seiten = ceil($num / $limit);
			$a = prepage() * $limit - $limit;
		
			$codes = array();
			$sql = $GLOBALS['db']->Query("SELECT * FROM " . PREFIX . "_shop_gutscheine $dbsort LIMIT $a,$limit");
			while($row = $sql->fetchrow()) 
			{
				if($row->Bestellnummern!='')
				{
					
					$on = explode(',', $row->Bestellnummern);
					$multi = array();
					foreach($on as $id => $order)
					{
						$r_status = $GLOBALS['db']->RowQuery("SELECT Status,Id FROM " . PREFIX . "_shop_bestellungen WHERE Id = '$order'");
						if(is_object($r_status)) array_push($multi, $r_status);
					}
					$row->Multi = $multi;
				} else {
					$multi = array();
					$r_status = $GLOBALS['db']->RowQuery("SELECT Status,Id FROM " . PREFIX . "_shop_bestellungen WHERE Id = '$row->Bestellnummer'");
					if(is_object($r_status)) array_push($multi, $r_status);
					$row->Multi = $multi;
				}
				
				$GLOBALS['tmpl']->assign('row',$row);
				$row->InfT = $GLOBALS['tmpl']->fetch($GLOBALS['config']['source'] . '/shop/couponcodes_inf.tpl');
				$row->InfT = htmlspecialchars($row->InfT);
				array_push($codes, $row);
			}
			
			if($num > $limit)
			{
				$GLOBALS['tmpl']->assign('navi',$navi = pagenav($seiten, '', " <a class=\"page_navigation\" href=\"index.php?do=shop&sub=couponcodes&amp;show=$_REQUEST[show]&amp;limit=$limit&amp;page={s}\">{t}</a> "));
			}
			
			$new = array();
			for($i=1; $i<4; $i++) array_push($new,$this->CouponRandom(6));
			
			$GLOBALS['tmpl']->assign('new_till', mktime(0, 0, 0, date("m")+3, date("d"),   date("Y")));
			$GLOBALS['tmpl']->assign('nc', $new);
			$GLOBALS['tmpl']->assign('codes', $codes);
			$GLOBALS['tmpl']->assign('title', $GLOBALS['config_vars']['Shop_couponcodes_title']);
			$GLOBALS['tmpl']->assign('content', $GLOBALS['tmpl']->fetch($GLOBALS['config']['source'] . '/shop/couponcodes.tpl'));
		}
	}
	
	function Specifications($id)
	{
		if(perm('shop_specifications'))
		{
			// Speichern
			if(isset($_POST['save']) && $_POST['save']==1)
			{
				$q = '';
				for($i=1; $i<=15; $i++)
				{
					$q .= "
					Spez_{$i} = '" . @$_POST['Spez_' . $i] . "',
					Spez_{$i}_2 = '" . (empty($_POST['Spez_' . $i . '_2']) ? @$_POST['Spez_' . $i] : @$_POST['Spez_' . $i . '_2']) . "',
					Spez_{$i}_3 = '" . (empty($_POST['Spez_' . $i . '_3']) ? @$_POST['Spez_' . $i] : @$_POST['Spez_' . $i . '_3']) . "',
					";
				}
			
				$GLOBALS['db']->Query("UPDATE " . PREFIX . "_shop_kategorie_spezifikation SET $q Kategorie = '$id' WHERE Kategorie = '$id'");
				echo "<script>window.opener.location.reload(); window.close();</script>";
			}
			
			$res = $GLOBALS['db']->ArrQuery("SELECT * FROM " . PREFIX . "_shop_kategorie_spezifikation WHERE Kategorie = '$id'");
			if(!is_array($res)) 
			{
				$GLOBALS['db']->Query("INSERT INTO " . PREFIX . "_shop_kategorie_spezifikation (Id, Kategorie) VALUES ('','$id')");
			}
			
			
			$GLOBALS['tmpl']->assign('res', $res);
			$GLOBALS['tmpl']->assign('title', $GLOBALS['config_vars']['Shop_articles_spez']);
			$GLOBALS['tmpl']->assign('content', $GLOBALS['tmpl']->fetch($GLOBALS['config']['source'] . '/shop/specifications.tpl'));
		}
	}
	
	function CategVariants($id)
	{
		if(perm('shop_variants'))
		{
			if(isset($_POST['save']) && $_POST['save']==1)
			{
				if(isset($_POST['Name_1']))
				{
					foreach ($_POST['Name_1'] as $cid => $var)
					{
						$n1 = $_POST['Name_1'][$cid];
						$n2 = (empty($_POST['Name_2'][$cid])) ? $n1 : $_POST['Name_2'][$cid];
						$n3 = (empty($_POST['Name_3'][$cid])) ? $n1 : $_POST['Name_3'][$cid];
						
						$b1 = @$_POST['Beschreibung_1'][$cid];
						$b2 = (empty($_POST['Beschreibung_2'][$cid])) ? $b1 : $_POST['Beschreibung_2'][$cid];
						$b3 = (empty($_POST['Beschreibung_3'][$cid])) ? $b1 : $_POST['Beschreibung_3'][$cid];
						
						if(!empty($n1))
						{
							$GLOBALS['db']->Query("UPDATE " . PREFIX . "_shop_varianten_kategorien 
							SET
								Name_1 = '$n1',
								Name_2 = '$n2',
								Name_3 = '$n3',
								Beschreibung_1 = '$b1',
								Beschreibung_2 = '$b2',
								Beschreibung_3 = '$b3',
								Position = '" . $_POST['Position'][$cid] . "',
								Aktiv ='" . $_POST['Aktiv'][$cid] . "' 
							WHERE Id = '$cid'");
						}
						
						if(!empty($_POST['Del'][$cid])) 
						{
							$GLOBALS['db']->Query("DELETE FROM " . PREFIX . "_shop_varianten_kategorien WHERE  Id = '$cid'");
							$GLOBALS['db']->Query("DELETE FROM " . PREFIX . "_shop_varianten WHERE  KatId = '$cid'");
						}
					}
				}
				
				// Neu 
				if(!empty($_POST['Name_1_n']))
				{
					$n1 = $_POST['Name_1_n'];
					$n2 = (empty($_POST['Name_2_n'])) ? $n1 : $_POST['Name_2_n'];
					$n3 = (empty($_POST['Name_3_n'])) ? $n1 : $_POST['Name_3_n'];
					
					$b1 = @$_POST['Beschreibung_1_n'];
					$b2 = (empty($_POST['Beschreibung_2_n'])) ? $b1 : $_POST['Beschreibung_2_n'];
					$b3 = (empty($_POST['Beschreibung_3_n'])) ? $b1 : $_POST['Beschreibung_3_n'];
					
					$GLOBALS['db']->Query("INSERT INTO " . PREFIX . "_shop_varianten_kategorien 
					(
						Id,
						KatId,
						Name_1,
						Name_2,
						Name_3,
						Beschreibung_1,
						Beschreibung_2,
						Beschreibung_3,
						Aktiv,
						Position
					) VALUES (
						'',
						'$id',
						'$n1',
						'$n2',
						'$n3',
						'$b1',
						'$b2',
						'$b3',
						'1',
						'" . @$_POST['Position_n'] . "'
					)");
				}
			}
			
			
			$vars = array();
			$res  = $GLOBALS['db']->Query("SELECT * FROM " . PREFIX . "_shop_varianten_kategorien WHERE KatId = '$id' ORDER BY Position ASC");
			while($row = $res->fetchrow())
			{
				array_push($vars, $row);
			}
			
			$GLOBALS['tmpl']->assign('vars', $vars);
			$GLOBALS['tmpl']->assign('title', $GLOBALS['config_vars']['Shop_categvars_simple']);
			$GLOBALS['tmpl']->assign('content', $GLOBALS['tmpl']->fetch($GLOBALS['config']['source'] . '/shop/categ_variants.tpl'));
		}
	}
	
	//=======================================================
	// Hersteller
	//=======================================================
	function Manufacturer()
	{
		if(perm('shop_manufacturer'))
		{
			// Neu
			if(isset($_POST['new']) && $_POST['new']==1)
			{
				foreach ($_POST['Name'] as $id => $var)
				{
					if(!empty($_POST['Name'][$id]))
					{
						$GLOBALS['db']->Query("INSERT INTO " . PREFIX . "_shop_hersteller
						(
							Id,
							Name,
							Adresse
						) VALUES (
							'',
							'" . $_POST['Name'][$id] . "',
							'" . $_POST['Adresse'][$id] . "'
						)");
					}
				}
				header('Location:index.php?do=shop&sub=manufacturer');
				exit;
			}
			
			// Speichern
			if(isset($_POST['save']) && $_POST['save']==1)
			{
				foreach ($_POST['Name'] as $id => $var)
				{
					$GLOBALS['db']->Query("UPDATE " . PREFIX . "_shop_hersteller
					SET 
						Name = '" . $_POST['Name'][$id] . "',
						Adresse = '" . $_POST['Adresse'][$id] . "' 
					WHERE Id='$id'");
					
					if(!empty($_POST['Del'][$id]) && $_POST['Del'][$id]==1)
					{
						$GLOBALS['db']->Query("DELETE FROM " . PREFIX . "_shop_hersteller  WHERE Id = '$id'");
					}
				}
				
				Logger('User ' . $_SESSION['user_name'] . ' save Manufacturer', '3', $_SESSION['benutzer_id']);
				header('Location:index.php?do=shop&sub=manufacturer');
				exit;
			}
			
			// Auslesen
			$manufacturer = array();
			$sql = $GLOBALS['db']->Query("SELECT * FROM " . PREFIX . "_shop_hersteller ORDER BY Name ASC");
			while($row = $sql->fetchrow()) array_push($manufacturer, $row);
			
			$GLOBALS['tmpl']->assign('manufacturer', $manufacturer);
			$GLOBALS['tmpl']->assign('title', $GLOBALS['config_vars']['Shop_manufaturer_title']);
			$GLOBALS['tmpl']->assign('content', $GLOBALS['tmpl']->fetch($GLOBALS['config']['source'] . '/shop/manufacturer.tpl'));
		}
	}
	
	//=======================================================
	// Einheiten
	//=======================================================
	function Units()
	{
		if(perm('shop_units'))
		{
			// Neu
			if(isset($_POST['new']) && $_POST['new']==1 && !empty($_POST['Titel_1'])  && !empty($_POST['Mz_1']))
			{
				$t1 = $_POST['Titel_1'];
				$t2 = (!empty($_POST['Titel_2'])) ? $_POST['Titel_2'] : $_POST['Titel_1'];
				$t3 = (!empty($_POST['Titel_3'])) ? $_POST['Titel_3'] : $_POST['Titel_1'];
				
				$m1 = $_POST['Mz_1'];
				$m2 = (!empty($_POST['Mz_2'])) ? $_POST['Mz_2'] : $_POST['Mz_1'];
				$m3 = (!empty($_POST['Mz_3'])) ? $_POST['Mz_3'] : $_POST['Mz_1'];
				
				$GLOBALS['db']->Query("INSERT INTO " . PREFIX . "_shop_einheiten
				(
					Id,
					Titel_1,
					Titel_2,
					Titel_3,
					Mz_1,
					Mz_2,
					Mz_3
				) VALUES (
					'',
					'$t1',
					'$t2',
					'$t3',
					'$m1',
					'$m2',
					'$m3'
				)");
				Logger('User ' . $_SESSION['user_name'] . ' insert new Unit ($t1)', '3', $_SESSION['benutzer_id']);
				header('Location:index.php?do=shop&sub=units');
			}
			
			
			// Speichern
			if(isset($_POST['save']) && $_POST['save']==1)
			{
				foreach ($_POST['Titel_1'] as $id => $var)
				{
					$GLOBALS['db']->Query("UPDATE " . PREFIX . "_shop_einheiten 
					SET 
						Titel_1 = '" . $_POST['Titel_1'][$id] . "',
						Titel_2 = '" . $_POST['Titel_2'][$id] . "',
						Titel_3 = '" . $_POST['Titel_3'][$id] . "',
						Mz_1 = '" . $_POST['Mz_1'][$id] . "',
						Mz_2 = '" . $_POST['Mz_2'][$id] . "',
						Mz_3 = '" . $_POST['Mz_3'][$id] . "'
					WHERE Id='$id'");
					
					if(!empty($_POST['Del'][$id]) && $_POST['Del'][$id]==1)
					{
						$GLOBALS['db']->Query("DELETE FROM " . PREFIX . "_shop_einheiten  WHERE Id = '$id'");
					}
				}
				
				Logger('User ' . $_SESSION['user_name'] . ' save Shop-Units', '3', $_SESSION['benutzer_id']);
				header('Location:index.php?do=shop&sub=units');
				exit;
			}
			
			$units = array();
			$sql = $GLOBALS['db']->Query("SELECT * FROM " . PREFIX . "_shop_einheiten ORDER BY Titel_1 ASC");
			while($row = $sql->fetchrow()) array_push($units, $row);
			
			$GLOBALS['tmpl']->assign('units', $units);
			$GLOBALS['tmpl']->assign('title', $GLOBALS['config_vars']['Shop_units_title']);
			$GLOBALS['tmpl']->assign('content', $GLOBALS['tmpl']->fetch($GLOBALS['config']['source'] . '/shop/units.tpl'));
		}
	}
	
	//=======================================================
	// Zufallscodefunktion
	//=======================================================
	function CouponRandom($c=0)
	{
		$pass = "";
		$chars = array("1", "2", "3", "4", "5", "6", "7", "8", "9", "0",
			"a", "A", "b", "B", "c", "C", "d", "D", "e", "E", "f", "F", "g", "G", "h", "H", "i", "I", "j", "J",
			"k", "K", "l", "L", "m", "M", "n", "N", "o", "O", "p", "P", "q", "Q", "r", "R", "s", "S", "t", "T",
			"u", "U", "v", "V", "w", "W", "x", "X", "y", "Y", "z", "Z");
		$ch = ($c!=0) ? $c : 6;
		$count = count($chars) - 1;
		srand((double)microtime() * 1000000);
		for($i = 0; $i < $ch; $i++) $pass .= $chars[rand(0, $count)];
		return($pass);
	}
	
	function keyParter()
	{
		$pass = "";
		$chars = array("2", "3", "4", "5", "6", "7", "8", "9",
			"a", "A", "b", "B", "c", "C", "d", "D", "e", "E", "f", "F", "g", "G", "h", "H", "i", "j", "J",
			"k", "K", "L", "m", "M", "n", "N", "o", "O", "p", "P", "q", "Q", "r", "R", "s", "S", "t", "T",
			"u", "U", "v", "V", "w", "W", "x", "X", "y", "Y", "z", "Z");
		$ch = 3;
		$count = count($chars) - 1;
		srand((double)microtime() * 1000000);
		for($i = 0; $i < $ch; $i++) $pass .= $chars[rand(0, $count)];
		return($pass);
	}
	
	function newKey()
	{
		$pf = (defined('CNPF')) ? CNPF : '';
		return $pf . $this->keyParter() . '-' . $this->keyParter()  . date('y') . '-' . $this->keyParter() . date('s');
	}
	
	function DigitRandom($c=8)
	{
		$erg = "";
		$chars = array("1", "2", "3", "4", "5", "6", "7", "8", "9", "0");
		$ch = ($c!=0) ? $c : 8;
		$count = count($chars) - 1;
		srand((double)microtime() * 1000000);
		for($i = 0; $i < $ch; $i++) $erg .= $chars[rand(0, $count)];
		return($erg);
	}
	
	//=======================================================
	// Steuersaetze
	//=======================================================
	function Taxes()
	{
		if(perm('shop_taxes'))
		{
			// Speichern
			if(isset($_POST['save']) && $_POST['save']==1)
			{
				foreach ($_POST['Name'] as $id => $var)
				{
					$GLOBALS['db']->Query("UPDATE " . PREFIX . "_shop_ustzone
					SET 
						Name = '" . $_POST['Name'][$id] . "',
						Wert = '" . str_replace(',','.',$_POST['Wert'][$id]) . "' 
					WHERE Id='$id'");
				}
				Logger('User ' . $_SESSION['user_name'] . ' save Taxes', '3', $_SESSION['benutzer_id']);
				header('Location:index.php?do=shop&sub=taxes');
				exit;
			}
			
			$taxes = array();
			$sql = $GLOBALS['db']->Query("SELECT * FROM " . PREFIX . "_shop_ustzone ORDER BY Id ASC");
			while($row = $sql->fetchrow()) array_push($taxes, $row);
			
			$GLOBALS['tmpl']->assign('taxes', $taxes);
			$GLOBALS['tmpl']->assign('title', $GLOBALS['config_vars']['Shop_taxes_title']);
			$GLOBALS['tmpl']->assign('content', $GLOBALS['tmpl']->fetch($GLOBALS['config']['source'] . '/shop/taxes.tpl'));
		}
	}
	
	function TimeTillShipping($s='Lieferzeit_1 ASC')
	{
		$items = array();
		$sql = $GLOBALS['db']->Query("SELECT *, Lieferzeit_1 AS Name FROM " . PREFIX . "_shop_packzeiten ORDER BY $s");
		while($row = $sql->fetchrow()) array_push($items, $row);
		return $items;
	}
	
	
	
	function Availabilities()
	{
		if(perm('shop_availability'))
		{
			// Speichern
			if(isset($_POST['save']) && $_POST['save']==1)
			{
				foreach ($_POST['Titel_1'] as $id => $var)
				{
					if(!empty($_POST['Titel_1'][$id]) && !empty($_POST['Titel_2'][$id]) && !empty($_POST['Titel_3'][$id]))
					{
						$GLOBALS['db']->Query("UPDATE " . PREFIX . "_shop_verfuegbarkeit 
						SET 
							Titel_1 = '" . $_POST['Titel_1'][$id] . "',
							Titel_2 = '" . $_POST['Titel_2'][$id] . "',
							Titel_3 = '" . $_POST['Titel_3'][$id] . "',
							Text_1 = '" . $_POST['Text_1'][$id] . "',
							Text_2 = '" . $_POST['Text_2'][$id] . "',
							Text_3 = '" . $_POST['Text_3'][$id] . "' 
						WHERE Id='$id'");
					}
				}
				header('Location:index.php?do=shop&sub=availabilities');
				exit;
			}
			
			
			$GLOBALS['tmpl']->assign('items', $this->getAvailabilities());
			$GLOBALS['tmpl']->assign('title', $GLOBALS['config_vars']['Shop_availabilities_title']);
			$GLOBALS['tmpl']->assign('content', $GLOBALS['tmpl']->fetch($GLOBALS['config']['source'] . '/shop/availabilities.tpl'));
		}
	}
	
	
	
	function ShippingReady()
	{
		if(perm('shop_shippingready'))
		{
			// Neu
			if(isset($_POST['new']) && $_POST['new']==1 && !empty($_POST['Lieferzeit_1']))
			{
				$lz1 = $_POST['Lieferzeit_1'];
				$lz2 = (!empty($_POST['Lieferzeit_2'])) ? $_POST['Lieferzeit_2'] : $_POST['Lieferzeit_1'];
				$lz3 = (!empty($_POST['Lieferzeit_3'])) ? $_POST['Lieferzeit_3'] : $_POST['Lieferzeit_1'];
				$GLOBALS['db']->Query("INSERT INTO " . PREFIX . "_shop_packzeiten
				(
					Id,
					Lieferzeit_1,
					Lieferzeit_2,
					Lieferzeit_3
				) VALUES (
					'',
					'$lz1',
					'$lz2',
					'$lz3' 
				)");
				Logger('User ' . $_SESSION['user_name'] . ' insert new Packing-Time', '3', $_SESSION['benutzer_id']);
				header('Location:index.php?do=shop&sub=shippingready');
			}
			
			// Speichern
			if(isset($_POST['save']) && $_POST['save']==1)
			{
				foreach ($_POST['Lieferzeit_1'] as $id => $var)
				{
					if(!empty($_POST['Lieferzeit_1'][$id]) && !empty($_POST['Lieferzeit_2'][$id]) && !empty($_POST['Lieferzeit_3'][$id]))
					{
						$GLOBALS['db']->Query("UPDATE " . PREFIX . "_shop_packzeiten
						SET 
							Lieferzeit_1 = '" . $_POST['Lieferzeit_1'][$id] . "',
							Lieferzeit_2 = '" . $_POST['Lieferzeit_2'][$id] . "',
							Lieferzeit_3 = '" . $_POST['Lieferzeit_3'][$id] . "' 
						WHERE Id='$id'");
					}
					if(!empty($_POST['Del'][$id]) && $_POST['Del'][$id]==1)
					{
						$GLOBALS['db']->Query("DELETE FROM " . PREFIX . "_shop_packzeiten WHERE Id = '$id'");
						Logger('User ' . $_SESSION['user_name'] . ' delete new Packing-Time', '3', $_SESSION['benutzer_id']);
					}
				}
				header('Location:index.php?do=shop&sub=shippingready');
				exit;
			}
			
			$GLOBALS['tmpl']->assign('items', $this->TimeTillShipping('Id ASC'));
			$GLOBALS['tmpl']->assign('title', $GLOBALS['config_vars']['Shop_shippingready_title']);
			$GLOBALS['tmpl']->assign('content', $GLOBALS['tmpl']->fetch($GLOBALS['config']['source'] . '/shop/shippingready.tpl'));
		}
	}
	
	function groupSettings()
	{
		if(perm('shop_groupsettings'))
		{
			// Speichern
			if(isset($_POST['save']) && $_POST['save']==1)
			{
				foreach ($_POST['Gruppe'] as $id => $var)
				{
					
					$GLOBALS['db']->Query("UPDATE " . PREFIX . "_benutzer_gruppen 
					SET 
						Rabatt = '" . str_replace(',','.',$_POST['Rabatt'][$id]) . "',
						ShopAnzeige = '" . $_POST['ShopAnzeige'][$id] . "' 
					WHERE Id = '$id'");
				}
			}
			
			$GLOBALS['tmpl']->assign('groups', $this->Groups(2));
			$GLOBALS['tmpl']->assign('title', $GLOBALS['config_vars']['Shop_groupsettings']);
			$GLOBALS['tmpl']->assign('content', $GLOBALS['tmpl']->fetch($GLOBALS['config']['source'] . '/shop/groupsettings.tpl'));
		}
	}
	
	
	//
	function openclose($a,$id)
	{
		$GLOBALS['db']->Query("UPDATE " . PREFIX . "_shop_produkte SET Aktiv='$a' WHERE Id = '$id'");
		echo "<script>window.opener.location.reload();window.close();</script>";
	}
	
	//=======================================================
	// Downloads einlesen
	//=======================================================
	function fetchEsdFiles()
	{
		$verzname = BASE_DIR . '/uploads/shop/files/';
		$dh = @opendir( $verzname );
		$esds = array();
		while ( @gettype( $datei = @readdir ( $dh )) != @boolean )
		{
			if ( @is_file( "$verzname/$datei" ))
			{
				if ($datei != "." && $datei != ".." && $datei != ".htaccess")
				{
					@array_push($esds, $datei);
				} 
			}
		}
		@closedir( $dh );
		return $esds;
	}
	
	function getCategName($id)
	{
		$shipper = array();
		$res = $GLOBALS['db']->RowQuery("SELECT Name_1 AS Name FROM " . PREFIX . "_shop_kategorie WHERE Id = '$id'");
		return $res->Name;
	}
	
	function Shipper()
	{
		$shipper = array();
		$sql = $GLOBALS['db']->Query("SELECT Id,Name_1 AS Name FROM " . PREFIX . "_shop_versandarten ORDER BY Position ASC");
		while($row = $sql->fetchrow()) array_push($shipper, $row);
		return $shipper;
	}
	
	//=================================================================
	//=================================================================
	function Countries()
	{
		$countries = array();
		$sql = $GLOBALS['db']->Query("SELECT * FROM " . PREFIX . "_laender WHERE Aktiv=1 ORDER BY Name ASC");
		while($row = $sql->fetchrow()) array_push($countries, $row);
		return $countries;
	}
	
	//=================================================================
	//=================================================================
	function Groups($not='')
	{
		$groups = array();
		$db_not = ($not!='') ? "WHERE Id != {$not}" : "";
		$sql = $GLOBALS['db']->Query("SELECT Rabatt,ShopAnzeige,Name_Intern,Name,Id FROM " . PREFIX . "_benutzer_gruppen {$db_not} ORDER BY Name ASC");
		while($row = $sql->fetchrow()) array_push($groups, $row);
		return $groups;
	}
	
	//=================================================================
	//=================================================================
	function noperm()
	{
		$GLOBALS['tmpl']->assign('content', $GLOBALS['tmpl']->fetch($GLOBALS['config']['source'] . '/error/no_perm.tpl'));
	}
	
	
	
	
	//=================================================================
	function getShipperName($id)
	{
		$rl = $GLOBALS['db']->RowQuery("SELECT Name_" . $_SESSION['AdminLangcode'] . " AS Name FROM " . PREFIX . "_shop_versandarten WHERE Id = '{$id}'");
		return (is_object($rl)) ? $rl->Name : '&nbsp;';
	}
	
	//=================================================================
	//=================================================================
	function getPaymentName($id)
	{
		$rl = $GLOBALS['db']->RowQuery("SELECT Name_" . $_SESSION['AdminLangcode'] . " AS Name FROM " . PREFIX . "_shop_zahlungsmethoden WHERE Id = '{$id}'");
		return $rl->Name;
	}
	
	//=================================================================
	//=================================================================
	function listManufaturer()
	{
		$manufaturer = array();
		$sql = $GLOBALS['db']->Query("SELECT Name, Id FROM " . PREFIX . "_shop_hersteller  ORDER BY Name ASC");
		while($row = $sql->fetchrow())
		{
			array_push($manufaturer, $row);
		}
		return $manufaturer;
	}
	
	//=================================================================
	//
	//=================================================================
	function cutter()
	{
		$cutter  = str_replace('\\r', "\015", $this->cutter);
		$cutter  = str_replace('\\n', "\012", $cutter);
		$cutter  = str_replace('\\t', "\011", $cutter);
		return $cutter;
	}
	
	//=================================================================
	//
	//=================================================================
	function getAvailabilities()
	{
		$avail = array();
		$sql = $GLOBALS['db']->Query("SELECT *,Id,Titel_" . $_SESSION['AdminLangcode'] . " AS Name FROM " . PREFIX . "_shop_verfuegbarkeit ORDER BY Id ASC");
		while($row = $sql->fetcharray()) array_push($avail,$row);
		return $avail;
	}

	
	//=================================================================
	// Einheiten auslesen
	//=================================================================
	function getUnits()
	{
		$units = array();
		$sql = $GLOBALS['db']->Query("SELECT Id,Mz_" . $_SESSION['AdminLangcode'] . " AS Mz , Titel_" . $_SESSION['AdminLangcode'] . " AS Name FROM " . PREFIX . "_shop_einheiten ORDER BY Name ASC");
		while($row = $sql->fetcharray()) array_push($units,$row);
		return $units;
	}
	
	function getManufacturer()
	{	
		$m = array();
		$sql = $GLOBALS['db']->Query("SELECT Id,Name FROM " . PREFIX . "_shop_hersteller ORDER BY Name ASC");
		while($row = $sql->fetcharray())
		{
			array_push($m, $row);
		}
		return $m;
	}
	
	
	//=================================================================
	//
	//=================================================================
	function cleanArtNr($var)
	{
		return trim(eregi_replace('[^A-Za-zÀ-ÖØ-öø-ÿ0-9.-]', '', $var));
	}
	//=================================================================
	//
	//=================================================================
	function cleanNum($var)
	{
		return trim(eregi_replace('[^0-9]', '', $var));
	}
	
	function priceClean($var)
	{
		$var = trim($var);
		$var = str_replace(',','.', $var);
		return $var;
	}
	
	
	//=================================================================
	// Pruefung 
	//=================================================================
	function notExists($art)
	{
		$row = $GLOBALS['db']->RowQuery("SELECT Id FROM " . PREFIX . "_shop_produkte WHERE Artikelnummer = '{$art}'");
		if(!is_object($row)) return true;
		return false;
	}
	
	function getShopSettings($field)
	{
		$row_shopsettings = $GLOBALS['db']->RowQuery("SELECT $field FROM " . PREFIX . "_shop_einstellungen");
		return $row_shopsettings->$field;
	}
	
}
?>