<?php
/********************************************************************
 *                              DirCMS狟嶺等濬
 *                            ----------------------
 *   begin                : 2009-11-23
 *   copyright            : (C) 2009 DirCMS.cn
 *   email                : uuturn@126.com
 *
 *   $Id: select.class,v 1.0.0 2009-11-23 M Exp $
 ********************************************************************/

class select
{
	public $select;
	public $db;

	function __construct()
	{
		global $db;
		$this->db=$db;
	}

	function getSelect($sname,$default,$table,$createnew=false,$field='menu',$where=1,$js='')
	{
		$cachefile=DIRCMS_ROOT.'data/cache_html/'.$table.'_'.$sname.'.cache.html';
		if(file_exists($cachefile) && !$createnew)
		{
			return get_file_content($cachefile);
		}
		else
		{
			$this->getOption(0,$table,$field,$where);
			$id=preg_replace('/[^a-z0-9_]+/i','_',$sname);
			$selecthtml="<select name={$sname} id='{$id}' {$js}>\n\t<option value=0>{$default}</option>".$this->select."\n</select>\n";
			file_put_contents($cachefile,$selecthtml);
			@chmod($cachefile,0777);
			return $selecthtml;
		}
	}

	function getOption($parentid,$table,$field='menu',$where=1,$defualtvalue=array())
	{
		static $i=0;
		$r=$this->db->fetch_all("SELECT * FROM `{$table}` WHERE {$where} AND {$table}.parentid=".intval($parentid)); 

		if($r)foreach($r as $val)
		{	
			$r_=cache_read('parentid'.$val['id'].'.cache.php',DIRCMS_ROOT.'data/cache_category/');
			if($r_)
			{
				$t="SELECT `".DB_PRE."category`.`id` FROM `".DB_PRE."category` WHERE {$where} AND `".DB_PRE."category`.`parentid`=".$val['id']." LIMIT 0,1";
			}
			else
			{
				$t="SELECT `".DB_PRE."category`.`id` FROM `".DB_PRE."category` WHERE {$where} LIMIT 0,1";
			}

			if($table==DB_PRE.'category')
			{
				if($this->db->fetch_one($t))
				{
					$islelected=in_array($val['id'],$defualtvalue)?' selected="selected"':'';
					$pre=@str_repeat("&nbsp;&nbsp;",$i*3);
					$this->select.="\n\t<option value={$val['id']}$islelected>{$pre}念{$val[$field]}</option>";
					$i++;
					$this->getOption(intval($val['id']),$table,$field,$where,$defualtvalue);
				}
			}
			else
			{
				$islelected=in_array($val['id'],$defualtvalue)?' selected="selected"':'';
				$pre=@str_repeat("&nbsp;&nbsp;",$i*3);
				$this->select.="\n\t<option value={$val['id']}$islelected>{$pre}念{$val[$field]}</option>";
				$i++;
				$this->getOption(intval($val['id']),$table,$field,$where,$defualtvalue);
			}
		}
		$i--;
	}
	
	function __destruct()
	{
		unset($this->select); //庋溫曹講
	}
}
?>