Index: branches/2.8.x/CHANGELOG
===================================================================
--- branches/2.8.x/CHANGELOG	(revision 1642)
+++ branches/2.8.x/CHANGELOG	(revision 1643)
@@ -11,7 +11,9 @@
 ! = Update/Change
 ===============================================================================
 
-
+22 Mar-2012 Build 1643 Werner v.d.Decken(DarkViper)
++ added backend functions to copy themes and import htt-template files
+  according to the the new theme fallback functionality
 22 Mar-2012 Build 1642 Dietmar Woellbrink (Luisehahne)
 ! update header info.php wb_themes
 22 Mar-2012 Build 1641 Dietmar Woellbrink (Luisehahne)
Index: branches/2.8.x/wb/admin/templates/details.php
===================================================================
--- branches/2.8.x/wb/admin/templates/details.php	(revision 1642)
+++ branches/2.8.x/wb/admin/templates/details.php	(revision 1643)
@@ -82,7 +82,8 @@
 								'AUTHOR' => $row['author'],
 								'DESCRIPTION' => $row['description'],
 								'VERSION' => $row['version'],
-								'DESIGNED_FOR' => $row['platform']
+								'DESIGNED_FOR' => $row['platform'],
+								'LICENSE' => $row['license'],
 								)
 						);
 
@@ -98,10 +99,11 @@
 								'TEXT_VERSION' => $TEXT['VERSION'],
 								'TEXT_DESIGNED_FOR' => $TEXT['DESIGNED_FOR'],
 								'TEXT_DESCRIPTION' => $TEXT['DESCRIPTION'],
-								'TEXT_BACK' => $TEXT['BACK']
+								'TEXT_BACK' => $TEXT['BACK'],
+								'TEXT_LICENSE' => '',
 								)
 						);
-
+$template->set_var('TEXT_FUNCTION', ($row['function'] == 'theme' ? $TEXT['THEME'] : $TEXT['TEMPLATE']));
 // Parse template object
 $template->parse('main', 'main_block', false);
 $template->pparse('output', 'page');
Index: branches/2.8.x/wb/admin/templates/index.php
===================================================================
--- branches/2.8.x/wb/admin/templates/index.php	(revision 1642)
+++ branches/2.8.x/wb/admin/templates/index.php	(revision 1643)
@@ -30,11 +30,12 @@
 
 // Insert values into template list
 $template->set_block('main_block', 'template_list_block', 'template_list');
