<?php
/**
 * This file is part of
 *
 * SiriusGallery
 *
 * for pragmamx (www.pragmamx.org)
 *
 * $Version 1.0 $
 * $Author: Olaf Herfurth / TerraProject  http://www.tecmu.de $
 * $Date: 2011/05/01 $
 *
 */


defined('mxMainFileLoaded') or die('access denied');

function sg_getUserGroups()
{
        global $prefix, $currentlang,$module_name, $WSCFG;
		
		$result = sql_query("SELECT access_id,access_title from ${prefix}_groups_access ") ;
		$usergroup=array();
		while (list($id,$title)=sql_fetch_row($result)) {
			$usergroup[$id]=$title;
		}
		
		return $usergroup;
}

// ermittelt alle Caterorien, die einem user zugeordnet sind
function sg_getNumUserGallery($userid) 
{
        global $prefix, $currentlang,$module_name, $WSCFG;
		
		$result = sql_num_rows(sql_query("SELECT aid from ".SG_TABLE_CATEGORY." where userid ='".$userid."' ")) ;
		return $result;
		
}

// ermittelt die Anzahl der hochgeladenen Bilder eines Users
function sg_getNumUserPictures ($userid=0)
{
        global $prefix, $currentlang,$module_name, $WSCFG, $SGCFG;
		$picnum=0;
		if ($userid > 0)   {
		    $picnum=sql_num_rows(sql_query("select pid from ".SG_TABLE_PICTURE." where userid=$userid"));
		}
		return $picnum;

}

// ermittel die UserGallery eines Users

function sg_getUserGallery($userid) {
        global $prefix, $currentlang,$module_name, $WSCFG, $SGCFG;
		$aid=NULL;
		if ($userid>0)   {
		     $result=sql_query("SELECT aid from ".SG_TABLE_CATEGORY." where parentaid='1' and userid ='".$userid."' ");
			 list($aid)=sql_fetch_row($result);
	    }
			 return $aid; 
}

// Ermittelt die Anzahl der angelegten Subcategorien 
function sg_getNumUserCategories($cat)
{
        global $prefix, $currentlang,$module_name, $WSCFG, $SGCFG;
		$result=sql_query("select aid from ".SG_TABLE_CATEGORY." where parentaid=$cat");
		
		$idlist=sql_num_rows($result);
		
		if ($idlist>0) {
			while  (list($aid)=sql_fetch_row($result)) {
				$idlist += intval(sg_getNumUserCategories($aid));
			}
		} else {
		  $islist=1;
		}
		unset ($result);
		return $idlist;
}

// ermittelt, ob die Category dem user gehört
function sg_isMyCategory($cat) 
{
        global $prefix, $currentlang,$module_name, $WSCFG, $SGCFG;
		if ($cat<2) return false;		// globale kategorien

	    $userdata = mxGetUserData();   
		$userid=$userdata['uid'];
        $result=sql_num_rows(sql_query("SELECT aid from ".SG_TABLE_CATEGORY." where aid=$cat and userid ='".$userid."' "));
		if ($result==1) {
		   return true;
		   } else {
		   return false;
		}
		
}

// ermittelt, ob eine Categorie eine zu einer Userkategorie gehört
function sg_isUserCategory($cat)
{
        global $prefix, $currentlang,$module_name, $WSCFG, $SGCFG;
        
		if ($cat<2) return false;
		if ($cat==1) return true;
		
		$result=sql_query("select parentaid from ".SG_TABLE_CATEGORY." where aid=$cat");
		list($parentaid)=sql_fetch_row($result);
        switch($parentaid) {
		   case 0: 
		      return false;
			  break;
		   case 1: 
		      return true;
			  break;
			  
		   default:
		      return sg_isUserCategory($parentaid);
		   
		}
		
}

