<?php
/*
自动扫描磁盘影片到数据库
*/
class ScanModel extends DBModel {
	public  $filter = array('.rmvb', '.mpg', '.flv', '.rm', '.asf', '.wmv', '.mpge', '.avi','.mp3');
	public $files = array();
	public $limit = 0;
	public $mode=0;
	public $basedir;
	public $num=0;
	public $virtual;
	public $player;
	public $server;
	public $lookgid;
	function search($path){
		set_time_limit(999);
		$this->basedir = str_replace('\\', '/' ,realpath($path));
		$this->scandir($path);
		$this->write();
		$this->read();
		if (!defined('SUCCEED_VODCMS')){
			exit();
		}
	}
	function scandir($dir){
		$dh  = opendir($dir);
		while (false !== ($filename = readdir($dh))) {
			$this->limit= $this->limit+1;
			if ($filename != '.' && $filename !='..'){
				if (is_dir($dir.'/'.$filename)){
					$this->scandir($dir.'/'.$filename);
				}elseif( in_array(strrchr($filename, '.'), $this->filter)===true){
					$this->files[] = realpath(stripslashes($dir.'/'.$filename));
				}
			}
		}
		//print_r($this->files);
	}
	function write(){
		if (count($this->files)>0){
			$fp = fopen(ROOT.'Cache/scan.log', 'w');
			fwrite($fp, implode("\n\r", $this->files));
			fclose($fp);
		}
	}
	/*
	从文件读出影片路径然后添加到数据库中
	*/
	function read(){
		$contents = explode("\n\r", file_get_contents(ROOT.'Cache/scan.log'));
		foreach($contents as $filename){
			$this->addmovie($filename);
		}
		unset($contents);
	}
	function addmovie($filename){
		if ($this->mode == 0){
			$data['title'] = addslashes(array_shift(explode(".", basename($filename))));
			$data['mkey'] = substr(md5($filename.$this->category),8 ,16);
		}else{
			$arr = explode('\\', realpath($filename));
			$data['title'] = $arr[count($arr)-2];
			$data['mkey'] = substr(md5(dirname($filename).$data['title']), 8 ,16);
		}
		$data['addtime'] = time();
		$data['modifytime'] = time();
		$data['sid'] = $this->server;
		$data['look'] = 1;
		$data['category'] = $this->category;
		$data['player'] = $this->player;
		$data['lookgid'] = $this->usergroup;
		$data['area'] = $this->area;
		$data['pic'] = 'upload/nopic.gif';
		$data['content'] = _('暂无介绍');
		$data['alt'] = array(addslashes(array_shift(explode(".", basename($filename)))));
		$url = str_replace('\\', '/', $filename);
		$url = addslashes(str_replace(str_replace('\\', '/', stripslashes($this->basedir)), '', $url));
		if ($this->virtual){
			$url = $this->virtual.$url;
		}
		$data['url'] = array($url);
		$movie = new MovieModel();
		$movid = $movie->exists(array('mkey'=>$data['mkey']));
		if ($movid == 0){	//新增
			if ($movie->add($data)===false){
				print_r($movie->error);
				exit;
			}
		}elseif ($this->mode==1){	//连续剧模式
			$movie->addUrl($movid, $data['url'], $data['alt'], 1);
		}
		unset($data);
		$this->num = $this->num+1;
	}
}?>