-$result = $database->query("SELECT * FROM ".TABLE_PREFIX."addons WHERE type = 'template' order by name");
-if($result->numRows() > 0) {
-	while($addon = $result->fetchRow()) {
+$sql = 'SELECT `directory`, `name`, `function` FROM `'.TABLE_PREFIX.'addons` '
+     . 'WHERE `type`=\'template\' ORDER BY `name`';
+if(($result = $database->query($sql))) {
+	while($addon = $result->fetchRow(MYSQL_ASSOC)) {
 		$template->set_var('VALUE', $addon['directory']);
-		$template->set_var('NAME', $addon['name']);
+		$template->set_var('NAME', (($addon['function'] == 'theme' ? '[Theme] ' : '').$addon['name']));
 		$template->parse('template_list', 'template_list_block', true);
 	}
 }
Index: branches/2.8.x/wb/admin/skel/themes/htt/templates_details.htt
===================================================================
--- branches/2.8.x/wb/admin/skel/themes/htt/templates_details.htt	(revision 1642)
+++ branches/2.8.x/wb/admin/skel/themes/htt/templates_details.htt	(revision 1643)
@@ -1,6 +1,6 @@
 <!-- BEGIN main_block -->
 
-<h2>{HEADING_TEMPLATE_DETAILS}</h2>
+<h2>{HEADING_TEMPLATE_DETAILS} ({TEXT_FUNCTION})</h2>
 
 <table summary="" cellpadding="5" cellspacing="0" border="0">
 <tr>
@@ -23,6 +23,10 @@
 	<td valign="top">{TEXT_DESCRIPTION}:</td>
 	<td style="text-align: justify;">{DESCRIPTION}</td>
 </tr>
+<tr>
+	<td>{TEXT_LICENSE}:</td>
+	<td>{LICENSE}</td>
+</tr>
 </table>
 
 <br />
Index: branches/2.8.x/wb/admin/interface/version.php
===================================================================
--- branches/2.8.x/wb/admin/interface/version.php	(revision 1642)
+++ branches/2.8.x/wb/admin/interface/version.php	(revision 1643)
@@ -51,5 +51,5 @@
 
 // check if defined to avoid errors during installation (redirect to admin panel fails if PHP error/warnings are enabled)
 if(!defined('VERSION')) define('VERSION', '2.8.3');
-if(!defined('REVISION')) define('REVISION', '1642');
+if(!defined('REVISION')) define('REVISION', '1643');
 if(!defined('SP')) define('SP', '');
Index: branches/2.8.x/wb/admin/addons/CopyTheme.php
===================================================================
--- branches/2.8.x/wb/admin/addons/CopyTheme.php	(nonexistent)
+++ branches/2.8.x/wb/admin/addons/CopyTheme.php	(revision 1643)
@@ -0,0 +1,370 @@
+<?php
+/**
+ *
+ * @category        WBCore
+ * @package         WBCore_addons
+ * @author          Werner v.d.Decken
+ * @copyright       Website Baker Org. e.V.
+ * @link			http://www.websitebaker2.org/
+ * @license         http://www.gnu.org/licenses/gpl.html
+ * @revision        $Revision$
+ * @filesource		$HeadURL$
+ * @lastmodified    $Date$
+ */
+
+class CopyTheme{
+
+// global vars
+	private $_oDb             = null;
+	private $_aLang           = array();
+	private $_aGlobals        = array();
+// class properties
+	private $_sThemesBasePath = ''; // (/var/www/httpdocs/wb/templates)
+	private $_sSourceDir      = ''; // (default_theme)
+	private $_sNewThemeDir    = ''; // (MyNewBackendTheme)
+	private $_sNewThemeName   = ''; // ('my new Backend Theme')
+
+	private $_aErrors         = array();
+
+/**
+ *
+ * @param string $sSourceThemePath (THEME_PATH.'/templates/'.DEFAULT_THEME)
+ * @param string $sNewThemeName (NewName)
+ */
+	public function __construct()
+	{
+	// import global vars
+		$this->_oDb   = $GLOBALS['database'];
+		$this->_aLang = $GLOBALS['MESSAGE'];
+	// import global Consts
+		$this->_aGlobals['TablePrefix']     = TABLE_PREFIX;
+		$this->_aGlobals['Debug']           = (defined('DEBUG') && DEBUG === true);
+		$this->_aGlobals['IsLinux']         = ((substr(__FILE__, 0, 1)) == '/');
+		$this->_aGlobals['StringDirMode']   = STRING_DIR_MODE;
+		$this->_aGlobals['StringFileMode']  = STRING_FILE_MODE;
+	}
+/**
+ * start copy current theme into a new theme
+ * @param string $sSourceThemePath (/var/www/httpdocs/wb/templates/destination_theme)
+ * @param string $sNewThemeName (NewName)
+ * @return bool 
+ */
+	public function execute($sSourceThemePath, $sNewThemeName)
+	{
+		$bRetval = false;
+		$this->clearError();
+		$this->_init($sSourceThemePath, $sNewThemeName);
+		if(!is_writeable($this->_sThemesBasePath)) {
+			$this->_setError( $this->_aLang['THEME_DESTINATION_READONLY'].' >> '
+			                  .$this->_sThemesBasePath );
+			return false;
+		}
+		if($this->_copyTree()) {
+			if($this->_modifyInfoFile()) {
+				if($this->_registerNewTheme()) {
+					return true;
+				}
+			}
+		}
+		$dir = $this->_sThemesBasePath.'/'.$this->_sNewThemeDir;
+		$this->_doRollback($dir);
+		return false;
+	}
+/**
+ * initialize the class
+ * @param string $sSourceThemePath (/var/www/httpdocs/wb/templates/destination_theme)
+ * @param string $sNewThemeName (NewName)
+ * @return boolean
+ */
+	private function _init($sSourceThemePath, $sNewThemeName)
+	{
+	// sanitize arguments and calculate local vars
+		$this->_sThemesBasePath = str_replace('\\','/', dirname($sSourceThemePath));
+		$this->_sSourceDir = basename($sSourceThemePath);
+		$this->_sNewThemeDir = $this->_SanitizeNewDirName($sNewThemeName);
+		$this->_sNewThemeName = $this->_SanitizeNewName($sNewThemeName);
+	}
+/**
+ * sanitize the new name and make it unique
+ * @param string $sName
+ * @return string
+ */
+	private function _SanitizeNewName($sName)
+	{
+		$sName = mysql_real_escape_string($sName);
+		$iCount = '';
+		do {
+			$sSearch = $sName.($iCount ? ' '.$iCount : '');
+			$sql = 'SELECT COUNT(*) FROM `'.$this->_aGlobals['TablePrefix'].'addons` '
+				 . 'WHERE LOWER(`name`)=\''.strtolower($sSearch).'\' AND `function`=\'theme\'';
+			$exists = $this->_oDb->get_one($sql);
+			$iCount = (int)$iCount + 1;
+		}while($exists);
+		return ($sName != $sSearch ? $sSearch : $sName);
+	}
+/**
+ * generate a unique valid dirname from template name
+ * @param string $sName
+ * @return string
+ */	
+	private function _SanitizeNewDirName($sName)
+	{
+		// remove all of the ASCII controllcodes
+		$sName = preg_replace('/[^0-9a-zA-Z \-_]/', '', strtolower($sName));
+		$sName = str_replace(array('-', '_'), array('- ', ' '), $sName);
+		$sName = str_replace(' ', '', ucwords($sName));
+		$sName = ($sName == '' ? 'MyNewTheme' : $sName);
+		$iCount = '';
+		do {
+			$sSearch = $sName.($iCount ? '_'.$iCount : '');
+			$sql = 'SELECT COUNT(*) FROM `'.$this->_aGlobals['TablePrefix'].'addons` '
+				 . 'WHERE `directory`=\''.$sSearch.'\' AND `function`=\'theme\'';
+			$exists = $this->_oDb->get_one($sql);
+			$iCount = (int)$iCount + 1;
+		}while($exists);
+		return ($sName != $sSearch ? $sSearch : $sName);
+	}
+/**
+ * copy the complete theme - directory tree with all included files
+ * @return boolean true if ok
+ */
+	private function _copyTree()
+	{
+		$bRetval = true;
+		$sSourceDir = $this->_sThemesBasePath.'/'.$this->_sSourceDir;
+		// build file list to copy into destination theme
+		$aFileList = array();
+		try {
+			$oIterator = new RecursiveDirectoryIterator($sSourceDir);
+			foreach (new RecursiveIteratorIterator($oIterator) as $cur) {
+				if($cur->isDir() || strpos($cur, '.svn') !== false) { continue; }
+				$sPattern = '/^'.preg_quote($sSourceDir, '/').'/';
+				$sFilename = preg_replace($sPattern, '', $cur->getPathname());
+				$sFilePath = preg_replace($sPattern, '', $cur->getPath());
+				$aFileList[$sFilename] = $sFilePath;
+			}
+			natsort($aFileList);
+		}catch(Exeption $e) {
+			$msg  = 'CopyTheme::_copyTree => '.$this->_aLang['GENERIC_FAILED_COMPARE'];
+			$msg .= '<br />'.$e->getMessage();
+			$this->_setError($msg);
+			$bRetval = false;
+		}
+		if($bRetval) {
+		// create all needed directories
+			$aDirectories = array_unique(array_values($aFileList));
+			$bRetval = $this->_createDirs($aDirectories);
+		}
+		if($bRetval) {
+			// copy all needed files
+			$aFiles = array_keys($aFileList);
+			$bRetval = $this->_copyFiles($aFiles);
+		}
+		return $bRetval;
+	}
+/**
+ * create all the directories from $aNewDirs-list under $sBaseDir
+ * @param array $aNewDirList ( array('', '/images', '/images/files')
+ */
+	private function _createDirs($aNewDirList)
+	{
+		$bRetval = true;
+		foreach($aNewDirList as $sDir) {
+			$sNewDir = $this->_sThemesBasePath.'/'.$this->_sNewThemeDir.$sDir;
+			if(!file_exists($sNewDir) &&  mkdir($sNewDir, 0777, true)) {
+				if($this->_aGlobals['IsLinux']) {
+					if(!chmod($sNewDir, $this->_aGlobals['StringDirMode'])) {
+						$sMsg = 'CopyTheme::createDirs::chmod('.$sNewDir.') >> '
+								.$this->_aLang['GENERIC_FAILED_COMPARE'];
+						$this->_setError($sMsg);
+						$bRetval = false;
+						break;
+					}
+				}
+			}else {
+				$sMsg = 'CopyTheme::createDirs::mkdir('.$sNewDir.') >> '
+						.$this->_aLang['GENERIC_FAILED_COMPARE'];
+				$this->_setError($sMsg);
+				$bRetval = false;
+				break;
+			}
+		}
+		return $bRetval;
+	}
+/**
+ * copies a list of files from source directory to destination directory
+ * @param array $aFileList (array('/index.php', '/images/index.php', '/images/files/index.php')
+ */
+	private function _copyFiles($aFileList)
+	{
+		$bRetval = true;
+		$sSourceDir = $this->_sThemesBasePath.'/'.$this->_sSourceDir;
+		$sDestinationDir = $this->_sThemesBasePath.'/'.$this->_sNewThemeDir;
+		foreach($aFileList as $sFile) {
+			if(copy($sSourceDir.$sFile, $sDestinationDir.$sFile)) {
+				if($this->_aGlobals['IsLinux']) {
+					if(!chmod($sDestinationDir.$sFile, $this->_aGlobals['StringFileMode'])) {
+						$sMsg = 'CopyTheme::copyFiles::chmod('.$sDestinationDir.$sFile.') >> '
+								.$this->_aLang['GENERIC_FAILED_COMPARE'];
+						$this->_setError($sMsg);
+						$bRetval = false;
+						break;
+					}
+				}
+			}else {
+				$sMsg = 'CopyTheme::copyFiles::copy('.$sDestinationDir.$sFile.') >> '
+						.$this->_aLang['GENERIC_FAILED_COMPARE'];
+				$this->_setError($sMsg);
+				$bRetval = false;
+				break;
+			}
+		}
+		return $bRetval;
+	}
+/**
+ * register a available theme in the database (gets values from info.php)
+ * @return bool TRUE if ok
+ */
+	private function _registerNewTheme()
+	{
+		$bRetval = true;
+		$sThemeInfoFile = $this->_sThemesBasePath.'/'.$this->_sNewThemeDir.'/info.php';
+		$aVariables = $this->_getThemeInfo($sThemeInfoFile);
+		$sql = 'INSERT INTO `'.$this->_aGlobals['TablePrefix'].'addons` '
+		     . 'SET `type`=\'template\', '
+		     .     '`function`=\'theme\', '
+		     .     '`directory`=\''.$aVariables['directory'].'\', '
+		     .     '`name`=\''.$aVariables['name'].'\', '
+		     .     '`description`=\''.mysql_real_escape_string($aVariables['description']).'\', '
+		     .     '`version`=\''.$aVariables['version'].'\', '
+		     .     '`platform`=\''.$aVariables['platform'].'\', '
+		     .     '`author`=\''.mysql_real_escape_string($aVariables['author']).'\', '
+		     .     '`license`=\''.mysql_real_escape_string($aVariables['license']).'\'';
+		if(!$this->_oDb->query($sql)) {
+			$sMsg = 'CopyTheme::registerNewTheme('.$this->_sNewThemeName.') >> '
+			        .$this->_aLang['GENERIC_NOT_UPGRADED'];
+			$sMsg .= (($this->_aGlobals['Debug']) ? '<br />'.$this->_oDb->get_error() : '');
+			$this->_setError($sMsg);
+			$bRetval = false;
+		}
+		return $bRetval;
+	}
+/**
+ * modify info-file of copied theme
+ * @return bool TRUE if ok
+ */
+	private function _modifyInfoFile()
+	{
+		$bRetval = false;
+		$sThemeInfoFile = $this->_sThemesBasePath.'/'.$this->_sNewThemeDir.'/info.php';
+		$aVariables = $this->_getThemeInfo($sThemeInfoFile);
+		$aVariables['directory']   = $this->_sNewThemeDir;
+		$aVariables['name']        = $this->_sNewThemeName;
+		$aVariables['version']     = '0.0.1';
+		$aVariables['description'] = '(copy): '.$aVariables['description'];
+		if(file_exists($sThemeInfoFile)) {
+			$sInfoContent = file_get_contents($sThemeInfoFile);
+			foreach($aVariables as $key=>$val) {
+				$sSearch  = '/(\$template_'.$key.'\s*=\s*(["\'])).*?(\2)\s*;/s';
+				$sReplace = ($val != '' && is_numeric($val[0])) ? '${1}' : '$1';
+				$sReplace .= $val.'$2;';
+				$sInfoContent = preg_replace($sSearch, $sReplace, $sInfoContent);
+			}
+			// remove trailing "\?\>" to sanitize the php file
+			$sInfoContent = preg_replace('/\s*?\?>\s*$/', '', $sInfoContent)."\n";
+			if(file_put_contents($sThemeInfoFile, $sInfoContent) !== false) {
+				return true;
+			}
+		}
+		$this->_setError('CopyTheme::modifyInfoFile('.$this->_sNewThemeDir.'/info.php) >> '
+		               .$this->_aLang['GENERIC_NOT_UPGRADED']);
+		return $bRetval;
+	}
+/**
+ * read old values from old info-file
+ * @param string $sThemeInfoFile
+ * @return array
+ */
+	private function _getThemeInfo($sThemeInfoFile)
+	{
+		if(file_exists($sThemeInfoFile)) {
+			include $sThemeInfoFile;
+			return array(
+				'directory' => $template_directory?$template_directory:null,
+				'name' => $template_name?$template_name:null,
+				'version' => $template_version?$template_version:null,
+				'description' => $template_description?$template_description:null,
+				'platform' => $template_platform?$template_platform:null,
+				'author' => $template_author?$template_author:null,
+				'license' => $template_license?$template_license:null,
+			);
+		} else {
+			return array(
+				'directory' => null,
+				'name' => null,
+				'version' => null,
+				'description' => null,
+				'platform' => null,
+				'author' => null,
+				'license' => null,
+			);
+		}
+	}
+/**
+ * on Error undo all already done copy/create actions
+ * @param string $dir
+ */
+	private function _doRollback($dir)
+	{
+		$iFileErrors = 0;
+		$iDirErrors  = 0;
+		$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir),
+												  RecursiveIteratorIterator::CHILD_FIRST);
+		foreach ($iterator as $path) {
+			if ($path->isDir()) {
+				rmdir($path->__toString());
+			} else {
+				unlink($path->__toString());
+			}
+		}
+		unset($path);
+		unset($iterator);
+		if(file_exists($dir)) { rmdir($dir); }
+	}
+/**
+ * add a new error message to the queue
+ * @param string $sErrMsg
+ */
+	private function _setError($sErrMsg)
+	{
+		$this->_aErrors[] = $sErrMsg;
+	}
+/**
+ * clear the errors queue
+ */
+	public function clearError()
+	{
+		$this->_aErrors = array();
+	}
+/**
+ * true if there is an error otherwise false
+ * @return bool
+ */
+	public function isError()
+	{
+		return (sizeof($this->_aErrors) > 0);
+	}
+/**
+ * gets all error messages as multiline string
+ * @param bool $nl2br true seperates lines by "<br />" else by "\n"
+ * @return string 
+ */
+	public function getError($nl2br = true)
+	{
+		$sClue = ($nl2br ? '<br />' : "\n");
+		$sErrorMsg = implode($sClue, $this->_aErrors);
+		return $sErrorMsg;
+	}
+
+
+} // end class
\ No newline at end of file

