<?php
// ======================================================================== //
//   KOOBI - CMS                                                            //
//   SCRiPTMAFiA 2005 - THE DiRTY HANDS ON YOUR SCRiPTS                     //
//                                                                          //
//   DREAM4 - AM MICHELSGRUND 7 - 69469 WEINHEIM - GERMANY                  //    
//   TEL. +49(0) 6201 - 980442 / FAX. +49(0) 6201 - 64809                   //
// ======================================================================== //
if(!checkactive(download)) include(dirname(__FILE__)."/lib/notactive.php" );

if (!permission('candownload')) {
	$EOUT = stderror("nopermission", $lang['nopermission_t'], str_replace("__URL__", "index.php", $lang['redirect']), "index.php", 1);
	$error = 1;
	$NOOUT = 1;
}

$getid = ($_REQUEST['parent']!="") ? escs($_REQUEST['parent']) : 0 ;
$extra = ($_REQUEST['categ']!="") ? escs($_REQUEST['categ']) : 0 ;

//=====================================================================
// <<-- PRUEFEN OB DER BENUTZER DIE BERECHTIGUNG HAT -->>
//=====================================================================
$group_ids = array();

// =====================================================================================
// miscrechte
// =====================================================================================
if (@is_numeric(UID)) {
	$queryfirst = "SELECT group_id_misc FROM " . PREFIX . "_user WHERE uid = " . UID;
	$result = new dbc($queryfirst);
	$user = $result->fetchrow();
	
	// wenn misc nicht leer ist...
	if($user->group_id_misc != ""){
		$group_ids_pre = UGROUP . ";" . $user->group_id_misc;
		$group_ids     = @explode(";", $group_ids_pre);
		
		// wennn misc leer ist und user eingeloggt ist
	} else {
		$group_ids[] = UGROUP;
	}
	// wenn user nicht eingeloggt ist
	} else {
	$group_ids[] = 2;
}
// =====================================================================================

//=====================================================================
// <<-- DATEIEN AUSLESEN UND IN ARRAY VERFRACHTEN -->>
//=====================================================================
$searchstring = kspecialchars(escs($_REQUEST['qdownload']));

