<?
// | Last update : 2005-11-24        - Bugfix for multibyte charsets
// | Part of     : Update to Version 01.00.02
// +----------------------------------------------------------------------+
// | Der Dirigent 1.0                                                     |
// +----------------------------------------------------------------------+
// | Copyright (c) 2003-2004 the dedi-group <dedi-group@der-dirigent.de>  |
// +----------------------------------------------------------------------+
// | This program is free software; you can redistribute it and/or modify |
// | it under the terms of the GNU General Public License                 |
// |                                                                      |
// | This program is subject to the GPL license, that is bundled with     |
// | this package in the file LICENSE.TXT.                                |
// | If you did not receive a copy of the GNU General Public License      |
// | along with this program write to the Free Software Foundation, Inc., |
// | 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA               |
// |                                                                      |
// | This program 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 General Public License for more details.                         |
// |                                                                      |
// +----------------------------------------------------------------------+
// | Authors: Roland Braband <stam@der-dirigent.de>,                      |
// |          Björn Brockmann <björn@der-dirigent.de>                     |
// |          Paul Eppner <paul@twomoons.de>                              |
// |          Sven Bräutigam <sven777b@der-dirigent.de>                   |
// +----------------------------------------------------------------------+

/**
 * 1. Benötigte Funktionen und Klassen includieren
 */

include('inc/fnc.tpl.php');
include('inc/fnc.mipforms.php');

/**
 * 2. Eventuelle Actions/ Funktionen abarbeiten
 */

//um den Bereich betreten zu dürfen, muß das Recht bearbeiten gesetzt sein
if(is_numeric($idtpl)) $perm->check(3, 'tpl', $idtpl);
else $perm->check(3, 'area_tpl', 0);

switch($action) {
	case 'save':  // Template bearbeiten
		$errno = tpl_save($idtpl, $idlay, $tplname, $description, $tpl_overwrite_all);
		if (!$errno) {
			header ('Status: 302 Moved Temporarily');
			header ("Location:".$sess->url("main.php?area=tpl"));
			exit;
		}
		break;
	case 'change':  // Layout oder Modul wechseln
		$cconfig = tpl_change($idlay);
		remove_magic_quotes_gpc($tplname);
		remove_magic_quotes_gpc($description);
		$tplname = htmlspecialchars($tplname);
		$description = htmlspecialchars($description);
		break;
}

/**
 * 3. Eventuelle Dateien zur Darstellung includieren
 */

include('inc/inc.header.php');

/**
 * 4. Bildschirmausgabe aufbereiten und ausgeben
 */

echo "<center>\n";
echo "<table cellspacing=\"0\" cellpadding=\"0\" border=\"0\" width=\"98%\">\n";
echo "  <tr>\n";
echo "    <td>&nbsp;".$dedi_lang['area_tpl_edit']."&nbsp;";
if ($errno) echo "&nbsp;<span class=\"errormsg\">".$dedi_lang["err_$errno"]."</span>&nbsp;";
echo "</td>\n";
echo "  </tr>\n";
echo "  <tr>\n";
echo "    <td colspan=\"2\"><br>\n";

// Templateeinstellungen suchen
if ($idtpl && (!$idlay || $idlay == '0')) {
	// Template suchen
	$sql = "SELECT A.name, A.description, B.idlay
		FROM ". $dedi_db['tpl'] ." A
		LEFT JOIN ". $dedi_db['lay'] ." B using(idlay)
		WHERE A.idtpl='$idtpl'";
	$db->query($sql);
	$db->next_record();
	$tplname = htmlspecialchars($db->f('name'));
	$description = htmlspecialchars($db->f('description'));

	// Template zurücksetzen
	if ($idlay < 1) {
		$idlay = $db->f('idlay');
		$list = browse_layout_for_containers($idlay);
		if (is_array($list)) {
			foreach ($list['id'] as $value) unset(${'c'.$value});
		}
	} else $idlay = $db->f('idlay');

	// Containereinstellungen suchen
	$sql = "SELECT A.container, A.idmod, B.config, B.view, B.edit, C.input
                FROM $dedi_db[container] A
                LEFT JOIN $dedi_db[container_conf] B USING(idcontainer)
                LEFT JOIN $dedi_db[mod] C ON A.idmod=C.idmod
                WHERE A.idtpl='$idtpl' AND B.idtplconf='0'";
	$db->query($sql);
	while ($db->next_record()) {
		${'c'.$db->f('container')} = $db->f('idmod');
		${'cview'.$db->f('container')} = $db->f('view');
		${'cedit'.$db->f('container')} = $db->f('edit');
		${'cconfig'.$db->f('container')} = $db->f('config');
	}

// Templateeinstellungen übernehmen
} else {
	if (is_array($cconfig)) {
		foreach ($cconfig as $key => $value) {
			if ($changed != $key) ${'cconfig'.$key} = $value;
		}
	}
}