Property changes on: branches/2.8.x/wb/admin/addons/CopyTheme.php
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Added: svn:keywords
## -0,0 +1 ##
+Date Author Id Revision HeadURL
\ No newline at end of property
Index: branches/2.8.x/wb/admin/addons/CopyThemeHtt.php
===================================================================
--- branches/2.8.x/wb/admin/addons/CopyThemeHtt.php	(nonexistent)
+++ branches/2.8.x/wb/admin/addons/CopyThemeHtt.php	(revision 1643)
@@ -0,0 +1,102 @@
+<?php
+/**
+ *
+ * @category        WBCore
+ * @package         WBCore_addons
+ * @author          Werner v.d.Decken
+ * @copyright       Website Baker Org. e.V.
+ * @link			http://www.websitebaker2.org/
+ * @license         http://www.gnu.org/licenses/gpl.html
+ * @revision        $Revision$
+ * @filesource		$HeadURL$
+ * @lastmodified    $Date$
+ */
+
+class CopyThemeHtt {
+
+	private static $_sSkelPath  = ''; 
+	private static $_sThemePath = '';
+	private static $_sOs        = '';
+	private static $_sFileMode  = '';
+	private static $_aLang      = '';
+/**
+ * import all needed global constants and variables
+ */
+	private static function init()
+	{
+//		self::$_sSkelPath  = ADMIN_PATH.'/themes/templates/';
+		self::$_sSkelPath  = ADMIN_PATH.'/skel/themes/htt/';
+		self::$_sThemePath = THEME_PATH.'/templates/';
+		self::$_sOs        = OPERATING_SYSTEM;
+		self::$_sFileMode  = STRING_FILE_MODE;
+		self::$_aLang      = $GLOBALS['MESSAGE'];
+	}
+/**
+ * returns the difference between default and current theme
+ * @param string $sSourceDir
+ * @param string $sDestinationDir
+ * @param string $sExtension
+ * @return array
+ */
+	public static function getDivList($sSourceDir, $sDestinationDir, $sExtension)
+	{
+		$aDestinationTemplates = self::getFiles($sDestinationDir, $sExtension);
+		$aDefaultTemplates = self::getFiles($sSourceDir, $sExtension);
+		$aRetval = array_diff($aDefaultTemplates, $aDestinationTemplates);
+		return $aRetval;
+	}
+/**
+ * copy template files from default theme dir into the current theme dir
+ * @param array $aFileList
+ * @return array|null
+ */
+	public static function doImport($aFileList)
+	{
+		self::init();
+		$aErrors = array();
+		if(is_array($aFileList)) {
+			if(isset($aFileList['none'])) { unset($aFileList['none']); }
+			if(sizeof($aFileList) > 0 ) {
+				foreach($aFileList as $sFile) {
+					$sFile = basename($sFile);
+					if(copy(self::$_sSkelPath.$sFile, self::$_sThemePath.$sFile)) {
+						if(self::$_sOs == 'linux') {
+							chmod(self::$_sThemePath.$sFile, self::$_sFileMode);
+						}
+					}else {
+						$aErrors[] = self::$_aLang['UPLOAD_ERR_CANT_WRITE'].' ['.$sFile.']';
+					}
+				}
+			}
+		}
+		if(sizeof($aErrors) > 0) {
+			return $aErrors;
+		}else {
+			return null;
+		}
+	}
+/**
+ * generate a filelist containing all files with $sExtension from dir $sDirectory
+ * @param string $sDirectory
+ * @param string $sExtension
+ * @return array
+ */
+	private static function getFiles($sDirectory, $sExtension)
+	{
+		$aRetval = array();
+		try {
+			$oIterator = new DirectoryIterator($sDirectory);
+			foreach ($oIterator as $oFileinfo) {
+				if ($oFileinfo->isFile() && 
+				   (pathinfo($oFileinfo->getFilename(), PATHINFO_EXTENSION) == $sExtension))
+				{
+					$aRetval[$oFileinfo->getBasename('.'.$sExtension)] = $oFileinfo->getBasename();
+				}
+			}
+		} catch (Exception $e) {
+			return array();
+		}
+		ksort($aRetval);
+		return $aRetval;
+	}
+}
\ No newline at end of file

