<?php 
function module_not_installed($what='')
{
	$GLOBALS['tmpl']->assign('title', $GLOBALS['config_vars']['Partners']); 
	$GLOBALS['tmpl']->assign('content', $GLOBALS['tmpl']->fetch($GLOBALS['config']['source'] . '/error/module_not_found.tpl'));
}

function KoobiReadFile($filename,$retbytes=true)
{
   $chunksize = 1*(1024*1024); 
   $buffer = '';
   $cnt =0;

   $handle = fopen($filename, 'rb');
   if ($handle === false)
   {
	   return false;
   }
   while (!feof($handle))
   {
	   $buffer = fread($handle, $chunksize);
	   echo $buffer;
	   flush();
	   if ($retbytes) {
		   $cnt += strlen($buffer);
	   }
   }
	   $status = fclose($handle);
   if ($retbytes && $status)
   {
	   return $cnt; 
   }
   return $status;
} 
	
function nopermDoc()
{
	$GLOBALS['tmpl']->assign('content', $GLOBALS['tmpl']->fetch($GLOBALS['config']['source'] . '/error/no_perm_document.tpl'));
}

function getContentLinks($a)
{
	$docs = array();
	$query = $GLOBALS['db']->Query("SELECT Id,Sektion,Titel1 FROM " . PREFIX . "_content WHERE Sektion = '" . $a . "' ORDER BY Titel1 ASC ");
	while($row = $query->fetchrow())
	{
		array_push($docs, $row);
	}
	return $docs;
}

//=================================================================
// Galerie-Kategorien holen
//=================================================================
function fetchGalleryCategs($area)
{
	$categs = array();
	$query = $GLOBALS['db']->Query("SELECT Id,Name_1 AS CategName FROM " . PREFIX . "_galerie_kategorien WHERE Sektion = '" . $area . "' ORDER BY Name_1 ASC ");
	while($row = $query->fetchrow())
	{
		$gals = array();
		$qg = $GLOBALS['db']->Query("SELECT Id AS GalId,Name_1 AS GalName FROM " . PREFIX . "_galerie WHERE Kategorie = '$row->Id' ORDER BY Name_1 ASC ");
		while($rowg = $qg->fetchrow())
		{
			array_push($gals, $rowg);
		}
		
		$row->Gals = $gals;
		array_push($categs, $row);
	}
	
	return $categs;
}

