<?php
page_open(array('sess' => 'dedi_Backend_Session',
                'auth' => 'dedi_Backend_Auth'));

// idcatside suchen
if (!$idcatside) {
	if ($idcat) {
		$sql  = 'SELECT idcatside ';
		$sql .= 'FROM ' . $dedi_db['cat_side'] . ' ';
		$sql .= 'WHERE idcat    = ' . $idcat;
		$sql .= ' AND  is_start = 1 ';
		$sql .= 'LIMIT 0,1';
	} else {
		$sql  = 'SELECT idcatside ';
		$sql .= 'FROM ' . $dedi_db['cat_side'] . ' AS A LEFT JOIN ';
		$sql .=   $dedi_db['cat'] . ' AS B USING(idcat) ';
		$sql .= 'WHERE is_start = 1';
		$sql .= ' AND idclient = ' . $client . ' ';
		$sql .= 'ORDER BY parent, B.sortindex LIMIT 0,1';
	}
	$db->query($sql);
	if ($db->next_record()) $idcatside = $db->f('idcatside');
	else header ('Status: 404 Not Found');
}
$sess->register('sid_idcatside');
$sid_idcatside = $idcatside;
$perm = &new dedi_perms($client, $lang);

// Zeichensatz senden
header('Content-Type: text/html; charset='.$perm->get_lang_charset());

// Seite generieren
if (!defined('IS_DEDI')) die();
include($dedi_path.'inc/fnc.generate_code.php');

//idcat is needed for have_perm()- call
//wenn vom frontend aus eine Kategorie angelegt wird, ist noch keine $idcatside vorhanden
if (!is_int($idcat) && !empty($idcatside)){
	$sql = "SELECT idcat FROM ". $dedi_db['cat_side'] ." WHERE idcatside=$idcatside";
	$db->query($sql);
	if ($db->next_record()) $idcat = $db->f('idcat');
}
// Modus einstellen: editieren/Vorschau/normal
if ($view == 'edit' && ! $perm->have_perm(19, 'side', $idcatside, $idcat)) {
	$dedi_side['next_view'] = 'edit';
	$dedi_side['view'] = 'preview';
} else {
	$dedi_side['next_view'] = $view;
	$dedi_side['view'] = $view;
}

// Editmodus einstellen
if ($dedi_side['view'] == 'edit') $dedi_side['edit'] = 'true';

// Querystring-Parameter Lang ermitteln
$querylang = ($lang != $cfg_client['startlang']) ? 'lang='.$lang.'&': '';

// Aufbau des Arrays $con_tree
$sql = "SELECT B.idcat, B.parent, B.sortindex, C.idcatlang, C.author, C.created, C.lastmodified,
	IF (((C.visible & 0x03) = 0x01) ,'1' ,'0') AS visible,
	IF (((C.visible & 0x04) = 0x00) ,'0' ,'1') AS locked,
	C.idtplconf, C.name, C.description
	FROM ".$dedi_db['cat']." B
	LEFT JOIN ".$dedi_db['cat_lang']." C USING(idcat)
	LEFT JOIN ".$dedi_db['tpl_conf']." D USING(idtplconf)
	LEFT JOIN ".$dedi_db['tpl']." E USING(idtpl)
	WHERE B.idclient='$client'
	AND C.idlang='$lang'
	ORDER BY parent, sortindex";