Property changes on: branches/2.8.x/wb/admin/addons/CopyThemeHtt.php
___________________________________________________________________
Added: svn:eol-style
## -0,0 +1 ##
+native
\ No newline at end of property
Added: svn:keywords
## -0,0 +1 ##
+Date Author Id Revision HeadURL
\ No newline at end of property
Index: branches/2.8.x/wb/admin/addons/reload.php
===================================================================
--- branches/2.8.x/wb/admin/addons/reload.php	(revision 1642)
+++ branches/2.8.x/wb/admin/addons/reload.php	(revision 1643)
@@ -1,146 +1,143 @@
 <?php
 /**
  *
- * @category        admin
- * @package         addons
- * @author          WebsiteBaker Project
- * @copyright       2004-2009, Ryan Djurovich
- * @copyright       2009-2011, Website Baker Org. e.V.
+ * @category        WBCore
+ * @package         WBCore_addons
+ * @author          Werner v.d.Decken
+ * @copyright       Website Baker Org. e.V.
  * @link			http://www.websitebaker2.org/
  * @license         http://www.gnu.org/licenses/gpl.html
- * @platform        WebsiteBaker 2.8.x
- * @requirements    PHP 5.2.2 and higher
- * @version         $Id$
+ * @revision        $Revision$
  * @filesource		$HeadURL$
  * @lastmodified    $Date$
- *
  */
 
 /**
- * check if there is anything to do
+ * loop through all resource directories of one type and reload the resources
+ * @param string $sType type of resource ( module / template / language )
+ * @return bool
  */