// Layoutbeschreibung raussuchen
$sql = "SELECT idlay, name, description
        FROM $dedi_db[lay]
        WHERE idclient='$client'
        ORDER BY name";
$db->query($sql);
while ($db->next_record()) {
	$lay['id'][] = $db->f('idlay');
	$lay[$db->f('idlay')]['name'] = $db->f('name');
	$lay[$db->f('idlay')]['description'] = $db->f('description');
}

// Modulliste erstellen
if ($idlay) {
	$sql = "SELECT idmod, cat, name, input, config, version, verbose, cat, source_id, idmod
                FROM $dedi_db[mod]
                WHERE idclient='$client'
                ORDER BY cat, name";
	$db->query($sql);
	while ($db->next_record()) {
		$mod['id'][] = $db->f('idmod');
		if ($db->f('cat') != '') $mod[$db->f('idmod')]['cat'] = $db->f('cat'). ':&nbsp;';
		$mod[$db->f('idmod')]['name'] = htmlspecialchars($db->f('name'));
		$mod[$db->f('idmod')]['input'] = $db->f('input');
		$mod[$db->f('idmod')]['config'] = $db->f('config');
		$mod[$db->f('idmod')]['version'] = htmlspecialchars($db->f('version'));
		$mod[$db->f('idmod')]['verbose'] = htmlspecialchars($db->f('verbose'));
                $mod[$db->f('idmod')]['cat'] = htmlspecialchars($db->f('cat'));
                $mod[$db->f('idmod')]['source_id'] = htmlspecialchars($db->f('source_id'));
                $mod[$db->f('idmod')]['idmod'] = htmlspecialchars($db->f('idmod'));
	}
}

// Template dublizieren
if($action == 'duplicate') {
	$idtpl_for_form = '';
	$tplname = $dedi_lang['tpl_copy_of'].$tplname;
	unset($idtpl);
} else $idtpl_for_form = $idtpl;

// Formular zur Templatebearbeitung
echo "    <form name=\"editform\" method=\"post\" action=\"".$sess->url("main.php?area=tpl_edit&idtpl=$idtpl_for_form#edit_container")."\">\n";
echo "    <input type=\"hidden\" name=\"action\" value=\"save\">\n";
echo "    <input type=\"hidden\" name=\"anchor\" value=\"\">\n";
echo "    <table cellpadding=\"$cellpadding\" cellspacing=\"$cellspacing\" border=\"$border\">\n";
echo "      <tr valign=\"top\">\n";
echo "        <td class=\"head\" width=\"110\" nowrap>&nbsp;".$dedi_lang['tpl_templatename']."&nbsp;</td>\n";
echo "        <td class=\"content\"><input type=\"text\" name=\"tplname\" value=\"$tplname\" size=\"90\" style=\"width:640\"></td>\n";
echo "      </tr>\n";

// rechte management
if (!empty($idtpl) && $action != 'duplicate' && $perm->have_perm(6, 'tpl', $idtpl)) {
	$panel = $perm->get_right_panel('tpl', $idtpl, array( 'formname'=>'editform' ), 'text');
	if (!empty($panel)) {
		echo "      <tr>\n";
		echo "        <td class=\"head\">&nbsp;" . $dedi_lang['gen_rights'] . "&nbsp;</td>\n";
		echo "        <td class=\"content\">";
		echo implode("", $panel);
		echo "      </tr>\n";
	}
}


echo "      <tr valign=\"top\">\n";
echo "        <td class=\"head\">&nbsp;".$dedi_lang['tpl_description']."&nbsp;</td>\n";
echo "        <td class=\"content\"><textarea name=\"description\" rows=\"3\" cols=\"52\" style=\"width:640\">$description</textarea></td>\n";
echo "      </tr>\n";

// Layout auswählen
echo "      <tr valign=\"top\">\n";
echo "        <td class=\"head\">&nbsp;".$dedi_lang['tpl_layout']."&nbsp;</td>\n";
echo "        <td class=\"content\"><select name=\"idlay\" size=\"1\" onchange=\"document.editform.action.value='change';document.editform.submit();\">\n";
if (!$idlay) $idlay = '0';
if ($idlay && $idtpl) echo "          <option value=\"0\">zurücksetzen</option>\n";
elseif ($idlay == '0') echo "          <option value=\"0\" selected>".$dedi_lang['form_nothing']."</option>\n";
else echo "          <option value=\"0\">".$dedi_lang['form_nothing']."</option>\n";
if (is_array($lay['id'])) {
	foreach ($lay['id'] as $value) {
		if ($value == $idlay) echo "      <option value=\"$value\" selected>".$lay[$value]['name']."</option>\n";
		else echo "      <option value=\"$value\">".$lay[$value]['name']."</option>\n";
	}
}
echo "        </select></td>\n";
echo "      </tr>\n";