//=================================================================
// getNavigationPath
// erzeugt einen pfad zur aktuellen position
// ausgangspunkt --> ... --> aktuelle position -->>
//=================================================================
function getNavigationPath($id, $table, $link, $key, $idtype, $nametype, $result = null, $extra = 0, $nav_op="0", $p="0", $parent_give="Parent_Id", $textra="", $main_link='', $linkname='')
{
	$sqlextra = '';
	$p = $_REQUEST['do']; 
	
	//=================================================================
	// Daten des aktuellen bereichs
    //=================================================================
	$q_item = "SELECT Parent_id,Name_1 as Name, $idtype, $nametype, $parent_give FROM " . PREFIX . "_$table WHERE $idtype = $id";
	$r_item = $GLOBALS['db']->Query($q_item);
    $item = $r_item->fetchrow(); 
	if(is_object($item) && !$item->$nametype) $item->$nametype = $item->DefName;
	
	$esn  = (is_object($item)) ? $item->$parent_give : '';
	
	if(is_object($item))
	{
	
		//=================================================================
		// Rekursion abgeschlossen
		//=================================================================
		if ($item->$parent_give == 0)
		{
			
			switch($p)
			{
				case 'gallery': 
					$GalInf = $GLOBALS['db']->RowQuery("SELECT Id,Name_1 AS Name FROM " . PREFIX . "_galerie_kategorien WHERE Id = '" . $_REQUEST['id'] . "'");
					return "<a href='{$link}'>" . $textra . "</a>" . ' - ' . '<a href="index.php?do=gallery&amp;sub=showincluded&amp;id='.$GalInf->Id.'">' . @$GalInf->Name . '</a>' . ' - ' . "<a href='index.php?do=gallery&sub=showincluded&id=".$_REQUEST['id']."&subgallery=".$item->Id."'>" . $item->$nametype . "</a>" . $result;
				break;
				
				case '':
				default:
					return "<a href='index.php?p={$link}'>" . $textra . "</a>" . $GLOBALS['config_vars']['PageSep'] . "<a href='index.php?p={$link}&amp;{$key}=" . $item->$idtype . "&amp;name=".seotitle($item->Name)."'>" . $item->$nametype . "</a>" . $result;
				break;
			}
		} 
		
		//=================================================================
		// Daten des Darueberliegenden Bereiches
		//=================================================================
		if ($extra == 1) $sqlextra = ", $parent_give";
		$q_parent  = "SELECT Parent_id,Name_1,Name_1 as Name, $idtype, $nametype, $parent_give, $idtype, $nametype  $sqlextra FROM " . PREFIX . "_$table WHERE $idtype = " . $item->$parent_give;
		$r_parent  = $GLOBALS['db']->Query($q_parent);
		$parent    = $r_parent->fetchRow();
		if(!$parent->$nametype) $parent->$nametype = $parent->DefName;
		
		if($extra == 1) $bextra = "&amp;parent=$parent->Id";
		
		switch($p)
		{
			case 'gallery':
				$GalInf = $GLOBALS['db']->RowQuery("SELECT Id,Name_1,Name_1 AS Name FROM " . PREFIX . "_galerie_kategorien WHERE Id = '" . $_REQUEST['id'] . "'");
				$result = " - <a href='index.php?do=gallery&sub=showincluded&id=".$_REQUEST['id']."&subgallery=".$item->Id."'>" . $item->$nametype . "</a>" . $result;
			break;
			
			case '':
			default:
				$result = $GLOBALS['config_vars']['PageSep'] . "<a title='" . $item->$nametype . "' href='index.php?p={$link}&amp;{$key}=" . $item->$idtype . "&amp;name=".seotitle($item->Name)."'>" . $item->$nametype . "</a>" . $result;
			break;
		}
		
	
		return getNavigationPath($item->$parent_give, $table, $link, $key, $idtype, $nametype, $result, $extra, $nav_op, $p, $parent_give, $textra);
	}
}

function getInlineForms()
{
	$cforms = array();
	$sql = $GLOBALS['db']->Query("SELECT * FROM " . PREFIX . "_kontakt_form WHERE Aktiv='1' ORDER BY Id ASC");
	while($row = $sql->fetchrow())
	{
		array_push($cforms,$row);
	}
	return $cforms;
	
}

function imgPrefix($text='')
{
	$base = substr($_SERVER['PHP_SELF'],0,-15);
	$text = str_replace("%%ECRUOS_GMI_IBOOK%%", $base, $text);
	return $text;
}

function imgToPrefix($text='')
{
	$base = substr($_SERVER['PHP_SELF'],0,-15);
	$text  = str_replace('src=\"' . $base, 'src=\"%%ECRUOS_GMI_IBOOK%%', $text);
	return $text;
}

function textToPrefix($text='')
{
	$base = substr($_SERVER['PHP_SELF'],0,-15) . 'uploads/';
	$text  = str_replace($base ,'%%ECRUOS_GMI_IBOOK%%uploads/', $text);
	return $text;
}



function notFound()
{
	$GLOBALS['tmpl']->assign('content', $GLOBALS['tmpl']->fetch($GLOBALS['config']['source'] . '/error/not_found.tpl'));
}
	
function no_perm()
{
	$GLOBALS['tmpl']->assign('content', $GLOBALS['config_vars']['NoPermTLong']);
}

function getlimit($limit=15)
{
    $limit = (isset($_REQUEST['pp']) && $_REQUEST['pp'] != '') ? $_REQUEST['pp'] : $limit;
    return abs((int)$limit);
} 

