<?php
//=================================================================
// KOOBI R7 - CMS - PORTALSOFTWARE(c) DREAM4(r) 
// HTTP://WWW.DREAM4.DE
//=================================================================
// ACHTUNG!
// DIESER PROGRAMMCODE IST URHERRECHTLICH GESCHUETZT
// DIE URHEBERRECHTE LIEGEN BEI DEN JEWEILIGEN AUTOREN.
// AENDERUNGEN IN DIESER DATEI ERFOLGEN AUF EIGENE GEFAHR!
// ES IST NICHT GESTATTET, DEN COPYRIGHTHINWEIS ZU AENDERN ODER ZU
// ENTFERNEN. NUR WENN SIE EINE COPYRIGHTHINWEIS-ENTFERNUNG BESTELLT
// HABEN, DUERFEN SIE DIESEN ENTFERNEN.
//================================================================
// BEI FRAGEN WENDEN SIE SICH BITTE AN: KONTAKT@DREAM4.DE
//=================================================================
class Gallery
{
	var $_max_size_wm = 1285;
	
	function GetSettings()
	{
		$sql = $GLOBALS['db']->Query("SELECT * FROM " . PREFIX . "_galerie_einstellungen LIMIT 1" );
		$gal_settings = $sql->fetchrow();
		return $gal_settings;
	}
	
	function AjaxAddFavorite($id,$galid)
	{
		define('AJAX_OUTPUT',1);
		$Settings = $this->GetSettings();
		
		if($Settings->Favoriten && $_SESSION['user_group']!=2)
		{
			$id = cleanInt($id);
			$galid = cleanInt($galid);
			
			$GLOBALS['db']->Query("INSERT INTO " . PREFIX . "_galerie_bilderfavoriten (Id,Benutzer,Bild_Id,Galerie_Id) VALUES ('','" . $_SESSION['benutzer_id'] . "','$id','$galid;')");
			echo '<br /><small>' . $GLOBALS['config_vars']['Gallery_AddedFavorite'] . '</small>';
			//echo '<a href="javascript:void(0);" onclick="deleteFavorite(\'favo_' . $id . '\',\'' . $id . '\',\'' . $galid . '\');"><img class="absmiddle" src="' . IMG_PATH . '/page/faves_delete.png" alt="" border="0" /></a>';
		} 
	}
	
	
	function getExtenGallery($gals,$tpl='')
	{
		$LC = @$_SESSION['Langcode'];
		$garray = explode(',',$gals);
		$galleries = array();
		foreach($garray as $galid=>$gid)
		{
			$row_g = $GLOBALS['db']->RowQuery("SELECT Id,Kategorie,Name_{$LC} AS GalName FROM " . PREFIX . "_galerie WHERE Id = '$gid' AND Aktiv = '1'");
			
			if(is_object($row_g))
			{
				$row_g->Link = 'index.php?p=gallery&amp;action=showgallery&amp;id=' . $row_g->Id . '&amp;categ=' . $row_g->Kategorie . '&amp;name=' . seotitle($row_g->GalName) . '&amp;area=' . AREA;
			
				$row_imgC = $GLOBALS['db']->RowQuery("SELECT COUNT(Id) AS ImgCount FROM " . PREFIX . "_galerie_bilder WHERE Galerie_Id = '$row_g->Id'");
				$row_img = $GLOBALS['db']->RowQuery("SELECT Bildname,Id FROM " . PREFIX . "_galerie_bilder WHERE Galerie_Id = '$row_g->Id' ORDER BY RAND() LIMIT 1");
				if(is_object($row_img))
				{
					$endg = @$this->getEndg($row_img->Bildname);
					$row_g->Img = ((file_exists('cache/' . md5('medium_' . $row_img->Bildname). $endg))  ? "cache/" . md5('medium_' . $row_img->Bildname) . $endg : "system/thumb.php?img_id=" .  $row_img->Id . "&amp;smode=2") ;
				} else {
					$row_g->Img = '';
				}
				
				$row_g->ICount = (is_object($row_img)) ? $row_imgC->ImgCount : 0;
				array_push($galleries,$row_g);
			}
			
		}
		$GLOBALS['tmpl']->assign('externGals', $galleries);
		$t = ($tpl!='') ? $tpl : 'galleries_included.tpl';
		return $GLOBALS['tmpl']->fetch($GLOBALS['config']['source'] . '/gallery/' . $t);
	}
	
	function AjaxDeleteFavorite($id,$galid)
	{
		define('AJAX_OUTPUT',1);
		$Settings = $this->GetSettings();
		
		if($Settings->Favoriten && $_SESSION['user_group']!=2)
		{
			$id = cleanInt($id);
			$galid = cleanInt($galid);
			
			$GLOBALS['db']->Query("DELETE FROM " . PREFIX . "_galerie_bilderfavoriten WHERE Bild_Id = '$id' AND Benutzer = '" . $_SESSION['benutzer_id'] . "'");
			echo '<br /><small>' . $GLOBALS['config_vars']['Gallery_DeletedFavorite'] . '</small>';
			//echo '<a href="javascript:void(0);" onclick="addFavorite(\'favo_' . $id . '\',\'' . $id . '\',\'' . $galid . '\');"><img class="absmiddle" src="' . IMG_PATH . '/page/faves_add.png" alt="" border="0" /></a>';
		}
	}
	
	function deleteFavoritesGallery($id,$categ,$name)
	{
		$GLOBALS['db']->Query("DELETE FROM " . PREFIX . "_galerie_bilderfavoriten WHERE Galerie_Id = '$id' AND Benutzer = '" . $_SESSION['benutzer_id'] . "'");
		refer('index.php?p=gallery&action=showgallery&id=' . $id . '&categ=' . $categ . '&name=' . $name . '&area=' . AREA);
		exit;
	}
	
	//=================================================================
	// AJAX-Bilder Vorschau mit XML-Callback
	//=================================================================
	function AjaxSlide($id,$ascdesc='desc',$blanc=0,$firstid='',$top=0, $categ=0)
	{
		define('AJAX_OUTPUT',1);
		
		$orderby = '';
		$first = max(0, intval($_GET['first']) - 1);
		$last  = max($first + 1, intval($_GET['last']) - 1);
		
		if($top==1)
		{
			$ascdesc = '';
			$orderby = 'Klicks DESC';
		} else {
			$orderby = 'Id';
		}
		
		$length = $last - $first + 1;
		$LC = $_SESSION['Langcode'];
		
		$GLOBALS['tmpl']->clear_config();
		$GLOBALS['tmpl']->config_load(BASE_DIR . '/lang/' . $_SESSION['lang'] . '/rewrite.txt');
		$c_vars = $GLOBALS['tmpl']->get_config_vars();
		
		$more = array();
		$sql_more = $GLOBALS['db']->Query("SELECT Klicks,Id,Galerie_Id,Bildname,Name_{$LC} AS ImageName, Beschreibung_{$LC} AS ImageDescr FROM " . PREFIX . "_galerie_bilder WHERE Galerie_Id = '$id' ORDER BY {$orderby} {$ascdesc}");
		while($row_more = $sql_more->fetchrow())
		{
			$endg = @$this->getEndg($row_more->Bildname);
			$link_blanc = ($blanc==1) ? '&amp;blanc=1&amp;first_id=' . $firstid : '';
			$imgage_link = HOME_PATH . "/index.php?p=gallery&amp;action=showimage&amp;id=" . $row_more->Id . "&amp;galid=" . $row_more->Galerie_Id . "&amp;ascdesc=desc&amp;categ=" . $categ . '&amp;area=' . AREA . $link_blanc;
			
			if($GLOBALS['settings']['use_seo']==1 && $blanc!=1) $imgage_link = preg_replace("/index.php([?])p=gallery&amp;action=showimage&amp;id=([0-9]*)&amp;galid=([0-9]*)&amp;ascdesc=([A-Za-zÀ-ÖØ-öø-ÿ0-9-]*)&amp;categ=([0-9]*)&amp;area=([0-9]*)/", $c_vars['gallery']."/" . $c_vars['galleryimage'] . "/\\2/\\3/\\4/\\5/\\6/", $imgage_link);
			
			$images[] = ((file_exists('cache/' . md5('small_' . $row_more->Bildname). $endg))  ? "&lt;a href='$imgage_link'&gt; &lt;img  alt='' border='0'  src='" . HOME_PATH . "/cache/" . md5('small_' . $row_more->Bildname) . $endg ."'&gt;&lt;/a&gt;" : "&lt;a href='$imgage_link'&gt; &lt;img src='" . HOME_PATH . "/system/thumb.php?img_id=" . $row_more->Id . "&amp;smode=1' alt='' border='0' /&gt;&lt;/a&gt;") ;
			$row_more->ImageText  = ($row_more->ImageName != '') ? '<strong>' . koobispecialchars($row_more->ImageName) . '</strong><br />' .  koobispecialchars($row_more->ImageDescr) : '';
			array_push($more, $row_more);
		}
		
		$total    = count($images);
		$selected = array_slice($images, $first, $length);
		
		//=================================================================
		// XML-Callback
		//=================================================================
		header('Content-Type: text/xml');
		echo '<data>';
		echo '  <total>' . $total . '</total>';
		foreach ($selected as $img)
		{
			echo '  <image>' . $img . '</image>';
		}
		echo '</data>';
	}
	