$db->query($sql, 1, 'frontend_tree');
while($db->next_record()) {
	$idcat_loop = $db->f('idcat');
	$link_loop = $cfg_client['contentfile'] . '?' . $querylang . 'idcat=' . $idcat_loop . '&view=' . $dedi_side['next_view'];
	// sichtbar wenn:
	// online & nicht gesperrt
	// online & frontendzugang und (frontendsehrecht oder eigenes sehrecht) oder (frontendeditierrecht und eigenes editierrecht)
         // online & backendzugang und eigenes sehrecht oder eigenes editierrecht
	// offline & frontendzugang und (frontendeditierrecht und eigenes editierrecht)
         // offline & backendzugang und eigenes editierrecht
	$dedi_backend['visible'] = (($db->f('visible') == 1 && $db->f('locked') == 0)
		|| ($db->f('visible') == 1 && $perm->have_perm('area_frontend') && ($perm->have_perm(2, 'area_frontend', 0) || $perm->have_perm(1, 'cat', $db->f('idcat'))) || ($perm->have_perm(3, 'area_frontend', 0) && $perm->have_perm(19, 'cat', $db->f('idcat'))))
                 || ($db->f('visible') == 1 && $perm->have_perm('area_backend') && ($perm->have_perm(1, 'cat', $db->f('idcat')) || $perm->have_perm(19, 'cat', $db->f('idcat'))))
		|| ($db->f('visible') == 0 && $perm->have_perm('area_frontend') && ($perm->have_perm(3, 'area_frontend', 0) && $perm->have_perm(19, 'cat', $db->f('idcat'))))
                 || ($db->f('visible') == 0 && $perm->have_perm('area_backend') && $perm->have_perm(19, 'cat', $db->f('idcat')))) ? 1 : 0;
	$con_tree[$idcat_loop] = array('idcat'		=>$idcat_loop,
				       'link'         	=>$sess->url($link_loop),
                                        'idcatlang'	=>$db->f('idcatlang'),
                                        'author'		=>$db->f('author'),
                                        'created'	=>$db->f('created'),
                                        'lastmodified'	=>$db->f('lastmodified'),
                                        'parent'		=>$db->f('parent'),
                                        'visible'	=>$dedi_backend['visible'],
                                        'idtplconf'	=>$db->f('idtplconf'),
                                        'description'	=>$db->f('description'),
                                        'name'		=>$db->f('name'));
	$tlo_tree[$db->f('parent')][$db->f('sortindex')] = $idcat_loop;
}
unset($dedi_backend['visible']);
$link_loop = '';
tree_level_order('0', 'catlist');