// ermittelt die eigene Usergallerie, wenn nicht vorhanden, wird sie angelegt
function sg_getMyGallery()
{
     global $prefix, $currentlang,$module_name, $WSCFG, $SGCFG;
	
	 $userdata = mxGetUserData();   
	 $result1=sql_query("select aid from ".SG_TABLE_CATEGORY." where parentaid=1 and userid=".$userdata['uid']."");
	 $result2=sql_query("select * from ".SG_TABLE_CATEGORY." where aid=1");
	 $usergallery=sql_fetch_assoc($result2);
	 if (sql_num_rows($result1)== 1) {
	       list($myusergallery_id)=sql_fetch_row($result1);
	 } else {
	       $xconfig["FRONT_TEMPLATE"]="0";
	       sql_query("insert into ".SG_TABLE_CATEGORY." set 
		            parentaid='1', 
					userid='".$userdata['uid']."', 
					title='".$userdata['uname']."', 
					publish=0,
					access=0,
					sort='".$usergallery['sort']."',
					comments='".$usergallery['comments']."',
					votes='".$usergallery['votes']."',
					thumb=-1,
					config='".$usergallery['config']."'
					");
		   $myusergallery_id=sql_insert_id();
	 }
	unset ($result1); 
    return $myusergallery_id;
}

// ermittelt alle ID's der Unterkategorien einer Kategorie
// die Ids werden in einer Kommegetrennten liste zurückgegeben, um sie in SQL-Abfragen z.Bsp. mittes IN(...) zu verwenden

function sg_getSubcat($basecat=0) 
{
        global $prefix, $currentlang,$module_name, $WSCFG, $SGCFG;
        $idlist=$basecat;
		$result=sql_query("select aid from ".SG_TABLE_CATEGORY." where parentaid=$basecat");
		
		$numid=sql_num_rows($result);
		if ($numid>0) {
			while  (list($aid)=sql_fetch_row($result)) {
				$idlist .= ",".sg_getSubcat($aid);
			}
		}
		unset ($result);
		return $idlist;
}

// ermittelt alle anzeigbaren ID's der Unterkategorien einer Kategorie
// die Ids werden in einer Kommegetrennten liste zurückgegeben, um sie in SQL-Abfragen z.Bsp. mittes IN(...) zu verwenden

function sg_getSubcatView($basecat=0) 
{
        global $prefix, $currentlang,$module_name, $WSCFG, $SGCFG;
        $idlist=$basecat;
		$userid=0;
		$result=sql_query("select aid, alb_pass_id,userid,access from ".SG_TABLE_CATEGORY." where parentaid=$basecat");
		if (MX_IS_USER) {
			$userdata=mxGetUserData();
			$userid=$userdata['uid'];
		}
		$uid=$userid;
		$numid=sql_num_rows($result);
		if ($numid>0) {
			while  (list($aid,$alb_pass_id,$userid,$access)=sql_fetch_row($result)) {
			  if ((($alb_pass_id > 0) and mxSessionGetVar("sgid".$alb_pass_id)) or $uid==$userid or $alb_pass_id==0) {
				if (sg_isCategoryAllowed($aid)) $idlist .= ",".sg_getSubcatView($aid);
			  }
			}
		}
		unset ($result);
		return $idlist;
}


// ermittelt alle anzeigbaren Subcategories 
function sg_getCategoryView($basecat=0)
{
        global $prefix, $currentlang,$module_name, $WSCFG, $SGCFG;
		$result1=array();
		$userdata=mxGetUserData();
		$userid=(MX_IS_USER)?$userdata['uid']:0;
		// sg_updateCategory_pictures($basecat);
		$viewemptycat="";
		
		// prüfen ob leere Kategorien angezeigt werden sollen
//		if (($SGCFG['FRONT_VIEWEMPTYCAT']==0 )and $basecat>0 ) {		//
//		  $viewemptycat=(sg_getCategoryContent($basecat,$userid)>0)?" and (uploads > 0 or childcat > 0)":" and uploads > 0 and childcat >0 ";
//		}
		
			// jetzt erst abfragen
			switch($SGCFG['CAT_SORT']) {
			   case 0:
			   		$sortorder=" datum desc ";
			  	 	break;
			   case 1:
			   		$sortorder=" datum asc ";
			   		break;
			   case 2:
			   		$sortorder=" title asc ";
			   		break;
			   case 3:
			   		$sortorder=" title desc ";
			   		break;
			   default:
			   		$sortorder=" aid asc";
			   		break;
			}
			
			$result=sql_query("select * from ".SG_TABLE_CATEGORY." where parentaid=$basecat  and IF(userid >'0' and userid ='".$userid."' ,true, publish='1' ) ".$viewemptycat." order by ".$sortorder); //
			$cat_lock="<img src=\"modules/$module_name/style/lock.png\" width=\"10\" height=\"10\" style=\"border:none;\" />";
			
			while ($result2=sql_fetch_assoc($result))
			{
				$catnums=($SGCFG['FRONT_VIEWEMPTYCAT']==0 and $result2['uploads']==0)?sg_getCategoryContent($result2['aid'],$userid):1;
			   
			   if ($catnums>0  ) {

					$result2['thumb']=sg_getCategoryAvatar($result2['aid'],$result2['thumb']);
					$result2['lock']=($result2['alb_pass_id']>0)?$cat_lock:"";
					
					$result2['title']=($result2['publish']==1)?$result2['title']:"(<i>".$result2['title']."</i>)";
					// ."-".$result2['uploads']."-".$result2['childcat']."-".sg_getCategoryContent($result2['aid']
				   switch($result2['access']) {
					 case 1:		// for User only
						if (MX_IS_USER or MX_IS_ADMIN)	$result1[]=$result2;
						break;
					 case 2:		// for Owner only
						if ($userid==$result2['userid'])$result1[]=$result2;
						break;
					 default:
					    if (!($SGCFG['FRONT_VIEWEMPTYCAT']==0 and $result2['aid']==1 and $result2['publish']==0)) {
							$result1[]=$result2;
						}
						break;
					}					
						
				}
				
			}//and (CASE access WHEN 2 THEN userid=".$userid." END )
			
			//$result1=sql_fetch_array($result);
			unset($result, $result2);
		   //}
		return $result1;

}
// Durchsucht alle Unterverzeichnisse eines Basisverzeichnisses und gibt die Anzahl der Bilder zurück
function sg_getCategoryContent($basecat=0,$userid)
{
        global $prefix, $currentlang,$module_name, $WSCFG, $SGCFG;
		
		$catresult=0;
		
		$catcontent=0;
		
		$result=sql_query("select aid, uploads, childcat, access, userid from ".SG_TABLE_CATEGORY." where parentaid=$basecat and IF( userid<>$userid , publish=1,true ) ");
		while (list($aid,$uploads,$childcat,$access,$catuser)=sql_fetch_row($result)) {
		    $acc_flag=false;
			switch($access) {
					 case 1:		// for User only
						if (MX_IS_USER or MX_IS_ADMIN) {
							$acc_flag=true;
//						} else {
//							$catcontent=0;	  
						}
						break;
					 case 2:		// for Owner only
						if ($userid==$catuser) {
							$acc_flag=true;
//						} else {
//							$catcontent=0;	  
						}
						break;
					 default:
						$acc_flag=true;
						break;
			}					
		    if ($acc_flag) {
		       $catresult=sg_getCategoryContent($aid,$userid);			   
		       $catcontent=intval($uploads)+intval($catresult)+intval($catcontent);
		    }
		}
        return $catcontent;
}

// überprüft, ob die Kategorie angezeigt werden darf
function sg_isCategoryAllowed($basecat=0)
{
        global $prefix, $currentlang,$module_name, $WSCFG, $SGCFG;
		$userdata=mxGetUserData();
		$userid=(MX_IS_USER)?$userdata['uid']:0;
		$result=sql_query("select userid, access, alb_pass_id from ".SG_TABLE_CATEGORY." where aid=$basecat  and IF( userid<>$userid , publish=1,true )"); //
		
		if (sql_num_rows($result)==0) return false;
		
	    list ($uid,$access,$alb_pass_id)=sql_fetch_row($result);

		if ((($alb_pass_id > 0) and mxSessionGetVar("sgid".$alb_pass_id)  )) return true;   //or $alb_pass_id==0

		switch($access) {
			     case 1:		// for User only
				    if (MX_IS_USER or MX_IS_ADMIN)	return true;
					break;
			     case 2:		// for Owner only
				    if ($userid==$uid) return true;
					break;
			     case 0:
					return true;
					break;
		}					
		
					
		return false;

}

// überprüft, ob diese Categorie existiert
// wichtig bei verweisten Bildern.
function sg_isCategoryDeleted($cat) 
{
        global $prefix, $currentlang,$module_name, $WSCFG, $SGCFG;
		$userdata=mxGetUserData();
		$userid=(MX_IS_USER)?$userdata['uid']:0;
		
		$result=sql_num_rows(sql_query("select aid from ".SG_TABLE_CATEGORY." where aid=$cat "));
		if ($result > 0 ) return false;
		return true;

}

function sg_ValueToText($tmp)
{
    $tmp = str_replace(chr(10), "", $tmp);
    $tmp = str_replace(chr(9), "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;", $tmp);
    $tmp = preg_replace("/</", "&lt;", $tmp);
    $tmp = preg_replace("/>/", "&gt;", $tmp);
    $tmp = preg_replace("/\"/", "&quot;", $tmp);
    $tmp = preg_replace("/\'/", "&quot;", $tmp);
    $tmp = preg_replace("/\&\#039;/", "&quot;", $tmp);
    $tmp = str_replace(chr(13), " ", $tmp);
    $tmp = nl2br($tmp);
    return $tmp;
} 


function sg_SelectCategory($cLegend,$fieldname,$cText,$fpos,$secid,$noCat=0) 
{
        global $prefix, $currentlang,$module_name, $WSCFG;
		$mycat=array();
		$result = sql_query("SELECT aid, title, parentaid from ".SG_TABLE_CATEGORY." ") ;
		
		$ausdruck = "<tr>";
		$ausdruck .= "<td class=\"form\">".$cLegend."</td>";
		$ausdruck .= "<td >";
		$ausdruck .= "<select name=\"".$fieldname."\" size=\"1\" ><option value=\"0\" >"._CATEGORY_INDEX."</option>";
		
		while ($mycat = sql_fetch_assoc($result)) {
         $sel="";
		  if (!sg_isChildCategory($mycat['aid'], $secid)) {
			 if ($mycat['aid']== intval($fpos)) $sel=" selected=\"selected\"";
			   
			   $pathway=sg_getCategoryTitle($mycat['aid'],$secid);
			  
			  if ($mycat['aid'] != $noCat && $pathway !='' ) $ausdruck .="<option value='".$mycat['aid']."'". $sel.">".$pathway."</option>";
			}
		 }
		$ausdruck .="</select>";
		$ausdruck .="</td>";
		$ausdruck .="<td class=\"tiny\">".$cText."</td>";
		$ausdruck .="</tr>";
		return $ausdruck;
}


// Managed functions of configs in DB 



function getConfigAll()
{
    global $prefix, $module_name,$SGCFG;
	$cfgtemp=array();
    $result=sql_query("select name,value from ".SG_TABLE_CONFIG."");
	
	while (list ($name,$value)=sql_fetch_row($result)) {
		if (is_array($value)) {
		$cfgtemp[$name]=unserialize($value);
		 } else { 
   		$cfgtemp[$name]=$value;
		}
	}
	
	if (MX_IS_USER) {
		$userdata=mxGetUserData();
		$usergroup=$userdata['user_ingroup'];
		$useraccess=unserialize($cfgtemp["USERACCESS"]);
		
		$useraccess[$usergroup]['USERGROUPUSE']=($useraccess[$usergroup]['USERGROUPUSE']=="")?$SGCFG['USERGROUP']:$useraccess[$usergroup]['USERGROUPUSE'];
		$useraccess[$usergroup]['USERMAXCAT']=($useraccess[$usergroup]['USERMAXCAT']=="")?$SGCFG['USERMAXCAT']:$useraccess[$usergroup]['USERMAXCAT'];
		$useraccess[$usergroup]['USERMAXIMAGES']=($useraccess[$usergroup]['USERMAXIMAGES']=="")?$SGCFG['USERMAXIMAGES']:$useraccess[$usergroup]['USERMAXIMAGES'];
		$useraccess[$usergroup]['USERMAXIMAGESIZE']=($useraccess[$usergroup]['USERMAXIMAGESIZE']=="")?$SGCFG['USERMAXIMAGESIZE']:$useraccess[$usergroup]['USERMAXIMAGESIZE'];
		$useraccess[$usergroup]['USERUPLOADADMIN']=($useraccess[$usergroup]['USERUPLOADADMIN']=="")?$SGCFG['USERUPLOADADMIN']:$useraccess[$usergroup]['USERUPLOADADMIN'];
		 
		if ($useraccess[$usergroup]['USERGROUPUSE']==0 or $usergroup==0 ) $usergroup=1;
		
		$cfgtemp["USER_MAXCAT"]	=$useraccess[$usergroup]['USERMAXCAT'];    
		$cfgtemp["USER_MAXIMAGES"] =$useraccess[$usergroup]['USERMAXIMAGES'];  
		$cfgtemp["USER_MAXIMAGESIZE"] =$useraccess[$usergroup]['USERMAXIMAGESIZE']; 
		$cfgtemp["USER_UPLOADADMIN"] =$useraccess[$usergroup]['USERUPLOADADMIN'];   
		
	}	
		$cfgtemp["MIME_TYPES"]=array("image/jpeg","image/jpg","image/bmp","image/png","image/gif","image/pjpeg","image/x-png");
		$cfgtemp["IMG_EXTENSIONS"]=array("jpeg","jpg","bmp","png","gif");
		
		unset($useraccess,$result);
    return $cfgtemp;
}

function getConfig($key)
{
    global $prefix, $module_name;
	$cfgtemp=array();
    $result=sql_query("select value from ".SG_TABLE_CONFIG." where name='".$key."'");
	
	list ($value)=sql_fetch_row($result);
    return $value;
}

function setConfigAll($varray,$opt=false) 
{
    global $prefix, $module_name;
	// wenn $opt=wahr, dann wird die ganze config-Tabelle glöscht !!!
	if ($opt) {
	   sql_query("TRUNCATE TABLE ".SG_TABLE_CONFIG."");
       sql_query("insert ".SG_TABLE_CONFIG." set value='".time()."' , name='saved'");
	}
	
	foreach ($varray as $key =>$value) {
	   setConfig($key,$value,false);
	}
    sql_query("update ".SG_TABLE_CONFIG." set value='".time()."' where name='saved'");
}

function setConfig ($key,$value,$opt=true) 
{
    global $prefix, $module_name;
	
	$value=mxAddSlashesForSQL($value);
	$key=mxAddSlashesForSQL($key);
	
    $result=sql_query("select value from ".SG_TABLE_CONFIG." where name='".$key."'");
	if (sql_num_rows($result)==0)  {
	  sql_query("insert ".SG_TABLE_CONFIG." set name='$key', value='$value' ");
	  } else {
	  sql_query("update ".SG_TABLE_CONFIG." set value='$value' where name='$key'");
	}  
	  if ($opt) sql_query("update ".SG_TABLE_CONFIG." set value='".time()."' where name='saved'");
    
}

function getConfigSavedTime() 
{
    global $prefix, $module_name;
    return mx_strftime("%c",getConfig("saved"));
}

// ------------------------------------- end config ---------------------------------------------------



function sg_updateCategory_child($cat) {
    $nums=sg_updateCategory_pictures($cat);
	return $nums;
}


function sg_updateCategory_pictures($cat) {
    $numscat=sql_num_rows(sql_query("SELECT aid from ".SG_TABLE_CATEGORY." where parentaid ='".$cat."' and publish=1")) ;
    $nums=sql_num_rows(sql_query("SELECT pid from ".SG_TABLE_PICTURE." where aid ='".$cat."' and published=1 ")) ;
	sql_query("Update ".SG_TABLE_CATEGORY." set uploads='".$nums."', childcat='".$numscat."' where aid ='".$cat."' ");
	return $nums;
}

function sg_updatePictures_Category($pid) {
    list($cat)=sql_fetch_row(sql_query("SELECT aid from ".SG_TABLE_PICTURE." where pid ='".$pid."' ")) ;
    $nums=sg_updateCategory_pictures($cat);
	return $nums;
}

// holt alle Daten der Category
function sg_getCategory($cat) {
        global $prefix, $currentlang,$module_name, $WSCFG;
		//sg_isCategoryAllowed($cat);
		
		$category=array();
		if ($cat>0) {
			$result = sql_query("SELECT * from ".SG_TABLE_CATEGORY." where aid ='".$cat."'") ;
			$category=sql_fetch_array($result);
			$xcat=array();
			$xcat=unserialize($category['config']);
			$category['config']=$xcat;
			//$category['thumb']="modules.php?name=$module_name&amp;act=getimage&amp;pic=".$category['thumb'];
			unset($result);
		} else {
		    $category['userid']=0;
		    $category['publish']=1;
		    $category['access']=0;
		    $category['alb_pass_id']=0;
		    //$category['userid']=0;
			
		}
		return $category;

}

// gibt die URL vom Thumbnail der Kategorie zurück

//function sg_getCategoryThumb($cat)
//{
//		$result=sql_query("SELECT  thumb from ".SG_TABLE_CATEGORY." where aid ='".$cid."' ");
//		list($thumb)=sql_fetch_row($result) ;
//		$forder="";
//		switch ($thumb) {
//			case -1:
//			  $forder=" order by rand";
//			break;
//			case 0:
//			  $forder=" order by datetime desc";
//			break;
//			default:
//			  $forder=" and pid='$thumb'";
//			 break;
//		}
//		$result= sql_query("SELECT thumb_url from ".SG_TABLE_PICTURE." where aid ='".$cat."' and published='1' ".$forder);
//		list($thumb_url)=sql_fetch_row($result) ;
//		return $thumb_url;
//		
//}
function sg_getCategoryAvatar($cat,$thumb)
{
   global $prefix, $currentlang,$module_name, $WSCFG,$SGCFG;
   
   //sg_isCategoryAllowed($cat) ;
   $xcat=sg_getCategory($cat);
   $userid=($xcat['userid']>0)?$xcat['userid']:0;
   
   switch ($thumb) {
   	  case -2:
	     if ($userid>0) {
		    $user=mxGetUserDataFromUid($xcat['userid']);
			$avatar=$user['user_avatar'];
			if (file_exists($avatar))	return $avatar;
		 }
		   $sort=" and published=1 order by rand() ";
	  	 break;	

      case -1:
	     $sort=" and published=1 order by rand() ";
	     break;
      case 0:
	     $sort=" and published=1 order by datetime desc ";
	     break;
      default:
	     $sort=" and pid=".$thumb;
	     $pic=$thumb;
	     break;
   }
    $userdata=mxGetUserData();
	$userid=(MX_IS_USER)?$userdata['uid']:0;
	if ((($xcat['alb_pass_id']!=0) && mxSessionGetVar("sgid".$xcat['alb_pass_id'])) or $userid==$xcat['userid'] or $xcat['alb_pass_id']==0) {
	   $subcats="";
	   $subcats=($xcat['uploads']==0)? " in(".sg_getSubcatView($cat).")":"='".$cat."'";
	   $result=sql_query("Select pid,thumb_url from  ".SG_TABLE_PICTURE." where aid".$subcats." ".$sort." limit 1");
	   list($img,$thumb_url)=sql_fetch_array($result);
	   unset($result);
	}   else {  
	   $img="";
	}
	if ($SGCFG['PATH_HIDDEN']==1 ) {
   		$avatar=($img !="" )?"modules.php?name=".$module_name."&amp;act=getimage&amp;pic=".$img:"modules.php?name=".$module_name."&amp;act=getimage&amp;pic=0";
   		} else {
		$avatar=($img !="" )?$thumb_url:"modules.php?name=".$module_name."&amp;act=getimage&amp;pic=0";
	}
   
   return $avatar;
   
}


function sg_getCategoryText($cat) {
        global $prefix, $currentlang,$module_name, $WSCFG;
		
		$result = sql_query("SELECT description from ".SG_TABLE_CATEGORY." where aid ='".$cat."'") ;
		list($text)=sql_fetch_array($result);
		unset($result);
		return $text;

}


// gibt den Kategorie-Titel zurück 
function sg_getCategoryTitle($cid=0,$noCat=0,$secid=0)
{
        global $prefix, $currentlang,$module_name, $WSCFG;
		
		if ($cid==0 || $cid==$noCat ) return ;
		
		$csec=($secid>0) ?" and secid=$secid":"";
		
		$result = sql_query("SELECT aid, title, parentaid from ".SG_TABLE_CATEGORY." where aid ='".$cid."' ") ;
		list($cid,$title,$parentid)=sql_fetch_array($result);

	  return $title;

}

// ermittelt alle Unterkategorien zu $cat und gibt eine kommagetrennte Liste der ID's zurück

function sg_getCategorySubCat ($cat=0) {
        global $prefix, $currentlang,$module_name, $WSCFG;
		$catlist=$cat;
		$result = sql_query("SELECT aid from ".SG_TABLE_CATEGORY." where parentaid ='".$cat."'") ;
		while (	list($cid)=sql_fetch_array($result)) {
		  $catlist .= ",".$cid;
		}
		unset($result);
		return $catlist;

}

// ermittelt den kompletten Path zu einer Kategorie
function sg_getCategoryPathAdmin($cid=0,$noCat=0)
{
        global $prefix, $currentlang,$module_name, $WSCFG;
		
		if ($cid==0 || $cid==$noCat ) return "";
		
		$result = sql_query("SELECT aid, title, parentaid from ".SG_TABLE_CATEGORY." where aid ='".$cid."'") ;
		list($cid,$title,$parentid)=sql_fetch_array($result);
		unset($result);
		
	    if ($parentid != $noCat  ) {
		
		      $temp=sg_getCategoryPathAdmin($parentid,$noCat);
		      $title=$temp."&nbsp;&raquo;&nbsp;".$title."";
			
		}

	  return $title;

}

function sg_setSecondaryRights($cat)
{
        global $prefix, $currentlang,$module_name, $WSCFG, $SGCFG;
        
		if ($cat<2) return;  //wenn Index oder Usercategory , dann raus hier
		
		$result=sql_query("select * from ".SG_TABLE_CATEGORY." where aid=$cat");
		$xcat=sql_fetch_array($result);
		unset($result);

		$setuser=$xcat['userid'];
		$published=$xcat['publish'];
		$setaccess=$xcat['access'];
		$pass_id=$xcat['alb_pass_id'];
		if ($setuser>0) sql_query("update ".SG_TABLE_PICTURE." set userid=$setuser where aid='".$cat."'");
		sg_updateSecondaryRights($cat,$setuser,$published,$setaccess,$pass_id);
		return;
}

function sg_updateSecondaryRights($cat,$userid,$published,$access,$passid) 
{
        global $prefix, $currentlang,$module_name, $WSCFG, $SGCFG;
		$setpublish=" publish='".$published."'";
		$setuserid=($userid > 0 )?", userid='".$userid."'":"";
		
		$result=sql_query("select aid,access from ".SG_TABLE_CATEGORY." where parentaid=$cat");
		while($setcat=sql_fetch_assoc($result)) {
		    $setaccess=($setcat['access'] < $access)?", access='".$access."'":"";
			// todo $setpassid 
			$setpassid=($passid>0)?", alb_pass_id='".$passid."'":"";
			
			sql_query("update ".SG_TABLE_CATEGORY." set ".$setpublish." ".$setuserid." ".$setaccess." ".$setpassid." where aid='".$setcat['aid']."'");
			if ($userid>0) sql_query("update ".SG_TABLE_PICTURE." set userid=$userid where aid='".$setcat['aid']."'");
			sg_updateSecondaryRights($setcat['aid'],$userid,$published,$setcat['access'],$passid);
		}
		unset($result);
		return;
}

function sg_getParentUser($cat) 
{
  if ($cat > -1) { 
   $result=sql_query("select parentaid,userid from ".SG_TABLE_CATEGORY." where aid=$cat");
   list($parentaid,$userid)=sql_fetch_row($result);
   if ($parentaid != 0) {
   	   $result2=sql_query("select userid from ".SG_TABLE_CATEGORY." where aid=$parentaid");
	   list($userid)=sql_fetch_row($result2);
   }
   return $userid;
  }
}

/*
 ermittelt alle Kategorien mit Pfad
 allCat = ID der Kategorie
 child= true/false  - true, wenn nur die  Subkategorien, von allCat ermittelt werden sollen
                      false, wenn alle, aussen den Subkategorien von allCat ermittel werden soll
					  
 $user = filtert allen noch mal nach der User ID
 
*/
function sg_getCategoryTree($allCat=0,$child=true,$user=0,$withindex=true,$withbase=false)
{
		$cattree=array();
		$sqlUser=($user==0)?"":" where userid='$user'";
		
		$result = sql_query("SELECT aid, parentaid,title from ".SG_TABLE_CATEGORY. $sqlUser);
        

		if ($withindex) $cattree[0]="&gt; "._CATEGORY_INDEX;
		if ($withbase) $cattree[$allCat]=sg_getCategoryTitle($allCat);
		
		while(list($aid,$parentaid,$title)=sql_fetch_row($result)) {
		 
		  if (sg_isChildCategory($aid, $allCat)==$child) {
		   //$aid=($child)?$allCat:$aid;
		   $cattree[$aid] = sg_getCategoryPathAdmin($aid,$allCat,$user);
		  }
		}
		natcasesort($cattree);
		return $cattree;
}


function sg_getCategoryTreeLink($allCat=0)
{
		$cattree=array();
		
		$result = sql_query("SELECT aid, parentaid,title from ".SG_TABLE_CATEGORY);//." where parentaid ='$allCat'") ;
        while(list($aid,$parentaid,$title)=sql_fetch_row($result)) {
		  if (sg_isChildCategory($aid, $allCat)) {
		   $cattree[$aid] = sg_getCategoryPath($aid,$allCat);
		  }
		}
		natcasesort($cattree);
		return $cattree;
}


function sg_isChildCategory($aid, $baseCat)
{
   	
	if ($aid==0) return false;
	if ($aid==$baseCat) return true;
	$result = sql_query("SELECT parentaid from ".SG_TABLE_CATEGORY." where aid ='$aid'") ;
	list($parentaid)=sql_fetch_row($result);
	if ($parentaid== $baseCat) {
	   return true;
	   } else {
  	  return sg_isChildCategory($parentaid, $baseCat);
    }
}

function sg_setCategoryPublish($cat)
{
   sql_query("update ".SG_TABLE_CATEGORY." set publish='1' where aid=$cat");
   sg_updateCategory_pictures($cat);
}

function sg_setCategoryUnpublish($cat)
{
   sql_query("update ".SG_TABLE_CATEGORY." set publish='0' where aid=$cat");
   sg_updateCategory_pictures($cat);   
}

// frontend
#------------------------------------------------------------------------------------------------------
function sg_getCategoryPath($cid=0,$noCat=0)
{
        global $prefix, $currentlang,$module_name, $WSCFG;
		
		if ($cid==0 ) return _CATEGORY_INDEX;
		if ($cid==$noCat ) return "";
		
		$result = sql_query("SELECT aid, title, parentaid from ".SG_TABLE_CATEGORY." where aid ='".$cid."'") ;
		list($cid,$title,$parentid)=sql_fetch_array($result);
		
	    if ($parentid != $noCat) {
		
		      $temp=sg_getCategoryPath($parentid,$noCat);
		      $title=$temp."&nbsp;&raquo;&nbsp;<a href='modules.php?name=$module_name&amp;cat=$cid'>".$title."</a>";
			} else {
				  return "";
		}
		unset($result);

	  return $title;

}
function sg_Breadcrump($cid=0,$noCat=0)
{
        global $prefix, $currentlang,$module_name, $WSCFG,$SGCFG;
		
		if ($cid==0 ) return "<a href=\"modules.php?name=$module_name\">"._SG_INDEX."</a>";
		$result = sql_query("SELECT aid, title, parentaid from ".SG_TABLE_CATEGORY." where aid ='".$cid."'") ;
		list($cid,$title2,$parentid)=sql_fetch_array($result);
        $temp=sg_Breadcrump($parentid,$noCat);
		$title=$temp."&nbsp;&raquo;&nbsp;<a href='modules.php?name=$module_name&amp;cat=$cid'>".$title2."</a>";
		unset($result);

	  return $title;

}
function sg_commentdelete_direct($pid)
{
	// Comments löschen
	   sql_query("Delete from ".SG_TABLE_COMMENT." where id=$pid");
	// Userpoints korrigieren ?
	
	return;
	
}
function sg_setCommentPublish($cat)
{
   sql_query("update ".SG_TABLE_COMMENT." set publish='1' where id=$cat");
  
}

function sg_setCommentUnpublish($cat)
{
   sql_query("update ".SG_TABLE_COMMENT." set publish='0' where id=$cat");
   
}

function sg_imgagesdelete_fromUser($userid) 
{
    $result=sql_query("select pid from ".SG_TABLE_PICTURE." where userid=$userid");
	while (list($pid)=sql_fetch_row($result)) {
		sg_imagesdelete_direct($pid);
	}

}

// speichert neues Image in der DB anhand eines Arrays
function sg_imagesSaveAdd($image)
{
   global $SGCFG;
   if (!is_array($image)) return false;
   extract($image);
   $newid=false;
					
		sql_query("insert into ".SG_TABLE_PICTURE." set 
		  aid='".$aid."',
		  title='".mxAddSlashesForSQL($title)."',
		  author='".mxAddSlashesForSQL($author)."',
		  filename='".mxAddSlashesForSQL($filename)."',
		  orig_url='".mxAddSlashesForSQL($orig_url)."',
		  thumb_url='".mxAddSlashesForSQL($thumb_url)."',
		  pic_url='".mxAddSlashesForSQL($pic_url)."',
		  description='".mxAddSlashesForSQL($description)."',
		  userid='".$userid."',
		  uname='".mxAddSlashesForSQL($uname)."',
		  datetime='".time()."',
		  mimetyp='".$mimetyp."',
		  filesize='".$filesize."',
		  published='".$published."',
		  views='".$views."',
		  votes='".$votes."',
		  rating='".$rating."',
		  position='".$position."',
		  import='".$import."',
		  keywords='".mxAddSlashesForSQL($keywords)."'
		  
		"); 
		$newid=sql_insert_id();
		
		sg_updateCategory_pictures($aid);

return $newid;

}

function sg_imagesSave($image,$pid)
{
   global $SGCFG;
   if (!is_array($image)) return false;
   extract($image);
   
   $newid=false;
					
		sql_query("Update ".SG_TABLE_PICTURE." set 
		  aid='".$aid."',
		  title='".mxAddSlashesForSQL($title)."',
		  author='".mxAddSlashesForSQL($author)."',
		  filename='".mxAddSlashesForSQL($filename)."',
		  orig_url='".mxAddSlashesForSQL($orig_url)."',
		  thumb_url='".mxAddSlashesForSQL($thumb_url)."',
		  pic_url='".mxAddSlashesForSQL($pic_url)."',
		  description='".mxAddSlashesForSQL($description)."',
		  userid='".$userid."',
		  uname='".mxAddSlashesForSQL($uname)."',
		  datetime='".time()."',
		  mimetyp='".$mimetyp."',
		  filesize='".$filesize."',
		  published='".$published."',
		  views='".$views."',
		  votes='".$votes."',
		  rating='".$rating."',
		  position='".$position."',
		  import='".$import."',
		  keywords='".mxAddSlashesForSQL($keywords)."'
		  where pid=$pid;
		"); 

return ;

}

function sg_imagesdelete_direct($pid)
{
	global $SGCFG;

    // Picture ermitteln...
	$result=sql_query("SELECT * from ".SG_TABLE_PICTURE." where pid=$pid");
	
	if (sql_num_rows($result)) {
	   // dann Bild vorhanden
	  $pic=sql_fetch_array($result);
	  $cat=$pic['aid'];
	   
		
		// Comments löschen
		   sql_query("Delete from ".SG_TABLE_COMMENT." where pid=$pid");
		// Votes löschen
		   sql_query("Delete from ".SG_TABLE_VOTES." where pid=$pid");
		
		// Bilder löschen
	   if (!(substr($pic['import'],0,7)=="SGCLONE")) {		// geklonte Bilder nicht löschen
		   if (file_exists($pic['orig_url']) and empty($pic['import'])) @unlink ($pic['orig_url']); // importierte Bilder nicht löschen
		   if (file_exists($pic['pic_url'])) @unlink ($pic['pic_url']);
		   if (file_exists($pic['thumb_url'])) @unlink ($pic['thumb_url']);
		}
		
		// jetzt erst DB-Eintrag löschen
		   sql_query("Delete from ".SG_TABLE_PICTURE." where pid=$pid");
		   $cresult=sql_query("select pid from ".SG_TABLE_PICTURE." where import='SGCLONE".$pid."'");  // geklonte  Bilder auch löschen
			while($cpic=sql_fetch_row($cresult)) {
				sg_imagesdelete_direct($cpic);
			}
			unset ($cresult);
		// Anzahl Bilder in Kategorie neuberechnen?
		   sg_updateCategory_pictures($pic['aid'])	;
		// Userpoints korrigieren ?
	unset($result,$pic);
	}
	return;
}

function sg_Image($pic)
{
   $result=sql_query("select * from ".SG_TABLE_PICTURE."  where pid=$pic");
   return sql_fetch_array($result);
}

/* gibt die sprachabhängigen Daten des Bildes zurück als Array
    KEY=Bezeichnung des Wertes
	VALUE = Wert
	-leere Felder werden nicht mit zurückgegeben
	
    $image=Array(Bilddaten aus DB)
	
*/
function sg_getImageData($image)
{
	global $SGCFG;
    $imgdata=array();
	$user=mxGetUserDataFromUid($image['userid']);
	if ($image['uname']!="") 	{
			$image['uname']=$user['uname'];
	}
	
	//if ($image['title']!="") 		$imgdata[IMG_TITLE]=mxPrepareToDisplay($image['title']);
	if ($image['description']!="" ) 	$imgdata[IMG_DESCRIPTION]=mxPrepareToDisplay($image['description']);
	if ($image['uname']!="" and $SGCFG['DETAIL_UNAME']==1) 		$imgdata[IMG_UNAME]=mxPrepareToDisplay($image['uname']);
	if ($image['author']!="" and $SGCFG['DETAIL_AUTHOR']==1) 		$imgdata[IMG_AUTHOR]=mxPrepareToDisplay($image['author']);
	if ($image['filesize']!="" and $SGCFG['DETAIL_FILESIZE']==1) 		$imgdata[IMG_FILESIZE]=mxPrepareToDisplay(intval($image['filesize']/10.24)/100)." kBytes";
	if ($image['views']!="" and $SGCFG['DETAIL_VIEWS']==1) 		$imgdata[IMG_VIEWS]=mxPrepareToDisplay($image['views']);
	if ($image['rating']!="" and $SGCFG['USER_VOTING']==1) 		$imgdata[IMG_RATING]=mxPrepareToDisplay($image['rating']);
	if ($image['datetime']!="" and $SGCFG['DETAIL_DATE']==1) 		$imgdata[IMG_DATE]=mx_strftime('%x',$image['datetime']);
	
	return $imgdata;
}


function sg_getImageDataFromId($pic)
{
   $imagedata=sg_Image($pic);
   return sg_getImageData($imagedata);
}

function sg_setImagePublish($cat)
{
   sql_query("update ".SG_TABLE_PICTURE." set published='1' where pid=$cat");
   sg_updatePictures_Category($cat);
}

function sg_setImageUnpublish($cat)
{
   sql_query("update ".SG_TABLE_PICTURE." set published='0' where pid=$cat");
   sg_updatePictures_Category($cat);
}

function sg_setImageOwner($pid,$userid)
{
   if ($userid>0)  sql_query("update ".SG_TABLE_PICTURE." set userid='".$userid."' where pid=".$pid."");
   sg_updatePictures_Category($cat);
}


function sg_getImagesView($cat,$start=0, $limit=0,$style=true)
{
   global $prefix, $currentlang,$module_name, $WSCFG,$SGCFG;
   //$limit=
   $images=array();
   
   if ($cat==0)return $images;
   
   
   $category=sg_getCategory($cat);
   
   switch($category['sort']) {
     case 0: $sort="datetime asc";
	      break;
     case 1: $sort="datetime desc";
	      break;
     case 2: $sort="rating desc";
	      break;
     case 3: $sort="views desc";
	      break;
     case 4: $sort="title asc";
	      break;
     case 5: $sort="title desc";
	      break;
	 default:
		 $sort="datetime asc";
		 break;
   }
   
   $getlimit=($limit>0)?"limit ".$start.",".$limit:"";
   
   $result=sql_query("Select * from  ".SG_TABLE_PICTURE." where aid=$cat and published='1' order by ".$sort." ".$getlimit); 
   $imgcount=sql_num_rows($result);
   $images=array();
   $ipos=0;
   while($image=sql_fetch_assoc($result)) {
     $ipos++;
     if ($SGCFG['PATH_HIDDEN']==1) {
	 		$image['thumb_url']="modules.php?name=".$module_name."&amp;act=getimage&amp;pic=".$image['pid'];
			$image['pic_url']="modules.php?name=".$module_name."&amp;act=getimage&amp;pic=".$image['pid']."&amp;size=1";
			$image['orig_url']="modules.php?name=".$module_name."&amp;act=fullsize&amp;pic=".$image['pid']."";
	 } else {
			$image['pic_url'].=($style)?"\" style=\"max-width:".$SGCFG["IMAGE_MAXSIZE"]."px; max-height:".$SGCFG["IMAGE_MAXSIZE"]."px;":"";	 
	 }
	 
	 $detaillink="href=\"modules.php?name=".$module_name."&amp;act=detail&amp;pic=".$image['pid']."\"";
	 $baselink="href=\"".$image['orig_url']."\" ";
	 if ($imgcount>1) {
	  	$baselink .="rel=\"pretty[sg]\" ";
		} else {
	  	$baselink .="rel=\"pretty\" ";
	 }	
     $image['link_url']=($SGCFG['CAT_DETAIL']==1)?$detaillink:$baselink;
	 $image['position']=$ipos;
     $images[]=$image;
   }
   return $images;
}

function sg_getImagesList($alist,$start=0, $limit=0)
{
   global $prefix, $currentlang,$module_name, $SGCFG;
   //$limit=
   $images=array();
   
   if ($alist=="")return $images;
   
   //$category=sg_getCategory($cat);
   //$sort="rand()";
   switch($alist) {
     case "newest": 
	 		$sort="order by  datetime desc";
			$cver=0;
	      break;
     case "top": 
	 		$sort="and rating>0 and votes >0 order by rating desc, votes desc,pid asc  ";
			$cver=0;
	      break;
     case "mostviewed": 
	 		$sort="and views>0 order by views desc";
			$cver=0;
	      break;
     case "random": 
	 		$sort="order by rand()";
			$cver=0;
	      break;
     case "newcomments": 
	 		$sort="";
			$cver=1;
	      break;
   }
   
   $getlimit=($limit>0)?"limit ".$start.",".$limit:"";
	$subids=sg_getSubcatView(0);

   switch ($cver) {
	case 1:
		$result=sql_query("Select pic.* from ".SG_TABLE_COMMENT." as com, ".SG_TABLE_PICTURE." as pic 
				where pic.aid in(".$subids.") and pic.published='1'  
				and pic.pid=com.pid and com.publish=1 order by com.created desc ".$getlimit); 
		break;
   	case 0:
	default:
		$result=sql_query("Select * from  ".SG_TABLE_PICTURE." where aid in(".$subids.") and published='1'  ".$sort." ".$getlimit); 
		break;
	}
   $imgcount=sql_num_rows($result);
   $images=array();
   $ipos=0;
   while($image=sql_fetch_assoc($result)) {
     $ipos++;
     if ($SGCFG['PATH_HIDDEN']==1) {
	 		$image['thumb_url']="modules.php?name=".$module_name."&amp;act=getimage&amp;pic=".$image['pid'];
			$image['pic_url']="modules.php?name=".$module_name."&amp;act=getimage&amp;pic=".$image['pid']."&amp;size=1";
			$image['orig_url']="modules.php?name=".$module_name."&amp;act=fullsize&amp;pic=".$image['pid']."";
	 } else {
			$image['pic_url'].="\" width=\"".$SGCFG["IMAGE_MAXSIZE"]."";	 
	 }
	 
	 $detaillink="href=\"modules.php?name=".$module_name."&amp;act=detail&amp;pic=".$image['pid']."\"";
	 $baselink="href=\"".$image['orig_url']."\" ";
	 if ($imgcount>1) {
	  	$baselink .="rel=\"pretty[sg]\" ";
		} else {
	  	$baselink .="rel=\"pretty\" ";
	 }	
     $image['link_url']=($SGCFG['CAT_DETAIL']==1)?$detaillink:$baselink;
	 $image['position']=$ipos;
     $images[]=$image;
   }
   return $images;
}

function sg_getImagesSearch($search,$start=0,$limit=25)
{
   global $prefix, $currentlang,$module_name, $SGCFG;
 
   $images=array();
   
   if ($search=="")return $images;
   
   
   $getlimit=($limit>0)?"limit ".$start.",".$limit:"";
	$subids=sg_getSubcatView(0);
	
   $result=sql_query("Select * from  ".SG_TABLE_PICTURE." where aid in(".$subids.") and published='1' and MATCH(title,uname,keywords,description) AGAINST('$search' IN BOOLEAN MODE) ".$getlimit); 
   $imgcount=sql_num_rows($result);
   $images=array();
   $ipos=0;
   while($image=sql_fetch_assoc($result)) {
     $ipos++;
     if ($SGCFG['PATH_HIDDEN']==1) {
	 		$image['thumb_url']="modules.php?name=".$module_name."&amp;act=getimage&amp;pic=".$image['pid'];
			$image['pic_url']="modules.php?name=".$module_name."&amp;act=getimage&amp;pic=".$image['pid']."&amp;size=1";
			$image['orig_url']="modules.php?name=".$module_name."&amp;act=fullsize&amp;pic=".$image['pid']."";
	 } else {
			$image['pic_url'].="\" width=\"".$SGCFG["IMAGE_MAXSIZE"]."";	 
	 }
	 
	 $detaillink="href=\"modules.php?name=".$module_name."&amp;act=detail&amp;pic=".$image['pid']."\"";
	 $baselink="href=\"".$image['orig_url']."\" ";
	 if ($imgcount>1) {
	  	$baselink .="rel=\"pretty[sg]\" ";
		} else {
	  	$baselink .="rel=\"pretty\" ";
	 }	
     $image['link_url']=($SGCFG['CAT_DETAIL']==1)?$detaillink:$baselink;
	 $image['position']=$ipos;
     $images[]=$image;
   }
   return $images;
}

function sg_getImagesCount($cat)
{
   global $prefix, $currentlang,$module_name, $WSCFG,$SGCFG;

   $result=sql_query("Select pid from  ".SG_TABLE_PICTURE." where aid=$cat and published='1' ");
   $imgcount=sql_num_rows($result);
   unset($result);
   return $imgcount;
   
}

function sg_getImagesListCount()
{
   global $prefix, $currentlang,$module_name, $WSCFG,$SGCFG;
   
   //	if (!sg_isCategoryAllowed($cat) && $cat!=0) mxErrorScreen(_GROUPRESTRICTEDAREA);

   $result=sql_query("Select pid from  ".SG_TABLE_PICTURE." where published='1' ");
   $imgcount=sql_num_rows($result);
   unset($result);
   return $imgcount;
   
}


function sg_getImagesCountAll($cat)
{
   global $prefix, $currentlang,$module_name, $WSCFG,$SGCFG;
   
   //	if (!sg_isCategoryAllowed($cat) && $cat!=0) mxErrorScreen(_GROUPRESTRICTEDAREA);

   $result=sql_query("Select count(*) from  ".SG_TABLE_PICTURE." where aid=$cat group by aid ");
   list($imgcount)=sql_fetch_row($result);
   unset($result);
   return intval($imgcount);
   
}


function sg_updateImageCount($pid)
{
   global $prefix, $currentlang,$module_name, $WSCFG,$SGCFG;
   
   //	if (!sg_isCategoryAllowed($cat) && $cat!=0) mxErrorScreen("falsch");

   $result=sql_query("update ".SG_TABLE_PICTURE." set views=views+1 where pid=$pid ");
   return ;
}

function sg_getImage($pid,$size=0)
{
   global $prefix, $currentlang,$module_name, $WSCFG,$SGCFG;
    
	$serverself="".$_SERVER['HTTP_HOST'].dirname($_SERVER['PHP_SELF']);
    $serverlen=strlen($serverself);
	$fremdip=$_SERVER['REMOTE_ADDR'];
	$selfip=$_SERVER['SERVER_ADDR'];

	// Bild holen
	$result= sql_query("SELECT * from ".SG_TABLE_PICTURE." where pid='".$pid."'");
	$pic=sql_fetch_array($result);
		
	
	switch ($size) {
		case 0: 	$picpath=$pic['thumb_url'];
	   				$pic['mimetyp']="image/jpg";
			break;
		case 1: 	$picpath=$pic['pic_url'];
	   				$pic['mimetyp']="image/jpg";
			break;
		case 2:
					$picpath=$pic['orig_url'];					
			break;
		default: 	$picpath=$pic['thumb_url'];
					$pic['mimetyp']="image/jpg";
			break;
    }


	
	if (!file_exists($picpath) or $pid==0 ) {
	    $picpath="modules".DS.$module_name.DS."style".DS."noimage.png";
	   $pic['mimetyp']="image/png";
	}
	
	//if ($fremdip != $selfip) {
//    if (!(substr ($_SERVER['HTTP_REFERER'],0,$serverlen)==$serverself)) {
//	   $picpath="modules".DS.$module_name.DS."templates".DS."forbidden.png";; 
//	   $pic['mimetyp']="image/png";
//	}
	
	// eventuell vorhandenen Ausgabepuffer loeschen
	while (ob_get_length()) {
		ob_end_clean();
	}
	
	//$_SERVER['HTTP_ACCEPT_ENCODING'] = 'none';
	header("HTTP/1.1 200 OK");
	
	// Das Bild ausgeben
	
	header('Content-type: '.$pic['mimetyp']);
	//$typearray=array("image/jpeg","image/jpg","image/bmp","image/png","image/gif","image/pjpeg","image/x-png");
    $size = getimagesize($picpath);
	
	switch (strtolower($pic['mimetyp'])) {
		case "image/jpg":
		case "image/jpeg":
		case "image/pjpeg":
				$x= imagecreatefromjpeg($picpath);	
				
				imagejpeg($x);
				break;
		case "image/bmp":
		case "image/wbmp":
				$x= imagecreatefrombmp($picpath);
				
				imagewbmp($x);
				break;
		case "image/png":
		case "image/x-png":
				$x= imagecreatefrompng($picpath);
				$mimetype="image/png";	
				$size = getimagesize($picpath);
				$im_tc = imagecreatetruecolor($size[0],$size[1]);
				imagesavealpha($im_tc, true); 
				$color = imagecolorallocatealpha($im_tc,0x00,0x00,0x00,127);
				imagefill($im_tc, 0, 0, $color); 
				imagecopy($im_tc,$x,0,0,0,0,$size[0],$size[1]);
				imagepng($im_tc);
				imagedestroy($im_tc);
				break;
		case "image/gif":
				$x= imagecreatefromgif($picpath);
				
				imagegif ($x);
				break;
	}

		// Convert the Image to PNG-24
//		$im_tc = imagecreatetruecolor($size[0],$size[1]);
//		imagecopy($im_tc,$x,0,0,0,0,$size[0],$size[1]);
//		imagedestroy($x);
//	   
//    	if ($size==1) $im_result=sg_ImageResize($picpath);
//	
//		//And now convert it back to PNG-8
//		$im_result = imagecreate($size[0],$size[1]);
//		imagecopy($im_result,$im_tc,0,0,0,0,$size[0],$size[1]);
//		imagedestroy($im_tc);
	   
    //imagejpeg($x);
	// Den Speicher freigeben
	imagedestroy($x);	
	unset($pic,$result);
	// Script beenden
	exit;

}

function sg_getImageDownload($pid,$size=0)
{
  global $SGCFG;
    $x=false;
    $imgoptuser=false;
	 
	if ($SGCFG['IMG_DOWNLOAD']==1) {
		switch($SGCFG['IMG_DOWNLOAD_USER']) {
			case 0:		// all
				$imgoptuser=true;
			break;
			case 1:		// user only
				if (MX_IS_USER or MX_IS_ADMIN) $imgoptuser=true;
			break;
			case 2:		// admin only
				if (MX_IS_ADMIN) $imgoptuser=true;
			break;
		}
	}
    if (!$imgoptuser) die('access denied');
	// Bild holen
	$result= sql_query("SELECT * from ".SG_TABLE_PICTURE." where pid='".$pid."'");
	$pic=sql_fetch_array($result);
		
	$waterflag=false;
	switch ($size) {
		case 0: 	$picpath=$pic['thumb_url'];
			break;
		case 1: 	$picpath=$pic['pic_url'];
			$waterflag=true;
			break;
		case 2: 	$picpath=$pic['orig_url'];
			$waterflag=true;
			break;
	
		default: 	
			$picpath=$pic['thumb_url'];
			break;
    }
	
	$waterflag=(($SGCFG['IMG_WATERMARK']==1 )&& $waterflag);
	$filesize=filesize($picpath);
	
	// eventuell vorhandenen Ausgabepuffer loeschen
	while (ob_get_length()) {
		ob_end_clean();
	}
	
	
	$_SERVER['HTTP_ACCEPT_ENCODING'] = 'none';
	header("HTTP/1.1 200 OK");
	// fix for IE
	header('Cache-control: private');
	header('Content-disposition: attachment; filename='.string_to_filename($pic['filename']));
	// Dateigroesse mitsenden
	header('Content-Length: ' . $filesize);
	
	// Das Bild ausgeben
	header('Content-type: '.$pic['mimetyp']);
	
	switch (strtolower($pic['mimetyp'])) {
		case "image/jpg":
		case "image/jpeg":
		case "image/pjpeg":
				$x= imagecreatefromjpeg($picpath);
				$mimetype="image/jpg";	
				if ($waterflag) $x=sg_getImageWatermark($x);
				imagejpeg($x);
				break;
		case "image/bmp":
		case "image/wbmp":
				$x= imagecreatefrombmp($picpath);
				$mimetype="image/bmp";	
				$size = getimagesize($picpath);
				$im_tc = imagecreatetruecolor($size[0],$size[1]);
				//imagesavealpha($im_tc, true); 
				//$color = imagecolorallocatealpha($im_tc,0x00,0x00,0x00,127);
				//imagefill($im_tc, 0, 0, $color); 
				imagecopy($im_tc,$x,0,0,0,0,$size[0],$size[1]);
				if ($waterflag) $im_tc=sg_getImageWatermark($x);
				imagejpeg($im_tc);
				break;
		case "image/png":
		case "image/x-png":
				$x= imagecreatefrompng($picpath);
				$mimetype="image/png";	
				$size = getimagesize($picpath);
				$im_tc = imagecreatetruecolor($size[0],$size[1]);
				imagesavealpha($im_tc, true); 
				$color = imagecolorallocatealpha($im_tc,0x00,0x00,0x00,127);
				imagefill($im_tc, 0, 0, $color); 
				imagecopy($im_tc,$x,0,0,0,0,$size[0],$size[1]);
				if ($waterflag) $im_tc=sg_getImageWatermark($x);
				imagepng($im_tc);
				imagedestroy($im_tc);
				break;
		case "image/gif":
				$x= imagecreatefromgif($picpath);
				$mimetype="image/gif";	
				$size = getimagesize($picpath);
				$im_tc = imagecreatetruecolor($size[0],$size[1]);
				imagesavealpha($im_tc, true); 
				$color = imagecolorallocatealpha($im_tc,0x00,0x00,0x00,127);
				imagefill($im_tc, 0, 0, $color); 
				imagecopy($im_tc,$x,0,0,0,0,$size[0],$size[1]);
				if ($waterflag) $im_tc=sg_getImageWatermark($x);
				imagegif ($im_tc);
				imagedestroy($im_tc);
				break;
	}
		// Convert the Image to 24bit
//		imagedestroy($x);
//	  
		//if ($waterflag) $im_tc=sg_getImageWatermark($im_tc);
//	
//		And now convert it back to PNG-8
//		$im_result = imagecreate($size[0],$size[1]);
//		imagecopy($im_result,$im_tc,0,0,0,0,$size[0],$size[1]);
//		imagedestroy($im_tc);
	   
   // imagejpeg($x);
	// Den Speicher freigeben
	imagedestroy($x);	
	
	unset($pic,$result);
	// Script beenden
	exit;

}

// erzeugt ein JPG-Bild, welches in der Größe "Ansicht" als leeres Quadrat erzeugt wird und das Bild eingepasst wird

function sg_getImageSlideshow($pid)
{
   global $prefix, $currentlang,$module_name, $WSCFG,$SGCFG,$bgcolor1, $bgcolor2, $bgcolor3;
   $serverself="http://".$_SERVER['HTTP_HOST'].dirname($_SERVER['PHP_SELF']);
   $serverlen=strlen($serverself);
	$fremdip=$_SERVER['REMOTE_ADDR'];
	$selfip=$_SERVER['SERVER_ADDR'];

	// Bild holen
	$result= sql_query("SELECT * from ".SG_TABLE_PICTURE." where pid='".$pid."'");
	$pic=sql_fetch_array($result);
		
	
	$picpath=$pic['pic_url'];
	$pic['mimetyp']="image/jpg";
	
	
	if (!file_exists($picpath)) {
	    $picpath="modules".DS.$module_name.DS."style".DS."templates".DS."noimage.png";
	   $pic['mimetyp']="image/png";
	}
	if ($fremdip==$selfip) {
    //if (!(substr ($_SERVER['HTTP_REFERER'],0,$serverlen)==$serverself)) {
	   $picpath="modules".DS.$module_name.DS."style".DS."templates".DS."forbidden.png";; 
	   $pic['mimetyp']="image/png";
	}
	// Bild einlesen
	$versatz=30;
	$x= imagecreatefromjpeg($picpath);	
	$tx=intval($SGCFG['IMAGE_MAXSIZE']-$versatz);
	$thb = imagecreatetruecolor ($tx+$versatz, $tx+$versatz);
	$color= HexToRGB($SGCFG['FRONT_SLIDESHOWCOLOR']);
	$color1=imagecolorallocate($thb, $color['r'],$color['g'],$color['b']);
    imagefill($thb, 0,0, $color1);
	imagepalettecopy($thb,$x);
	
	list ($src_width, $src_height) = getimagesize($picpath);
           if ($src_width > $src_height ) {
               $thumb_width = $tx;
               $thumb_height = floor($src_height * ($tx / $src_width));
           } else if ($src_width < $src_height ) {
               $thumb_height = $tx;
               $thumb_width = floor($src_width * ($tx / $src_height));
           } else {
               $thumb_width = $tx;
               $thumb_height = $tx;
           }
    $startx=($tx-$thumb_width+$versatz)/2;
	$starty=($tx-$thumb_height+$versatz)/2;
    imagecopyresampled($thb, $x, $startx, $starty, 0, 0, $thumb_width, $thumb_height, $src_width, $src_height) ;

	
	// eventuell vorhandenen Ausgabepuffer loeschen
	while (ob_get_length()) {
		ob_end_clean();
	}
	
	//$_SERVER['HTTP_ACCEPT_ENCODING'] = 'none';
	header("HTTP/1.1 200 OK");

	
	// Das Bild ausgeben
	
	header('Content-type: '.$pic['mimetyp']);
	imagejpeg($thb,null,91);
    
	// Den Speicher freigeben
	imagedestroy($x);	
	imagedestroy($thb);
	unset($pic,$result);
	// Script beenden
	exit;

}

// fügt einem Bild eine Watermark hinzu
// $x = Image-Handel
function sg_getImageWatermark(&$x)
{
  global $SGCFG;
	$fwatermark=$SGCFG['PATH_WATERMARK'].DS.$SGCFG['PATH_FILE_WATERMARK'];
	$watermark=@imagecreatefrompng($fwatermark);
	imgwatermark ($x, $watermark, imagesx($x), imagesy($x), imagesx($watermark), imagesy($watermark), intval($SGCFG['IMG_WATERMARK_POS']));
	return $x;

}
#----------------------------------------------------------------------------------------

function tmb_header($ext_title="")
{
  include ("header.php");
  //ws_addCss();
  isHome();
  if (!empty($ext_title)) $ext_title=" - ".$ext_title;
  title(_MODULNAME.$ext_title);

}

function tmb_footer() 
{
	tmb_copyright();
    include("footer.php");

}


function tmb_copyright() {
   echo "<br />";
   echo "<div class='align-right tiny'><br /><a href='http://www.tecmu.de' 
   target=\"_blank\" title=\"SiriusGallery by tecmu.de\">&copy; &Dagger;tp&Dagger;</a><br /></div>";
    
}

function tmb_checktables($act)
{
			$result = sql_query("SHOW TABLES;");
			while (list($tablename) = sql_fetch_row($result)) {
				$tables[] = $tablename;
			}
			if (!in_array(SG_TABLE_PICTURE, $tables)) {
			  $act="install";
			}
			unset($tables);
			return $act;
}

function HexToRGB($hex) {
	$hex = str_replace("#", "", $hex);
	$color = array();
	 
	if(strlen($hex) == 3) {
	$color['r'] = hexdec(substr($hex, 0, 1) . $r);
	$color['g'] = hexdec(substr($hex, 1, 1) . $g);
	$color['b'] = hexdec(substr($hex, 2, 1) . $b);
	}
	else if(strlen($hex) == 6) {
	$color['r'] = hexdec(substr($hex, 0, 2));
	$color['g'] = hexdec(substr($hex, 2, 2));
	$color['b'] = hexdec(substr($hex, 4, 2));
}
 
return $color;
}
 
function RGBToHex($r, $g, $b) {
	//String padding bug found and the solution put forth by Pete Williams (http://snipplr.com/users/PeteW)
	$hex = "#";
	$hex.= str_pad(dechex($r), 2, "0", STR_PAD_LEFT);
	$hex.= str_pad(dechex($g), 2, "0", STR_PAD_LEFT);
	$hex.= str_pad(dechex($b), 2, "0", STR_PAD_LEFT);
	 
return $hex;
}

function sg_getMD5($pass="")
{
  return ($pass xor md5("31265653165988"));
}

function sg_ImageResize($original) {
	
	global $SGCFG;
	
	if (!is_file($original)) return false;
	
	$quality=91;
	$max_width=$SGCFG["IMAGE_MAXSIZE"];
	$max_height=$SGCFG["IMAGE_MAXSIZE"];
	
	list ($src_width, $src_height, $type, $w) = getimagesize($original);
	$imgtype=image_type_to_mime_type($type);
   
    switch ($imgtype) {
    case "image/gif":
        // "Image is a gif";
		if (!$srcImage = @imagecreatefromgif($original)) {
			return false;
		}
        break;
    case "image/jpeg":
    case "image/jpg":
    case "image/pjpeg":
        // "Image is a jpeg";
		if (!$srcImage = @imagecreatefromjpeg($original)) {
			return false;
		}
        break;
    case "image/png":
    case "image/x-png":
        // "Image is a png";
		if (!$srcImage = @imagecreatefrompng($original)) {
			return false;
		}
        break;
    case "image/bmp":
    case "image/wbmp":
        // "Image is a bmp";
		if (!$srcImage = @imagecreatefrombmp($original)) {
			return false;
		}
        break; 
	}
	
		$srcImage = imagecreatetruecolor($src_width, $src_height);
		imagecopy($srcImage,$x,0,0,0,0,$src_width, $src_height);
		imagedestroy($x);	
        
            # image resizes to natural height and width
            if ($src_width > $src_height ) {
                $thumb_width = $max_width;
                $thumb_height = floor($src_height * ($max_width / $src_width));
            } else if ($src_width < $src_height ) {
                $thumb_height = $max_height;
                $thumb_width = floor($src_width * ($max_height / $src_height));
            } else {
                $thumb_width = $max_height;
                $thumb_height = $max_height;
            }

            @$destImage = imagecreatetruecolor($thumb_width, $thumb_height) ;
           
            @imagecopyresampled($destImage, $srcImage, 0, 0, 0, 0, $thumb_width, $thumb_height, $src_width, $src_height) ;
            
         imagedestroy($srcImage);  
	return $destImage;
}

?>