<?php
// $Id: admin.templates.php,v 1.15 2004/03/28 21:36:49 rcastley Exp $
/**
* Template admin
* @package Mambo Open Source
* @Copyright (C) 2000 - 2003 Miro International Pty Ltd
* @ All rights reserved
* @ Mambo Open Source is Free Software
* @ Released under GNU/GPL License: http://www.gnu.org/copyleft/gpl.html
* @version $Revision: 1.15 $
**/

// ensure this file is being included by a parent file
defined( '_VALID_MOS' ) or die( 'Direct Access to this location is not allowed.' );

// ensure user has access to this function
if (!$acl->acl_check( 'administration', 'config', 'users', $my->usertype )) {
	mosRedirect( 'index2.php', _NOT_AUTH );
}

require_once( $mainframe->getPath( 'admin_html' ) );
// XML library
require_once( "$mosConfig_absolute_path/administrator/classes/minixml/minixml.inc.php" );

$task = trim( strtolower( mosGetParam( $_REQUEST, "task", "" ) ) );
$cid = mosGetParam( $_REQUEST, "cid", array(0) );

if (!is_array( $cid )) {
	$cid = array(0);
}

switch ($task) {
	case "new":
		mosRedirect ("index2.php?option=template_installer");
		break;

	case "view":
		showTemplateInfo( $cid[0], $option );
		break;

	case "edit_source":
		editTemplateSource( $cid[0], $option );
		break;

	case "save_source":
		saveTemplateSource( $option );
		break;

	case "edit_css":
		editTemplateCSS( $cid[0], $option );
		break;

	case "save_css":
		saveTemplateCSS( $option );
		break;

	case "remove":
		removeTemplate( $cid[0], $option );
		break;

	case "publish":
		publishTemplate( $cid[0], $option );
		break;

	case "cancel":
		mosRedirect( "index2.php?option=$option" );
		break;

	default:
		viewTemplates( $option );
		break;
}

/**
* Compiles a list of installed, version 4.5+ templates
*
* Based on xml files found.  If no xml file found the template
* is ignored
*/
function viewTemplates( $option ) {
	global $database, $mainframe;
	global $mosConfig_absolute_path;

	$limit = $mainframe->getUserStateFromRequest( "viewlistlimit", 'limit', 10 );
	$limitstart = $mainframe->getUserStateFromRequest( "view{$option}limitstart", 'limitstart', 0 );

	$rows 		= array();
	// Read the template dir to find templates
	$templateBaseDir	= mosPathName(mosPathName($mosConfig_absolute_path) . "templates");
	$templateDirs		= mosReadDirectory($templateBaseDir);

	$database->setQuery( "SELECT cur_template FROM #__templates" );
	$cur_template = $database->loadResult();

	$rowid = 0;
	// Check that the directory contains an xml file
	foreach($templateDirs as $templateDir) {
		$dirName = mosPathName($templateBaseDir . $templateDir);
		$xmlFilesInDir = mosReadDirectory($dirName,".xml");

		//mosDebugVar($xmlFilesInDir);
		foreach($xmlFilesInDir as $xmlfile) {
			// Read the file to see if it's a valid template XML file
			$xmlDoc = new MiniXMLDoc($dirName . $xmlfile);
			$xmlDoc->fromFile($dirName . $xmlfile);

			$element = &$xmlDoc->getElementByPath('mosinstall');

			mosDebugVar($element);

			if (is_null( $element )) {
				continue;
			}
			if ($element->attribute( "type" ) != "template") {
				continue;
			}

			$row = new StdClass();
			$row->id = $rowid;
			$row->directory = $templateDir;
			$element = &$xmlDoc->getElementByPath('mosinstall/name');
			$row->name = $element->getValue();

			$element = &$xmlDoc->getElementByPath('mosinstall/creationDate');
			$row->creationdate = $element->getValue();

			$element = &$xmlDoc->getElementByPath('mosinstall/author');
			$row->author = $element->getValue();

			$element = &$xmlDoc->getElementByPath('mosinstall/copyright');
			$row->copyright = $element->getValue();

			$element = &$xmlDoc->getElementByPath('mosinstall/authoremail');
			$row->authoremail = $element->getValue();

			$element = &$xmlDoc->getElementByPath('mosinstall/authorurl');
			$row->authorurl = $element->getValue();
			
			$element = &$xmlDoc->getElementByPath('mosinstall/version');
			$row->version = $element->getValue();

			// Get info from db
			if ($cur_template == $templateDir) {
				$row->published	= 1;
			} else {
				$row->published = 0;
			}

			$row->checked_out = 0;
			$row->mosname = strtolower( str_replace( " ", "_", $row->name ) );
			$rows[] = $row;
			$rowid++;
		}
	}

	require_once("includes/pageNavigation.php");
	$pageNav = new mosPageNav( count( $rows ), $limitstart, $limit );

	$rows = array_slice( $rows, $pageNav->limitstart, $pageNav->limit );

	HTML_templates::showTemplates( $rows, $pageNav, $option );
}

