<?php
/*
* @package LabCMS
* @copyright (c) 2006 Alexander Levin aka Loki (loki_angel@mail.ru)
* @support http://labcms.ru
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
*/

class admin_main extends ModuleTools
{
	protected $admin_modules=array('admin', 'admin_dumper', 'admin_groups', 'admin_modules',
 'admin_pages', 'admin_redirect', 'admin_tree', 'admin_users',
 'blocks_static_edit', 'lang_editor', 'admin_settings');
 
	public function __construct()
	{
		if (!access('admin')) return LabCMS::i()->error403();
		LabCMS::setAllowFileUpload();
	}
	
	public function main()
	{
		if ($_SERVER['REQUEST_METHOD']=="POST") {
			switch($_POST['action'])
			{
				case('purge_cache'):
					LabCMS::reset_cache('all');
					refresh();
					break;
				case('purge_cache_parsed'):
					LabCMS::reset_cache('parsed');
					refresh();
					break;
				case('recompile'):
					$this->_forceCompileAllTemplates();
					LabCMS::reset_cache('all');
					refresh();
					break;
			}
		}
		
		self::_assign($this->_getCMSStat());
		self::_assign($this->_getAdminModules());

		
		self::_setTpl('admin');
	}
	
	public function phpinfo()
	{
		if (DEMO_MODE) include(dirname(__FILE__)."/phpinfo.demo.php");
		else phpinfo();
		exit;
	}
	
	protected function _forceCompileAllTemplates()
	{
		$skins=glob(LAB_PATH_TEMPLATE.'/*', GLOB_ONLYDIR);
		ob_implicit_flush(true);
		ob_end_flush();
		foreach ($skins as $skin) {
			Tpl::i()->compile_id=basename($skin);
			Tpl::i()->setTemplateDir($skin);
			Tpl::i()->compileAllTemplates('.tpl', true, 0, 1);
		}
	}
	
	protected function _getDbData()
	{
		$database_size=$counter=0;
		$tables=Db::i()->select("SHOW TABLE STATUS");
		foreach ($tables as $table) {
			if (isset($table['Engine'])
				&& ($table['Engine'] == 'MyISAM' || $table['Engine'] == 'InnoDB')) {
				if (strpos($table['Name'], config::get('core.prefix')) !== false) {
					$database_size += $table['Data_length'] + $table['Index_length'];
					$counter++;
				}
			}
		}
		return array($database_size, $counter);
	}


	protected function _getDirInfo($dir)
	{
		$dir_size=$counter=0;
		if ($hdir = @opendir($dir)) {
			while (($file = readdir($hdir)) !== false) {
				if (is_file($dir.'/'.$file)) {
					$dir_size += filesize($dir.'/'.$file);
					$counter++;
				}
			}
			closedir($hdir);
			return array($dir_size, $counter);
		}
		else return false;
	}
	
	protected function _getAdminModules()
	{
		return Db::i()->selectCol(
			"SELECT module AS ARRAY_KEY, path
			FROM ?_tree t
			JOIN ?_includes i ON t.tree_id=i.tree_id
			JOIN ?_modules m ON i.module_id=m.module_id
			WHERE module IN (?a) AND `show`=1
			GROUP BY module", $this->admin_modules
		);
	}
	
	protected function _getCMSStat()
	{
		$admin_info=array();

		list($html['size'], $html['files'])=$this->_getDirInfo(LAB_PATH_DATA.'/cache');
		list($ext['size'], $ext['files'])=$this->_getDirInfo(LAB_PATH_DATA.'/external');

		$admin_info['cache_files']=intval($html['files']+$ext['files']);
		$admin_info['cache_dir_size']=intval($html['size']+$ext['size']);

		if (config::get('core.cache')
			&& (config::get('core.use_memcached')
			|| config::get('core.use_memcached_db')
			|| config::get('core.use_memcached_tpl'))
			&& !config::get('core.debug_mode')) {
			$cache=Cache_Generic::init('memcache');
			if (is_object($cache)) {
				$b=$cache->getStats();
				$admin_info['cache_memcached']=get_formatted_filesize($b['bytes']);
			}
			else
				self::_error($cache);
		}

		//не учитываем количество гостей и удаленных пользователей
		$admin_info['total_users'] = (Db::i()->selectCell('SELECT COUNT(user_id)	FROM ?_users WHERE `status`>=0'));
		$admin_info['db_version'] = DEMO_MODE?'5.0.45-community-nt':mysqli_get_server_info(Db::i()->link);
		list($admin_info['db_size'], $admin_info['db_table_count'])=$this->_getDbData();

		$admin_info['db_size']=get_formatted_filesize($admin_info['db_size']);
		$admin_info['cache_dir_size']=get_formatted_filesize($admin_info['cache_dir_size']);
		include LAB_PATH_KERNEL.'/install/revision.php';
		$admin_info['cms_version']=config::get('core.version').'.'.$revision.' ('.$branch.')';
		$admin_info['php_version']=DEMO_MODE?'5.2.4':PHP_VERSION;
		
		return $admin_info;
	}
}