-$post_check = array('reload_modules', 'reload_templates', 'reload_languages');
-foreach ($post_check as $index => $key) {
-	if (!isset($_POST[$key])) unset($post_check[$index]);
-}
-if (count($post_check) == 0) die(header('Location: index.php?advanced'));
-
+	function ReloadAddonLoop($sType)
+	{
+		global $database;
+		$database->query('DELETE FROM `'.TABLE_PREFIX.'addons` WHERE `type`=\''.$sType.'\'');
+		try{
+			$oIterator = new DirectoryIterator(WB_PATH.'/'.$sType.'s');
+			$_Function = 'load_'.$sType;
+			foreach ($oIterator as $oFileinfo) {
+				if( ( $oFileinfo->isFile() &&
+					   $sType == 'language' &&
+					   preg_match('/^([A-Z]{2}.php)/', $oFileinfo->getBasename())
+					) ||
+				    ($oFileinfo->isDir() && $sType != 'language')
+				  )
+				{
+					if(substr($oFileinfo->getBasename(), 0,1) != '.') {
+						$_Function($oFileinfo->getPathname());
+					}
+				}
+			}
+		}catch(Exception $e) {
+			return false;
+		}
+		return true;
+	}
 /**
  * check if user has permissions to access this file
  */
-// include WB configuration file and WB admin class
-require_once('../../config.php');
-require_once('../../framework/class.admin.php');
-
+// include all needed core files and check permission
+	require_once('../../config.php');
+	require_once('../../framework/class.admin.php');
+	$aMsg = array();
+	$aErrors = array();
 // check user permissions for admintools (redirect users with wrong permissions)