/**
* Publish, or make current, the selected template
*/
function publishTemplate( $p_tname, $option ) {
	global $database;

	$database->setQuery("SELECT col_main FROM #__templates WHERE id=0");
	$col_main = $database->loadResult();

	$database->setQuery("DELETE FROM #__templates");
	$database->query();

	$database->setQuery("INSERT INTO #__templates SET cur_template='$p_tname', col_main='$col_main'");
	$database->query();

	$_SESSION["cur_template"] = $p_tname;

	mosRedirect("index2.php?option=$option");
}

/**
* Remove the selected template
*/
function removeTemplate( $cid, $option ) {
	global $database;

	$database->setQuery("SELECT cur_template FROM #__templates WHERE id=0");
	$cur_template = $database->loadResult();

	if ($cur_template == $cid) {
		echo "<script>alert(\"You can not delete template in use.\"); window.history.go(-1); </script>\n";
		exit();
	}

	mosRedirect("index2.php?option=template_installer&task=remove&cid=" . $cid);
}

function showTemplateInfo( $p_tname, $option ) {
	global $database;
	global $mosConfig_absolute_path;

	$database->setQuery( "SELECT cur_template FROM #__templates" );
	$cur_template = $database->loadResult();

	// Read the template dir to find templates
	$templateDir = mosPathName( "$mosConfig_absolute_path/templates/$p_tname" );

	$xmlFilesInDir = mosReadDirectory( $templateDir, ".xml" );

	mosDebugVar($xmlFilesInDir);
	foreach ($xmlFilesInDir as $xmlfile) {
		// Read the file to see if it's a valid template XML file
		$xmlDoc = new MiniXMLDoc( "$templateDir$xmlfile" );
		$xmlDoc->fromFile( "$templateDir$xmlfile" );

		$element = &$xmlDoc->getElementByPath('mosinstall');

		if (is_null( $element )) {
			continue;
		}

		if ($element->attribute("type") != "template") {
			continue;
		}

		$element = &$xmlDoc->getElementByPath('mosinstall/name');

		$row = new StdClass();
		//$row->id = $rowid;
		$element = &$xmlDoc->getElementByPath('mosinstall/name');
		$row->name = $element->getValue();

		$element = &$xmlDoc->getElementByPath('mosinstall/creationDate');
		$row->creationdate = $element->getValue();

		$element = &$xmlDoc->getElementByPath('mosinstall/author');
		$row->author = $element->getValue();

		$element = &$xmlDoc->getElementByPath('mosinstall/copyright');
		$row->copyright = $element->getValue();

		$element = &$xmlDoc->getElementByPath('mosinstall/authoremail');
		$row->authoremail = $element->getValue();

		$element = &$xmlDoc->getElementByPath('mosinstall/authorurl');
		$row->authorurl = $element->getValue();

		$element = &$xmlDoc->getElementByPath('mosinstall/description');
		$row->description = $element->getValue();

		$element = &$xmlDoc->getElementByPath('mosinstall/version');
		$row->version = $element->getValue();

		// Get info from db
		if( $cur_template == strtolower(str_replace(" ","_",$row->name) )) {
			$row->published	= 1;
		} else {
			$row->published = 0;
		}

		$row->checked_out = 0;
		$row->mosname = strtolower(str_replace(" ","_",$row->name));
		$row->templatedir = $p_tname;

		$row->source = mosShowSource( "{$templateDir}index.php" );
		$row->source_css = mosShowSource( "{$templateDir}css/template_css.css" );
	}

	HTML_templates::showTemplateInfo( $row, $option );
}

function editTemplateSource( $p_tname, $option) {
	$file = stripslashes( "../templates/$p_tname/index.php" );

	if ($fp = fopen( $file, "r" )) {
		$content = fread( $fp, filesize( $file ) );
		$content = htmlspecialchars( $content );

		HTML_templates::editTemplateSource( $p_tname, $content, $option );
	} else {
		mosRedirect( "index2.php?option=$option&mosmsg=Operation Failed: Could not open $file" );
	}
}

function saveTemplateSource( $option ) {
	$template = trim( mosGetParam( $_POST, 'template', '' ) );
	$filecontent = mosGetParam( $_POST, 'filecontent', '', _MOS_ALLOWHTML );

	if (!$template) {
		mosRedirect( "index2.php?option=$option&mosmsg=Operation failed: No template specified." );
	}
	if (!$filecontent) {
		mosRedirect( "index2.php?option=$option&mosmsg=Operation failed: Content empty." );
	}

	$file = "../templates/$template/index.php";
	if (is_writable( $file ) == false) {
		mosRedirect( "index2.php?option=$option&mosmsg=Operation failed: The file is not writable." );
	}

	if ($fp = fopen ($file, "w")) {
		fputs( $fp, stripslashes( $filecontent ) );
		fclose( $fp );
		mosRedirect( "index2.php?option=$option" );
	} else {
		mosRedirect( "index2.php?option=$option&mosmsg=Operation failed: Failed to open file for writing." );
	}

}