function format_size($size, $round = 0)
{
    //Size must be bytes!
    $sizes = array('B', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB');
    for ($i=0; $size > 1024 && $i < count($sizes) - 1; $i++) $size /= 1024;
    return round($size,$round).$sizes[$i];
} 

function return_bytes($val) {
    $val = trim($val);
    $last = strtolower($val{strlen($val)-1});
    switch($last) {
        // The 'G' modifier is available since PHP 5.1.0
        case 'g':
            $val *= 1024;
        case 'm':
            $val *= 1024;
        case 'k':
            $val *= 1024;
    }

    return $val;
}

function post_max()
{
	$pm_size = (@ini_get('post_max_size')) ? return_bytes(ini_get('post_max_size')) : 6*1024*1024;
	return $pm_size;
}

function post_maxMb()
{
	return format_size(post_max());
}

//=================================================================
// Laender
//=================================================================
function Countries()
{
	$countries = array();
	$sql = $GLOBALS['db']->Query("SELECT * FROM " . PREFIX . "_laender WHERE Aktiv=1 ORDER BY Name ASC");
	while($row = $sql->fetchrow()) array_push($countries, $row);
	return $countries;
}

//=================================================================
// Navigationen listen 
//=================================================================
function getNavis($a=1)
{
	$navis = array();
	$sql = $GLOBALS['db']->Query("SELECT * FROM ".PREFIX."_navi_cat WHERE Sektion='$a' ORDER BY Name_1 ASC");
	while($row = $sql->fetchrow())
	{
		array_push($navis,$row);
	}
	return $navis;
}

function getNavisWithEntries($a=1)
{
	$navis = array();
	$sql = $GLOBALS['db']->Query("SELECT * FROM ".PREFIX."_navi_cat WHERE Sektion='$a' ORDER BY Name_1 ASC");
	while($row = $sql->fetchrow())
	{
		// 1. Ebene
		$items = array();
		$sql2 = $GLOBALS['db']->Query("SELECT * FROM ".PREFIX."_navi WHERE ParentId='0' AND NaviCat='$row->Id' ORDER BY Titel_1 ASC");
		while($row2 = $sql2->fetchrow())
		{
			array_push($items,$row2);
		}
		$row->Items = $items;
		array_push($navis,$row);
	}
	return $navis;
}

//=================================================================
// Benutzergruppen
//=================================================================
function UserGroups()
{
	$groups = array();
	$sql = $GLOBALS['db']->Query("SELECT Id,Name_Intern,Name FROM ".PREFIX."_benutzer_gruppen ORDER BY Id ASC");
	while($row = $sql->fetchrow())
	{
		array_push($groups,$row);
	}
	return $groups;
}

function umlaut2text($text)
{
	$text = str_replace(array('ü','Ü','ä','Ä','ö','Ö','ß'),array('ue','Ue','ae','Ae','oe','Oe','ss'),$text);
	return $text;
}

// ================================================================
// generiert ein 6- stelliges passwort
// ================================================================
function MakePass($c=0)
{
    $pass = "";
    $chars = array("1", "2", "3", "4", "5", "6", "7", "8", "9", "0",
        "a", "A", "b", "B", "c", "C", "d", "D", "e", "E", "f", "F", "g", "G", "h", "H", "i", "I", "j", "J",
        "k", "K", "l", "L", "m", "M", "n", "N", "o", "O", "p", "P", "q", "Q", "r", "R", "s", "S", "t", "T",
        "u", "U", "v", "V", "w", "W", "x", "X", "y", "Y", "z", "Z");
	$ch = ($c!=0) ? $c : 6;
    $count = count($chars) - 1;
    srand((double)microtime() * 1000000);
    for($i = 0; $i < $ch; $i++) $pass .= $chars[rand(0, $count)];
    return($pass);
}

function WebLink()
{
	return "http://" . $_SERVER['HTTP_HOST'] . str_replace('admin/index.php','',$_SERVER['PHP_SELF']);
}



function SectionSwitchPanel()
{
	if(isset($_SESSION['user_group']) && $_SESSION['user_group']!=2)
	{
		$sections = array();
		$sql = $GLOBALS['db']->Query("SELECT Id,Name FROM ".PREFIX."_sektionen WHERE Id != '" . $_SESSION['a_area'] . "' ORDER BY Id ASC");
		$section = '';
		while($row = $sql->fetchrow())
		{
			$res_p = $GLOBALS['db']->RowQuery("SELECT Rechte_Admin FROM ".PREFIX."_berechtigungen WHERE Sektion='$row->Id' AND Gruppe='" . $_SESSION['user_group'] . "'");
			$perms = explode(',',$res_p->Rechte_Admin);
			if(in_array('all',$perms) || in_array('adminpanel',$perms))
			{
				array_push($sections, $row);
				$section++;
			}
		}
		
		if($section>=1)
		{
			$GLOBALS['tmpl']->assign('sections', $sections);
			$switcher = $GLOBALS['tmpl']->fetch($GLOBALS['config']['source'] . '/navigation/section_switch.tpl');
			return $switcher;
		}
	}
}




function fckInit($fck_value='', $fieldname='', $height='', $type='Default', $expand='true')
{
	$type = (empty($type)) ? 'Default' : $type;
	$height = (empty($height)) ? 450 : $height;
	 

	include_once(BASE_DIR . "admin/editor/fckeditor.php") ;
	
	$oFCKeditor->BasePath = BASE_DIR. "admin/editor/" ;
	$oFCKeditor = new FCKeditor("{$fieldname}") ;
	$oFCKeditor->ToolbarStartExpanded = $expand;
	$oFCKeditor->ToolbarSet = "{$type}" ; 
	$oFCKeditor->Height = "{$height}" ; 
	$oFCKeditor->Value	= "{$fck_value}";
	$field = $oFCKeditor->Create();
	
	return $field;
}

function startsWith($str, $in)
{
	return(substr($in, 0, strlen($str)) == $str);
}


function getThemeByArea($area)
{
	$res = $GLOBALS['db']->RowQuery("SELECT Template FROM ".PREFIX."_sektionen WHERE Id='$area'");
	return $res->Template;
}

//////////////////////////////////////
function getUserCount()
{
	$res = $GLOBALS['db']->RowQuery("SELECT COUNT(Id) AS ResCount FROM ".PREFIX."_benutzer");
	return $res->ResCount;
}

//////////////////////////////////////
function getShopCount()
{
	$res = $GLOBALS['db']->RowQuery("SELECT COUNT(Id) AS ResCount FROM ".PREFIX."_shop_produkte");
	return $res->ResCount;
}

//////////////////////////////////////
function getShopOrderCount()
{
	$res = $GLOBALS['db']->RowQuery("SELECT COUNT(Id) AS ResCount FROM ".PREFIX."_shop_bestellungen");
	return $res->ResCount;
}

//////////////////////////////////////
function clearCache()
{
	if(KOOBIDEMO==1 || !perm('settings'))
	{
		echo $GLOBALS['config_vars']['NoPermAction'];
		
	} else {
		@ini_set("max_execution_time",15);
		$verzname = BASE_DIR . 'cache/';
		$dh = opendir( $verzname );
		$sel = "";
		
		while ( @gettype( $datei = @readdir ( $dh )) != @boolean ){
			if ( is_file( "$verzname/$datei" )){
				if ($datei != "." && $datei != "..") {
					@unlink($verzname . $datei);
				} 
			}
		}
		@closedir( $dh );
		
		del_cache(BASE_DIR . 'uploads/shop/icons_thumbnails/big/');
		del_cache(BASE_DIR . 'uploads/shop/icons_thumbnails/medium/');
		del_cache(BASE_DIR . 'uploads/shop/icons_thumbnails/normal/');
		del_cache(BASE_DIR . 'uploads/shop/icons_thumbnails/small/');
		del_cache(BASE_DIR . 'uploads/shop/icons_thumbnails/xsmall/');
		echo $GLOBALS['config_vars']['Sys_clearcache_ok'];
	}
	exit;
}


function del_cache($f)
{
	$verzname = $f;
	$dh = opendir( $verzname );
	$sel = "";
	
	while ( @gettype( $datei = @readdir ( $dh )) != @boolean ){
		if ( is_file( "$verzname/$datei" )){
			if ($datei != "." && $datei != "..") {
				@unlink($verzname . $datei);
			} 
		}
	}
	@closedir( $dh );
}

function clearTplCache()
{
	if(KOOBIDEMO==1 || !perm('settings'))
	{
		echo $GLOBALS['config_vars']['NoPermAction'];
		
	} else {
		@ini_set("max_execution_time",15);
		$verzname = BASE_DIR . 'compiled/' . $_SESSION['a_area'] .'/';
		$dh = opendir( $verzname );
		$sel = "";
		
		while ( @gettype( $datei = @readdir ( $dh )) != @boolean ){
			if ( is_file( "$verzname/$datei" )){
				if ($datei != "." && $datei != "..") {
					@unlink($verzname . $datei);
				} 
			}
		}
		@closedir( $dh );
		echo $GLOBALS['config_vars']['Sys_clearTplcache_ok'];
		
	}
	exit;
}


//================================================================
// Datenbankfunktionen
//================================================================
function db_size($name) 
{
	$sql = "SHOW TABLE STATUS FROM $name"; 
	if($query = $GLOBALS['db']->Query($sql)) 
	{
		while($result = $query->fetcharray()) 
		{
			$tabledata[] = $result;
		}
	
		$dbsize = 0;
		for($i=0; $i<count($tabledata); $i++)
		{
			$dbsize += $tabledata[$i]["Data_length"] + $tabledata[$i]["Index_length"];
		}
		return @file_size($dbsize/1024);
	}
}

function Tabellen($dbprefix)
{
	$tabellen = "";
		
	$sql = $GLOBALS['db']->Query("SHOW TABLES");
	while ($row = $sql->FetchArray()) 
	{
		$titel = $row[0];
		if (substr($titel, 0, strlen($dbprefix)) == $dbprefix) 
		{
			$titel = ( (defined("KOOBIDEMO") && KOOBIDEMO==1) ? str_replace($dbprefix,'***', $titel) :  $titel);
			$tabellen .= "<option value=\"$titel\" selected>" . $titel . "</option>\n";
		}
	}
	return $tabellen;
}

function Felder($table) 
{
	$res = array();
	$result = $GLOBALS['db']->Query("SHOW FIELDS FROM $table");
	while ($row = $result->fetchrow()) 
	{
		$res[count($res)+1] = $row->Field;
	}
	return $res;
}

//================================================================
// Tabellen fuer den Export auflisten
//================================================================
function TableDef($table)
{
	$result = $GLOBALS['db']->Query("SHOW FIELDS FROM $table");
	$prim_array = '';
	$felder = array();
	$prim = array();
	$res = '';
	while ($row = $result->fetchrow()) 
	{
		if (!$row->Extra=="") 
		{
			$extra = " " . $row->Extra;
		} else {
			$extra = "";
		}
		if ($row->Default=="") 
		{
			$default = " NULL";
		} else {
			$default = " '" . $row->Default . "'";
		}
		if ($row->Key=="PRI") 
		{
			$prim_array[] = "`" . $row->Field . "`";
		}
		
		$felder[count($felder)+1] = "  " . $row->Field . " " . $row->Type . " DEFAULT $default $extra";
	}
	if($prim_array!="")
	{
		$prim[count($prim)+1] = "  PRIMARY KEY (" . @implode(",", $prim_array) . ")";
	}
		
	$res .= "DROP TABLE IF EXISTS `$table`;\n";
	$res .= "CREATE TABLE `$table` (\n";
	$frak = array_merge($felder, $prim);
	for ($i=0; $i<=count($frak)-1; $i++) 
	{
		$res .= $frak[$i];
		if ($i == count($frak)-1) 
		{
			$res .= "\n";
		} else {
			$res .= ",\n";
		}
	}
	$res .= ") TYPE=MyISAM;\n\n";
	$result->close();
	return $res;
}

//================================================================
// Datenbank-Optionen
//================================================================
function db_options($what='',$dbprefix)
{
	if(KOOBIDEMO==1 || !perm('settings'))
	{
		echo $GLOBALS['config_vars']['NoPermAction'];
		exit;
	}
	
	$arr = @$_REQUEST['ta'];
	reset ($arr);
	$tables = '';
	$dump = '';
	
	//================================================================
	// Datenbankbackup erstellen
	//================================================================
	if($what=="dump")
	{
	// dump start
		$arr = $_REQUEST['ta'];
		while (list($key, $val) = each ($arr)) 
		{
			$doit = true;
			if(!ereg("^" . preg_quote($dbprefix), $val)) 
		{
			$doit = false;
		}
		
		if ($doit) 
		{
			$dump .= (TableDef($val));
			$felder = Felder($val);
			$sql = "SELECT * FROM " . $val . "";
			$zeilen = $GLOBALS['db']->Query($sql);
			while ($zrow = $zeilen->fetcharray()) 
			{
				$def = "";
				$cnt = "";
				for ($i=1; $i<=count($felder); $i++) 
				{
					$def .= ", " . $felder[$i];
					$cnt .= ", '" . str_replace("\r\n", '\r\n', addslashes($zrow[$felder[$i]])) . "'";
					
				}
				$def = substr($def, 2);
				$cnt = substr($cnt, 2);
				$dump .= "INSERT INTO `" . $val . "` (" . $def . ") VALUES (" . str_replace('\n','\\n',$cnt) . ");\n";
			}
			$dump .= "\n";
			$zeilen->close();
			}
		}
		//================================================================
		// Dump herunterladen
		//================================================================
		//downloadfile($dump, "koobi_" . KOOBI_VERSION . "_" .  date("d-m-Y") . ".sql", 'text/plain');
	} 
	
	while (list($key, $val) = each ($arr)) 
	{
		$tables .= ", `$val`";
	}
	$tables = substr($tables, 1);
	
	if($what=="optimize")
	{
		$query = "OPTIMIZE TABLE  ";
		$query_msg = $GLOBALS['config_vars']['Sys_db_optimized'];
	}
	if($what=="repair")
	{
		$query = "REPAIR TABLE ";
		$query_msg = $GLOBALS['config_vars']['Sys_db_repaired'];
	}
	$query .= $tables;
	
	
	if ($sql = $GLOBALS['db']->Query($query)) 
	{
		$ok = true;
	} else {
		$ok = false;
	}
	if ($ok) 
	{
		echo $query_msg . $GLOBALS['config_vars']['Sys_errors_no'];
		exit;
	} else {
		echo $query_msg . $GLOBALS['config_vars']['Sys_errors'];
		exit;
	}
	
}


//================================================================
//================================================================
function getLastPostsStartpage($param='')
{
	$lastposts_sp = array();
	$sql_fids = $GLOBALS['db']->Query("SELECT title,forum_id,id,last_post_int FROM " . PREFIX . "_f_topic  ORDER BY id DESC LIMIT 5");
	while($row_fids = $sql_fids->fetchrow())
	{
		$sql_lp = $GLOBALS['db']->Query("SELECT 
			p.id,
		
			p.title,
			p.message,
			p.datum,
			p.topic_id,
			p.uid,
			u.Benutzername as uname,
			u.Regdatum as user_regdate
		FROM 
			" . PREFIX . "_f_post AS p, 
			" . PREFIX . "_benutzer AS u 
		WHERE
			p.topic_id = " . $row_fids->id . " AND 
			u.Id = p.uid 
		GROUP BY
			p.id 
		ORDER BY
			datum DESC
		LIMIT 1;");
		$row_lp = $sql_lp->fetchrow();
		$q_post = "SELECT COUNT(id) as Antworten FROM " . PREFIX . "_f_post WHERE topic_id = '$row_lp->topic_id'";
		$r_post = $GLOBALS['db']->Query($q_post);
		$post = $r_post->fetchrow();
		
		// Zu welcher Seite muss gesprungen werden?
		$numPages = getPageNum($post->Antworten, 15);
		
		$row_fids->Datum = $row_lp->datum;
		
		$row_fids->LpLink = '../index.php?p=showtopic&amp;toid='.$row_lp->topic_id.'&amp;pp=15&amp;page='.$numPages.'#pid_'.$row_lp->id.'';
		$row_fids->LpTitle =  ($row_lp->title == '') ? $row_lp->message : $row_lp->title;
		array_push($lastposts_sp, $row_fids);
		
	}

	$GLOBALS['tmpl']->assign('last_post_array', $lastposts_sp);
	return $GLOBALS['tmpl']->fetch($GLOBALS['config']['source'] . '/forum/lastposts.tpl');
}

function getPageNum($repliesCount, $limit)
{ 
	$limit = (!$limit) ? 15 : $limit;
    if (($repliesCount % $limit) == 0) return $repliesCount / $limit;
    return ($repliesCount + ($limit - ($repliesCount % $limit))) / $limit;
}



function open_page($url,$f=1,$c=2,$r=0,$a=0,$cf=0,$pd=""){
$return='';
 global $oldheader;
 $url = str_replace("http://","",$url);
 if (preg_match("#/#","$url")){
  $page = $url;
  $url = @explode("/",$url);
  $url = $url[0];
  $page = str_replace($url,"",$page);
  if (!$page || $page == ""){
   $page = "/";
  }
  $ip = gethostbyname($url);
 }else{
  $ip = gethostbyname($url);
  $page = "/";
 }
 $open = fsockopen($ip, 80, $errno, $errstr, 60);
 if ($pd){
  $send = "POST $page HTTP/1.0\r\n";
 }else{
  $send = "GET $page HTTP/1.0\r\n";
 }
 $send .= "Host: $url\r\n";
 if ($r){
  $send .= "Referer: $r\r\n";
 }else{
  if (@$_SERVER['HTTP_REFERER']){
   $send .= "Referer: {$_SERVER['HTTP_REFERER']}\r\n";
  }
 }
 if ($cf){
  if (@file_exists($cf)){
   $cookie = urldecode(@file_get_contents($cf));
   if ($cookie){
    $send .= "Cookie: $cookie\r\n";
    $add = @fopen($cf,'w');
    fwrite($add,"");
    fclose($add);
   }
  }
 }
 $send .= "Accept-Language: en-us, en;q=0.50\r\n";
 if ($a){
  $send .= "User-Agent: $a\r\n";
 }else{
  $send .= "User-Agent: {$_SERVER['HTTP_USER_AGENT']}\r\n";
 }
 if ($pd){
  $send .= "Content-Type: application/x-www-form-urlencoded\r\n"; 
  $send .= "Content-Length: " .strlen($pd) ."\r\n\r\n";
  $send .= $pd;
 }else{
  $send .= "Connection: Close\r\n\r\n";
 }
 fputs($open, $send);
 while (!feof($open)) {
  $return .= fgets($open, 4096);
 }
 fclose($open);
 $return = @explode("\r\n\r\n",$return,2);
 $header = $return[0];
 if ($cf){
  if (preg_match("/Set\-Cookie\: /i","$header")){
   $cookie = @explode("Set-Cookie: ",$header,2);
   $cookie = $cookie[1];
   $cookie = explode("\r",$cookie);
   $cookie = $cookie[0];
   $cookie = str_replace("path=/","",$cookie[0]);
   $add = @fopen($cf,'a');
   fwrite($add,$cookie,strlen($read));
   fclose($add);
  }
 }
 if ($oldheader){
  $header = "$oldheader<br /><br />\n$header";
 }
 $header = str_replace("\n","<br />",$header);
 if ($return[1]){
  $body = $return[1];
 }else{
  $body = "";
 }
 if ($c === 2){
  if ($body){
   $return = $body;
  }else{
   $return = $header;
  }
 }
 if ($c === 1){
  $return = $header;
 }
 if ($c === 3){
  $return = "$header$body";
 }
 if ($f){
  if (preg_match("/Location\:/","$header")){
   $url = @explode("Location: ",$header);
   $url = $url[1];
   $url = @explode("\r",$url);
   $url = $url[0];
   $oldheader = str_replace("\r\n\r\n","",$header);
   $l = "&#76&#111&#99&#97&#116&#105&#111&#110&#58";
   $oldheader = str_replace("Location:",$l,$oldheader);
   return open_page($url,$f,$c,$r,$a,$cf,$pd);
  }else{
   return $return;
  }
 }else{
  return $return;
 }
}


?>