<?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 sitemap_sitemap
{
	function getForSE()
	{
		$sitemap=$this->_getForSE();
		
		if (is_array(config::get('sitemap_modules')) && count(config::get('sitemap_modules'))) {
			$modules=Db::i()->select(
				"SELECT module, name, module_id
				FROM ?_modules
				WHERE module IN (?a) AND disable=0", config::get('sitemap_modules')
			);
		
			foreach ($modules as $module) {
				$classname=$module['module'].'_api';
				Factory::set($classname, $classname, LAB_PATH_MODULES.'/'.$module['module']."/class.api.php");
				$obj=Factory::create($classname);
				$sitemap=array_merge($sitemap, $obj->sitemap());
			}
		}
		return $sitemap;
	}
	

	public function getTree($id=0)
	{
		$this->_loadData();
		return $this->_buildTree($id);
	}
	
	protected function _getForSE($id=0)
	{
		$this->_loadData();
		return $this->_buildSETree($id);
	}
	
	protected function _loadData()
	{
		$this->tmp=Db::i()->select("SELECT * FROM ?_tree WHERE sitemap=1 ORDER BY pos");
	}
	
	protected function _buildTree($id=0)
	{
		$result=$this->_getChildren($id);
		if (count($result)) {
			foreach ($result as $key=>$v) {
				$tree[$key] = array(
				'path' => $v['path'],
				'name' => $v['name'],
				'subtree' => $this->_buildTree($v['tree_id'])
				);
				if (!is_array($tree[$key]['subtree'])) unset($tree[$key]['subtree']);
			}
			return $tree;
		}
	}
	
	protected function _buildSETree($id=0, $tree=array())
	{
		$result=$this->_getChildren($id);
		foreach ($result as $var) {
			$tree[_url(false, false, false, $var['path'])]=array();
			$tree=$this->_buildSETree($var['tree_id'], $tree);
		}
		return $tree;
	}
	
	protected function _getChildren($tree_id)
	{
		$result=array();
		if (is_array($this->tmp)) {
			foreach ($this->tmp as $data) {
				if ($tree_id==$data['parent_id']) {
					$result[]=$data;
					unset($this->tmp[$tree_id]);
				}
			}
		}
		return $result;
	}
}