<?php global $basepath, $config;
/**
 * Project:     BeCast WebEngine - simple site engine
 * File:        init_core.inc.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 2009-2025 becast.at
 * @author Bernhard Jaud <bernhard at becast dot at>
 * @package BcWe core
 * @license http://opensource.org/licenses/gpl-license.php GNU Public License
 * @version $Id: 1ddb6c082eed54eabb523b63fe4ed74f15ceec59 $
 */

const in_astat = true;

function getTime(): string
{
    $timer = explode( ' ', microtime() );
	return $timer[1] . $timer[0];
}

$start = getTime(); 
/**
* Configuration
*/
if(!is_file(dirname(__FILE__, 2) .'/inc/config.inc.php')){
	header("Location: install/install.php");
} else {
	require dirname(__FILE__, 2) . '/inc/config.inc.php';
}
/**
* Smarty
*/
require $basepath.'template/libs/Smarty.class.php';
use Smarty\Smarty;

/**
* Database
*/
require $basepath.'database/'.$config['db_class'].'.class.php';

/**
* Functions
*/
include dirname(__FILE__, 2) .'/inc/functions.class.php';

/**
* Logger
*/
require dirname(__FILE__, 2) .'/inc/logger.class.php';

/**
* Logger
*/
require dirname(__FILE__, 2) .'/inc/datacache.class.php';

/**
* Cache
*/
require dirname(__FILE__, 2) .'/inc/cache.class.php';

/**
* Errors
*/
include dirname(__FILE__, 2) .'/inc/error.class.php';

/**
* Plugins
*/
include dirname(__FILE__, 2) .'/inc/plugin.class.php';

/**
* Mail
*/
include dirname(__FILE__, 2) .'/inc/mail.class.php';

/**
 * Captcha
 */
include dirname(__FILE__, 2) .'/inc/captcha.class.php';
$plugin=new plugins();

$db= new db($config['host'], $config['user'], $config['pass'], $config['db'],'utf8', true);

/** 
*  Select $config vars form Database
*  
*/
$result = $db->query("SELECT `name`, `value` FROM `" . $config['prefix'] . "config`");
while ($row = $db->fetch_array($result)){
    	$config[$row['name']] = $row['value'];
}

/**
* Set LC Lang for Dates 
*/
if($config['LCLANG']){
	setlocale(LC_ALL,$config['LCLANG']);
}

/** 
*  Start Datacache
*  
*/
$cache=new datacache();

/** 
*  Start Datacache
*  
*/
$ccache=new cache();

/** 
*  Look if we have a path Variable and try to autoset if not.
*  
*/
if(!isset($config['path'])){
	$path = explode('/', $_SERVER['SCRIPT_NAME']);
	$last = array_pop($path);
	$path = str_replace('/' . $last, '', $_SERVER['SCRIPT_NAME']);
	$config['path'] = $path;
	$db->query("INSERT INTO `" . $config['prefix'] . "config` (`name`, `value`, `title`, `description`, `option`, `category`) VALUES
( 'path', '".$path."', 'Pfad', 'Der Pfad auf ihrem Webserver z.b. /cms', 'text', 1)");
}else{
	$path=$config['path'];
}

/** 
*  Start Logger
*  
*/
$log=new logger($config['logtype'], dirname(__FILE__, 2) .'/logs/'.$config['logfile'],$config['loglevel']);
$tpl = new Smarty();
$error = new errorhandler();
$functions = new functions();
$root = $_SERVER['DOCUMENT_ROOT'] . $config['path'];

/** 
*  Start Language
*  
*/
require dirname(__FILE__, 2) .'/inc/lang.class.php';
$lang=new lang();
$lang->setlang($config['lang']);

/** 
*  Check if we have a Theme variable and the Theme exists
*  @TODO Theme Management
*  
*/
if(isset($config['theme']) && $config['theme']!='' && is_dir($root . '/themes/'.$config['theme'])){
	$tpl->setTemplateDir($root . '/themes/'.$config['theme']);
}else{
	
	/** 	
	*  Fallback
	*/
	$tpl->setTemplateDir($root . '/themes/default');
}
$tpl->setCompileDir($root . '/core/template/templates_c');
$tpl->setCacheDir($root . '/core/template/cache');
$tpl->setConfigDir($root . '/core/template/config');
try {
	$tpl->registerFilter(\Smarty\Smarty::FILTER_OUTPUT, 'trimwhitespace');
	$tpl->registerFilter(\Smarty\Smarty::FILTER_OUTPUT, "lang");
} catch (\Smarty\Exception $e) {
	$log->write("Smarty Register Filter error", $e->getMessage());
}
//var_dump($tpl -> getAutoloadFilters());
/** 
*  Well... This should vanish with Thememanagement
*  
*/
$addnav['right'] = TRUE;
$addnav['left'] = TRUE;


/** 
*  Start Sessions
*  
*/
require dirname(__FILE__, 2) .'/inc/sessions.class.php';
$session=new session();


/** 
* Initiate Core Class
*  
*/
require dirname(__FILE__, 2) .'/inc/core.class.php';
$core=new core($db, $log, $tpl);

if(defined('INSTALLED')){
	if(is_dir(dirname(__FILE__, 2) .'/install')){
		$core->message($lang->_('DELINSTALLDIR'), $lang->_('DELINSTALLDIRTEXT'),FALSE);
		return;
	}
}else{
	header("Location: install/install.php");
}

$captcha = new captcha();

/** 	
*  OpenID
*/
if($config['use_openid']==1){
	include dirname(__FILE__, 2) .'/inc/SimpleOpenID.class.php';
}
/** 
*  Get all *.plugin.php files from the Modules and register the Pluginhooks
*  
*/
$core->load_modules();
foreach($core->mod_ as $key=>$val){
	if(file_exists($root.'/modules/'.$val['file'].'/' . $val['file'] . '.plugins.php')){
		include_once $root.'/modules/'.$val['file'].'/' . $val['file']. '.plugins.php';
			$class='plugins_'.$val['file'];	
			if(class_exists($class)){
				$imod=new $class();
				if(is_callable(array($imod,'register_plugins'))){
					$imod->register_plugins($plugin);
				}
			}
	}
}

$plugin->run_hook('init_core');


function lang($code, \Smarty\Template $template) {
	$source = $code;
	return preg_replace_callback ('/##(.+?)##/', 'langstr', $source);
}

function langstr($treffer)
{
	global $lang;
	return $lang->_($treffer[1]);
}

/** 
*  This loads *.class.php files from the /core/modules dir.
*  Its useful but "undocumented".
*  
*/
$moduledir = dirname(__FILE__, 2) .'/core/modules';
$modules = opendir($moduledir);
while ($mods = readdir($modules)) {
    if (preg_match('/^.*?\.class.php$/', $mods)) {
        require_once($moduledir.'/'.$mods);
        }
    }
@closedir($modules);