function editTemplateCSS( $p_tname, $option) {
	$file = stripslashes( "../templates/$p_tname/css/template_css.css" );

	if ($fp = fopen( $file, "r" )) {
		$content = fread( $fp, filesize( $file ) );
		$content = htmlspecialchars( $content );

		HTML_templates::editCSSSource( $p_tname, $content, $option );
	} else {
		mosRedirect( "index2.php?option=$option&mosmsg=Operation Failed: Could not open $file" );
	}
}

function saveTemplateCSS( $option ) {
	$template = trim( mosGetParam( $_POST, 'template', '' ) );
	$filecontent = mosGetParam( $_POST, 'filecontent', '', _MOS_ALLOWHTML );

	if (!$template) {
		mosRedirect( "index2.php?option=$option&mosmsg=Operation failed: No template specified." );
	}

	if (!$filecontent) {
		mosRedirect( "index2.php?option=$option&mosmsg=Operation failed: Content empty." );
	}

	$file = "../templates/$template/css/template_css.css";
	if (is_writable( $file ) == false) {
		mosRedirect( "index2.php?option=$option&mosmsg=Operation failed: The file is not writable." );
	}

	if ($fp = fopen ($file, "w")) {
		fputs( $fp, stripslashes( $filecontent ) );
		fclose( $fp );
		mosRedirect( "index2.php?option=$option" );
	} else {
		mosRedirect( "index2.php?option=$option&mosmsg=Operation failed: Failed to open file for writing." );
	}

}

function showtemplates($templateshtml, $database, $_dbprefix) {
	global $mosConfig_live_site, $mosConfig_absolute_path;
	$database->setQuery("SELECT cur_template FROM #__templates");
	$cur_template = $database->loadResult();

	$database->setQuery("SELECT col_main FROM #__templates");
	$col_main = $database->loadResult();

	$p_file = $mosConfig_absolute_path ."/templates/$cur_template/templateDetails.xml";
	if(file_exists($p_file))
	{
		$xmlDoc = new MiniXMLDoc($p_file);
		$xmlDoc->fromFile($p_file);

		$element = &$xmlDoc->getElementByPath('mosinstall/name');
		$tn = $element->getValue();

		$element = &$xmlDoc->getElementByPath('mosinstall/creationDate');
		$cd = $element->getValue();

		$element = &$xmlDoc->getElementByPath('mosinstall/author');
		$author = $element->getValue();

		$element = &$xmlDoc->getElementByPath('mosinstall/copyright');
		$cr = $element->getValue();

		$element = &$xmlDoc->getElementByPath('mosinstall/authoremail');
		$ae = $element->getValue();
		$element = &$xmlDoc->getElementByPath('mosinstall/authorurl');
		$au = $element->getValue();

	}
	else
	{
		die("Could not read file : " . $mosConfig_absolute_path ."/templates/$cur_template/templateDetails.xml");
	}

	// get a list of templates
	$templates = array();
	$previews = array();
	if ($handle = opendir("$mosConfig_absolute_path/templates/")) {
		while (false !==($file = readdir($handle))) {
			if ($file != "." && $file != ".." && $file != "CVS") {
				$templates[] = 	mosHTML::makeOption( $file );
				if (file_exists( "$mosConfig_absolute_path/templates/$file/template_thumbnail.png" )) {
					$previews[$file] = "$mosConfig_live_site/templates/$file/template_thumbnail.png";
				} else {
					$previews[$file] = "$mosConfig_live_site/administrator/images/no_preview.png";
				}
			}
		}
	}

	$templateList = mosHTML::selectList( $templates, 'cur_template',
	'onChange="document.forms[0].imagelib.src=previews[getSelectedValue(\'adminForm\',\'cur_template\')];"',
	'value', 'text', $cur_template );

	HTML_templates::showtemplates($cur_template, $col_main, $tn, $cd, $author, $cr, $ae, $au, $templateList, $previews );
}

function saveTemplates($database, $_dbprefix, $cur_template, $col_main, $option)
{
	$database->setQuery("DELETE FROM #__templates");
	$database->query();

	$database->setQuery("INSERT INTO #__templates SET cur_template='$cur_template', col_main='$col_main'");
	$database->query();

	$_SESSION["cur_template"] = $cur_template;
	echo "<script>document.location.href='index2.php?option=$option'</script>\n";
}

?>