	function GalCategQuickSearch($name)
	{
		$LC = @$_SESSION['Langcode'];
		define('AJAX_OUTPUT',1);
		$q = preg_replace('/[^-A-Za-zA-ÖO-öo-y0-9_. ]/', '', $name) ;
		$q = strtolower($q);
		if (!$q) return;
		
		$pattern = preg_replace('/([^-A-Za-zÀ-ÖØ-öø-ÿ0-9. ]*)/', '',$q);
		$pattern_umlaut = umlautQuery($q);
			
		$res = array();
		$result = $GLOBALS['db']->Query("SELECT Name_{$LC} AS Name FROM " . PREFIX . "_galerie_kategorien WHERE Aktiv='1' AND Sektion = '" . $_SESSION['area'] . "' AND (Name_{$LC} LIKE '%{$pattern}%')");
		while($row = $result->fetchrow())
		{
			array_push($res, $row->Name);
		}
		if(strlen($name)>=3)
		{
			foreach ($res as $key=>$value) 
			{
				if (strpos(strtolower($value), $q) !== false) echo stripslashes(koobispecialchars($value)) . "\n"; // $key;
			}
		}
	} 
	
	// Neue Galerien
	function newGalleries($limit=5)
	{
		$LC = $_SESSION['Langcode'];
		$galleries = array();
		$sql = $GLOBALS['db']->Query("SELECT Id, Kategorie, Name_{$LC} AS Name, Beschreibung_{$LC} AS Text FROM " . PREFIX . "_galerie WHERE Aktiv='1' AND Sektion = '" . $_SESSION['area'] . "' ORDER BY Id DESC LIMIT {$limit}");
		while($row = $sql->fetchrow())
		{
			$row->Link = 'index.php?p=gallery&amp;action=showgallery&amp;id=' . $row->Id . '&amp;categ=' . $row->Kategorie . '&amp;name=' . seotitle($row->Name) . '&amp;area=' . AREA;
			$row->Text = strip_tags($row->Text);
			$row_img = $GLOBALS['db']->RowQuery("SELECT Bildname,Id FROM " . PREFIX . "_galerie_bilder WHERE Galerie_Id = '$row->Id' ORDER BY Id DESC LIMIT 1");
			if(is_object($row_img))
			{
				$endg = @$this->getEndg($row_img->Bildname);
				$row->Img = ((file_exists('cache/' . md5('medium_' . $row_img->Bildname). $endg))  ? "cache/" . md5('medium_' . $row_img->Bildname) . $endg : "system/thumb.php?img_id=" .  $row_img->Id . "&amp;smode=2") ;
			} else {
				$row->Img = '';
			}
			
			array_push($galleries,$row);
		}
		return $galleries;
	}
	
	
	//=================================================================
	// Galerie-Kategorien listen
	//=================================================================
	function ShowAll()
	{
		$LC = $_SESSION['Langcode'];
		$galsettings = $this->GetSettings();
		$def_sort      = " ORDER BY Name_{$LC} ASC";
		$def_sort_n    = "&amp;ascdesc=asc";
		$def_search    = "";
		$def_search_n  = "&amp;q=empty";
		$pattern = "";
		$pattern_umlaut = "";
		$def_searcht    = "";
		$def_searcht_n  = "&amp;searchtype=full";
		
		if(isset($_REQUEST['q']) && !empty($_REQUEST['q']) && $_REQUEST['q'] != 'empty' && strlen($_REQUEST['q'])>=3)
		{
			$pattern = preg_replace('/([^-A-Za-zÀ-ÖØ-öø-ÿ0-9. ]*)/', '', $_REQUEST['q']);
			$pattern_umlaut = umlautQuery($pattern);
			$_REQUEST['q']  = $pattern;
			$def_search_n   = "&amp;q=" . urlencode($pattern);
			
			if(isset($_REQUEST['searchtype']) && !empty($_REQUEST['searchtype']))
			{
				switch($_REQUEST['searchtype'])
				{
					default: case 'full':$def_search     = " AND ((Name_{$LC} LIKE '%{$pattern}%' OR Text_{$LC} LIKE '%{$pattern}%') OR (Name_{$LC} LIKE '%{$pattern_umlaut}%' OR Text_{$LC} LIKE '%{$pattern_umlaut}%'))";break;
					case 'tags': $def_search     = " AND ((Tags LIKE '%{$pattern}%' OR Tags LIKE '{$pattern},%' OR Tags LIKE '%,{$pattern}') OR (Tags LIKE '%{$pattern_umlaut}%' OR Tags LIKE '{$pattern_umlaut},%' OR Tags LIKE '%,{$pattern_umlaut}'))"; break;
				}
			}			
		}
		
		if(isset($_REQUEST['ascdesc']) && !empty($_REQUEST['ascdesc']))
		{
			switch($_REQUEST['ascdesc'])
			{
				default:
				case 'asc':
					$def_sort = " ORDER BY Name_{$LC} ASC";
					$def_sort_n = "&amp;ascdesc=asc";
				break;
				
				case 'desc':
					$def_sort = " ORDER BY Name_{$LC} DESC";
					$def_sort_n = "&amp;ascdesc=desc";
				break;
			}
		}
		
		if(isset($_REQUEST['searchtype']) && !empty($_REQUEST['searchtype']))
		{
			switch($_REQUEST['searchtype'])
			{
				default:
				case 'full':
					$def_searcht_n  = "&amp;searchtype=full";
				break;
				
				case 'tags':
					$def_searcht_n  = "&amp;searchtype=tags";
				break;
			}
		}
		
		$query = $GLOBALS['db']->Query("SELECT Id FROM " . PREFIX . "_galerie_kategorien WHERE Aktiv='1' AND Sektion = '" . $_SESSION['area'] . "' {$def_search} {$def_sort}");
		$num = $query->numrows();
        
		$limit =$galsettings->Limit_Start;
		$seiten = ceil($num / $limit);
        $a = prepage() * $limit - $limit;
		
		$galleries = array();
		$sql = $GLOBALS['db']->Query("SELECT Id, Name_{$LC} AS Name, Text_{$LC} AS Text, Bild, Tags FROM " . PREFIX . "_galerie_kategorien WHERE Aktiv='1' AND Sektion = '" . $_SESSION['area'] . "' {$def_search} {$def_sort} LIMIT $a,$limit");
		while($row = $sql->fetchrow())
		{
			if($pattern!='')
			{
				// Suche-Log
				if(@$_SESSION['query_galerie_kategorien'] != $pattern_umlaut)
				{
					queryLog($pattern_umlaut, 'galerie_kategorien');
					$_SESSION['query_galerie_kategorien'] = $pattern_umlaut;
				}
				if(@$_REQUEST['searchtype'] != 'tags') $row->Text = high($row->Text,$pattern_umlaut);
			}
			
			if($row->Tags)
			{
				$row->Tags = array_unique(explode(',', $row->Tags));
				@sort($row->Tags);
			}
			array_push($galleries,$row);
		}
		
		// Seiten-Navigation
		if ($num > $limit) 
		{
            $GLOBALS['tmpl']->assign('GalNavi', pagenav($seiten, '', " <a class=\"page_navigation\" href=\"index.php?p=gallery{$def_search_n}{$def_searcht_n}{$def_sort_n}&amp;page={s}&amp;area=" . AREA . "\">{t}</a> "));
        }
		
		$GLOBALS['tmpl']->assign('headernav', $GLOBALS['config_vars']['Gallery_Name']);
		$GLOBALS['tmpl']->assign('pagetitle_html', $GLOBALS['config_vars']['Gallery_Name']);
		$GLOBALS['tmpl']->assign('galleries', $galleries);
		$GLOBALS['tmpl']->assign('galsettings', $galsettings);
		$GLOBALS['tmpl']->assign('tagCloud', $this->getTagCloud());
		$GLOBALS['tmpl']->assign('def_sort_n', $def_sort_n);
		$GLOBALS['tmpl']->assign('content', $GLOBALS['tmpl']->fetch($GLOBALS['config']['source'] . '/gallery/gallerycategs.tpl')); 
	}
	
	
	//=================================================================
	// Alle Galerien anzeigen
	//=================================================================
	function ShowIncluded($galid)
	{
		$LC = $_SESSION['Langcode'];
		$Settings = $this->GetSettings();
		$galsettings = $Settings;
		$def_sort      = " ORDER BY Name_{$LC} ASC";
		$def_sort_n    = "&amp;sort=nameasc";
		$def_search    = "";
		$def_search_n  = "&amp;q=empty";
		$pattern = "";
		$pattern_umlaut = "";
		$def_searcht    = "";
		$def_searcht_n  = "&amp;searchtype=full";
		$def_sort_name  = "nameasc"; 
		$def_sort_img_name = "sorter_up";
		$def_sort_date  = "datedesc"; 
		$def_sort_img_date = "sorter_none";
		$def_sort_author  = "userdesc"; 
		$def_sort_img_author = "sorter_none";
		
		$_REQUEST['searchtype'] = (isset($_REQUEST['searchtype']) && ($_REQUEST['searchtype']=='full' || $_REQUEST['searchtype']=='tags')) ? $_REQUEST['searchtype'] : 'full';
		$_REQUEST['q']          = (!isset($_REQUEST['q']) || empty($_REQUEST['q'])) ? 'empty' : urldecode($_REQUEST['q']);
		$_REQUEST['sort']       = (!isset($_REQUEST['sort']) || empty($_REQUEST['sort'])) ? 'nameasc' : $_REQUEST['sort'];
		
		//=================================================================
		// Suche (Volltext oder Tags)
		//=================================================================
		if(isset($_REQUEST['q']) && !empty($_REQUEST['q']) && $_REQUEST['q'] != 'empty' && strlen($_REQUEST['q'])>=3)
		{
			$pattern = preg_replace('/([^-A-Za-zÀ-ÖØ-öø-ÿ0-9. ]*)/', '', $_REQUEST['q']);
			$pattern_umlaut = umlautQuery($pattern);
			$_REQUEST['q']  = $pattern;
			$def_search_n   = "&amp;q=" . urlencode($pattern);
			
			if(isset($_REQUEST['searchtype']) && !empty($_REQUEST['searchtype']))
			{
				switch($_REQUEST['searchtype'])
				{
					default: case 'full':$def_search     = " AND ((Name_{$LC} LIKE '%{$pattern}%' OR Beschreibung_{$LC} LIKE '%{$pattern}%') OR (Name_{$LC} LIKE '%{$pattern_umlaut}%' OR Beschreibung_{$LC} LIKE '%{$pattern_umlaut}%'))";break;
					case 'tags': $def_search     = " AND ((Tags LIKE '%{$pattern}%' OR Tags LIKE '{$pattern},%' OR Tags LIKE '%,{$pattern}') OR (Tags LIKE '%{$pattern_umlaut}%' OR Tags LIKE '{$pattern_umlaut},%' OR Tags LIKE '%,{$pattern_umlaut}'))"; break;
				}
			}			
		}
		
		//=================================================================
		// Sortierung
		//=================================================================
		if(isset($_REQUEST['sort']) && !empty($_REQUEST['sort']))
		{
			
			switch($_REQUEST['sort'])
			{
				default:
				case 'namedesc':
					$def_sort = " ORDER BY Name_{$LC} DESC";
					$def_sort_n = "&amp;sort=nameasc";
					$def_sort_name  = "nameasc"; 
					$def_sort_img_name = "sorter_down";
				break;
				
				case 'nameasc':
					$def_sort = " ORDER BY Name_{$LC} ASC";
					$def_sort_n = "&amp;sort=namedesc";
					$def_sort_name  = "namedesc"; 
					$def_sort_img_name = "sorter_up";
				break;
				
				case 'datedesc':
					$def_sort = " ORDER BY Datum DESC";
					$def_sort_n = "&amp;sort=datedesc";
					$def_sort_date  = "dateasc"; 
					$def_sort_img_date = "sorter_down";
					$def_sort_img_name = "sorter_none";
				break;
				
				case 'dateasc':
					$def_sort = " ORDER BY Datum ASC";
					$def_sort_n = "&amp;sort=dateasc";
					$def_sort_date  = "datedesc"; 
					$def_sort_img_date = "sorter_up";
					$def_sort_img_name = "sorter_none";
				break;
				
				case 'userdesc':
					$def_sort = " ORDER BY Autor DESC";
					$def_sort_n = "&amp;sort=userdesc";
					$def_sort_author  = "userasc"; 
					$def_sort_img_author = "sorter_down";
					$def_sort_img_name = "sorter_none";
				break;
				
				case 'userasc':
					$def_sort = " ORDER BY Autor ASC";
					$def_sort_n = "&amp;sort=userasc";
					$def_sort_author  = "userdesc"; 
					$def_sort_img_author = "sorter_up";
					$def_sort_img_name = "sorter_none";
				break;
			}
		}
		
		//=================================================================
		// Typ der Suche ermitteln
		//=================================================================
		if(isset($_REQUEST['searchtype']) && !empty($_REQUEST['searchtype']))
		{
			switch($_REQUEST['searchtype'])
			{
				default:case 'full':$def_searcht_n  = "&amp;searchtype=full";break;
				case 'tags':$def_searcht_n  = "&amp;searchtype=tags";break;
			}
		}
		
		
        //=================================================================
		// Abfrage Galerien (Anzahl fuer Navigation)
        //=================================================================
		$query = $GLOBALS['db']->Query("SELECT Id FROM " . PREFIX . "_galerie WHERE Parent_Id = '0' AND Kategorie = '$galid' AND Sektion = '" . $_SESSION['area'] . "' AND Aktiv = 1 {$def_search} {$def_sort} ");
		$num = $query->numrows();
        
		$limit = $Settings->Limit_Start;
		$seiten = ceil($num / $limit);
        $a = prepage() * $limit - $limit;

		//=================================================================
		// Abfrage Galerien
		//=================================================================
		$galleries = array();
       	$query = $GLOBALS['db']->Query("SELECT *, Name_{$LC} AS GalName, Beschreibung_{$LC} AS GalText FROM " . PREFIX . "_galerie WHERE Parent_Id = '0'  AND Kategorie = '$galid' AND Sektion = '" . $_SESSION['area'] . "' AND Aktiv = 1 {$def_search} {$def_sort} LIMIT $a, $limit");
		while($row = $query->fetchrow())
		{
			if($pattern!='')
			{
				// Suche-Log
				if(@$_SESSION['query_galerie_enthalten'] != $pattern_umlaut)
				{
					queryLog($pattern_umlaut, 'galerie_enthalten');
					$_SESSION['query_galerie_enthalten'] = $pattern_umlaut;
				}
				if(@$_REQUEST['searchtype'] != 'tags') $row->GalText = high($row->GalText,$pattern_umlaut);
			}
			//=================================================================
			// Letztes Bild
			//=================================================================
			$LastImage  = $GLOBALS['db']->RowQuery("SELECT Id,Bildname FROM " . PREFIX . "_galerie_bilder WHERE Galerie_Id = '$row->Id' ORDER BY " . ($Settings->Zufall_Start == 'TRUE' ? 'RAND()' : 'Id') . " " . $Settings->Sortierung_Start . " LIMIT 1");
			$row->ImageCount = $GLOBALS['db']->RowQuery("SELECT COUNT(Id) AS ImageCount FROM " . PREFIX . "_galerie_bilder WHERE Galerie_Id = '$row->Id'");
			
			
			if(is_object($LastImage))
			{
				$endg = @$this->getEndg($LastImage->Bildname);
				$row->Thumb = (file_exists('cache/' . md5('medium_' . $LastImage->Bildname) . $endg)) ? '<img class="gallery_categs_img" src="cache/' . md5('medium_' . $LastImage->Bildname) . $endg . '" border="0" alt="" />' : '<img class="gallery_categs_img" src="system/thumb.php?img_id=' . $LastImage->Id . '&amp;smode=2" border="0" alt="" />';
			}else {
				$row->Thumb	= '';
			}
			$row->Link  = 'index.php?p=gallery&amp;action=showgallery&amp;id=' . $row->Id. '&amp;categ=' . $_REQUEST['categ'] . '&amp;name=' . seotitle($row->GalName) . '&amp;area=' . AREA;
			$row->Author = fetchusername($row->Autor);
			$row->AuthorLink = 'index.php?p=user&amp;id=' . $row->Autor;
			
			//=================================================================
			// Untergalerien
			//=================================================================
			$sub_galleries = array();
			$sql_sub = $GLOBALS['db']->Query("SELECT Id,Name_{$LC} AS SubGalName FROM " . PREFIX . "_galerie WHERE Parent_Id = $row->Id AND Sektion = '" . $_SESSION['area'] . "' AND Aktiv = 1");
			while($row_sub = $sql_sub->fetchrow())
			{
				$row_sub->Link = 'index.php?p=gallery&amp;action=showgallery&amp;id=' . $row_sub->Id . '&amp;categ=' . $_REQUEST['categ'] . '&amp;name=' . seotitle($row_sub->SubGalName) . '&amp;area=' . AREA;
				array_push($sub_galleries, $row_sub);
			}
			
			$row->subGalleries = $sub_galleries;
			
			if($row->Tags)
			{
				$row->Tags = array_unique(explode(',', $row->Tags));
				@sort($row->Tags);
			}
			
			array_push($galleries, $row);
		}
		
		//=================================================================
		// Galeriename
		//=================================================================
		$GalInf = $GLOBALS['db']->RowQuery("SELECT Name_{$LC} AS Name FROM " . PREFIX . "_galerie_kategorien WHERE Id = '" . $_REQUEST['categ'] . "'");
		$GalName = @koobispecialchars($GalInf->Name);
		$thisLink = '<a href="index.php?p=gallery&amp;action=showincluded&amp;categ=' . $_REQUEST['categ'] . '&amp;name=' . @seotitle($GalInf->Name) . '&amp;area='. AREA . '">' . @koobispecialchars($GalInf->Name) . '</a>';
		$headernav = '<a href="index.php?p=gallery&amp;area='. AREA . '">' . $GLOBALS['config_vars']['Gallery_Name'] . '</a>' . $GLOBALS['config_vars']['PageSep'] . $thisLink;
		
		if ($num > $limit) 
		{
            $GLOBALS['tmpl']->assign('GalNavi', pagenav($seiten, '', " <a class=\"page_navigation\" href=\"index.php?p=gallery&amp;action=showincluded&amp;categ=$_REQUEST[categ]&amp;name=" . seotitle($GalName) . "&amp;q=$_REQUEST[q]&amp;searchtype=$_REQUEST[searchtype]&amp;page={s}&amp;sort=$_REQUEST[sort]&amp;area=" . AREA ."\">{t}</a> "));
        }
		
		$_REQUEST['q'] = urlencode($_REQUEST['q']);
		
		$GLOBALS['tmpl']->assign('def_sort_n', $def_sort_n);
		$GLOBALS['tmpl']->assign('def_sort_name', $def_sort_name);
		$GLOBALS['tmpl']->assign('def_sort_img_name', $def_sort_img_name);
		$GLOBALS['tmpl']->assign('def_sort_date', $def_sort_date);
		$GLOBALS['tmpl']->assign('def_sort_img_date', $def_sort_img_date);
		$GLOBALS['tmpl']->assign('def_sort_author', $def_sort_author);
		$GLOBALS['tmpl']->assign('def_sort_img_author', $def_sort_img_author);
		$GLOBALS['tmpl']->assign('headernav', $headernav );
		$GLOBALS['tmpl']->assign('pagetitle_html', clean_page_title($headernav));
		$GLOBALS['tmpl']->assign('galleries', $galleries);
		$GLOBALS['tmpl']->assign('categ', $_REQUEST['categ']);
		$GLOBALS['tmpl']->assign('galname',$GalName);
		$GLOBALS['tmpl']->assign('tagCloud', $this->getTagCloud($_REQUEST['categ']));
		$GLOBALS['tmpl']->assign('content', $GLOBALS['tmpl']->fetch($GLOBALS['config']['source'] . '/gallery/gallery.tpl')); 
	}
	
	
	function getTagCloud($categ='')
	{
		$tags    = '';
		$where   = ($categ!='') ? "SELECT Tags FROM " . PREFIX . "_galerie WHERE Kategorie = '" . $categ . "'" : "SELECT Tags FROM " . PREFIX . "_galerie_kategorien WHERE Aktiv='1' AND  Sektion = '" . $_SESSION['area'] . "'";
		$where_m = ($categ!='') ? "FROM " . PREFIX . "_galerie WHERE  Kategorie = '" . $categ . "'" : "FROM " . PREFIX . "_galerie_kategorien WHERE Aktiv='1' AND  Sektion = '" . $_SESSION['area'] . "'";
		$query = $GLOBALS['db']->Query($where);
		while($row = $query->fetchrow())
		{
			$tags .= $row->Tags . ',';
		}
		
		$tagss = array_unique(explode(',',$tags));
		@sort($tagss);
		$cloud = array();
		foreach($tagss as $key => $val)
		{
			$obj = '';
			if($val) 
			{
				$obj->Name = $val;
				$res = $GLOBALS['db']->RowQuery("SELECT COUNT(Id) AS GalCount $where_m AND (Tags LIKE '%{$obj->Name}%' OR Tags LIKE '{$obj->Name},%' OR Tags LIKE '%,{$obj->Name}' )");
				$obj->GCount = $res->GalCount;
				switch($obj->GCount)
				{
					case ($obj->GCount <= 1): $obj->Class = 'tagcloud1'; break;
					case ($obj->GCount == 2): $obj->Class = 'tagcloud2'; break;
					case ($obj->GCount == 3): $obj->Class = 'tagcloud3'; break;
					case ($obj->GCount >= 4): $obj->Class = 'tagcloud4'; break;
				}
				array_push($cloud, $obj);
			}
		}
		return $cloud;
	}
	