// Aufbau des Arrays $con_side
if(is_array($con_tree)) {
	$sql = "SELECT D.idcatside, D.idcat, D.sortindex, E.idside, D.is_start, F.user_protected,
		IF ((F.online & 0x03) = 0x01 OR ((F.online & 0x02) = 0x02 AND (UNIX_TIMESTAMP(NOW()) BETWEEN F.start AND F.end)), 1 , 0) AS online,
		IF (((F.online & 0x04) = 0x00) ,'0' ,'1') AS locked,
		F.title, F.idsidelang, F.idtplconf, F.created, F.lastmodified
		FROM ".$dedi_db['cat_side']." AS D
		LEFT JOIN ". $dedi_db['side'] ." AS E USING(idside)
		LEFT JOIN ". $dedi_db['side_lang'] ." AS F USING(idside)
		WHERE E.idclient = '$client'
		AND F.idlang = '$lang'
		ORDER BY D.idcatside";
	$db->query($sql, 1, 'frontend_tree');
	while($db->next_record()) {
		$loop_idcat = $db->f('idcat');
		$loop_idcatside = $db->f('idcatside');
		$con_side[$loop_idcatside]['idcat'] = $loop_idcat;

		// neu angelegte Seiten finden
		if($db->f('sortindex') > 0) {
			$con_side[$loop_idcatside]['sortindex'] = $db->f('sortindex');
			if(!empty($sidelist[$loop_idcat][$db->f('sortindex')])) {
				array_push($sidelist[$loop_idcat], $loop_idcatside);
				$reindex[$loop_idcat] = 1;
		} else $sidelist[$loop_idcat][$db->f('sortindex')] = $loop_idcatside;
		} elseif (is_array($sidelist[$loop_idcat])) {
			$con_side[$loop_idcatside]['sortindex'] = array_push($sidelist[$loop_idcat], $loop_idcatside);
			$reindex[$loop_idcat] = 1;
		} else {
			$sidelist[$loop_idcat] = array($loop_idcatside);
			$con_side[$loop_idcatside]['sortindex'] = 1;
			$reindex[$loop_idcat] = 1;
		}
		// online wenn:
		// online & nicht gesperrt
		// online & frontendzugang und (frontendsehrecht oder eigenes sehrecht) oder (frontendeditierrecht und eigenes editierrecht)
		// online & backendzugang und eigenes sehrecht oder eigenes editierrecht
		// offline & frontendzugang und (frontendeditierrecht und eigenes editierrecht)
		// offline & backendzugang und eigenes editierrecht
		$dedi_backend['online'] = (($db->f('online') == 1 && $db->f('locked') == 0)
			|| ($db->f('online') == 1 && $perm->have_perm('area_frontend') && ($perm->have_perm(2, 'area_frontend', 0) || $perm->have_perm(17, 'side', $db->f('idcatside'), $db->f('idcat'))) || ($perm->have_perm(3, 'area_frontend', 0) && $perm->have_perm(19, 'side', $db->f('idcatside'), $db->f('idcat'))))
			|| ($db->f('online') == 1 && $perm->have_perm('area_backend') && ($perm->have_perm(17, 'side', $db->f('idcatside'), $db->f('idcat')) || $perm->have_perm(19, 'side', $db->f('idcatside'), $db->f('idcat'))))
			|| ($db->f('online') == 0 && $perm->have_perm('area_frontend') && ($perm->have_perm(3, 'area_frontend', 0) && $perm->have_perm(19, 'side', $db->f('idcatside'), $db->f('idcat'))))
			|| ($db->f('online') == 0 && $perm->have_perm('area_backend') && $perm->have_perm(19, 'side', $db->f('idcatside'), $db->f('idcat')))) ? 1 : 0;
		$con_side[$loop_idcatside]['link'] = $sess->url($cfg_client['contentfile'].'?'.$querylang.'idcatside='.$loop_idcatside.'&view='.$dedi_side['next_view']);
		$con_side[$loop_idcatside]['idside'] = $db->f('idside');
		$con_side[$loop_idcatside]['name'] = $db->f('title');
		$con_side[$loop_idcatside]['created'] = $db->f('created');
		$con_side[$loop_idcatside]['lastmodified'] = $db->f('lastmodified');
		$con_side[$loop_idcatside]['online'] = $dedi_backend['online'];
		$con_side[$loop_idcatside]['idsidelang'] = $db->f('idsidelang');
		$con_side[$loop_idcatside]['is_start'] = $db->f('is_start');
		$con_side[$loop_idcatside]['idtplconf'] = $db->f('idtplconf');
		$con_side[$loop_idcatside]['user_protected'] = $db->f('user_protected');
	}
}
unset($dedi_backend['online']);

// neue Seiten einsortieren
if($reindex) {
	foreach (array_keys($reindex) as $kat) {
		ksort($sidelist[$kat]);
		$index = 0;
		foreach ($sidelist[$kat] as $value) {
			$index++;
			$sql = "UPDATE $dedi_db[cat_side] SET sortindex='$index' WHERE idcatside = '$value'";
			$db->query($sql);
		}
	}
    // Navigationstree aus Cache löschen
	$db->delete_cache('frontend_tree');
}

// idcatside prüfen, da der User auch in einer Kategorie sein kann, wo es noch keine seite
// und damit idcatside gibt.
if(! empty($idcatside) ){
	$sql = "SELECT
				meta_author, meta_description, meta_keywords, meta_robots, meta_redirect,
				meta_redirect_url, summary, author, created, lastmodified
			FROM
				".$dedi_db['side_lang']."
			WHERE
				idsidelang= ". $con_side[$idcatside]['idsidelang'];
	$db->query($sql);
	$db->next_record();
	$con_side[$idcatside]['meta_author'] = $db->f('meta_author');
	$con_side[$idcatside]['meta_description'] = $db->f('meta_description');
	$con_side[$idcatside]['meta_keywords'] = $db->f('meta_keywords');
	$con_side[$idcatside]['meta_robots'] = $db->f('meta_robots');
	$con_side[$idcatside]['meta_redirect'] = $db->f('meta_redirect');
	$con_side[$idcatside]['meta_redirect_url'] = $db->f('meta_redirect_url');
	$con_side[$idcatside]['summary'] = $db->f('summary');
	$con_side[$idcatside]['author'] = $db->f('author');
	$con_side[$idcatside]['created'] = $db->f('created');
	$con_side[$idcatside]['lastmodified'] = $db->f('lastmodified');
}

