<?php
/**
 * Project:   BeCast WebEngine - simple site engine
 * File:      /admin/navigation.apnl.php
 * 
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 * @link http://www.becast.at
 * @copyright 2017 becast.at
 * @author Bernhard Jaud <bernhard at becast dot at>
 * @package BeCast WebEngine core
 * @license http://opensource.org/licenses/gpl-license.php GNU Public License
 * @version $Id: b03e6d4819250bbfd800d481e064e431f32cf46b $
*/
If (!defined("IN_BCWE_ADMIN")) {
    die("Dieses Script kann nicht ausserhalb des Frameworks laufen!");
} 
$addnav["right"]=FALSE;
$session->page_begin("Sort", True);


class navigation_panel extends admin_module{

	function output(){
		global $module,$config,$db,$panel,$cache,$log,$plugin,$mainmodule,$asmodule;
			if(isset($_POST['left']) && !empty($_POST['left'])){
				$order_array = explode('&', $_POST['left']);
				foreach($order_array as $position=>$id) {
					$id=str_replace('left[]=','',$id);
					if($id=='nugget'){
						$db->query("INSERT INTO `" . $config["prefix"] . "navigation` (name,side,sort) VALUES ('HTML-Block','l','".$position."')");
					}elseif(!intval($id)){
						$db->query("INSERT INTO `" . $config["prefix"] . "navigation` (name,side,sort,file) VALUES ('".$db->escape($id)."','l','".$position."','".$db->escape($id)."')");
					}else{
						$db->query("UPDATE `" . $config["prefix"] . "navigation` set side='l',sort='".$position."' WHERE id='".$id."'");
					}
				}
				$cache->update_sidebars();
			}
			if(isset($_POST['right']) && !empty($_POST['right'])){
				var_dump($_POST);
				$order_array = explode('&', $_POST['right']);
				foreach($order_array as $position=>$id) {
					$id=str_replace('right[]=','',$id);
					if($id=='nugget'){
						$db->query("INSERT INTO `" . $config["prefix"] . "navigation` (name,side,sort) VALUES ('HTML-Block','r','".$position."')");
					}elseif(!intval($id)){
						$db->query("INSERT INTO `" . $config["prefix"] . "navigation` (name,side,sort,file) VALUES ('".$db->escape($id)."','r','".$position."','".$db->escape($id)."')");
					}else{
						$db->query("UPDATE `" . $config["prefix"] . "navigation` set side='r',sort='".$position."' WHERE id='".$id."'");
					}
				}
				$cache->update_sidebars();
			}
			if(isset($_POST['main']) && !empty($_POST['main'])){
				$order_array = explode('&', $_POST['main']);
				foreach($order_array as $position=>$id) {
					$id=str_replace('main[]=','',$id);
					if($id=='nugget'){
						$db->query("INSERT INTO `" . $config["prefix"] . "navigation` (name,side,sort) VALUES ('HTML-Block','m','".$position."')");
					}elseif(!intval($id)){
						$db->query("INSERT INTO `" . $config["prefix"] . "navigation` (name,side,sort,file) VALUES ('".$db->escape($id)."','m','".$position."','frontpage_".$db->escape($id)."')");
					}else{
						$db->query("UPDATE `" . $config["prefix"] . "navigation` set side='m',sort='".$position."' WHERE id='".$id."'");
					}
				}	
				$cache->update_sidebars();
			}
			if(isset($_POST['delete'])){
				$id=str_replace('id_','',$_POST['delete']);
				$db->query("DELETE FROM `" . $config["prefix"] . "navigation` WHERE id='".$id."'");
				$cache->update_sidebars();
			}
			if(isset($_GET['editprop']) && $_GET['editprop']!=''){
				if(isset($_POST['send']) && !empty($_POST['name']) && !empty($_POST['id'])){
					$db->query("UPDATE `" . $config["prefix"] . "navigation` set name='".$db->escape($_POST["name"])."',content='".$db->escape(str_replace("&","&amp;",$_POST["content"]))."' WHERE id='".intval($_POST["id"])."'");
					$cache->update_sidebars();
					$panel->admin_message('Daten &uuml;bernommen!','Die Daten wurden erfolgreich &uuml;bernommen.',True,'navigation',3);
				}else{
					$panel->title='Navigationsverwaltung';
					$panel->form(array('action'=>$config['path'].'/admin/index.php?panel=navigation&editprop='.$_GET['editprop']));
					$result=$db->query('SELECT * FROM `' . $config['prefix'] . 'navigation` WHERE id=\''.intval($_GET['editprop']).'\'');
					$data = $db->fetch_array($result);						
					$panel->content.='<h3>Titel:</h3>';
					$panel->field(array('name'=>'name','typ'=>'text','value'=>$data['name']));
					if($data['file']==''){
						$panel->content.='<h3>Inhalt:</h3>';
						$panel->textarea(array('name'=>'content','value'=>$data['content'],'rows'=>20,'cols'=>60));
					}else{
						$panel->content.='<br />Dieses Modul wird von einer Navigationsdatei bereitgestellt.';
					}			
					$panel->content.='<br />';			
					$panel->field(array('name'=>'send','typ'=>'hidden','value'=>'1'));
					$panel->field(array('name'=>'id','typ'=>'hidden','value'=>$_GET['editprop']));
					$panel->submit();
					$panel->formClose();
					$panel->parse_page();
				}
			}elseif(isset($_GET['editmain']) && $_GET['editmain']!=''){
				if(isset($_POST['send']) && !empty($_POST['name']) && !empty($_POST['id'])){
					$db->query("UPDATE `" . $config["prefix"] . "navigation` SET `name`='".$db->escape($_POST["name"])."',`valid`='".$db->escape($_POST["valid"])."',`content`='".$db->escape(str_replace("&","&amp;",$_POST["content"]))."' WHERE `id`='".intval($_POST["id"])."'") or die($db->error());
					$cache->update_sidebars();
					$panel->admin_message('Daten &uuml;bernommen!','Die Daten wurden erfolgreich &uuml;bernommen.',True,'navigation',3);
				}else{
					$panel->title='Navigationsverwaltung';
					$panel->form(array('action'=>$config['path'].'/admin/index.php?panel=navigation&editmain='.$_GET['editmain']));
					$result=$db->query('SELECT * FROM `' . $config['prefix'] . 'navigation` WHERE id=\''.intval($_GET['editmain']).'\'');
					$data = $db->fetch_array($result);						
					$panel->content.='<h3>Titel:</h3>';
					$panel->field(array('name'=>'name','typ'=>'text','value'=>$data['name']));
					$panel->content.='<h3>G&uuml;tigkeitsbereich:</h3>';
					$panel->select(array('&Uuml;berall'=>'E','Startseite'=>'F'),$data['valid'],'valid');
					if($data['file']==''){
						$panel->content.='<h3>Inhalt:</h3>';
						$panel->textarea(array('name'=>'content','value'=>$data['content'],'rows'=>20,'cols'=>60));
					}else{
						$panel->content.='<br />Dieses Modul wird von einer Datei bereitgestellt.';
					}			
					$panel->content.='<br />';			
					$panel->field(array('name'=>'send','typ'=>'hidden','value'=>'1'));
					$panel->field(array('name'=>'id','typ'=>'hidden','value'=>$_GET['editmain']));
					$panel->submit();
					$panel->formClose();
					$panel->parse_page();
				}
				
			}else{
				$left='';
				$right='';
				$main='';
				$asmodule='';
				$mainmodule='';
				$lresult=$db->query("SELECT * FROM `" . $config['prefix'] . "navigation` WHERE side='l' ORDER by sort");
				while ($row = $db->fetch_array($lresult)){
					$left.='<div id="id_'.$row['id'].'" class="lineitem"><a onclick="return deleteItem('.$row['id'].');" href="index.php?panel=navigation&amp;delprop='.$row['id'].'"><img style="float:right;" src="images/icons/cross.png" /></a><a href="index.php?panel=navigation&amp;editprop='.$row['id'].'"><img style="float:right;" src="images/icons/wrench.png" /></a> '.$row["name"].' </div>';
				}
				$rresult=$db->query("SELECT * FROM `" . $config['prefix'] . "navigation` WHERE side='r' ORDER by sort");
				while ($row = $db->fetch_array($rresult)){
					$right.='<div id="id_'.$row["id"].'" class="lineitem"><a  onclick="return deleteItem('.$row['id'].');" href="index.php?panel=navigation&amp;delprop='.$row["id"].'"><img style="float:right;" src="images/icons/cross.png" /></a><a href="index.php?panel=navigation&amp;editprop='.$row["id"].'"><img style="float:right;" src="images/icons/wrench.png" /></a> '.$row["name"].' </div>';
				}
				$mresult=$db->query("SELECT * FROM `" . $config['prefix'] . "navigation` WHERE side='m' ORDER by sort");
				while ($row = $db->fetch_array($mresult)){
					if($row['name']=='maincontent'){
						$main.='<div id="id_'.$row['id'].'" class="fixitem">Seitencontent</div>';
					}else{
						$main.='<div id="id_'.$row['id'].'" class="lineitem"><a  onclick="return deleteItem('.$row['id'].');" href="index.php?panel=navigation&amp;delprop='.$row['id'].'"><img style="float:right;" src="images/icons/cross.png" /></a><a href="index.php?panel=navigation&amp;editmain='.$row["id"].'"><img style="float:right;" src="images/icons/wrench.png" /></a> '.$row["name"].' </div>';
					}
				}
				$av_module=$this->avaiable_modules();
				if(is_array($av_module)){
					foreach($av_module as $module){
						$asmodule.='<div id="module_mod-'.$module.'" class="lineitem">'.$module.' </div>';
					}
				}
				$plugin->run_hook('navigation_mainmodule',array($mainmodule));
				$plugin->run_hook('navigation_leftmodule',array($left));
				$plugin->run_hook('navigation_rightmodule',array($right));
				$panel->title='Navigationsverwaltung';
				$panel->content='Hier kann man die Sortierung von Modulen ver&auml;ndern oder sie anders auf der Seite anordnen.</p>
				<span id="loading" style="display: none">
				     <div class="loadlayer"><img src="images/spinner.gif" alt="Arbeite..." /> Arbeite...</div>
				    </span>

				<div id="page">
					<div id="left" class="section"  style="float:left;width:200px;">
						<h3 class="handle">Links</h3>
						'.$left.'
					</div>

					<div id="main" class="section" style="float:left;width:340px;">
						<h3 class="handle" style="background-color:#F0CF6A;">Hauptseite</h3>
						'.$main.'
					</div>

					<div id="right" class="section" style="float:right;width:200px;">
						<h3 class="handle">Rechts</h3>
						'.$right.'
					</div>
					<br style="clear:both;" />
					<div id="asmodule" class="section" style="float:left;width:200px;">
						<h3 class="handle">Verf&uuml;gbare Module</h3>
						<div id="html_nugget" class="lineitem">HTML-Block</div>
						'.$asmodule.'
					</div>
					<div id="mainmodule" class="section" style="float:right;width:200px;">
						<h3 class="handle" style="background-color:#F0CF6A;">Verf&uuml;gbare Hauptseitenmodule</h3>
						<div id="html_nugget" class="lineitem">HTML-Block</div>
						'.$mainmodule.'
					</div>
				</div>

	<br style="clear:both;" />
					<input type="button" onClick="saveGroupOrder();" value="Speichern" />';
				$panel->foot='<script type="text/javascript">
					// <![CDATA[
					       Sortable.create(\'left\',
					       {tag:\'div\',constraint:\'\',containment: [\'left\',\'right\',\'asmodule\'], dropOnEmpty: true});
					       Sortable.create(\'main\', 
					       {tag:\'div\',constraint:\'\',containment: [\'main\',\'mainmodule\'], dropOnEmpty: true});
						Sortable.create(\'mainmodule\', 
					       {tag:\'div\',constraint:\'\',containment: [\'main\',\'mainmodule\'], dropOnEmpty: true});
					       Sortable.create(\'right\', 
					       {tag:\'div\',constraint:\'\',containment: [\'left\',\'right\',\'asmodule\'], dropOnEmpty: true});
					       Sortable.create(\'asmodule\', 
					       {tag:\'div\',constraint:\'\',containment: [\'left\',\'right\',\'asmodule\'], dropOnEmpty: true});
					// ]]>
				 </script>';
				
		}
	}

	function avaiable_modules() {
		global $config,$db,$panel,$userinfo,$admin,$root,$firephp;
 		$install_mods=array();
		$nav=array();
		$result=$db->query("SELECT * FROM `" . $config['prefix'] . "navigation`");
		while ($row = $db->fetch_array($result)){
			if($row['file']!=''){
				$filename='nav_'.$row['file'].'.php';
				$nav[$filename]=TRUE;
			}
		}	
		$root = $_SERVER['DOCUMENT_ROOT'] . $config['path'];
		if ($dir = @opendir($root.'/nav_modules')){
			while ($file = readdir($dir)){
				if (is_file($root.'/nav_modules/'.$file) && strstr($file, 'nav_') && strstr($file, '.php')){
					if (empty($nav[$file]))
					{
        					$install_mods[] = str_replace('.php', '', $file);
					}
				}
			}
		return $install_mods;
		}
	}

		function meta() {
			global $module,$config,$db,$panel,$userinfo,$admin,$root;
			$meta='<script type="text/javascript" src="'.$config["path"].'/js/scriptaculous/prototype.js"></script>
				<script type="text/javascript" src="'.$config["path"].'/js/scriptaculous/scriptaculous.js"></script>	
				<script type="text/javascript">
				function saveGroupOrder() {
					document.getElementById(\'loading\').style.display = \'\';
					new Ajax.Request(\'index.php?panel=navigation\' , {
					method: "post",
					parameters: {left:Sortable.serialize(\'left\'),main:Sortable.serialize(\'main\'),right:Sortable.serialize(\'right\')}});
					setTimeout("document.getElementById(\'loading\').style.display = \'none\';",1250);
					
					return false;
				}
				
				</script>
				<script type="text/javascript">
				function deleteItem(item) {
					if(confirmLink(this, "Willst du wirklich dieses Modul deinstallieren? Alle Daten diese Moduls werden gel&ouml;scht!")==true){
					name="id_"+item;
					Effect.SwitchOff(name);
					new Ajax.Request(\'index.php?panel=navigation\' , {
					method: "post",
					parameters: {delete:name}});
					}
					return false;
				}
				
				</script>
			<style type="text/css">
				.loadlayer {
					position: absolute;
					padding: 15px;
					width: 250px;
					background: #ffffff;
					border: 3px solid #c90000;
					text-align: center;
					margin-top: 60px;
					left: 50%;
					margin-left: -150px;
					margin-top: 100px;
					font-weight: bold;
					z-index:5;
				}
				div.section,div#createNew {
					border: 1px solid #CCCCCC;
					margin: 30px 5px;
					padding: 0px 0px 10px 0px;
					background-color: #EFEFEF;
				}

				div#createNew input { margin-left: 5px; }

				div#createNew h3, div.section h3{
					font-size: 14px;
					padding: 2px 5px;
					margin: 0 0 10px 0;
					background-color: #CCCCCC;
					display: block;
				}

				div.section h3 {
					cursor: move;
				}

				div.lineitem {
					margin: 3px 10px;
					padding: 2px;
					background-color: #FFFFFF;
					cursor: move;
				}
				
				div.fixitem {
					margin: 3px 10px;
					padding: 2px;
					background-color: #CDCDCD;
				}
				
				h1 {
					margin-bottom: 0;
					font-size: 18px;
				}
			</style>
			<script type="text/javascript">
				function confirmLink(theLink, text)
				{
				// Confirmation is not required in the configuration file
				// or browser is Opera (crappy js implementation)
				if (typeof(window.opera) != \'undefined\') {
				return true;
				}
				
				var is_confirmed = confirm(text);
				if (is_confirmed) {
				if ( typeof(theLink.href) != \'undefined\' ) {
				theLink.href += \'&is_js_confirmed=1\';
				} else if ( typeof(theLink.form) != \'undefined\' ) {
				theLink.form.action += \'?is_js_confirmed=1\';
				}
				}
				
				return is_confirmed;
				} 
				</script>';
			return $meta;
				
		}

	
}
?>