	//=================================================================
	// Galerie anzeigen
	//=================================================================
	function ShowGallery($id)
	{
		$db_extra    = '';
		$images_favs = '';
		$Settings = $this->GetSettings();
		$Comments = new Comments();
		
		if(perm('gal_fastupload') && isset($_REQUEST['gal_fastupload']) && $_REQUEST['gal_fastupload']==1)
		{
			$this->FastUpload();
		}
		
		if(isset($_REQUEST['favorites']) && $_REQUEST['favorites'] == 1 && $_SESSION['user_group']!=2 && $Settings->Favoriten == 1)
		{
			$images = '';
			$qf = $GLOBALS['db']->Query("SELECT * FROM " . PREFIX . "_galerie_bilderfavoriten WHERE Galerie_Id = $id AND Benutzer = '" . $_SESSION['benutzer_id'] . "'");
			while($rf = $qf->fetchrow())
			{
				$images[] = $rf->Bild_Id;
			}
			$db_extra = ($images) ? 'AND (Id = ' . implode(' OR Id = ',$images). ')' : 'AND (Id = -1)';
		}
		
		if(!permission('gallery')) noperm();
		$LC = $_SESSION['Langcode'];
		
		
		$query = $GLOBALS['db']->Query("SELECT Id FROM " . PREFIX . "_galerie_bilder WHERE Galerie_Id = $id {$db_extra}");
		$num = $query->numrows();
		
        $limit = (isset($_REQUEST['pp']) && $_REQUEST['pp'] > 1) ? $_REQUEST['pp'] : $Settings->Bilder_Seite;
		$seiten = ceil($num / $limit);
        $a = prepage() * $limit - $limit;
		
		$gallery_inf = $GLOBALS['db']->RowQuery("SELECT Id, Autor, Datum, Name_{$LC} AS GalName, Beschreibung_{$LC} AS GalText FROM " . PREFIX . "_galerie WHERE Id = $id ");
		
		//=================================================================
		// Umleitung wenn ungueltiger Aufruf
		//=================================================================
		if(!$gallery_inf) refer('index.php?p=gallery');
		$gallery_inf->AutorLink = '<a href="index.php?p=user&amp;id=' . $gallery_inf->Autor . '">' . fetchusername($gallery_inf->Autor) . '</a>';
		$gallery_inf->Images = $num;
		$gallery_inf->TitleGalName = $gallery_inf->GalName;
		$gallery_inf->GalName = seotitle($gallery_inf->GalName);
		
		$items = array();
		
		$sort  = (isset($_REQUEST['ascdesc']) && ($_REQUEST['ascdesc'] == 'asc' || $_REQUEST['ascdesc'] == 'desc')) ? strtoupper($_REQUEST['ascdesc']) : 'desc';
		$navsort = strtolower($sort);
		$sql = $GLOBALS['db']->Query("SELECT Klicks,Bildname,Id,Name_{$LC} AS ImageName, Beschreibung_{$LC} AS ImageText FROM " . PREFIX . "_galerie_bilder WHERE Galerie_Id = $id {$db_extra} ORDER BY Id {$sort} LIMIT $a, $limit");
		
		while($row = $sql->fetchrow())
		{
			$endg = @$this->getEndg($row->Bildname);
			$row->Thumbnail_Normal = (file_exists(BASE_DIR . '/cache/' . md5('normal_' . $row->Bildname) . $endg)) ? 'cache/' . md5('normal_' . $row->Bildname) . $endg : 'system/thumb.php?img_id=' . $row->Id . '&amp;smode=3';
			$row->PopUpText =  ($row->ImageName!='') ? '<strong>' . (($row->ImageName!='') ? koobispecialchars($row->ImageName) : '?') . '</strong><br />' . (($row->ImageText!='') ? $row->ImageText : '') : '';
			$row->Thumbnail = (file_exists(BASE_DIR . '/cache/' . md5('medium_' . $row->Bildname). $endg)) ? 'cache/' . md5('medium_' . $row->Bildname) . $endg : 'system/thumb.php?img_id=' . $row->Id . '&amp;smode=2';
			
			$row->Comments = $Comments->CommentCount('galerie',$row->Id);
			$GLOBALS['tmpl']->assign('row_i', $row);
			$row->Helper =  $GLOBALS['tmpl']->fetch($GLOBALS['config']['source'] . '/gallery/images_helper.tpl');
			array_push($items, $row );
			
			
		}
		
		if ($num > $limit) 
		{
			$fav_nav = (isset($_REQUEST['favorites']) && $_REQUEST['favorites']==1) ? "&amp;favorites=1" : "";         
		    $GLOBALS['tmpl']->assign('GalNavi', pagenav($seiten, '', " <a class=\"page_navigation\" href=\"index.php?p=gallery&amp;action=showgallery&amp;id={$id}&amp;categ=" . $_REQUEST['categ'] . "&amp;name=" . seotitle($gallery_inf->GalName) . "&amp;ascdesc={$navsort}&amp;pp={$limit}&amp;page={s}{$fav_nav}&amp;area=" . AREA . "\">{t}</a> "));
        }
		
		// Galeriename
		$GalInf = $GLOBALS['db']->RowQuery("SELECT Name_{$LC} AS Name FROM " . PREFIX . "_galerie_kategorien WHERE Id = '" . $_REQUEST['categ'] . "'");
		
		$headernav = getNavigationPath($id, 'galerie', 'gallery&amp;action=showgallery', 'id', 'Id', 'Name_' . $LC,'','','','','Parent_Id', $GLOBALS['config_vars']['Gallery_Name'],'gallery','1');

		// Erstes Bild
		$gallery_inf->First = $GLOBALS['db']->RowQuery("SELECT Id FROM " . PREFIX . "_galerie_bilder WHERE Galerie_Id = $id ORDER BY Id DESC LIMIT 1");
		
		//=================================================================
		// Untergalerien
		//=================================================================
		$sub_galleries = array();
		$sql_sub = $GLOBALS['db']->Query("SELECT Id,Name_{$LC} AS SubGalName FROM " . PREFIX . "_galerie WHERE Parent_Id = $gallery_inf->Id AND Sektion = '" . $_SESSION['area'] . "' AND Aktiv = 1");
		while($row_sub = $sql_sub->fetchrow())
		{
			$row_sub->Link = 'index.php?p=gallery&amp;action=showgallery&amp;id=' . $row_sub->Id. '&amp;categ=' . $_REQUEST['categ'] . '&amp;name=' . seotitle($row_sub->SubGalName) . '&amp;area=' . AREA;
			array_push($sub_galleries, $row_sub);
		}
		
		
		$qf = $GLOBALS['db']->Query("SELECT * FROM " . PREFIX . "_galerie_bilderfavoriten WHERE Galerie_Id = $id AND Benutzer = '" . $_SESSION['benutzer_id'] . "'");
		while($rf = $qf->fetchrow())
		{
			$images_favs[] = $rf->Bild_Id;
		}
		
		
		$GLOBALS['tmpl']->assign('Favorites', $images_favs);
		$GLOBALS['tmpl']->assign('subGalleries', $sub_galleries);
		$GLOBALS['tmpl']->assign('Galsettings', $Settings);
		$GLOBALS['tmpl']->assign('Gallery_inf', $gallery_inf);
		$GLOBALS['tmpl']->assign('items', $items);
		$GLOBALS['tmpl']->assign('headernav', $headernav);
		$GLOBALS['tmpl']->assign('pagetitle_html', clean_page_title($headernav));
		$GLOBALS['tmpl']->assign('content', $GLOBALS['tmpl']->fetch($GLOBALS['config']['source'] . '/gallery/galleryimages.tpl')); 
	}
	
