<?php
class Gallery
{
	function GalSettings()
	{
		if(perm('gallery_overview'))
		{
			if(isset($_POST['save']) && $_POST['save']==1)
			{
				 $GLOBALS['db']->Query("UPDATE " . PREFIX . "_galerie_einstellungen SET 
				 	Bilder_Klein = '" . $_POST['Bilder_Klein'] . "', 	
					Bilder_Mittel = '" . $_POST['Bilder_Mittel'] . "', 	 	
					Bilder_Gross = '" . $_POST['Bilder_Gross'] . "', 	 	
					Bilder_Seite = '" . $_POST['Bilder_Seite'] . "', 	 	
					Bilder_Zeile = '" . $_POST['Bilder_Zeile'] . "', 	 	
					Limit_Start = '" . $_POST['Limit_Start'] . "', 	 	
					Wasserzeichen = '" . $_POST['Wasserzeichen'] . "', 		
					Wasserzeichen_Vorschau = '" . $_POST['Wasserzeichen_Vorschau'] . "', 
					Transparenz = '" . $_POST['Transparenz'] . "',  	
					Quali_Gross = '" . $_POST['Quali_Gross'] . "', 	 	
					Diashow_Zeit = '" . $_POST['Diashow_Zeit'] . "', 	 	
					Banner_Code = '" . $_POST['Banner_Code'] . "', 	 	 	
					Kommentare = '" . $_POST['Kommentare'] . "', 	 	
					Favoriten = '" . $_POST['Favoriten'] . "', 	 	
					Download = '" . $_POST['Download'] . "', 	 	
					Meist_Gesehen = '" . $_POST['Meist_Gesehen'] . "', 		
					Kategorien_zeile = '1', 		
					Kategorie_Icon_Breite = '" . $_POST['Bilder_Mittel'] . "'
				 ");
				 
				 if(isset($_POST['renew']) && $_POST['renew']==1)
				 {
					$d = BASE_DIR . 'cache';
					$handle = opendir($d); 
					$templates = array();
					while ($file = readdir ($handle)){ 
						if($file != '.' && $file != '..' && $file != '.htaccess') { 
							$f = '';
							if(is_file($d.'/'.$file))
							{ 
								@unlink($d.'/'.$file);
							} 	
						} 
					}
				}
				header('Location:index.php?do=gallery&sub=gallerysettings');
				exit;
			}
			
			$res = $this->GetSettings();
			
			$GLOBALS['tmpl']->assign('res', $res);
			$GLOBALS['tmpl']->assign('title', $GLOBALS['config_vars']['Gallery_settings']); 
			$GLOBALS['tmpl']->assign('content', $GLOBALS['tmpl']->fetch($GLOBALS['config']['source'] . '/gallery/settings.tpl')); 
		} else {
			no_perm();
		}
	}
	
	function ListCategs()
	{
		if(perm('gallery_overview'))
		{
			// Speichern
			if(isset($_POST['save']) && $_POST['save']==1)
			{
				foreach($_POST['Aktiv'] as $lid => $li)
				{
					$GLOBALS['db']->Query("UPDATE " . PREFIX . "_galerie_kategorien SET Aktiv = '" . $_POST['Aktiv'][$lid] . "' WHERE Id = '$lid'");
				}
			}
			
			$LC = 1;
			$galsettings = $this->GetSettings();
			$db_sort      = " ORDER BY Name_1 ASC";
			$nav_sort   = "&amp;sort=name_asc";
			$datesort = '';
			$activesort = '';
			$imgsort = '';
			$usersort = '';
			$def_search_n = '';
			$def_search = '';
			$namesort = '';
			
			
			switch(@$_REQUEST['sort'])
			{
				case '':case 'name_asc':default:$db_sort = 'ORDER BY Name_1 ASC';$nav_sort = '&amp;sort=name_asc';$namesort = 'name_desc';break;
				case'name_desc':$db_sort='ORDER BY Name_1 DESC';$nav_sort='&amp;sort=name_desc';$namesort='name_asc';break;
				case'date_asc':$db_sort='ORDER BY Datum ASC';$nav_sort='&amp;sort=date_asc';$datesort='date_desc';break;
				case'date_desc':$db_sort='ORDER BY Datum DESC';$nav_sort='&amp;sort=date_desc';$datesort='date_asc';break;
				case'img_asc':$db_sort='ORDER BY Bilder ASC';$nav_sort='&amp;sort=img_asc';$imgsort='img_desc';break;
				case'img_desc':$db_sort='ORDER BY Bilder DESC';$nav_sort='&amp;sort=img_desc';$imgsort='img_asc';break;
				case'active_asc':$db_sort='ORDER BY Aktiv ASC';$nav_sort='&amp;sort=active_asc';$activesort='active_desc';break;
				case'active_desc':$db_sort='ORDER BY Aktiv DESC';$nav_sort='&amp;sort=active_desc';$activesort='active_asc';break;
				case'user_asc':$db_sort='ORDER BY Autor ASC';$nav_sort='&amp;sort=user_asc';$usersort='user_desc';break;
				case'user_desc':$db_sort='ORDER BY Autor DESC';$nav_sort='&amp;sort=user_desc';$usersort='user_asc';break;
			}
			
			if(isset($_REQUEST['q']) && !empty($_REQUEST['q']) && $_REQUEST['q'] != 'empty' && strlen($_REQUEST['q'])>=3)
			{
				$pattern = preg_replace('/([^-A-Za-zÀ-ÖØ-öø-ÿ0-9. ]*)/', '', $_REQUEST['q']);
				$_REQUEST['q']  = $pattern;
				$def_search_n   = "&amp;q=" . urlencode($pattern);
				$def_search     = " AND (Name_1 LIKE '%{$pattern}%') ";
			}
			
			$GLOBALS['tmpl']->assign('namesort', $namesort);
			$GLOBALS['tmpl']->assign('datesort', $datesort);
			$GLOBALS['tmpl']->assign('imgsort', $imgsort);
			$GLOBALS['tmpl']->assign('activesort', $activesort);
			$GLOBALS['tmpl']->assign('usersort', $usersort);
			
			
			
			$query = $GLOBALS['db']->Query("SELECT Id FROM " . PREFIX . "_galerie_kategorien WHERE Sektion = '" . $_SESSION['a_area'] . "' {$def_search} {$db_sort}");
			$num = $query->numrows();
			
			$limit = getLimit(15);
			$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, Autor, Datum, Aktiv FROM " . PREFIX . "_galerie_kategorien WHERE Sektion = '" . $_SESSION['a_area'] . "' {$def_search} {$db_sort} LIMIT $a,$limit");
			while($row = $sql->fetchrow())
			{
				$row->User = getUsername($row->Autor);
				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?do=gallery{$def_search_n}{$nav_sort}&amp;pp={$limit}&amp;page={s}\">{t}</a> "));
			}
			
			$GLOBALS['tmpl']->assign('title', $GLOBALS['config_vars']['Gallery_categoverview']); 
			$GLOBALS['tmpl']->assign('galleries', $galleries);
			$GLOBALS['tmpl']->assign('galsettings', $galsettings);
			$GLOBALS['tmpl']->assign('limit', $limit);
			$GLOBALS['tmpl']->assign('def_sort_n', $nav_sort);
			$GLOBALS['tmpl']->assign('content', $GLOBALS['tmpl']->fetch($GLOBALS['config']['source'] . '/gallery/galleryshow.tpl')); 
		} else {
			no_perm();
		}
	}
	
	//=================================================================
	// Kategorie loeschen
	//=================================================================
	function delCateg($id)
	{
		if(perm('gallery_delete'))
		{
			
			$sql = $GLOBALS['db']->Query("SELECT Id,Parent_Id FROM " . PREFIX . "_galerie WHERE Kategorie='$id'");
			while($row_g = $sql->fetchrow())
			{
				$this->GalDel($row_g->Id,'0');
			}
			
			$GLOBALS['db']->Query("DELETE FROM " . PREFIX . "_galerie_kategorien WHERE Id='$id'");
		}
		echo "<script>window.opener.location.reload(); window.close();< /script>";
	}
	
	//=================================================================
	// Kategorie anlegen
	//=================================================================
	function addCateg()
	{
		
		if(perm('gallery_edit'))
		{	
			if(isset($_POST['save']) && $_POST['save']==1)
			{
				$tags = (!empty($_POST['Tags'])) ? umlaut2text(trim(str_replace(array("\n","\r\n"), "", $_POST['Tags']))) : '';
				$img = (!empty($_POST['newImg_1'])) ? preg_replace('/([^-A-Za-zÀ-ÖØ-öø-ÿ0-9.]*)/', '', $_POST['newImg_1']) : '';
				
				$Name_1 = $_POST['Name_1'];
				$Name_2 = !empty($_POST['Name_2']) ? $_POST['Name_2'] : $_POST['Name_1'];
				$Name_3 = !empty($_POST['Name_3']) ? $_POST['Name_3'] : $_POST['Name_1'];
				$Text_1 = $_POST['Text_1'];
				$Text_2 = !empty($_POST['Text_2']) ? $_POST['Text_2'] : $Text_1;
				$Text_3 = !empty($_POST['Text_3']) ? $_POST['Text_3'] : $Text_1;
				
				$GLOBALS['db']->Query("INSERT INTO " . PREFIX . "_galerie_kategorien 
				(
					Name_1,
					Name_2,
					Name_3,
					Text_1,
					Text_2,
					Text_3,
					Aktiv,
					Tags,
					Bild,
					Datum,
					Autor,
					Sektion
				) VALUES (
					'" . $Name_1 . "',
					'" . $Name_2 . "',
					'" . $Name_3 . "',
					'" . $Text_1 . "',
					'" . $Text_2 . "',
					'" . $Text_3 . "',
					'" . $_POST['Aktiv'] . "',
					'" . $tags . "',
					'" . $img . "',
					'" . stime() . "',
					'" . $_SESSION['benutzer_id'] . "',
					'" . $_SESSION['a_area'] . "'
				)");
				echo "<script>window.opener.location.reload(); window.close();</script>";
			}
			
			$GLOBALS['tmpl']->assign('Beschreibung_1', fckInit(' ', 'Text_1', 150, 'Basic'));
			$GLOBALS['tmpl']->assign('Beschreibung_2', fckInit(' ', 'Text_2', 150, 'Basic'));
			$GLOBALS['tmpl']->assign('Beschreibung_3', fckInit(' ', 'Text_3', 150, 'Basic'));
			$GLOBALS['tmpl']->assign('content', $GLOBALS['tmpl']->fetch($GLOBALS['config']['source'] . '/gallery/newcateg.tpl')); 
			$GLOBALS['tmpl']->assign('title', $GLOBALS['config_vars']['Gallery_CategNew']); 
			
			
		} else {
			no_perm();
		}
	}
	
	//=================================================================
	// Kategorie bearbeiten
	//=================================================================
	function editCateg($id)
	{
		if(perm('gallery_edit'))
		{
			if(isset($_POST['save']) && $_POST['save']==1)
			{
				$tags = str_replace(array("\n","\r\n"), "", $_POST['Tags']); 
				$tags = umlaut2text(trim($tags));
				
				$Name_2 = !empty($_POST['Name_2']) ? $_POST['Name_2'] : $_POST['Name_1'];
				$Name_3 = !empty($_POST['Name_3']) ? $_POST['Name_3'] : $_POST['Name_1'];
				$Text_1 = $_POST['Text_1'];
				$Text_2 = !empty($_POST['Text_2']) ? $_POST['Text_2'] : $Text_1;
				$Text_3 = !empty($_POST['Text_3']) ? $_POST['Text_3'] : $Text_1;
				
				if((isset($_POST['delold']) && $_POST['delold']==1) || (isset($_POST['newImg_1']) && !empty($_POST['newImg_1'])))
				{
					@unlink(BASE_DIR . 'uploads/galerie_icons/' . @$_POST['oldimg']);
					$newImg = preg_replace('/([^-A-Za-zÀ-ÖØ-öø-ÿ0-9.]*)/', '', $_POST['newImg_1']);
				} else {
					$newImg = preg_replace('/([^-A-Za-zÀ-ÖØ-öø-ÿ0-9.]*)/', '', $_POST['oldimg']);
				}
				
				$GLOBALS['db']->Query("UPDATE " . PREFIX . "_galerie_kategorien 
				SET
					Name_1 = '" . @$_POST['Name_1'] . "',
					Name_2 = '" . $Name_2 . "',
					Name_3 = '" . $Name_3 . "',
					Text_1 = '$Text_1',
					Text_2 = '$Text_2',
					Text_3 = '$Text_3',
					Aktiv = '" . $_POST['Aktiv'] . "',
					Tags = '" . $tags . "',
					Bild =  '$newImg'
				WHERE 
					Id='$id'");
				echo "<script>window.opener.location.reload(); window.close();</script>";
			}
			
			$res = $GLOBALS['db']->RowQuery("SELECT * FROM " . PREFIX . "_galerie_kategorien WHERE Id='$id'");
			$res->Beschreibung_1 = fckInit($res->Text_1 . ' ', 'Text_1', 150, 'Basic');
			$res->Beschreibung_2 = fckInit($res->Text_2 . ' ', 'Text_2', 150, 'Basic');
			$res->Beschreibung_3 = fckInit($res->Text_3 . ' ', 'Text_3', 150, 'Basic');
			$res->Img = ($res->Bild!='' && file_exists(BASE_DIR . 'uploads/galerie_icons/' . $res->Bild)) ? '<img src="../uploads/galerie_icons/' . $res->Bild . '" />' : '';
			$res->ImgPath = $res->Bild;
			
			$GLOBALS['tmpl']->assign('res',$res);
			$GLOBALS['tmpl']->assign('title', $GLOBALS['config_vars']['Gallery_editCateg']); 
			$GLOBALS['tmpl']->assign('content', $GLOBALS['tmpl']->fetch($GLOBALS['config']['source'] . '/gallery/editcateg.tpl')); 
		} else {
			no_perm();
		}
	}
	
	//=================================================================
	// Neue Galerie
	//=================================================================
	function newGallery($id)
	{
		
		if(perm('gallery_edit'))
		{
			if(isset($_POST['save']) && $_POST['save']==1 && !empty($_POST['Name_1']))
			{
				$GLOBALS['db']->Query("INSERT INTO " . PREFIX . "_galerie 
				(
					Id,
					Kategorie,
					Parent_Id,
					Sektion,
					Name_1,
					Name_2,
					Name_3,
					Beschreibung_1,
					Beschreibung_2,
					Beschreibung_3,
					Datum,
					Autor,
					Tags,
					Aktiv
				) VALUES (
					'',
					'" . $id . "',
					'" . $_REQUEST['thegal'] . "',
					'" . $_SESSION['a_area'] . "',
					'" . $_POST['Name_1'] . "',
					'" . $_POST['Name_1'] . "',
					'" . $_POST['Name_1'] . "',
					'" . @$_POST['Beschreibung_1'] . "',
					'" . @$_POST['Beschreibung_1'] . "',
					'" . @$_POST['Beschreibung_1'] . "',
					'" . stime() . "',
					'" . $_SESSION['benutzer_id'] . "',
					'" . trim(@$_POST['Tags']) . "',
					'1'
				)");
				echo '<script>window.opener.location.reload(); window.close();</script>';
			}
			
			$res = $GLOBALS['db']->RowQuery("SELECT Name_1 FROM " . PREFIX . "_galerie_kategorien WHERE Id='$id'");
			$gallery = array();
			
			$this->getGallery(0, '', $gallery, $_SESSION['a_area'], '', '', '','',$_REQUEST['id'],'1000');
	
			$GLOBALS['tmpl']->assign('Beschreibung_1', fckInit(' ', 'Beschreibung_1', 150, 'Basic'));
			$GLOBALS['tmpl']->assign('title', $GLOBALS['config_vars']['Gallery']);
			$GLOBALS['tmpl']->assign('gallery', $gallery);
			$GLOBALS['tmpl']->assign('res', $res);
			$GLOBALS['tmpl']->assign('content', $GLOBALS['tmpl']->fetch($GLOBALS['config']['source'] . '/gallery/gallerynew.tpl')); 
			
		} else {
			no_perm();
		}
	}
	
	//=================================================================
	// Galerien listen
	//=================================================================
	function ListIncluded($id)
	{
		if(perm('gallery_overview'))
		{
			$area = $_SESSION['a_area'];
			$namesort = 'name_desc';
			$subg_nav = '&amp;subgallery=0';
			$datesort = '';
			$activesort = '';
			$imgsort = '';
			$usersort = '';
			$def_search_n = '';
			$def_search = '';
			
			if(isset($_POST['save']) && $_POST['save']==1 && perm('gallery_edit'))
			{
				foreach($_POST['galleryid'] as $cat => $gid) $GLOBALS['db']->Query("UPDATE " . PREFIX . "_galerie SET Aktiv='" . $_POST['Aktiv'][$gid] . "' WHERE Id='$gid'");
			}
			
			$res = $GLOBALS['db']->RowQuery("SELECT Name_1 FROM " . PREFIX . "_galerie_kategorien WHERE Id='$id'");
			
			// Galerien
			if(isset($_REQUEST['q']) && !empty($_REQUEST['q']) && $_REQUEST['q'] != 'empty' && strlen($_REQUEST['q'])>=3)
			{
				$pattern = preg_replace('/([^-A-Za-zÀ-ÖØ-öø-ÿ0-9. ]*)/', '', $_REQUEST['q']);
				$_REQUEST['q']  = $pattern;
				$def_search_n   = "&amp;q=" . urlencode($pattern);
				$def_search     = " AND (Name_1 LIKE '%{$pattern}%') ";
			}
			
			switch(@$_REQUEST['sort'])
			{
				case '':case 'name_asc':default:$db_sort = 'ORDER BY Name_1 ASC';$nav_sort = '&amp;sort=name_asc';$namesort = 'name_desc';break;
				case'name_desc':$db_sort='ORDER BY Name_1 DESC';$nav_sort='&amp;sort=name_desc';$namesort='name_asc';break;
				case'date_asc':$db_sort='ORDER BY Datum ASC';$nav_sort='&amp;sort=date_asc';$datesort='date_desc';break;
				case'date_desc':$db_sort='ORDER BY Datum DESC';$nav_sort='&amp;sort=date_desc';$datesort='date_asc';break;
				case'img_asc':$db_sort='ORDER BY Bilder ASC';$nav_sort='&amp;sort=img_asc';$imgsort='img_desc';break;
				case'img_desc':$db_sort='ORDER BY Bilder DESC';$nav_sort='&amp;sort=img_desc';$imgsort='img_asc';break;
				case'active_asc':$db_sort='ORDER BY Aktiv ASC';$nav_sort='&amp;sort=active_asc';$activesort='active_desc';break;
				case'active_desc':$db_sort='ORDER BY Aktiv DESC';$nav_sort='&amp;sort=active_desc';$activesort='active_asc';break;
				case'user_asc':$db_sort='ORDER BY Autor ASC';$nav_sort='&amp;sort=user_asc';$usersort='user_desc';break;
				case'user_desc':$db_sort='ORDER BY Autor DESC';$nav_sort='&amp;sort=user_desc';$usersort='user_asc';break;
			}
			
			$GLOBALS['tmpl']->assign('namesort', $namesort);
			$GLOBALS['tmpl']->assign('datesort', $datesort);
			$GLOBALS['tmpl']->assign('imgsort', $imgsort);
			$GLOBALS['tmpl']->assign('activesort', $activesort);
			$GLOBALS['tmpl']->assign('usersort', $usersort);
			
			$gallery = array();
			$subgallery = array();
			
			$subg = (isset($_REQUEST['subgallery']) && !empty($_REQUEST['subgallery'])) ? "WHERE Id='" . $_REQUEST['subgallery'] . "'" : "WHERE Parent_Id='0'";
			$subghn = (isset($_REQUEST['subgallery']) && !empty($_REQUEST['subgallery'])) ? $_REQUEST['subgallery'] : 0;
			
			$sql = $GLOBALS['db']->Query("SELECT Id FROM " . PREFIX . "_galerie  {$subg} {$def_search} AND Kategorie = '$id' AND Sektion = '$area' {$db_sort} ");
			$num = $sql->numrows();
			
			$limit = GetLimit(25);
			$seiten = ceil($num / $limit);
			$a = prepage() * $limit - $limit;
			
			$sql = $GLOBALS['db']->Query("SELECT 
				Name_1,
				Id,
				Parent_Id,
				Datum,
				Autor,
				Aktiv,
				Kategorie,
				Bilder  
			FROM 
				" . PREFIX . "_galerie  
				{$subg} 
				{$def_search} 
			AND Kategorie = '$id' AND Sektion = '$area' {$db_sort} LIMIT $a,$limit");
			
			
			while($row = $sql->fetchrow())
			{
				$img_count_1 = $GLOBALS['db']->RowQuery("SELECT COUNT(Id) AS Bilder FROM " . PREFIX . "_galerie_bilder WHERE Galerie_Id = $row->Id");
				$GLOBALS['db']->Query("UPDATE " . PREFIX . "_galerie SET Bilder='$img_count_1->Bilder' WHERE Id=$row->Id");
				
				//=================================================================
				// Untergalerien
				//=================================================================
				$sid=$row->Id;
				$row->subGalleries = $this->getSubGalls($sid, '&nbsp;-&nbsp;', $subgallery, $_SESSION['a_area'], '', '', '','','','1000');
				$row->Bilder = $img_count_1->Bilder;
				$row->User = getUsername($row->Autor);
				array_push($gallery, $row);
			}
			
			$headernav = getNavigationPath($subghn, 'galerie', 'index.php?do=gallery', 'id', 'Id', 'Name_1','','','','Parent_Id', 'Parent_Id',$GLOBALS['config_vars']['Gallery'],'1');
			
			if($num>$limit)
			{
				$GLOBALS['tmpl']->assign('Navi', pagenav($seiten, '', " <a class=\"page_navigation\" href=\"index.php?do=gallery&amp;sub=showincluded&amp;id=".$_REQUEST['id']."&amp;pp={$limit}&amp;subgallery=".$subghn."{$nav_sort}{$def_search_n}&amp;page={s}\">{t}</a> "));
			}

			$gallery_dd = array();
			$this->getGallery(0, '', $gallery_dd, $_SESSION['a_area'], '', '', '','',$_REQUEST['id'],'1000');
			
			$GLOBALS['tmpl']->assign('headernav', $headernav);
			$GLOBALS['tmpl']->assign('title', $GLOBALS['config_vars']['Gallery']);
			$GLOBALS['tmpl']->assign('gallery_dd', $gallery_dd);
			$GLOBALS['tmpl']->assign('gallery', $gallery);
			$GLOBALS['tmpl']->assign('res', $res);
			$GLOBALS['tmpl']->assign('limit', $limit);
			$GLOBALS['tmpl']->assign('content', $GLOBALS['tmpl']->fetch($GLOBALS['config']['source'] . '/gallery/galleryincluded.tpl')); 
		} else {
			no_perm();
		}
	}
	
	function getSubGalls($id, $prefix, &$subgallery, &$area, $active, $orderby, $ascdesc, $sorting = "0",$categ,$setlim='0')
	{
		$zusatz = '';
		$img_count_1 = $GLOBALS['db']->RowQuery("SELECT COUNT(Id) AS Bilder FROM " . PREFIX . "_galerie_bilder WHERE Galerie_Id = $id");
		$GLOBALS['db']->Query("UPDATE " . PREFIX . "_galerie SET Bilder='$img_count_1->Bilder' WHERE Id=$id");
		
		$query = $GLOBALS['db']->Query("SELECT Name_1,Id,Parent_Id,Datum,Autor,Aktiv,Kategorie,Bilder FROM " . PREFIX . "_galerie WHERE Parent_Id = '$id'  ORDER BY Name_1 ASC");
		if (!$query->numrows()) return;
	
		while ($item = $query->fetchrow())
		{
			$item->User = getUsername($item->Autor);
			$item->Expander = $prefix;
			$item->LinkName = $item->Name_1;
			array_push($subgallery, $item);
			$this->getSubGalls($item->Id, $prefix . "- ", $subgallery, $area, $active, $orderby, $ascdesc, $sorting,$categ,$setlim);
		} 
		return $subgallery;
	}
	
	
	
	function AddImages($id)
	{
		if(perm('gallery_addimages'))
		{
			
			if(isset($_REQUEST['autosave']) && $_REQUEST['autosave']==1)
			{
				echo '<script>jQuery.blockUI({message: \'' . $GLOBALS['config_vars']['Gallery_upProgress']. '\'});setTimeout(jQuery.unblockUI, 8000);</script>';
				$target = BASE_DIR . 'uploads/galerie';
				$source = BASE_DIR . 'uploads/galerie_autoupload/' . $_REQUEST['source'];
				$allowed = array(".jpg",".jpe",".png",".gif");
				
				$dh = opendir( $source );
				$sel = '';
				
				// Upload (Auto)
				$img = array();
				$c=0;
				while ( gettype( $file = readdir ( $dh )) != @boolean ){
					if (is_dir("$source")){
						$end = strtolower(substr($file,-4));
						if ($file != "." && $file != ".." && (in_array(strtolower($end), $allowed))) $c++;
					}
				}
				
				$dh = opendir( $source );
				$d=0;
				while ( gettype( $file = readdir ( $dh )) != @boolean )
				{
					$obj = '';
					if (is_dir("$source"))
					{
						if ($file != "." && $file != "..") 
						{
							$bildname = substr($file,0,-4);
							$end = strtolower(substr($file,-4));
							
							$bild_id = md5(time() . mt_rand(10001, 19999) . $bildname);
							$bildname_db = md5(time() . mt_rand(10001, 19999) . $bildname) . $end; 
							$bildname = md5(time() . mt_rand(10001, 19999) . $bildname); 
							
							$file_src = $file;
							$file = strtolower(trim($file));
							
							if(in_array(strtolower($end), $allowed))
							{
								$go = true;
								
								if($go)
								{
									copy("$source/$file_src", "$target/$bildname_db");
									@chmod("$target/$bildname_db" , 0777);
									
									$d++;
									$status = ($d * 100) / $c;
									
									$sql = $GLOBALS['db']->Query("INSERT INTO ".PREFIX."_galerie_bilder (Id,Galerie_Id,Bildname,Datum,Autor) VALUES ('','" . $_REQUEST['thegal'] . "','$bildname_db','".stime()."','" . $_SESSION['benutzer_id'] . "') ");
									$iid = $GLOBALS['db']->InsertId(); 
									
									$msgext = ($c==$d) ? 'jQuery.blockUI({message: \'<h2>' . $GLOBALS['config_vars']['Gallery_upStatusReady'] . '</h2>\'});setTimeout(jQuery.unblockUI, 4000);setTimeout(\'window.opener.location.reload();window.close()\',2000)' : 'jQuery.blockUI({message: \'' . str_replace('__NAME__',$bildname_db,$GLOBALS['config_vars']['Gallery_upStatus']). '<br><br><div><h2>' . round($status) . '%</h2> ' . $GLOBALS['config_vars']['Gallery_upStatusDone'] .'</div>\'}); ';
									echo '<img style="display:none"  class="gallery_categs_img" src="../system/thumb.php?img_id=' . $iid . '&amp;smode=1" border="0" alt="Lade..." />';
									echo '<img style="display:none"  class="gallery_categs_img" src="../system/thumb.php?img_id=' . $iid . '&amp;smode=2" border="0" alt="Lade..." />';
									echo '<img style="display:none"  onload="' . $msgext . '"  class="gallery_categs_img" src="../system/thumb.php?img_id=' . $iid . '&amp;smode=3" border="0" alt="Lade..." />';
								}
							}
						} 
						array_push($img,$obj);
					}
				}
				exit;
				$GLOBALS['tmpl']->assign('img', $img);
			}
			
			
			if(isset($_REQUEST['manusave']) && $_REQUEST['manusave']==1)
			{
				define('UPLOAD',1);
				$error = '';
				$allowed_man = array('image/pjpeg','image/jpeg','image/x-png','image/png','image/gif');
				
				$fz_oval = '';
				
				if(@count($_FILES['fileToUpload']['tmp_name']) < 1) exit;//echo $GLOBALS['config_vars']['Gallery_upNofile'];
				for($i=0;$i<@count($_FILES['fileToUpload']['tmp_name']);$i++)
				{	
					
					if(!empty($_FILES['fileToUpload']['tmp_name'][$i]) &&  $_FILES['fileToUpload']['tmp_name'][$i] != 'none')
					{	
						$f_check     = trim(strtolower($_FILES['fileToUpload']['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['fileToUpload']['type'][$i], $allowed_man)) && ($forbidden_1 != 'jpeg' && $forbidden_2 != 'pjpeg'))
						{
							$new_name = $this->getNewName($_FILES['fileToUpload']['type'][$i],$_FILES['fileToUpload']['tmp_name'][$i]);
							
							if(filesize($_FILES['fileToUpload']['tmp_name'][$i]) > post_max())
							{
								
							} else {
							
								if(@move_uploaded_file($_FILES['fileToUpload']['tmp_name'][$i], BASE_DIR . 'uploads/galerie/' . $new_name)) 
								{
									if(isset($_POST['resize']) && $_POST['resize']==1)
									{
										switch($_FILES['fileToUpload']['type'][$i])
										{
											case 'image/pjpeg': case 'image/jpeg':
												$CREATOR = 'imagecreatefromjpeg';
												$OUTPUT  = 'imagejpeg';
												
											break;
											
											case 'image/x-png': case 'image/png':
												$CREATOR = 'imagecreatefrompng';
												$OUTPUT  = 'imagepng';
											break;
											
											case 'image/x-gif': case 'image/gif':
												$CREATOR = 'imagecreatefromgif';
												$OUTPUT  = 'imagegif';
											break;
										}
										
										$sz         = ($_POST['newsize']<480) ? 480 : $_POST['newsize'];
										$altes_bild = $CREATOR(BASE_DIR . 'uploads/galerie/' . $new_name);
										
										
										
										$im_width  = imageSX($altes_bild);
										$im_height = imageSY($altes_bild);
										$factor    = $sz / $im_width;
										$w         = $sz;
										$h         = $im_height * $factor;
										
										if($im_width > $sz)
										{
											$neues_bild = @imagecreatetruecolor($w, $h);
											imagecopyresampled($neues_bild, $altes_bild, 0, 0, 0, 0, imagesx($neues_bild), imagesy($neues_bild), imagesx($altes_bild), imagesy($altes_bild));
											@unlink(BASE_DIR . 'uploads/galerie/' . $new_name);
											$OUTPUT($neues_bild, BASE_DIR . 'uploads/galerie/' . $new_name);
										}
									}
								}
								
								
								$Name = @$_POST['Name'][$i];
								$Text = @$_POST['Beschreibung'][$i];
								$sql = $GLOBALS['db']->Query("INSERT INTO ".PREFIX."_galerie_bilder (Id,Galerie_Id,Bildname,Datum,Autor,Name_1,Name_2,Name_3,Beschreibung_1,Beschreibung_2,Beschreibung_3) VALUES ('','" . $_REQUEST['thegal'] . "','$new_name','".stime()."','" . $_SESSION['benutzer_id'] . "', '$Name', '$Name', '$Name', '$Text', '$Text', '$Text') ");
								$iid = $GLOBALS['db']->InsertId(); 
									
								$msg_thumb_small = "document.getElementById('msgout_" . $i . "').innerHTML = 'Erstelle Thumbnails...'";
								echo "<img style=\"display:none\" onload=\"" . $msg_thumb_small . "\" class=\"gallery_categs_img\" src=\"../system/thumb.php?img_id=" . $iid . "&amp;smode=1\" border=\"0\" alt=\"\" />";
								echo "<img style=\"display:none\" onload=\"" . $msg_thumb_small . "\" class=\"gallery_categs_img\" src=\"../system/thumb.php?img_id=" . $iid . "&amp;smode=2\" border=\"0\" alt=\"\" />";
								echo "<img style=\"display:none\"  class=\"gallery_categs_img\" src=\"../system/thumb.php?img_id=" . $iid . "&amp;smode=3\" border=\"0\" alt=\"\" />";
								@chmod(BASE_DIR . '/uploads/galerie/' . $new_name,0777);
							}
						
							
						} else {
							if($_FILES['fileToUpload']['tmp_name'][$i]!='') echo "<script>alert('" . $GLOBALS['config_vars']['Gallery_upWrong'] . "')</script>";
						}
					}
				}
				exit;
			}
			
			$res = $GLOBALS['db']->RowQuery("SELECT Name_1 FROM " . PREFIX . "_galerie WHERE Id='$id'");
			$gallery = array();
			$this->getGallery(0, '', $gallery, $_SESSION['a_area'], '', '', '','',$_REQUEST['gid'],1000);
			
			$verzname = BASE_DIR . 'uploads/galerie_autoupload';
			$dh = opendir( $verzname );
			$sel = '';
			$galfolders = '';
			
			while ( gettype( $datei = readdir ( $dh )) != @boolean )
			{
				if ( is_dir( "$verzname/$datei" ))
				{
					if ($datei != "." && $datei != "..")
					{
						$galfolders .= "<option value=\"$datei\">$datei</option>";
						$datei = "";
					}
				}
			} 
			
			$GLOBALS['tmpl']->assign('post_max',post_max());
			$GLOBALS['tmpl']->assign('post_maxMb', post_maxMb());
			$GLOBALS['tmpl']->assign('galfolders', $galfolders);
			$GLOBALS['tmpl']->assign('title', $GLOBALS['config_vars']['Gallery_AddImages']);
			$GLOBALS['tmpl']->assign('gallery', $gallery);
			$GLOBALS['tmpl']->assign('res', $res);
			$GLOBALS['tmpl']->assign('content', $GLOBALS['tmpl']->fetch($GLOBALS['config']['source'] . '/gallery/addimages.tpl')); 
		
		} else {
			no_perm();
		}
	}
	
	
	//=================================================================
	// Bild bearbeiten
	//=================================================================
	function editImage($id)
	{
		if(perm('gallery_imageedit'))
		{
			$res = $GLOBALS['db']->RowQuery("SELECT * FROM " . PREFIX . "_galerie_bilder WHERE Id='$id'");
			
			if(isset($_POST['save']) && $_POST['save']==1)
			{
				$endg = strtolower(substr($res->Bildname,-3));
				switch($endg)
				{
					case 'jpg':
						$CREATOR = 'imagecreatefromjpeg';
						$OUTPUT  = 'imagejpeg';
						$HEADER  = 'Content-type: image/jpeg';
					break;
					
					case 'png':
						$CREATOR = 'imagecreatefrompng';
						$OUTPUT  = 'imagepng';
						$HEADER  = 'Content-type: image/png';
					break;
					
					case 'gif':
						$CREATOR = 'imagecreatefromgif';
						$OUTPUT  = 'imagegif';
						$HEADER  = 'Content-type: image/gif';
					break;
				}
				
				switch(@$_POST['edit_action'])
				{
					default:
					case 'rotate':
						ob_start();
						header($HEADER);
						
						$degrees = (!empty($_POST['degrees'])) ? $_POST['degrees'] : 90;
						$source = $CREATOR(BASE_DIR . 'uploads/galerie/' . $res->Bildname);
						$rotate = @imagerotate($source, $degrees, 0);
						
						$OUTPUT($rotate);
						
						$a = ob_get_contents();
						ob_end_clean();
						
						$fp = fopen(BASE_DIR . 'uploads/galerie/' . $res->Bildname, "wb+");
						fwrite($fp, $a);
						fclose($fp);
						
						$this->editUnlink($res->Bildname);
						
						echo "<img style=\"position:relative\" src=\"../system/thumb.php?img_id=" . $id . "&smode=3&time=" . stime() . "\" border=\"0\" alt=\"\" /> ";
						exit;
					break;
					
					case 'grayout':
						ob_start();
						header($HEADER);
						
						$source = $CREATOR(BASE_DIR . 'uploads/galerie/' . $res->Bildname);
						if ($source && imagefilter($source, IMG_FILTER_GRAYSCALE))
						{
							$OUTPUT($source);
							
							$a = ob_get_contents();
							ob_end_clean();
							
							$fp = fopen(BASE_DIR . 'uploads/galerie/' . $res->Bildname, "wb+");
							fwrite($fp, $a);
							fclose($fp);
							
							$this->editUnlink($res->Bildname);
						}
						echo "<img style=\"position:relative\" src=\"../system/thumb.php?img_id=" . $id . "&smode=3&time=" . stime() . "\" border=\"0\" alt=\"\" /> ";
						exit;
					break;
					
					case 'brightness':
						ob_start();
						header($HEADER);
						$source = $CREATOR(BASE_DIR . 'uploads/galerie/' . $res->Bildname);
						if ($source && imagefilter($source, IMG_FILTER_BRIGHTNESS, 25))
						{
							$OUTPUT($source);
							$a = ob_get_contents();
							ob_end_clean();
							$fp = fopen(BASE_DIR . 'uploads/galerie/' . $res->Bildname, "wb+");
							fwrite($fp, $a);
							fclose($fp);
							$this->editUnlink($res->Bildname);
						}
						echo "<img style=\"position:relative\" src=\"../system/thumb.php?img_id=" . $id . "&smode=3&time=" . stime() . "\" border=\"0\" alt=\"\" /> ";
						exit;
					break;
					
					case 'brightness_reduce':
						ob_start();
						header($HEADER);
						$source = $CREATOR(BASE_DIR . 'uploads/galerie/' . $res->Bildname);
						if ($source && imagefilter($source, IMG_FILTER_BRIGHTNESS, -25))
						{
							$OUTPUT($source);
							$a = ob_get_contents();
							ob_end_clean();
							$fp = fopen(BASE_DIR . 'uploads/galerie/' . $res->Bildname, "wb+");
							fwrite($fp, $a);
							fclose($fp);
							$this->editUnlink($res->Bildname);
						}
						echo "<img style=\"position:relative\" src=\"../system/thumb.php?img_id=" . $id . "&smode=3&time=" . stime() . "\" border=\"0\" alt=\"\" /> ";
						exit;
					break;
				}
				
				
				
			}
			
			$res = $GLOBALS['db']->RowQuery("SELECT * FROM " . PREFIX . "_galerie_bilder WHERE Id='$id'");
			
			$imgsize = @getimagesize(BASE_DIR . 'uploads/galerie/' . $res->Bildname);
			$imgdim =  $imgsize[0] . ' x ' . $imgsize[1];
			$res->Img = "<img style=\"position:relative\" src=\"../system/thumb.php?img_id=" . $res->Id . "&amp;smode=3&amp;time=" . stime() . "\" border=\"0\" alt=\"\" />";
			
			if($imgsize[0] > 1280 || $imgsize[1] > 1280)
			{
				$GLOBALS['tmpl']->assign('ImgWarning', $imgdim);
				
			}
			
			
			$GLOBALS['tmpl']->assign('canfilter', (function_exists('imagefilter') ? 1 : 0));
			$GLOBALS['tmpl']->assign('res', $res);
			$GLOBALS['tmpl']->assign('ImgDim', $imgdim);
			$GLOBALS['tmpl']->assign('content', $GLOBALS['tmpl']->fetch($GLOBALS['config']['source'] . '/gallery/editimage.tpl')); 
		} else {
			no_perm();
		}
	}
	
	
	function editUnlink($fname)
	{
		@unlink(BASE_DIR . 'cache/' . md5('small_' . $fname));
		@unlink(BASE_DIR . 'cache/' . md5('medium_' . $fname));
		@unlink(BASE_DIR . 'cache/' . md5('normal_' . $fname));
	}
	
	function getNewName($string,$tmpname)
	{
		switch($string)
		{
			case 'image/pjpeg' :
			case 'image/jpeg' :
			case '' :
				$new_name = md5(time() . mt_rand(10001, 19999) . $tmpname) . '.jpg';
			break;
			
			case 'image/x-png' :
			case 'image/png' :
				$new_name = md5(time() . mt_rand(10001, 19999) . $tmpname) . '.png';
			break;
			
			case 'image/gif' :
				$new_name = md5(time() . mt_rand(10001, 19999) . $tmpname) . '.gif';
			break;
		}	
		
		return $new_name;		
	}
	
	function EditImages($id)
	{
		if(perm('gallery_edit'))
		{
			$datesort = '';
			$hitssort = '';
			$autorsort = '';
			$name1sort = '';
			$name2sort = '';
			$name3sort = '';
			$nav_sort = '&amp;sort=date_asc';
			
			$limit = getlimit();
			
			
			if(isset($_POST['save']) && $_POST['save']==1 && perm('gallery_edit') && isset($_POST['Id']))
			{
				foreach($_POST['Id'] as $im => $imgid)
				{
					$n1 = @$_POST['Name_1'][$imgid];
					$n2 = @!empty($_POST['Name_2'][$imgid]) ? $_POST['Name_2'][$imgid] : $n1;
					$n3 = @!empty($_POST['Name_3'][$imgid]) ? $_POST['Name_3'][$imgid] : $n1;
					
					$t1 = @$_POST['Beschreibung_1'][$imgid];
					$t2 = @!empty($_POST['Beschreibung_2'][$imgid]) ? $_POST['Beschreibung_2'][$imgid] : $t1;
					$t3 = @!empty($_POST['Beschreibung_3'][$imgid]) ? $_POST['Beschreibung_3'][$imgid] : $t1;
					
					$GLOBALS['db']->Query("UPDATE " . PREFIX . "_galerie_bilder 
					SET 
						Name_1 = '$n1',
						Name_2 = '$n2',
						Name_3 = '$n3',
						Beschreibung_1 = '$t1',
						Beschreibung_2 = '$t2',
						Beschreibung_3 = '$t3' 
					WHERE Id='$imgid'");
					
					if(@$_POST['del'][$imgid]==1)
					{
						$res = $GLOBALS['db']->RowQuery("SELECT * FROM " . PREFIX . "_galerie_bilder WHERE Id='$imgid'");
						$GLOBALS['db']->Query("DELETE FROM " . PREFIX . "_galerie_bilder WHERE Id='$imgid'");
						@unlink(BASE_DIR . 'cache/' . md5('small_' . $res->Bildname));
						@unlink(BASE_DIR . 'cache/' . md5('medium_' . $res->Bildname));
						@unlink(BASE_DIR . 'cache/' . md5('normal_' . $res->Bildname));
						@unlink(BASE_DIR . 'uploads/galerie/' . $res->Bildname);
					}
				}
			}
			
			switch(@$_REQUEST['sort'])
			{
				case'':default:$db_sort='ORDER BY Id DESC';$nav_sort='&amp;sort=date_desc';break;
				case'date_asc':$datesort='date_desc';$db_sort='ORDER BY Id ASC';$nav_sort='&amp;sort=date_asc';break;
				case'date_desc':$datesort='date_asc';$db_sort='ORDER BY Id DESC';$nav_sort='&amp;sort=date_desc';break;
				case'hits_asc':$hitssort='hits_desc';$db_sort='ORDER BY Klicks ASC';$nav_sort='&amp;sort=hits_asc';break;
				case'hits_desc':$hitssort='hits_asc';$db_sort='ORDER BY Klicks DESC';$nav_sort='&amp;sort=hits_desc';break;
				case'autor_asc':$autorsort='autor_desc';$db_sort='ORDER BY Autor ASC';$nav_sort='&amp;sort=autor_asc';break;
				case'autor_desc':$autorsort='autor_asc';$db_sort='ORDER BY Autor DESC';$nav_sort='&amp;sort=autor_desc';break;
				case 'name3_asc':$name3sort = 'name3_desc';$db_sort = 'ORDER BY Name_3 ASC';$nav_sort = '&amp;sort=name3_asc';break;
				case 'name3_desc':$name3sort = 'name3_asc';$db_sort = 'ORDER BY Name_3 DESC';$nav_sort = '&amp;sort=name3_desc';break;
				case 'name2_asc':$name2sort = 'name2_desc';$db_sort = 'ORDER BY Name_2 ASC';$nav_sort = '&amp;sort=name2_asc';break;
				case 'name2_desc':$name2sort = 'name2_asc';$db_sort = 'ORDER BY Name_2 DESC';$nav_sort = '&amp;sort=name2_desc';break;
				case 'name1_asc':$name1sort = 'name1_desc';$db_sort = 'ORDER BY Name_1 ASC';$nav_sort = '&amp;sort=name1_asc';break;
				case 'name1_desc':$name1sort = 'name1_asc';$db_sort = 'ORDER BY Name_1 DESC';$nav_sort = '&amp;sort=name1_desc';break;
			}
			
			$res = $GLOBALS['db']->RowQuery("SELECT Id,Name_1,Kategorie FROM " . PREFIX . "_galerie WHERE Id='$id'");
			
			$sql = $GLOBALS['db']->Query("SELECT Id FROM " . PREFIX . "_galerie_bilder WHERE Galerie_Id='$id' {$db_sort}");
			$num = $sql->numrows();
			
			$limit = abs((int)$limit);
			$seiten = ceil($num / $limit);
			$a = prepage() * $limit - $limit;
			
			$images = array();
			$sql = $GLOBALS['db']->Query("SELECT * FROM " . PREFIX . "_galerie_bilder WHERE Galerie_Id='$id' {$db_sort} LIMIT $a,$limit");
			while($row = $sql->fetchrow())
			{
				$query_c = $GLOBALS['db']->RowQuery("SELECT COUNT(Id) AS Comments FROM " . PREFIX . "_kommentare WHERE Objekt_Id='$row->Id' AND Bereich='galerie'");
				$row->Comments = $query_c->Comments;
				$row->User = getUserName($row->Autor);
				$row->Thumb = (file_exists('../cache/' . md5('medium_' . $row->Bildname))) ? '<img class="gallery_categs_img" src="../cache/' . md5('medium_' . $row->Bildname) . '" border="0" alt="" />' : '<img class="gallery_categs_img" src="../system/thumb.php?img_id=' . $row->Id . '&amp;smode=2" border="0" alt="" />';
				array_push($images, $row);
			}
			
			// Seiten-Navigation
			if ($num > $limit) 
			{
				$GLOBALS['tmpl']->assign('Navi', pagenav($seiten, '', " <a class=\"page_navigation\" href=\"index.php?do=gallery&amp;sub=editimages&amp;id=$id&amp;noframes=1{$nav_sort}&amp;pp={$limit}&amp;page={s}\">{t}</a> "));
			}
			
			$GLOBALS['tmpl']->assign('datesort', $datesort);
			$GLOBALS['tmpl']->assign('hitssort', $hitssort);
			$GLOBALS['tmpl']->assign('autorsort', $autorsort);
			$GLOBALS['tmpl']->assign('name1sort', $name1sort);
			$GLOBALS['tmpl']->assign('name2sort', $name2sort);
			$GLOBALS['tmpl']->assign('name3sort', $name3sort);
			$GLOBALS['tmpl']->assign('res', $res);
			$GLOBALS['tmpl']->assign('ppformaction', "index.php?do=gallery&amp;sub=editimages&amp;id=$id&amp;noframes=1{$nav_sort}&amp;page=1");
			$GLOBALS['tmpl']->assign('limit', $limit);
			$GLOBALS['tmpl']->assign('images', $images);
			$GLOBALS['tmpl']->assign('title', $GLOBALS['config_vars']['Gallery_ShowImages']);
			$GLOBALS['tmpl']->assign('content', $GLOBALS['tmpl']->fetch($GLOBALS['config']['source'] . '/gallery/imagesshow.tpl')); 
		} else {
			no_perm();
		}
	}
	
	
	//=================================================================
	// Galerie bearbeiten
	//=================================================================
	function EditGallery($id)
	{
		if(perm('gallery_edit'))
		{
			if(isset($_POST['save']) && $_POST['save']==1)
			{
				$tags = umlaut2text(trim($_POST['Tags']));
				
				$Name_2 =  !empty($_POST['Name_2']) ? $_POST['Name_2'] : $_POST['Name_1'];
				$Name_3 =  !empty($_POST['Name_3']) ? $_POST['Name_3'] : $_POST['Name_1'];
				$Beschreibung_1 = $_POST['Beschreibung_1'];
				$Beschreibung_2 = !empty($_POST['Beschreibung_2']) ? $_POST['Beschreibung_2'] : $Beschreibung_1;
				$Beschreibung_3 = !empty($_POST['Beschreibung_3']) ? $_POST['Beschreibung_3'] : $Beschreibung_1;
				
				$GLOBALS['db']->RowQuery("UPDATE " . PREFIX . "_galerie 
				SET
					Name_1 = '" . $_POST['Name_1'] . "',
					Name_2 = '" . $Name_2 . "',
					Name_3 = '" . $Name_3 . "',
					Beschreibung_1 = '$Beschreibung_1',
					Beschreibung_2 = '$Beschreibung_2',
					Beschreibung_3 = '$Beschreibung_3',
					Aktiv = '" . $_POST['Aktiv'] . "',
					Tags = '" . $tags . "' 
				WHERE 
					Id='$id'");
				echo "<script>window.opener.location.reload(); window.close();</script>";
			}
			
			$gallery = array();
			
			$this->getGallery(0, '', $gallery, $_SESSION['a_area'], '', '', '','',$id,0);
			
			$res = $GLOBALS['db']->RowQuery("SELECT * FROM " . PREFIX . "_galerie WHERE Id='$id'");
			
			$GLOBALS['tmpl']->assign('res', $res);
			$GLOBALS['tmpl']->assign('Beschreibung_1', fckInit($res->Beschreibung_1, 'Beschreibung_1', 150, 'Basic'));
			$GLOBALS['tmpl']->assign('Beschreibung_2', fckInit($res->Beschreibung_2, 'Beschreibung_2', 150, 'Basic'));
			$GLOBALS['tmpl']->assign('Beschreibung_3', fckInit($res->Beschreibung_3, 'Beschreibung_3', 150, 'Basic'));
			$GLOBALS['tmpl']->assign('gallery', $gallery);
			$GLOBALS['tmpl']->assign('title', $GLOBALS['config_vars']['Gallery_Edit']);
			$GLOBALS['tmpl']->assign('content', $GLOBALS['tmpl']->fetch($GLOBALS['config']['source'] . '/gallery/galleryedit.tpl')); 
		} else {
			no_perm();
		}
	}
	
	//=================================================================
	// Galerien listen fuer Kategorie-Dropdown
	//=================================================================
	function getGallery($id, $prefix, &$gallery, &$area, $active, $orderby, $ascdesc, $sorting = "0",$categ,$setlim='0')
	{
		$zusatz = '';
		$ex_categ = ($categ!='') ? " AND Kategorie = '$categ'" : "";
		$query = $GLOBALS['db']->Query("SELECT Name_1,Id,Parent_Id FROM " . PREFIX . "_galerie WHERE Parent_Id = '$id' {$ex_categ} AND Sektion = '$area' ORDER BY Name_1 ASC");
		
		if (!$query->numrows()) return;
	
		while ($item = $query->fetchrow())
		{
			$item->visible_title = $prefix . " " . $item->Name_1;
			array_push($gallery, $item);
			$this->getGallery($item->Id, $prefix . "- - ", $gallery, $area, $active, $orderby, $ascdesc, $sorting,$categ,$setlim);
		} 
		return;
	}
	
	//=================================================================
	//=================================================================
	function getTagCloud($categ='')
	{
		$tags    = '';
		$where   = ($categ!='') ? "SELECT Tags FROM " . PREFIX . "_galerie WHERE Kategorie = '" . $categ . "'" : "SELECT Tags FROM " . PREFIX . "_galerie_kategorien WHERE Sektion = '" . $_SESSION['a_area'] . "'";
		$where_m = ($categ!='') ? "FROM " . PREFIX . "_galerie WHERE  Kategorie = '" . $categ . "'" : "FROM " . PREFIX . "_galerie_kategorien WHERE Sektion = '" . $_SESSION['a_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;
	}
	
	
	function GalDel($id,$close=1)
	{
		if(perm('gallery_delete'))
		{
			$query = $GLOBALS['db']->Query("SELECT Id, Parent_Id FROM " . PREFIX . "_galerie  WHERE Parent_Id=$id");
			while ($item = $query->fetchrow()) 
			{
				
				$sql = $GLOBALS['db']->Query("SELECT Bildname FROM " . PREFIX . "_galerie_bilder WHERE Galerie_Id=$item->Id");
				while($row_g = $sql->fetchrow())
				{
					@unlink(BASE_DIR . 'cache/' . md5('small_' . $row_g->Bildname));
					@unlink(BASE_DIR . 'cache/' . md5('medium_' . $row_g->Bildname));
					@unlink(BASE_DIR . 'cache/' . md5('normal_' . $row_g->Bildname));
					@unlink(BASE_DIR . 'uploads/galerie/' . $row_g->Bildname);
				}
				
				// <<--Rekursion -->>
				$this->GalDel($item->Id);
			}
			
			$sql = $GLOBALS['db']->Query("SELECT Bildname FROM " . PREFIX . "_galerie_bilder WHERE Galerie_Id=$id");
			while($row_g = $sql->fetchrow())
			{
				@unlink(BASE_DIR . 'cache/' . md5('small_' . $row_g->Bildname));
				@unlink(BASE_DIR . 'cache/' . md5('medium_' . $row_g->Bildname));
				@unlink(BASE_DIR . 'cache/' . md5('normal_' . $row_g->Bildname));
				@unlink(BASE_DIR . 'uploads/galerie/' . $row_g->Bildname);
			}
			
			$GLOBALS['db']->Query("DELETE FROM " . PREFIX . "_galerie WHERE Id=$id");			
			$GLOBALS['db']->Query("DELETE FROM " . PREFIX . "_galerie_bilder WHERE Galerie_Id=$id");
		}
		if($close==1) echo '<script>window.opener.location.reload();window.close(); </script>';
	}
	
	function GetSettings()
	{
		$sql = $GLOBALS['db']->Query("SELECT * FROM " . PREFIX . "_galerie_einstellungen LIMIT 1" );
		$gal_settings = $sql->fetchrow();
		return $gal_settings;
	}
	
}
?>