// Artikel wurde vom Redakteur für andere Redakteure zur Bearbeitung gesperrt
//if($con_side[$idcatside]['user_protected'] == '1' && $con_side[$idcatside]['author'] != $perm->user_id && $perm->have_perm('admin') == false) {
//	$dedi_side['view'] = 'preview';
//	unset($dedi_side['edit']);
//}

// $idcat und $idside ermitteln
if (!$idcat) $idcat = $con_side[$idcatside]['idcat'];
if (!$idside) $idside = $con_side[$idcatside]['idside'];


// Inhalt erstellen zum editieren der Seite
if(isset($dedi_side['view'])) {
	// es existiert noch keine Seite in diesem Ordner
	if(!$idcatside) unset($dedi_side['edit']);

	include($dedi_path.'inc/fnc.tpl.php');
	include($dedi_path.'inc/fnc.type.php');
	include($dedi_path.'inc/fnc.con_edit.php');
	include($dedi_path.'inc/inc.con_edit.php');
}

// Konfigurationslayer erstellen
$con_side[$idcatside]['config'] = generate_configlayer();

// Seite ausgeben
if ($code) {
	//redirect is active
	if($con_side[$idcatside]['meta_redirect'] == '1' && $con_side[$idcatside]['meta_redirect_url'] != '') {
		header ('Status: 302 Moved Temporarily');
		if (is_numeric($con_side[$idcatside]['meta_redirect_url'])){
			header ('Location: '.str_replace('&amp;', '&', $con_side[$con_side[$idcatside]['meta_redirect_url']]['link']));
		} else header ('Location: '.str_replace('&amp;', '&',$con_side[$idcatside]['meta_redirect_url']));
	}
	// throw out side
	else{

		eval('?>'.$code);

		$code = ob_get_contents ();
		ob_end_clean ();
		ob_start();
		// Links ersetzen
		// Dateilinks suchen:
		preg_match_all("!http://dedilink/fileid=(\d+)!", $code, $internlinks);
		$sql_links = implode(',', $internlinks[1]);
		if ($sql_links != '') {
			$sql = "SELECT
						A.idupl id, A.filename filename,B.dirname dirname
					FROM
						".$dedi_db['upl']." as A
						LEFT JOIN ". $dedi_db['directory'] ." as B USING(iddirectory)
					WHERE
						A.idclient=$client
						AND A.idupl IN ($sql_links)";
			$db->query($sql, 1, 'frontend_content');
			while($db->next_record()){
				$dedi_file[$db->f('id')] = $cfg_client['upl_htmlpath'].$db->f('dirname').$db->f('filename');
			}
		}
		//Links ersetzen
		$in = array("'http://dedilink/fileid=(\d+)'e",
			    "!http://dedilink/idcat=(\d+)!e",
			    "!http://dedilink/idcatside=(\d+)!e",
                             "!http://dedilink/temp_fileid=(\d+)!",
                             "!http://dedilink/temp_idcat=(\d+)!",
                             "!http://dedilink/temp_idcatside=(\d+)!");
		$out = array('\$dedi_file[\\1]',
			     '\$con_tree[\\1][\'link\']',
			     '\$con_side[\\1][\'link\']',
                              "http://dedilink/fileid=\\1",
                              "http://dedilink/idcat=\\1",
                              "http://dedilink/idcatside=\\1");
		$code = preg_replace($in, $out, $code);
		echo $code;

	}
}
else{
	if($cfg_client['errorpage'] != '0' && $cfg_client['errorpage'] != $idcatside){
		header ('Location: '.str_replace('&amp;', '&', $con_side[ $cfg_client['errorpage'] ]['link']));
	} else{
		header ('Status: 404 Not Found');
		exit;
	}

}

unset($code);
?>