	function getEndg($fname)
	{
		return '';
		#return substr($fname,-4);
	}
	//=================================================================
	// Bild anzeigen (Details)
	//=================================================================
	function ShowImage($image,$gallery)
	{
		$Slide_Start= '';
		$gal_id = $gallery;
		if(!permission('gallery')) noperm();
		$Settings = $this->GetSettings();
		
		//=================================================================
		// Bild-Download
		//=================================================================
		if(isset($_GET['download']) && $_GET['download']==1)
		{
			if($Settings->Download!=1 || !permission('gallery_download'))
			{
				// Kein Download
			} else {
				$this->ImageDownload($image,$gallery);
			}
		}
		
		// Zaehler
		$GLOBALS['db']->RowQuery("UPDATE " . PREFIX . "_galerie_bilder SET Klicks=Klicks+1 WHERE Id = $image");
		
		$LC = $_SESSION['Langcode'];
		$row = $GLOBALS['db']->RowQuery("SELECT Klicks,Bildname,Id,Name_{$LC} AS ImageName, Beschreibung_{$LC} AS ImageText FROM " . PREFIX . "_galerie_bilder WHERE Galerie_Id = $gallery AND Id = $image");
		
		// Umleitung wenn ungueltiger Aufruf
		if(!is_object($row)) refer('index.php?p=gallery');
		
		$endg = @$this->getEndg($row->Bildname);
		$row->Image = (file_exists('cache/' . md5('normal_' . $row->Bildname) . $endg)) ? 'cache/' . md5('normal_' . $row->Bildname) . $endg : 'system/thumb.php?img_id=' . $row->Id . '&amp;smode=3"';
		if(file_exists(BASE_DIR . "/uploads/galerie/" . $row->Bildname . $endg))
		{
			$size = @GetImageSize(BASE_DIR . "/uploads/galerie/" . $row->Bildname);
			$row->Image_Width = $size[0];
			$row->Image_Height = $size[1];
		}
		
		// Erstes Bild
		$ascdesc = (isset($_REQUEST['ascdesc']) && $_REQUEST['ascdesc'] != '' && ($_REQUEST['ascdesc'] == 'asc' || $_REQUEST['ascdesc'] == 'desc')) ? $_REQUEST['ascdesc'] : 'desc';
		$first   = $GLOBALS['db']->RowQuery("SELECT Id FROM " . PREFIX . "_galerie_bilder WHERE Galerie_Id = $gallery ORDER BY Id {$ascdesc} LIMIT 1");
		
		//=================================================================
		// Vorheriges und naechstes Bild
		//=================================================================
		$sql_i = $GLOBALS['db']->Query("SELECT Id,Name_{$LC} AS ImageName,Bildname,Beschreibung_{$LC} AS ImageText FROM " . PREFIX . "_galerie_bilder WHERE Galerie_Id = $gallery ORDER BY Id {$ascdesc}");
		$all = $sql_i->numrows();
		$gallery = array();
		$i = 1;
		$curr_pic = '0';
		$next_pic = '0';
		$prev_pic = '0';
		while($rowall = $sql_i->fetchrow())
		{
			$n = $i++;
			$rowall->number = $n;
			if ($rowall->Id == $row->Id) $curr_pic = $rowall;
			array_push($gallery,$rowall);
		}
		$pic_index = karray_search($curr_pic,$gallery);
		$prevImage_Id = ($pic_index > 0) ? $gallery[$pic_index - 1] : '0';
		$nextImage_Id = ($pic_index < (count($gallery) - 1)) ? $gallery[$pic_index + 1] : '0';
		
		if(is_object($prevImage_Id) && $prevImage_Id->Id!=0)
		{
			$endg = @$this->getEndg(@$prevImage_Id->Bildname);
			$row->PrefImageLink = 'index.php?p=gallery&amp;action=showimage&amp;id=' . $prevImage_Id->Id . '&amp;galid=' . @$_REQUEST['galid'] . '&amp;ascdesc=' . $ascdesc . '&amp;categ=' . @$_REQUEST['categ'] . '&amp;area=' . AREA;
			$row->PrefImage = (file_exists('cache/' . md5('small_' . @$prevImage_Id->Bildname) . $endg)) ? '<img class="absmiddle" src="cache/' . md5('small_' . @$prevImage_Id->Bildname) . $endg . '" border="0" alt="" />' : '<img class="absmiddle" src="system/thumb.php?img_id=' . @$prevImage_Id->Id . '&amp;smode=1" border="0" alt="" />';
		} else {
			$row->PrefImageLink = '';
			$row->PrefImage = '';
		}
		
		if(is_object($nextImage_Id) && $nextImage_Id->Id!=0)
		{
			$endg = @$this->getEndg(@$nextImage_Id->Bildname);
			$row->NextImageLink = 'index.php?p=gallery&amp;action=showimage&amp;id=' . $nextImage_Id->Id . '&amp;galid=' . @$_REQUEST['galid'] . '&amp;ascdesc=' . $ascdesc . '&amp;categ=' . @$_REQUEST['categ'] . '&amp;area=' . AREA;
			$row->NextImageLink_Blanc = 'index.php?blanc=1&amp;p=gallery&amp;action=showimage&amp;id=' . $nextImage_Id->Id . '&amp;galid=' . @$_REQUEST['galid'] . '&amp;ascdesc=' . $ascdesc . '&amp;categ=' . @$_REQUEST['categ'] . '&amp;first_id=' . $first->Id . '&amp;area=' . AREA;
			
			$row->NextImage = (file_exists('cache/' . md5('small_' . @$nextImage_Id->Bildname) . $endg))  ? '<img class="absmiddle" src="cache/' . md5('small_' . @$nextImage_Id->Bildname) . $endg . '" border="0" alt="" />' : '<img class="absmiddle" src="system/thumb.php?img_id=' . @$nextImage_Id->Id . '&amp;smode=1" border="0" alt="" />';
		} else {
			$row->NextImageLink = '';
			$row->NextImage = '';
		}
		
		//=================================================================
		// Weitere Bilder
		//=================================================================
		
		if($Settings->MehrBilder==1)
		{
			/*
			$more = array();
			$sql_more = $GLOBALS['db']->Query("SELECT Id,Bildname,Name_{$LC} AS ImageName, Beschreibung_{$LC} AS ImageDescr FROM " . PREFIX . "_galerie_bilder WHERE Galerie_Id = '$gal_id' ORDER BY Id {$ascdesc}");
			$img_count = 1;
			while($row_more = $sql_more->fetchrow())
			{
				$class_img = (isset($_GET['id']) && ($_GET['id'] == $row_more->Id))  ? 'gallery_more_thumb_active' : 'gallery_more_thumb';
				$row_more->ImageThumb = (file_exists('cache/' . md5('small_' . $row_more->Bildname)))  ? '<img class="' . $class_img . '" src="cache/' . md5('small_' . $row_more->Bildname) . '" border="0" alt="" />' : '<img class="' . $class_img . '" src="system/thumb.php?img_id=' . $row_more->Id . '&amp;smode=1" border="0" alt="" />';
				if($_REQUEST['id'] == $row_more->Id) 
				{
					$Slide_Start = $img_count;
				}
				
				$row_more->ImageText  = ($row_more->ImageName != '') ? '<strong>' . koobispecialchars($row_more->ImageName) . '</strong><br />' .  koobispecialchars($row_more->ImageDescr) : '';
				array_push($more, $row_more);
				$img_count++;
			}
			$row->MoreImages = $more;
			*/
		}
		
		
		//=================================================================
		// Kommentar neu
		//=================================================================
		if(permission('comments') && $Settings->Kommentare == 1)
		{
			$comment = new Comments;
			$comment->NewComment('galerie', @$_POST['Redir'], $image);
		}
		
		//=================================================================
		// Kommentare
		//=================================================================
		if($Settings->Kommentare == 1)
		{
			$comment = new Comments;
			if(isset($_POST['comment_action']) && $_POST['comment_action'] == 'edit' && permission('edit_comments')) $comment->EditComment('galerie',$_POST['comment_id']);
			$Comments = $comment->GetComments('galerie',$image,'index.php?p=gallery&amp;action=showimage&amp;id=' . $image . '&amp;galid=' . $gal_id . '&amp;ascdesc=' . $ascdesc . '&amp;categ=' . $_REQUEST['categ'] . '&amp;area=' . AREA);
			$GLOBALS['tmpl']->assign('GetComments',$GLOBALS['tmpl']->fetch($GLOBALS['config']['source'] . '/comments/comments.tpl'));
		}
		//=================================================================
		// Navigation
		//=================================================================
		$headernav = getNavigationPath($_GET['galid'], 'galerie', 'gallery&amp;action=showgallery', 'id', 'Id', 'Name_' . $LC,'','','','','Parent_Id', $GLOBALS['config_vars']['Gallery_Name'],'gallery');
		
		$qf = $GLOBALS['db']->Query("SELECT * FROM " . PREFIX . "_galerie_bilderfavoriten WHERE Galerie_Id = '". $_REQUEST['galid'] . "' AND Benutzer = '" . $_SESSION['benutzer_id'] . "'");
		while($rf = $qf->fetchrow())
		{
			$images_favs[] = $rf->Bild_Id;
		}
		
		
		$GLOBALS['tmpl']->assign('Favorites', @$images_favs);
		$GLOBALS['tmpl']->assign('Galsettings', $Settings);
		$GLOBALS['tmpl']->assign('listemos', listsmilies('14',1,1));
		$GLOBALS['tmpl']->assign('headernav', $headernav);
		$GLOBALS['tmpl']->assign('pagetitle_html', clean_page_title($headernav . $GLOBALS['config_vars']['PageSep'] . (($row->ImageName!='') ? $row->ImageName : $GLOBALS['config_vars']['Gallery_ImageNoName']) ));
		$GLOBALS['tmpl']->assign('data', $row);
		$GLOBALS['tmpl']->assign('first_id', $first->Id);
		$GLOBALS['tmpl']->assign('slide_start', $Slide_Start);
		$GLOBALS['tmpl']->assign('content', $GLOBALS['tmpl']->fetch($GLOBALS['config']['source'] . '/gallery/' . ((isset($_GET['blanc']) && $_GET['blanc']==1) ? 'gallerypic_diashow.tpl' : 'gallerypic.tpl'))); 
	}
	
	
	//=================================================================
	// Funktion zum Bild-Download
	//=================================================================
	function ImageDownload($image,$gallery)
	{
		if(!permission('gallery_download')) noperm();
		$Settings = $this->GetSettings();
		$w = false;
		$h = false;
		
		$row = $GLOBALS['db']->RowQuery("SELECT Bildname FROM " . PREFIX . "_galerie_bilder WHERE Galerie_Id = $gallery AND Id = $image");
		$endg = @$this->getEndg($row->Bildname);
		$file = BASE_DIR . "/uploads/galerie/" . $row->Bildname;
		
		$size = @GetImageSize(BASE_DIR . "/uploads/galerie/" . $row->Bildname . $endg);
		$w  = $size[0];
		$h  = $size[1];
		
		//=================================================================
		// Wasserzeichen einfuegen, wenn moeglich und eingestellt
		// wird nur erzeugt, wenn Bild kleiner oder gleich $this->_max_size_wm ist
		//=================================================================
		
		if(($w!=false && $h!=false && $w<=$this->_max_size_wm) && $Settings->Wasserzeichen==1 && function_exists('imagecolortransparent') && function_exists('imagecreatefrompng'))
		{
			$end = $endg; //substr($row->Bildname, -3);
			$q = BASE_DIR . "/uploads/galerie/" . $row->Bildname;
			
			// Den richtigen Header setzen
			switch($end)
			{
				case 'jpg':
					$quelle = imagecreatefromjpeg($q);
					$func   = 'imagejpeg';
					header ("Content-type: image/jpeg");
				break;
				case 'png':
					$quelle = imagecreatefrompng($q);
					$func   = 'imagepng';
					header ("Content-type: image/png");
				break;
				case 'gif':
					$quelle = imagecreatefromgif($q);
					$func   = 'imagegif';
					header ("Content-type: image/gif");
				break;
			}
			
			// Bild dynamisch erzeugen
			$ziel    = @imagecreatetruecolor($w, $h);
			imagecopyresampled($ziel, $quelle, 0, 0, 0, 0, $w, $h, imagesx($quelle), imagesy($quelle));
			
			// Wasserzeichen in Bild kopieren
			$insert = imagecreatefrompng(BASE_DIR . '/uploads/watermark.png');
			imagecolortransparent($insert, imagecolorexact($insert, 255, 0, 255));
			
			$insert_x = imagesx($insert);
			$insert_y = imagesy($insert);
			$dest_x   = imagesx($ziel) - $insert_x - 10;
			$dest_y   = imagesy($ziel) - $insert_y - 10;
			imagecopymerge($ziel, $insert, $dest_x, $dest_y, 0, 0, $insert_x, $insert_y, 50);
			ob_start();
			
			// Neues Bild erzeugen und als String puffern
			$bild = $func($ziel, '', $Settings->Quali_Gross);
			$download = ob_get_contents();
			ob_end_clean();
			
			// Puffer ausgeben (Download)
			header("Cache-control: private");
			header("Content-type: application/octet-stream"); 
			header('Expires: ' . gmdate('D, d M Y H:i:s') . ' GMT');
			header('Content-Disposition: attachment; filename=' . $row->Bildname);
			header('Content-Length: ' . strlen($download));
			header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
			header('Pragma: public');
			echo $download;
			exit;
		//=================================================================
		// Kein Wasserzeichen - Direktdownload
		//=================================================================
		} else {
			header("Cache-control: private");
			header("Content-type: application/octet-stream"); 
			header("Content-disposition:attachment; filename=" . $row->Bildname);
			header("Content-Length:" . filesize($file));
			@readfile($file);
			exit;
		}
	}
	
	
	//=================================================================
	// Ajax-Reload fuer Bildergalerie nach Upload
	//=================================================================
	function AjaxImages($id)
	{
		$LC = $_SESSION['Langcode'];
		$Settings = $this->GetSettings();
	
		$query = $GLOBALS['db']->Query("SELECT Id FROM " . PREFIX . "_galerie_bilder WHERE Galerie_Id = '$id'");
		$num = $query->numrows();
		$limit = (isset($_REQUEST['pp']) && $_REQUEST['pp'] > 1) ? $_REQUEST['pp'] : $Settings->Bilder_Seite;
		$seiten = ceil($num / $limit);
		$a = prepage() * $limit - $limit;
	
		$items = array();
		$sort = 'desc';
	
	
		$sql = $GLOBALS['db']->Query("SELECT Klicks,Bildname,Id,Name_{$LC} AS ImageName, Beschreibung_{$LC} AS ImageText FROM " . PREFIX . "_galerie_bilder WHERE Galerie_Id = '$id' ORDER BY Id {$sort} LIMIT $a, $limit");
		while($row = $sql->fetchrow())
		{
			$endg = @$this->getEndg($row->Bildname);
			$row->PopUpText = ($row->ImageName!='') ? '<strong>' . (($row->ImageName!='') ? koobispecialchars($row->ImageName) : '?') . '</strong><br />' . (($row->ImageText!='') ? $row->ImageText : '') : '';
			$row->Thumbnail = (file_exists('cache/' . md5('medium_' . $row->Bildname) . $endg)) ? 'cache/' . md5('medium_' . $row->Bildname) . $endg . '"' : 'system/thumb.php?img_id=' . $row->Id . '&amp;smode=2"';
			#$row->Thumbnail_Normal = (file_exists('cache/normal_' . $row->Bildname)) ? 'cache/normal_' . $row->Bildname . '"' : 'system/thumb.php?img_id=' . $row->Id . '&amp;smode=3"';
			array_push($items, $row );
		}
		
		
		$GLOBALS['tmpl']->assign('trenn', $Settings->Bilder_Zeile);
		$GLOBALS['tmpl']->assign('items', $items);
		$Out =  $GLOBALS['tmpl']->fetch($GLOBALS['config']['source'] . '/gallery/galleryimages_ajax.tpl');
		$Out = str_replace("'","\'", $Out);
		return $Out;
	}
	