-$admin = new admin('Admintools', 'admintools', false, false);
-
-if ($admin->get_permission('admintools') == false) die(header('Location: ../../index.php'));
-
-// check if the referer URL if available
-$referer = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] :
-	(isset($HTTP_SERVER_VARS['HTTP_REFERER']) ? $HTTP_SERVER_VARS['HTTP_REFERER'] : '');
-$referer = '';
-// if referer is set, check if script was invoked from "admin/modules/index.php"
-$required_url = ADMIN_URL . '/addons/index.php';
-if ($referer != '' && (!(strpos($referer, $required_url) !== false || strpos($referer, $required_url) !== false)))
-	die(header('Location: ../../index.php'));
-
-// include WB functions file
-require_once(WB_PATH . '/framework/functions.php');
-
-// load WB language file
-require_once(WB_PATH . '/languages/' . LANGUAGE .'.php');
-
-// create Admin object with admin header
-$admin = new admin('Addons', '', false, false);
-$js_back = ADMIN_URL . '/addons/index.php?advanced';
-
-if (!$admin->checkFTAN())
-{
-	$admin->print_header();
-	$admin->print_error($MESSAGE['GENERIC_SECURITY_ACCESS'],$js_back);
-}
-
-/**
- * Reload all specified Addons
- */
-$msg = array();
-$table = TABLE_PREFIX . 'addons';
-
-foreach ($post_check as $key) {
-	switch ($key) {
-		case 'reload_modules':
-			if ($handle = opendir(WB_PATH . '/modules')) {
-				// delete modules from database
-				$sql = "DELETE FROM `$table` WHERE `type` = 'module'";
-				$database->query($sql);
-
-				// loop over all modules
-				while(false !== ($file = readdir($handle))) {
-					if ($file != '' && substr($file, 0, 1) != '.' && $file != 'admin.php' && $file != 'index.php') {
-						load_module(WB_PATH . '/modules/' . $file);
-					}
+	$admin = new admin('Admintools', 'admintools', false, false);
+	if ($admin->get_permission('admintools'))
+	{
+		require_once(WB_PATH . '/framework/functions.php');
+		require_once(WB_PATH . '/languages/' . LANGUAGE .'.php');
+	// recreate Admin object without admin header
+		$admin = new admin('Addons', '', false, false);
+		$js_back = ADMIN_URL . '/addons/index.php?advanced';
+	// check transaction
+		if ($admin->checkFTAN())
+		{
+		// start the selected action
+			if(isset($_POST['cmdCopyTheme']))
+			{
+				$sNewTheme = (isset($_POST['ThNewTheme']) ? $_POST['ThNewTheme'] : '');
+				require(dirname(__FILE__).'/CopyTheme.php');
+				$ct = new CopyTheme();
+				$ct->execute(THEME_PATH, $sNewTheme);
+				if($ct->isError()) {
+					$aErrors[] = $ct->getError();
+				}else {
+					$aMsg[] = $TEXT['THEME_COPY_CURRENT'].' :: '.$MESSAGE['GENERIC_COMPARE'];
 				}
-				closedir($handle);
-				// add success message
-				$msg[] = $MESSAGE['ADDON']['MODULES_RELOADED'];
-
-			} else {
-				// provide error message and stop
-				$admin->print_error($MESSAGE['ADDON']['ERROR_RELOAD'], $js_back);
-			}
-			break;
-			
-		case 'reload_templates':
-			if ($handle = opendir(WB_PATH . '/templates')) {
-				// delete templates from database
-				$sql = "DELETE FROM `$table` WHERE `type` = 'template'";
-				$database->query($sql);
-
-				// loop over all templates
-				while(false !== ($file = readdir($handle))) {
-					if($file != '' AND substr($file, 0, 1) != '.' AND $file != 'index.php') {
-						load_template(WB_PATH . '/templates/' . $file);
-					}
+				unset($ct);
+		// ---------------------------
+			}elseif(isset($_POST['cmdCopyTemplate']))
+			{
+				$aFileList = (isset($_POST['ThTemplate']) ? $_POST['ThTemplate'] : array());
+				require(dirname(__FILE__).'/CopyThemeHtt.php');
+				$x = CopyThemeHtt::doImport($aFileList);
+				if(is_null($x)) {
+					$aMsg[] = $TEXT['THEME_IMPORT_HTT'].' :: '.$MESSAGE['GENERIC_COMPARE'];
+				}else {
+					$aErrors = array_merge($aErrors, $x);
 				}
-				closedir($handle);
-				// add success message
-				$msg[] = $MESSAGE['ADDON']['TEMPLATES_RELOADED'];
-
-			} else {
-				// provide error message and stop
-				$admin->print_header();
-				$admin->print_error($MESSAGE['ADDON']['ERROR_RELOAD'], $js_back);
-			}
-			break;
-
-		case 'reload_languages':
-			if ($handle = opendir(WB_PATH . '/languages/')) {
-				// delete languages from database
-				$sql = "DELETE FROM `$table` WHERE `type` = 'language'";
-				$database->query($sql);
-			
-				// loop over all languages
-				while(false !== ($file = readdir($handle))) {
-					if ($file != '' && substr($file, 0, 1) != '.' && $file != 'index.php') {
-						load_language(WB_PATH . '/languages/' . $file);
+		// ---------------------------
+			}elseif(isset($_POST['cmdReload']))
+			{
+				$aReloadType = (isset($_POST['reload']) && is_array($_POST['reload'])) ? $_POST['reload'] : array();
+				foreach($aReloadType as $sType) {
+					switch($sType) {
+						case 'modules':
+						// reload all modules
+							if(ReloadAddonLoop('module')) {
+								$aMsg[] = $MESSAGE['ADDON_MODULES_RELOADED'];
+							}else {
+								$aErrors[] = $MESSAGE['ADDON_ERROR_RELOAD'];
+							}
+							break;
+						case 'templates':
+						// reload all templates
+							if(ReloadAddonLoop('template')) {
+								$aMsg[] = $MESSAGE['ADDON_TEMPLATES_RELOADED'];
+							}else {
+								$aErrors[] = $MESSAGE['ADDON_ERROR_RELOAD'];
+							}
+							break;
+						case 'languages':
+						// reload all languages
+							if(ReloadAddonLoop('language')) {
+								$aMsg[] = $MESSAGE['ADDON_LANGUAGES_RELOADED'];
+							}else {
+								$aErrors[] = $MESSAGE['ADDON_ERROR_RELOAD'];
+							}
+							break;
+						default:
+							$aErrors[] = $MESSAGE['GENERIC_NOT_COMPARE'].' ['.$sType.']';
+							break;
 					}
 				}
-				closedir($handle);
-				// add success message
-				$msg[] = $MESSAGE['ADDON']['LANGUAGES_RELOADED'];
-				
-			} else {
-				// provide error message and stop
-				$admin->print_header();
-				$admin->print_error($MESSAGE['ADDON']['ERROR_RELOAD'], $js_back);
+			}else {
+		// ---------------------------
+				$aErrors[] = $MESSAGE['ADDON_ERROR_RELOAD'];
 			}
-			break;
+		}else { // invalid FTAN
+			$aErrors[] = $MESSAGE['GENERIC_SECURITY_ACCESS'];
+		}
+	}else { // no permission
+		$aErrors[] = $MESSAGE['ADMIN_INSUFFICIENT_PRIVELLIGES'];
 	}
-}
-
+	if(sizeof($aErrors) > 0)  {
+// output error message
+		$admin->print_header();
+		$admin->print_error(implode('<br />', $aErrors), $js_back);
+	}else {
 // output success message
-$admin->print_header();
-$admin->print_success(implode($msg, '<br />'), $js_back);
-$admin->print_footer();
+		$admin->print_header();
+		$admin->print_success(implode('<br />', $aMsg), $js_back);
+		$admin->print_footer();
+	}
Index: branches/2.8.x/wb/admin/addons/index.php
===================================================================
--- branches/2.8.x/wb/admin/addons/index.php	(revision 1642)
+++ branches/2.8.x/wb/admin/addons/index.php	(revision 1643)
@@ -46,14 +46,14 @@
  *	Obsolete as we are using blocks ... see "parsing the blocks" section
  */
 $display_none = "style=\"display: none;\"";
-if($admin->get_permission('modules') != true) 	$template->set_var('DISPLAY_MODULES', $display_none);	
-if($admin->get_permission('templates') != true)	$template->set_var('DISPLAY_TEMPLATES', $display_none);
-if($admin->get_permission('languages') != true)	$template->set_var('DISPLAY_LANGUAGES', $display_none);
-if($admin->get_permission('admintools') != true)	$template->set_var('DISPLAY_ADVANCED', $display_none);
+if($admin->get_permission('modules') != true) {	$template->set_var('DISPLAY_MODULES', $display_none); }
+if($admin->get_permission('templates') != true) { $template->set_var('DISPLAY_TEMPLATES', $display_none); }
+if($admin->get_permission('languages') != true) { $template->set_var('DISPLAY_LANGUAGES', $display_none); }
+if($admin->get_permission('admintools') != true) { $template->set_var('DISPLAY_ADVANCED', $display_none); }
 
-if(!isset($_GET['advanced']) || $admin->get_permission('admintools') != true)
+if(!isset($_GET['advanced']) || $admin->get_permission('admintools') != true) {
 	$template->set_var('DISPLAY_RELOAD', $display_none);
-
+}
 /**
  *	Insert section names and descriptions
  */
@@ -80,10 +80,50 @@
 /**
  *	Parsing the blocks ...
  */
-if ( $admin->get_permission('modules') == true) $template->parse('main_block', "modules_block", true);
-if ( $admin->get_permission('templates') == true) $template->parse('main_block', "templates_block", true);
-if ( $admin->get_permission('languages') == true) $template->parse('main_block', "languages_block", true);
-if ( isset($_GET['advanced']) AND $admin->get_permission('admintools') == true) $template->parse('main_block', "reload_block", true);
+if ( $admin->get_permission('modules') == true) { $template->parse('main_block', "modules_block", true); }
+if ( $admin->get_permission('templates') == true) { $template->parse('main_block', "templates_block", true); }
+if ( $admin->get_permission('languages') == true) { $template->parse('main_block', "languages_block", true); }
+// start advanced block
+if ( isset($_GET['advanced']) AND $admin->get_permission('admintools') == true) {
+	$template->set_var(array(
+		'TXT_THEME_COPY_CURRENT'  => $TEXT['THEME_COPY_CURRENT'],
+		'TXT_THEME_NEW_NAME'      => $TEXT['THEME_NEW_NAME'],
+		'TXT_THEME_CURRENT'       => $TEXT['THEME_CURRENT'],
+		'TXT_THEME_START_COPY'    => $TEXT['THEME_START_COPY'],
+		'TXT_THEME_IMPORT_HTT'    => $TEXT['THEME_IMPORT_HTT'],
+		'TXT_THEME_SELECT_HTT'    => $TEXT['THEME_SELECT_HTT'],
+		'TXT_THEME_NOMORE_HTT'    => $TEXT['THEME_NOMORE_HTT'],
+		'TXT_THEME_START_IMPORT'  => $TEXT['THEME_START_IMPORT'],
+		'MESSAGE_THEME_COPY_CURRENT'               => $MESSAGE['THEME_COPY_CURRENT'],
+		'MESSAGE_THEME_ALREADY_EXISTS'             => $MESSAGE['THEME_ALREADY_EXISTS'],
+		'MESSAGE_THEME_INVALID_SOURCE_DESTINATION' => $MESSAGE['THEME_INVALID_SOURCE_DESTINATION'],
+		'MESSAGE_THEME_DESTINATION_READONLY'       => $MESSAGE['THEME_DESTINATION_READONLY'],
+		'MESSAGE_THEME_IMPORT_HTT'                 => $MESSAGE['THEME_IMPORT_HTT'],
+		)
+	);
+// start copy current theme
+	$sql = 'SELECT `name` FROM `'.TABLE_PREFIX.'addons` '
+		 . 'WHERE `directory`=\''.DEFAULT_THEME.'\' AND `function`=\'theme\'';
+	$tmp = $database->get_one($sql);
+	$template->set_var('THEME_DEFAULT_NAME', $tmp);
+// end copy current theme
+// start template import
+	include(dirname(__FILE__).'/CopyThemeHtt.php');
+	$aTplList = CopyThemeHtt::getDivList(ADMIN_PATH.'/themes/templates',
+	                                     THEME_PATH.'/templates', 'htt');
+	$sOptionList = '';
+	if(sizeof($aTplList)) {
+		foreach($aTplList as $key=>$val) {
+			$sOptionList .= '<option value="'.$val.'">'.$key.'</option>'."\n";
+		}
+	}else {
+		$sOptionList = '<option value="none">'.$TEXT['THEME_NOMORE_HTT'].'</option>'."\n";
+	}
+	$template->set_var('THEME_TEMPLATE_LIST', $sOptionList);
+// end template import
+	$template->parse('main_block', "reload_block", true);
+}
+// end advanced block
 
 /**
  *	Parse template object
@@ -95,5 +135,3 @@
  *	Print admin footer
  */
 $admin->print_footer();
-
-?>
\ No newline at end of file
Index: branches/2.8.x/wb/templates/allcss/index.php
===================================================================
--- branches/2.8.x/wb/templates/allcss/index.php	(revision 1642)
+++ branches/2.8.x/wb/templates/allcss/index.php	(revision 1643)
@@ -1,3 +1,4 @@
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 <?php
 /**
  * $Id$
@@ -32,8 +33,6 @@
 
 // TEMPLATE CODE STARTS BELOW
 ?>
-<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
-"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
 <head>
 	<meta http-equiv="Content-Type" content="text/html; charset=<?php 
@@ -45,13 +44,12 @@
 	<link rel="stylesheet" type="text/css" href="<?php
 	echo TEMPLATE_DIR; ?>/print.css" media="print" />
 	<title><?php page_title('', '[WEBSITE_TITLE]'); ?></title>
-	<?php
+<?php
 	// automatically include optional WB module files (frontend.css, frontend.js)
-	if (function_exists('register_frontend_modfiles')) {
-		register_frontend_modfiles('css');
-		// register_frontend_modfiles('jquery');
-		register_frontend_modfiles('js');
-	} ?>
+	register_frontend_modfiles('css');
+	// register_frontend_modfiles('javascript');
+	register_frontend_modfiles('js');
+?>
 </head>
 
 <body>
@@ -142,7 +140,7 @@
 </div>
 <?php 
 // automatically include optional WB module file frontend_body.js)
-if (function_exists('register_frontend_modfiles_body')) { register_frontend_modfiles_body(); } 
+	register_frontend_modfiles_body();
 ?>
 </body>
 </html>
\ No newline at end of file
Index: branches/2.8.x/wb/templates/round/index.php
===================================================================
--- branches/2.8.x/wb/templates/round/index.php	(revision 1642)
+++ branches/2.8.x/wb/templates/round/index.php	(revision 1643)
@@ -1,3 +1,4 @@
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 <?php
 /**
  * $Id$
@@ -32,8 +33,6 @@
 
 // TEMPLATE CODE STARTS BELOW
 ?>
-<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
-"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
 <head>
 	<meta http-equiv="Content-Type" content="text/html; charset=<?php 
@@ -45,13 +44,12 @@
 	<link rel="stylesheet" type="text/css" href="<?php
 		echo TEMPLATE_DIR; ?>/print.css" media="print" />
 	<title><?php page_title('', '[WEBSITE_TITLE]'); ?></title>
-	<?php
+<?php
 	// automatically include optional WB module files (frontend.css, frontend.js)
-	if (function_exists('register_frontend_modfiles')) {
-		register_frontend_modfiles('css');
-		// register_frontend_modfiles('jquery');
-		register_frontend_modfiles('js');
-	} ?>
+	register_frontend_modfiles('css');
+	// register_frontend_modfiles('javascript');
+	register_frontend_modfiles('js');
+?>
 </head>
 
 <body>
@@ -249,7 +247,7 @@
 </table>
 <?php 
 // automatically include optional WB module file frontend_body.js)
-if (function_exists('register_frontend_modfiles_body')) { register_frontend_modfiles_body(); } 
+register_frontend_modfiles_body();
 ?>
 </body>
 </html>
\ No newline at end of file
Index: branches/2.8.x/wb/templates/simple/index.php
===================================================================
--- branches/2.8.x/wb/templates/simple/index.php	(revision 1642)
+++ branches/2.8.x/wb/templates/simple/index.php	(revision 1643)
@@ -1,3 +1,4 @@
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 <?php
 /**
  * $Id$
@@ -32,8 +33,6 @@
 
 // TEMPLATE CODE STARTS BELOW
 ?>
-<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
-"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
 <head>
 	<meta http-equiv="Content-Type" content="text/html; charset=<?php 
@@ -40,12 +39,11 @@
 	echo defined('DEFAULT_CHARSET') ? DEFAULT_CHARSET : 'utf-8'; ?>" />
 	<meta name="description" content="<?php page_description(); ?>" />
 	<meta name="keywords" content="<?php page_keywords(); ?>" />
-	<?php 
+<?php 
 	// automatically include optional WB module files (frontend.css, frontend.js)
-	if (function_exists('register_frontend_modfiles')) {
-		register_frontend_modfiles('css');
-		register_frontend_modfiles('js');
-	} ?>
+	register_frontend_modfiles('css');
+	register_frontend_modfiles('js');
+?>
 	<link rel="stylesheet" type="text/css" href="<?php 
 		echo TEMPLATE_DIR; ?>/template.css" media="screen,projection" />
 	<link rel="stylesheet" type="text/css" href="<?php 
@@ -102,7 +100,7 @@
 </table>
 <?php 
 // automatically include optional WB module file frontend_body.js)
-if (function_exists('register_frontend_modfiles_body')) { register_frontend_modfiles_body(); } 
+	register_frontend_modfiles_body();
 ?>
 </body>
 </html>
\ No newline at end of file
Index: branches/2.8.x/wb/templates/wb_theme/info.php
===================================================================
--- branches/2.8.x/wb/templates/wb_theme/info.php	(revision 1642)
+++ branches/2.8.x/wb/templates/wb_theme/info.php	(revision 1643)
@@ -34,4 +34,5 @@
 $template_license_terms		= '-';
 $template_description		= 'Default backend theme for Website Baker 2.8.';
 
-?>
\ No newline at end of file
+?>
+