if(strlen($searchstring) >=3 ) {
	
	$sql = new dbc("SELECT ctime,size,hits,title,id,password,catid FROM " . PREFIX . "_downloads WHERE title like '%$searchstring%' or text like '%$searchstring%' AND active='1'");
	$results = array();
	
	while($item= $sql->fetchrow()){
		$query = new dbc("SELECT group_id FROM " . PREFIX . "_downloadcat WHERE catid = '$item->catid'");
		
		$row = $query->fetchrow();
		$g_array = @explode(",", $row->group_id);
		
		if (array_intersect($group_ids, $g_array)) {
				$item->size = file_size($item->size);
				$item->ctime = mygmt($item->ctime);
				array_push($results, $item);
			}
		}
		
		$tmpl->assign('qdownload', stripslashes($searchstring));
		$tmpl->assign('results', $results);
		$tmpl->assign('showsearch', 1);
		
	} else {
		
		//=====================================================================
		// <<-- KATEGORIEN AUSLESEN (GRUPPEN WERDEN BERÜCKSICHTIGT) -->>
		//=====================================================================
		$dlcat = array();
		getDownloadcategs($getid, '', $dlcat, $area, $extra);
		
		switch($_REQUEST['sort']){
			case "" :
			case "date" :
			$sort = " ORDER BY ctime DESC";
			break;
			
			case "hits" :
			$sort = " ORDER BY hits DESC";
			break;
			
			case "name" :
			$sort = " ORDER BY title ASC";
			break;
			
			case "size" :
			$sort = " ORDER BY size DESC";
			break; 
		}
		
		switch($_REQUEST['ascdesc']){
			case '':
			case 'desc':
			$ascdesc = " DESC";
			break;
			
			case 'asc':
			$ascdesc = " ASC";
			break;
		}
		
		$limit = ($_REQUEST['pp']!='') ? (int)$_REQUEST['pp'] : 15 ;
		$sql_first = new dbc("SELECT id FROM " . PREFIX . "_downloads WHERE catid = '".escs($_REQUEST['categ'])."' AND active='1' ");
		$num = $sql_first->numrows();
		
		$seiten = ceil($num / $limit);
		$a = prepage() * $limit - $limit;
		
		$sql = new dbc("SELECT gallery,password,ctime,id,catid,title,hits,size FROM " . PREFIX . "_downloads WHERE catid = '".escs($_REQUEST['categ'])."' AND active='1' $sort $sascdesc limit $a,$limit");
		$files = array();
		
		// wenn es mehr Datensaetze gibt, als Limit erlaubt, Navi erzeugen...
		if($num > $limit){
			$tmpl->assign('nav', pagenav($seiten, $lang['aktpos'], " <a class=\"page_navigation\" href=\"index.php?sort=$_REQUEST[sort]&amp;pp=$_REQUEST[pp]&amp;categ=$_REQUEST[categ]&amp;parent=$_REQUEST[parent]&amp;p=downloads&amp;area=$_REQUEST[area]&amp;page={s}\">{t}</a> "));
			}
		
		// gruppenberechtigungen auslesen
		while($row = $sql->fetchrow()){
			$query = new dbc("SELECT group_id FROM " . PREFIX . "_downloadcat WHERE catid = '$row->catid'");
			$row_file = $query->fetchrow();
			$g_array = @explode(",", $row_file->group_id);
			
			if (array_intersect($group_ids, $g_array)) {
				$row->size = file_size($row->size);
				$row->ctime = mygmt($row->ctime);
				array_push($files, $row);
			}
		}
	}
	
	$tmpl->assign('dlcat', $dlcat);
	$tmpl->assign('catid', $_REQUEST['categ']);
	$tmpl->assign('files',$files);
	$tmpl->assign('lang',$lang);
	$tmpl->assign('area',$area);
	$tmpl->assign('ugroup',UGROUP);
	$tmpl->register_function('in_array', 'in_array');
	$tmpl->register_function('getdownloads', 'getdownloads');
	$tmpl->register_function('file_size', 'file_size');
	
	//=====================================================================
	// <<-- DATEI- DETAILS -->>
	//=====================================================================
	if($_REQUEST['showfile']==1) { 
		// ====================================================================================
		// <<-- KANN DOWNLOAD KOMMENTIERT WERDEN? -->>
		// ====================================================================================
		$sql = new dbc("SELECT cancomment FROM " . PREFIX . "_downloads WHERE id = '".escs($_REQUEST['fid'])."'");
		$row = $sql->fetchrow();
		if($row->cancomment == 1){
			// ====================================================================================
			// <<-- KOMMENTAR EINTRAGEN -->>
			// ====================================================================================
			$sql = new dbc("SELECT spamprotect,spamprotect_time,mailbycomment FROM " . PREFIX . "_settings");
			$row_spam = $sql->fetchrow();
			
			if($_REQUEST['post']==1){
				// ====================================================================================
				// <<-- WURDE DER SPAMSCHUTZ AKTIVIERT? -->>
				// ====================================================================================
				if($row_spam->spamprotect==1){
					$sql = new dbc("SELECT ip,ctime FROM ".PREFIX."_downloadcomments WHERE ip='".$_SERVER['REMOTE_ADDR']."' AND dlid='".$_REQUEST['fid']."' ORDER BY id DESC limit 1");
					
					$row = $sql->fetchrow();
					if($row){
						if( ($row->ctime) + (60*$row_spam->spamprotect_time) > time()){
							
							$EOUT = msg("spamprotect","spamprotect_text", str_replace("__URL__", "index.php?showfile=1&fid=$_REQUEST[fid]&p=downloads&area=$_REQUEST[area]&categ=$_REQUEST[categ]", $lang['redirect']), "index.php?showfile=1&fid=$_REQUEST[fid]&p=downloads&area=$_REQUEST[area]&categ=$_REQUEST[categ]");
							$NOOUT = 1;
							$error = 1;
						}
					}
				}
				
				// ====================================================================================
				// <<-- WENN NICHT IN SPAMSCHUTZ- ZEIT, KOMMENTAR EINTRAGEN -->>
				// ====================================================================================
				if(!$error){
					// ====================================================================================
					// <<-- WENN MAIL GESENDET WERDEN SOLL -->>
					// ====================================================================================
					if($row_spam->mailbycomment == 1){
						$adminlink = "http://" . $_SERVER['HTTP_HOST'] . str_replace("/index.php","",$_SERVER['PHP_SELF']) . "/admin/downloads.php?area=$_REQUEST[area]&action=comments&id=$_REQUEST[id]";
						$path = dirname(__FILE__);
						include($path ."/lib/mailbycomment.php" );
					}
					
					$text = formtext($_POST['text'],$MAXCOMMLENGTH);
					$sql = new dbc("
					INSERT INTO ".PREFIX."_downloadcomments(
					id,
					dlid,
					ctime,
					autor,
					title,
					comment,
					ip
					) VALUES (
					'',
					'".escs($_REQUEST['fid'])."',
					'".time()."', 
					'".$UID."',
					'".iform($_POST['title'],"255","")."',
					'".$text."',
					'".$_SERVER['REMOTE_ADDR']."'
					) 
					");
					$EOUT = msg("thankyou","pollcomments_thanks", str_replace("__URL__", "index.php?showfile=1&fid=$_REQUEST[fid]&p=downloads&area=$_REQUEST[area]&categ=$_REQUEST[categ]", $lang['redirect']), "index.php?showfile=1&fid=$_REQUEST[fid]&p=downloads&area=$_REQUEST[area]&categ=$_REQUEST[categ]");
					$NOOUT = 1;
				}
			}
			
			$limit = limit();
			if( !isset($_REQUEST['sort']) && $_REQUEST['sort']!="desc" && $_REQUEST['sort']!="asc" ){
				$sorts = "desc";
				$_REQUEST['sort'] = "desc";
			} else {
				$sorts = $_REQUEST['sort'];
				$_REQUEST['sort'] = $_REQUEST['sort'];
			}
			
			
			
			$sql =& new dbc("SELECT id FROM ".PREFIX."_downloadcomments WHERE  dlid='".escs($_REQUEST['fid'])."'");
			$num = $sql->numrows();
			
			
			$seiten = ceil($num / $limit);
			$a = prepage() * $limit - $limit;
			
			$sql =& new dbc("SELECT * FROM ".PREFIX."_downloadcomments WHERE  dlid='".escs($_REQUEST['fid'])."' ORDER BY id $sorts limit $a,$limit");
			$erg = $sql->numrows();
			
			
			$path = dirname(__FILE__);
			require_once($path ."/lib/pagesobjects.php" );
			require_once($path ."/lib/commentobjects.php" );
			
			// ====================================================================================
			// <<-- SEITEN- NAVIGATION KOMMENTARE -->>
			// ====================================================================================
			if($num>$limit){ $nav = pagenav($seiten, $lang['aktpos'], " <a class=\"page_navigation\" href=\"index.php?nav=1&amp;showfile=1&fid=$_REQUEST[fid]&p=downloads&area=$_REQUEST[area]&categ=$_REQUEST[categ]&amp;pp=$limit&amp;sort=$_REQUEST[sort]&amp;page={s}\">{t}</a> "); }
			
			$tmpl->assign('pages', $nav);
			$tmpl->assign('guest', $lang['guest']);
			$tmpl->assign('comments_array', $comments_array);
			$tmpl->assign('comments', parsetrue('container/'.container('comments'), $lang['newscomments'], $tmpl->fetch('comments/comments.tpl')));
			
			// ====================================================================================
			// <<-- DARF BENUTZER KOMMENTIEREN? -->>
			// ====================================================================================
			if(permission('download_comment')){
				$tmpl->assign('comment', $lang['commentonce']);
				$tmpl->assign('formlink', "index.php?docomment=1&amp;showfile=1&amp;fid=$_REQUEST[fid]&amp;p=downloads&amp;area=$_REQUEST[area]&amp;categ=$_REQUEST[categ]&amp;post=1");
				
				// ====================================================================================
				// <<-- HIER WIRD UEBERPRUEFT, OB SMILIES ODER BB- CODE VERWENDET WERDEN DARF -->>
				// ====================================================================================
				if(COMMENTSMILEYS == 1) {
					$tmpl->assign('smilie', 1);
					$tmpl->assign('listemos', $smilies);
				}
				
				if (COMMENTSBBCODE == 1) {
					$tmpl->assign('bbcodes', 1);
				}
				
				if($_REQUEST['print']!=1){
					$tmpl->assign('lang', $lang);
					$tmpl->assign('commentform', parsetrue('container/'.container('comments'), $lang['postcomment'], $tmpl->fetch('comments/commentform.tpl')));
				}
			}
			
			if(!permission('download_comment')){
				$tmpl->assign('commentform', $tmpl->fetch('comments/commentform_false.tpl'));
			}
		}
		$tmpl->assign('numcomm', $numcomm);
		
		// ====================================================================================
		// <<-- KANN DOWNLOAD KOMMENTIERT WERDEN? ENDE -->>
		// ====================================================================================
		
		// ===============================================================
		// <<-- HIER WIRD VERSUCHT, DEN BESTMÖGLICHSTEN KOMPROMIS ZU FINDEN, 
		//      DER KEINE COOKIES BENÖTIGT. ES WIRD DIE IP, SOWOHL DIE USER-
		//      ID DES BESUCHERS GESPEICHERT.  -->>
		// ===============================================================
		if( ($_REQUEST['vote']==1) && (is_numeric($_REQUEST['voting'])) &&  ($_REQUEST['voting'] <= 8) ){
			$sql = new dbc("SELECT canvote,votes_ip,votes_uid FROM " . PREFIX . "_downloads WHERE id = '$_REQUEST[fid]'");
			$row = $sql->fetchrow();
			if($row->canvote==1){
				$votes_ip = explode(";", $row->votes_ip);
				$votes_uid = explode(";", $row->votes_uid);
				
				if ( (@in_array($_SERVER['REMOTE_ADDR'], $votes_ip )) || (@in_array(UID, $votes_uid)) ) {
					$canvote = -1;
				} else { $canvote = 1; } ;
				if($canvote == 1){
					$sql = new dbc("UPDATE " . PREFIX . "_downloads set  votes_data= votes_data+$_REQUEST[voting],  votes=votes+1  WHERE id = '$_REQUEST[fid]'");
					if(UGROUP != 2) { 
						$zusatz = " , votes_uid = CONCAT(votes_uid, ';', '" . UID . "')";
					}
					$sql = new dbc("UPDATE " . PREFIX . "_downloads SET
					votes_ip = CONCAT(votes_ip, ';', '" . $_SERVER['REMOTE_ADDR'] . "') 
					$zusatz 
					WHERE id = $_REQUEST[fid]");
					header("Location:index.php?showfile=1&fid=$_REQUEST[fid]&p=downloads&area=$_REQUEST[area]&categ=$_REQUEST[categ]");
					
				} else {
					header("Location:index.php?showfile=1&fid=$_REQUEST[fid]&p=downloads&area=$_REQUEST[area]&categ=$_REQUEST[categ]");
				}
			}
		}
		
		//=====================================================================
		// <<-- DETAIL AUSGEBEN -->>
		//=====================================================================
		$today = date("dmY", time());
		$sql = new dbc("SELECT today FROM " . PREFIX . "_downloads WHERE id = '$_REQUEST[fid]'");
		$row_to = $sql->fetchrow();
		if($row_to->today != $today) {
			$sql = new dbc("UPDATE " . PREFIX . "_downloads set today='$today', hits_today='0' WHERE id = '$_REQUEST[fid]'");
		}
		
		$sql = new dbc("SELECT * FROM " . PREFIX . "_downloads WHERE catid='".$_REQUEST['categ']."' and id='".$_REQUEST['fid']."' "); 
		$row_f = $sql->fetchrow();
		
		$row_f->text = autowords($row_f->text);
		$row_f->text = high($row_f->text);
		$tmpl->assign('traffic',file_size($row_f->size*$row_f->hits));
		$tmpl->assign('traffic_today',file_size($row_f->size*$row_f->hits_today));
		$tmpl->assign('hits_left',($row_f->hits_perday-$row_f->hits_today));
		$tmpl->assign('row_f',$row_f);
		$tmpl->assign('size',$row_f->size);
		$tmpl->assign('sizedetail',file_size($row_f->size));
		$thenav_extra = SEPARATOR . $row_f->title;
		
		//=====================================================================
		// <<-- BEWERTUNGS- DROPDOWN -->>
		//=====================================================================
		$lang['pvoting'] = ",".$lang['pvoting'];
		$langpvote = explode(",",$lang['pvoting']);
		while (list($key, $value) = each ($langpvote)) {
			if($value){
				$pvote[$value]['val'] = $value;
				$pvote[$value]['key'] = $key;
			}
		}
		$tmpl->assign('pvote',$pvote);
		//=====================================================================
		// <<-- BEWERTUNGS- GRAFIK -->>
		//=====================================================================
		if($row_f->votes_data>0) { 
			$data = round($row_f->votes_data/$row_f->votes);
			$tmpl->assign('votedata', $data);
			$visitor_vote = explode(",", $lang['pvoting']);
			$visitor_vote = $visitor_vote[($data)];
			$tmpl->assign('vvote', $visitor_vote);
		}
		
		
		//=====================================================================
		// <<-- DOWNLOADZEITEN ERMITTELN -->>
		//=====================================================================
		function download_time($param) {
			global $row_f, $lang, $THEME, $lang, $area;
			$tmpl = new Koobi("templates/$THEME/download/");
			function sec_format($seconds) {
				global $row_f, $lang;
				$units = array( "$lang[day_o];$lang[day_extension]"=>86400,
				"$lang[hour_o];$lang[minutes_seconds_hours_extension]"=>3600,
				"$lang[minute_o];$lang[minutes_seconds_hours_extension]"=>60,
				"$lang[second_o];$lang[minutes_seconds_hours_extension]"=>1
				);
				if($seconds < 1) {
					return "< 1 $lang[second_o]";
				} else {
					$show = FALSE;
					$ausg = "";
					foreach($units as $key=>$value) {
						$t = round($seconds/$value);
						$seconds = $seconds%$value;
						list($s, $pl) = explode(";", $key);
						if($t > 0 || $show) {
							if($t == 1) {
								$ausg .= $t." ".$s.", ";
							} else {
								$ausg .= $t." ".$s.$pl.", ";
							}
							$show = TRUE;
						}
					}
					$ausg = substr($ausg, 0, strlen($ausg)-2);
					return $ausg;
				}
			}
			$values = array("DSL 3000"=>3000,
			"DSL 2000"=>2000,
			"DSL 1500"=>1500,
			"DSL 1000"=>1000,
			"DSL 768"=>768,
			"ISDN"=>128,
			"Modem"=>56.6
			);
			$size = $param['size']; 
			$size = $size * 1024;
			$size *= 8;
			$i = 0;
			foreach($values as $key=>$value) {
				$dltime[$i]['time'] = sec_format($size/($value*1024));
				$dltime[$i]['valspeed'] = $value;
				$dltime[$i]['valsys'] = $key;
				$i++;
			}
			$tmpl->assign('theme', $THEME);
			$tmpl->assign('theme', $THEME);
			$tmpl->assign('dltime', $dltime);
			$downloadtime = $tmpl->fetch('time.tpl');
			return $downloadtime;
		}
		
	}
	
	if($row_f->platform) $tmpl->assign('platform', fetch_platform($row_f->platform,1)); 
	if($row_f->gallery) $tmpl->assign('linkedgaleries', fetch_gallery($row_f->gallery));  
	$tmpl->register_function('downloadtimes', 'download_time');
	$tmpl->register_function('permission', 'permission');
	//=====================================================================
	// <<-- SEITENTITEL UND KOPF- NAVIGATION -->>
	//=====================================================================
	if($extra) $thenav = getNavigationPath($_REQUEST['categ'], 'downloadcat', 'downloads', 'categ','catid','catname', '','1');
	$dlid = ($_REQUEST['categ']!="") ? $_REQUEST['categ'] : 0;
	$sname = ($_REQUEST['categ']!="") ? simpletitle($lang['downloads'] . SEPARATOR . getNavigationptitle($dlid, 'downloadcat', 'downloads', '','catid','catname')) . $thenav_extra : simpletitle($lang['downloads'],$title);
	$headtitle = (!$_REQUEST['categ']) ? $lang['download_overviews'] : "<a class=\"boxnavi\" href=\"index.php?p=downloads&amp;area=".$area."\">" . $lang['download_overviews'] . "</a>" . SEPARATOR;
	
	$tmpl->assign('headernav', $headtitle . $thenav . $thenav_extra );
	
	//=====================================================================
	// <<-- AUSGABE -->>
	//=====================================================================
	$tmpl->assign('content', parsetrue('container/'.container('download_in'), $lang['downloads'], $tmpl->fetch('download/main.tpl')));
	
	?>