	//=================================================================
	// Ajax-Bildupload ohne Seiten-Refresh
	//=================================================================
	function AjaxUpload()
	{
		if(permission('gal_fastupload'))
		{
			define('AJAX_OUTPUT',1);
			$name = (isset($_REQUEST['name']) && !empty($_REQUEST['name'])) ? eregi_replace('[^- ._A-Za-zA-ÖO-öo-y0-9]', '', $_REQUEST['name']) : '';
			$text = (isset($_REQUEST['text']) && !empty($_REQUEST['text'])) ? eregi_replace('[^- ._A-Za-zA-ÖO-öo-y0-9]', '', $_REQUEST['text']) : '';
			$error = "";
			$msg = "";
			$allowed = array('image/pjpeg','image/jpeg','image/x-png','image/png','image/gif');
			$fileElementName = 'fileToUpload';
			
			if(!empty($_FILES[$fileElementName]['error']))
			{
				switch($_FILES[$fileElementName]['error'])
				{
		
					case '1':$error = $GLOBALS['config_vars']['Upload_ToBig1'];break;
					case '2':$error = $GLOBALS['config_vars']['Upload_ToBig2'];break;
					case '3':$error = $GLOBALS['config_vars']['Upload_The uploaded file was only partially uploaded'];break;
					case '4':$error = $GLOBALS['config_vars']['Upload_NoFile'];break;
					case '6':$error = $GLOBALS['config_vars']['Upload_Missing a temporary folder'];break;
					case '7':$error = $GLOBALS['config_vars']['Upload_Failed to write file to disk'];break;
					case '8':$error = $GLOBALS['config_vars']['Uplaod_File upload stopped by extension'];break;
					case '999':default:$error = 'No error code avaiable';break;
				}
			}elseif(empty($_FILES['fileToUpload']['tmp_name']) || $_FILES['fileToUpload']['tmp_name'] == 'none')
			{
				$error = $GLOBALS['config_vars']['Upload_NoFile'];
			}else 
			{
					switch($_FILES['fileToUpload']['type'])
					{
						case 'image/pjpeg' :
						case 'image/jpeg' :
						case '' :
							$new_name = md5(time() . mt_rand(10001, 19999) . $_FILES['fileToUpload']['tmp_name']) . '.jpg';
						break;
						
						case 'image/x-png' :
						case 'image/png' :
							$new_name = md5(time() . mt_rand(10001, 19999) . $_FILES['fileToUpload']['tmp_name']) . '.png';
						break;
						
						case 'image/gif' :
							$new_name = md5(time() . mt_rand(10001, 19999) . $_FILES['fileToUpload']['tmp_name']) . '.gif';
						break;
					}
						
					$f_check     = trim(strtolower($_FILES['fileToUpload']['name']));
					$forbidden_1 = strtolower(substr($f_check, strlen($f_check) - 4));
					$forbidden_2 = strtolower(substr($f_check, strlen($f_check) - 5));
					
					if((in_array($_FILES['fileToUpload']['type'], $allowed)) && ($forbidden_1 != 'jpeg' && $forbidden_2 != 'pjpeg'))
					{
						$msg .= $GLOBALS['config_vars']['Upload_Succes'] . '(' . $_FILES['fileToUpload']['name'] . ') ';
						// $msg .= " File Size: " . @filesize($_FILES['fileToUpload']['tmp_name'] . ' Bytes');
						@move_uploaded_file($_FILES['fileToUpload']['tmp_name'], BASE_DIR . '/uploads/galerie/' . $new_name);
						@chmod(BASE_DIR . '/uploads/galerie/' . $new_name,0777);
						
						$GLOBALS['db']->Query("INSERT INTO " . PREFIX . "_galerie_bilder 
							(	
								Id,
								Galerie_Id,
								Bildname,
								Name_1,
								Name_2,
								Name_3,
								Beschreibung_1,
								Beschreibung_2,
								Beschreibung_3,
								Autor,
								Datum
							) VALUES (
								'',
								'$_REQUEST[id]',
								'$new_name',
								'" . $name . "',
								'" . $name . "',
								'" . $name . "',
								'" . @$text . "',
								'" . @$text . "',
								'" . @$text . "',
								'',
								'" . stime() . "'
							)");
							$insert = $GLOBALS['db']->InsertId();
					} else {
						$error = $GLOBALS['config_vars']['Upload_ForbiddenFile'] . '(' . $_FILES['fileToUpload']['type'] . ')';
					}
						
					
			}		
			echo "{";
			echo				"error: '" . $error . "',\n";
			echo				"msg: '" . $msg  . "',\n";
			echo				"html: '" . $this->AjaxImages($_REQUEST['id']) . "'\n";
			echo "}";
		}
	}
	
	
	//=================================================================
	// Funktion zum hochladen von Bildern aus dem Produkt heraus
	// !! NICHT GENUTZT !!
	//=================================================================
	function FastUpload()
	{
		define('AJAX_OUTPUT',1);
		$count = 0;
		$images = '';
		$db_images = '';
		$allowed = array('image/pjpeg','image/jpeg','image/x-png','image/png');
		
		if(isset($_FILES['files']))
		{
			//print_r($_FILES);
			$anz = count($_FILES['files']['tmp_name']);
			for($i=0;$i<count($_FILES['files']['tmp_name']);$i++)
			{
				#if(empty($_FILES['files']['tmp_name'][$i])) $i=$i-1;
				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;
					}
					
					$f_check     = trim(strtolower($_FILES['files']['name'][$i]));
					$forbidden_1 = strtolower(substr($f_check, strlen($f_check) - 4));
					$forbidden_2 = strtolower(substr($f_check, strlen($f_check) - 5));
					
					if((in_array($_FILES['files']['type'][$i], $allowed)) && ($forbidden_1 != 'jpeg' && $forbidden_2 != 'pjpeg'))
					{
						@move_uploaded_file($_FILES['files']['tmp_name'][$i], BASE_DIR . '/uploads/galerie/' . $new_name);
						@chmod(BASE_DIR . '/uploads/galerie/' . $new_name,0777);
						$images[] = $new_name;
						$GLOBALS['db']->Query("INSERT INTO " . PREFIX . "_galerie_bilder 
						(	
							Id,
							Galerie_Id,
							Bildname,
							Name_1,
							Name_2,
							Name_3,
							Beschreibung_1,
							Beschreibung_2,
							Beschreibung_3,
							Autor,
							Datum
						) VALUES (
							'',
							'$_REQUEST[id]',
							'$new_name',
							'" . $_POST['Name_1'][$i] . "',
							'" . $_POST['Name_1'][$i] . "',
							'" . $_POST['Name_1'][$i] . "',
							'" . $_POST['Beschreibung_1'][$i] . "',
							'" . $_POST['Beschreibung_1'][$i] . "',
							'" . $_POST['Beschreibung_1'][$i] . "',
							'',
							'" . stime() . "'
						)");
						$insert = $GLOBALS['db']->InsertId();
						
						echo '<img style="display:none;width:1px;height:1px" src="system/thumb.php?img_id=' . $insert . '&amp;smode=3" border="0" alt="" />';
						echo '<img style="display:none;width:1px;height:1px" src="system/thumb.php?img_id=' . $insert . '&amp;smode=2" border="0" alt="" />';
						echo '<img  src="system/thumb.php?img_id=' . $insert . '&amp;smode=1" border="0" alt="" />';
						$count++;
					}
				}
			}			
		}
		echo '<body onload=window.opener.location.reload();window.close();>';
	}
	
	
}
?>