// wenn Layout gewählt
if ($idlay) {
	echo "      <tr valign=\"top\">\n";
	echo "        <td class=\"head\">&nbsp;".$dedi_lang['tpl_description']."&nbsp;</td>\n";
	echo "        <td class=\"content\" width=\"640\" nowrap>&nbsp;".$lay[$idlay]['description']."&nbsp;</td>\n";
	echo "      </tr>\n";
	echo "      <tr valign=\"top\">\n";
	echo "        <td colspan=\"2\">&nbsp;</td>\n";
	echo "      </tr>\n";
	echo "      <input type=\"hidden\" name=\"changed\" value=\"0\">\n";

	// Container auflisten
	$list = browse_layout_for_containers($idlay);
	if (is_array($list)) {
		echo "      <input type=\"hidden\" name=\"container\" value=\"".implode(',', $list['id'])."\">\n";
		natsort ($list['id']);
		foreach ($list['id'] as $value) {
			echo "      <tr valign=\"top\">\n";

			// Containername
			$_container_name = !empty($list[$value]['title']) ? $list[$value]['title']:"$value. ".$dedi_lang['tpl_container']."";
			printf ("        <td class=\"head\"%s>&nbsp;%s&nbsp;</td>\n", (${'c'.$value}) ? ' rowspan="2"':'', (!empty($list[$value]['title'])) ? $list[$value]['title']:"$value. ".$dedi_lang['tpl_container']."");
			if ($anchor == $_container_name) echo '<a name="edit_container">';

			// Modul auswählen
			printf ("        <td class=\"%s\">", (${'c'.$value}) ? 'head':'content');
			echo "        <table width=\"100%\" border=\"0\"><tr><td class=\"head\">";
                        $echo = "<select class=\"element\" name=\"c$value\" size=\"1\" onchange=\"document.editform.action.value='change';document.editform.changed.value='$value';document.editform.anchor.value='$_container_name';document.editform.submit();\">\n";
			if (${'c'.$value} < 1) {
                            $echo .= "          <option value=\"0\" selected>".$dedi_lang['form_nothing']."</option>\n";
                            $modinfo = "<img src=\"tpl/" . $cfg_dedi['skin'] . "/img/space.gif\" border=\"0\" alt=\"\" title=\"\" width=\"16\" height=\"16\">&nbsp;";
                        } else $echo .= "          <option value=\"0\">".$dedi_lang['form_nothing']."</option>\n";
			if (is_array($mod['id'])) {
				$_cat_arr = array();
                                foreach ($mod['id'] as $idmod) {
					if (!$perm->have_perm(15, 'mod', 0) && (strpos($mod[$idmod]['version'], 'dev') != false && $mod[$idmod]['version'] != '') && $idmod != ${'c'.$value}) continue;
					if (!$_cat_arr[$mod[$idmod]['cat']] && $mod[$idmod]['cat'] != '') {
                                            $_cat_arr[$mod[$idmod]['cat']] = true;
                                            $echo .= "          <optgroup label=\"".$mod[$idmod]['cat']."\" value=\"\">\n";
                                        }
                                        $mod[$idmod]['referer'] = (($mod[$idmod]['verbose'] != '') ? "'" . $mod[$idmod]['verbose'] . "'" : "'" . $mod[$idmod]['name'] . "'");
										$mod[$idmod]['referer'] .= empty($mod[$idmod]['version']) ? '' :' (' . $mod[$idmod]['version'] . ')';
                                        if ($idmod == ${'c'.$value}) {
                                            $echo .= "          <option value=\"$idmod\" selected>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;".$mod[$idmod]['referer']."</option>\n";
                                            $modtitel = ( ' ++ ' .$dedi_lang['gen_description'] . ' ++ &#10;' . (($mod[${'c'.$value}]['cat'] != '') ? $dedi_lang['gen_cat'] . ': ' . $mod[${'c'.$value}]['cat'] . ' &#10;' : '') .
                                                        (($mod[${'c'.$value}]['verbose'] != '') ? $dedi_lang['gen_verbosename'] . ': ' . $mod[${'c'.$value}]['verbose'] . ' &#10;' : '') .
                                                        (empty($mod[${'c'.$value}]['source_id']) ? $dedi_lang['gen_name'] : $dedi_lang['gen_original']) . ': ' . $mod[${'c'.$value}]['name'] . ' &#10;' .
                                                        (($mod[${'c'.$value}]['version'] != '') ? $dedi_lang['gen_version'] . ': ' . $mod[${'c'.$value}]['version'] . ' &#10;' : '') . 'IdMod: ' . $mod[${'c'.$value}]['idmod'] );
                                            $modcursor = strstr($_SERVER['HTTP_USER_AGENT'], 'MSIE 5') ? 'hand' : 'pointer';
                                            $modinfo = "<img style=\"cursor:$modcursor\" src=\"tpl/" . $cfg_dedi['skin'] . "/img/about.gif\" border=\"0\" alt=\"" . $modtitel .
                                                       "\" title=\"" . $modtitel . "\" width=\"16\" height=\"16\">&nbsp;";
                                        } else {
                                            $echo .= "          <option value=\"$idmod\">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;".$mod[$idmod]['referer']."</option>\n";
                                        }
				}
			}
			echo $modinfo . $echo . "        </select></td>\n";

			// Modul konfigurieren
			if (${'c'.$value}) {
				echo "<td width=\"100%\" align=\"right\"><select name=\"cview$value\" size=\"1\">\n";
				printf ("          <option value=\"0\"%s>". $dedi_lang['gen_mod_active'] ."</option>\n", (${'cview'.$value} == '0' || !${'cview'.$value}) ? ' selected':'');
				printf ("          <option value=\"-1\"%s>". $dedi_lang['gen_mod_deactive'] ."</option>\n", (${'cview'.$value} == '-1') ? ' selected':'');
				//printf ("          <option value=\"".$auth->auth['uid']."\"%s>ich</option>\n", (${'cview'.$value} > '0') ? ' selected':'');
				echo "        </select>&nbsp;<select name=\"cedit$value\" size=\"1\">\n";
				printf ("          <option value=\"0\"%s>". $dedi_lang['gen_mod_edit_allow'] ."</option>\n", (${'cedit'.$value} == '0' || !${'cedit'.$value}) ? ' selected':'');
				printf ("          <option value=\"-1\"%s>". $dedi_lang['gen_mod_edit_disallow'] ."</option>\n", (${'cedit'.$value} == '-1') ? ' selected':'');
				//printf ("          <option value=\"".$auth->auth['uid']."\"%s>ich</option>\n", (${'cedit'.$value} > '0') ? ' selected':'');
				echo "        </select>&nbsp;</td></tr></table>";
				echo "        </td>\n";
				echo "      </tr>\n";
				echo "      <tr>\n";
				echo "        <td class=\"content\">\n";

				// Modulkonfiguration einlesen
				$input = $mod[${'c'.$value}]['input'];

				// Developer-Modul
				if (strpos($mod[${'c'.$value}]['version'], 'dev') != false && $mod[${'c'.$value}]['version'] != '') $input = '<p align="center" class="errormsg">'.$dedi_lang['tpl_devmessage']."</p>\n".$input;

				$mod_tpl_conf = ${'cconfig'.$value};
				$mod_id = ${'c'.$value};
				$mod_conf = ( empty($mod_tpl_conf) ) ? $mod[$mod_id]['config']:$mod_tpl_conf;
				$tmp1 = preg_split("/&/", $mod_conf);
				$varstring = array();
				foreach ($tmp1 as $key1=>$value1) {
					$tmp2 = explode('=', $value1);
					foreach ($tmp2 as $key2=>$value2) $varstring["$tmp2[0]"]=$tmp2[1];
				}
				foreach ($varstring as $key3=>$value3) $dedi_mod['value'][$key3] = dedi_stripslashes(urldecode($value3));
				if (is_array($mod[${'c'.$value}])) foreach ($mod[${'c'.$value}] as $key4=>$value4) $dedi_mod['info'][$key4] = dedi_stripslashes(urldecode($value4));
				$input = str_replace("MOD_VAR", "C".$value."MOD_VAR" , $input);
				eval(' ?>'.$input);
				unset($dedi_mod['value'], $dedi_mod['info']);
			} else echo '</tr></table>';
			echo "</td>\n";
			echo "      </tr>\n";
		}
	}
}

// Einstellungen für alle Templates übernehmen
if(is_numeric($idtpl)) {
	echo "  <tr>\n";
	echo "    <td class=\"head\">&nbsp;Erweitert</td>\n";
	echo '    <td class="content"><input type="checkbox" name="tpl_overwrite_all" value="1" id="touchme"><label for="touchme">'.$dedi_lang['tpl_overwrite_all'].'</label></td>';
	echo "  </tr>\n";
}

// Abbrechen und Bestätigungsbutton
echo "  <tr>\n";
echo "    <td>&nbsp;</td>\n";
echo "    <td align=\"right\"><a href=".$sess->url('main.php?area=tpl')."><img src=\"tpl/".$cfg_dedi['skin']."/img/but_cancel.gif\" border=\"0\"></a>&nbsp;<input type=\"image\" src=\"tpl/".$cfg_dedi['skin']."/img/but_ok.gif\" border=\"0\"></td>\n";
echo "  </tr>\n";
echo "</table>\n";
echo "</form>\n";
include('tpl/'.$cfg_dedi['skin'].'/footer.php');
?>