<?
Class Projects{
	public $error = array();
	
	function saveProject($project_id=0){
		$project_id		= (int)$project_id;
		$domain 			= clearText($_POST['domain']);
		$path 				= clearText($_POST['path']);
		$spath 				= clearText($_POST['spath']);
		$scode 				= clearText($_POST['scode']);
		$ext 				= clearText($_POST['ext']);
		$exc 				= clearText($_POST['exc']);
		$excf				= clearText($_POST['excf']);
		$enc 				= clearText($_POST['enc']);
		$crypt_type			= clearText($_POST['crypt_type']);
		$maxdir				= clearText($_POST['maxdir']);
		$maxtime			= clearText($_POST['maxtime']);
		$maxdir				= (int)$maxdir>0 ? (int)$maxdir : 0;
		$maxtime			= (int)$maxtime>0 ? (int)$maxtime : 0;
		$check_hour 		= (int)$_POST['check_hour']>0 ? (int)$_POST['check_hour'] : 3;
		$protocol			= $_POST['protocol']=="https://" ? 'https://' : 'http://';
		$domain				= str_replace(array("https://","http://"),"",$domain);
		$domain 			= parse_url($protocol.$domain);
		$domain 			= $domain['host'];
		$is_active			= $_POST['is_active']=="no" ? 'no' : 'yes';
		$pusers_id			= (int)$_POST['users_id'];
		$is_change_email	= $_POST['is_change_email']=="no" ? 'no' : 'yes';
		
		if(empty($domain)){
			$this->error[] = "Укажите домен";
		}
		if(empty($path)){
			$this->error[] = "Укажите адрес скрипта мониторинга";
		}
		if(empty($spath)){
			$this->error[] = "Укажите стартовый путь мониторинга";
		}
		if(empty($scode)){
			$this->error[] = "Укажите секретный код";
		}
		if(empty($ext)){
			$this->error[] = "Укажите расширения сканируемых файлов!";
		}
		
		if($project_id>0){
			$where = array("id=".Serval::call('db')->Quote($project_id)); 
			if(Serval::call('Auth')->Data['type']=="user"){
      	$where[] = "(EXISTS(
					SELECT users_id FROM mod_projects2users WHERE mod_projects2users.projects_id=mod_projects.id
					AND mod_projects2users.users_id='".Serval::call('Auth')->ID."'
				) OR users_id=".Serval::call('Auth')->ID.")";
			}
			$getProject = Serval::call('db')->SelectRecord("mod_projects","id,users_id",implode(" AND ",$where));
			if(!$getProject){
				$this->error[] = "Проект не найден!";
			}
		}

		if(count($this->error)==0){
			$row = array(
					'protocol'=>$protocol,
					'domain'=>$domain,
					'path'=>$path,
					'spath'=>$spath,
					'scode'=>$scode,
					'ext'=>$ext,
					'exc'=>$exc,
					'excf'=>$excf,
					'enc'=>$enc,
					'check_hour'=>$check_hour,
					'crypt_type'=>$crypt_type,
					'maxdir'=>$maxdir,
					'maxtime'=>$maxtime,
					'is_active'=>$is_active,
					'is_change_email'=>$is_change_email,
				);
				
			if($project_id>0){  
				if(Serval::call('Auth')->Data['type']=="admin"){
					if($pusers_id>0){
						$row['users_id'] = $pusers_id;
					}
				}                                
				if(!Serval::call('db')->update("mod_projects",$row,"id='{$getProject['id']}'")){
					$this->error[] = "Не могу сохранить проект...";
					return false;
				}
			}else{
				$row['users_id'] = Serval::call('Auth')->ID;
				if(Serval::call('Auth')->Data['type']=="admin"){
					if($pusers_id>0){
						$row['users_id'] = $pusers_id;
					}
				} 
				$row['date'] = 'SQL_TIME_NOW()';
				
				$project_id = Serval::call('db')->insert("mod_projects",$row);
				if(!$project_id){
					$this->error[] = "Не могу создать проект...";
					return false;
				}
			}
			if($project_id>0){
				if($getProject['users_id']==Serval::call('Auth')->ID || Serval::call('Auth')->Data['type']=="admin"){
					Serval::call('db')->run("DELETE FROM mod_projects2users WHERE mod_projects2users.projects_id='{$project_id}'");
	      	if(is_array($_POST['users']) && count($_POST['users'])>0){
						foreach($_POST['users'] as $users_id){
							Serval::call('db')->insert("mod_projects2users",array('projects_id'=>$project_id,'users_id'=>(int)$users_id));
						}
					}
				}
			}
			return true;
		}
		return false;
	}
	
	function getProject($id){
		$res = false;
		switch(Serval::call('Auth')->Data['type']){
			case 'admin':
				$res = Serval::call('db')->SelectRecord("mod_projects","mod_projects.*","id=".Serval::call('db')->Quote($id));
			break;
			default:
				$res = Serval::call('db')->SelectRecord("mod_projects",
					"mod_projects.*",
					"mod_projects.id=".Serval::call('db')->Quote($id)." AND (EXISTS(
					SELECT users_id FROM mod_projects2users WHERE mod_projects2users.projects_id=mod_projects.id
					AND mod_projects2users.users_id='".Serval::call('Auth')->ID."'
				) OR users_id=".Serval::call('Auth')->ID.")");
			break;
		}

		if($res){
			if($users = Serval::call('db')->Select("mod_projects2users","","projects_id='{$res['id']}'")){
				foreach($users as $v){
					$res['_users'][$v['users_id']] = $v['users_id'];
				}
				unset($users);
			}
		}else{
			$this->error[] = "У Вас нет прав делать это!";
		}
		return $res;
	}
	
	function getList($param = array()){
		$where = array();
		if(mb_strlen($_GET['q'],"utf-8")>2){
			$where[] = "(domain LIKE(".Serval::call('db')->Quote('%'.clearText($_GET['q']).'%')."))";
		}
		switch(Serval::call('Auth')->Data['type']){
			case 'admin':
				if(isset($_GET['users_id']) && $_GET['users_id']<=0){
					unset($_SESSION['list_users_id']);
				}
				$_users_id = (int)$_GET['users_id']>0 ? (int)$_GET['users_id'] : (int)$_SESSION['list_users_id'];
				if($_users_id>0){
					$where[] = "mod_projects.users_id=".intval($_users_id);
					$_SESSION['list_users_id'] = $_users_id;
				}
				return Serval::call('db')->SelectSet("mod_projects","mod_projects.*, 
					(SELECT fio FROM mod_users WHERE mod_users.id=mod_projects.users_id LIMIT 1) AS createUser,
					IF(EXISTS(
						SELECT mod_scan.is_verified FROM mod_scan 
							WHERE mod_scan.project_id=mod_projects.id 
							AND mod_scan.status NOT IN('process','new')
							AND mod_scan.is_verified='no'
							AND mod_scan.is_last='no'	
					),'yes','no') AS is_verified,
					IF(mod_projects.status='process',(SELECT mod_scan.step FROM mod_scan WHERE mod_scan.project_id=mod_projects.id AND mod_scan.status='process' ORDER BY date  DESC LIMIT 1),'') AS _processStep",
					implode(" AND ",$where),"ORDER BY REPLACE(mod_projects.domain,'www.','')",20,$param['page']);
			break;
			default:
				return Serval::call('db')->SelectSet("mod_projects",
					"mod_projects.*, 
						(SELECT fio FROM mod_users WHERE mod_users.id=mod_projects.users_id LIMIT 1) AS createUser,
						IF(EXISTS(
							SELECT mod_scan.is_verified FROM mod_scan 
								WHERE mod_scan.project_id=mod_projects.id 
								AND mod_scan.status NOT IN('process','new')
								AND mod_scan.is_verified='no'
								AND mod_scan.is_last='no'	
						),'yes','no') AS is_verified,
						IF(mod_projects.status='process',(SELECT mod_scan.step FROM mod_scan WHERE mod_scan.project_id=mod_projects.id AND mod_scan.status='process' ORDER BY date  DESC LIMIT 1),'') AS _processStep",
					"(EXISTS(
					SELECT users_id FROM mod_projects2users WHERE mod_projects2users.projects_id=mod_projects.id
					AND mod_projects2users.users_id='".Serval::call('Auth')->ID."'
				) OR users_id=".Serval::call('Auth')->ID.")","ORDER BY REPLACE(mod_projects.domain,'www.','')",20,$param['page']);
			break;
		}
	}
	
	function getReportsWarning(){
		$where = array(
			"mod_scan.project_id=mod_projects.id",
			"mod_scan.status IN('warning','error')",
			"mod_scan.is_verified='no'",
			"(EXISTS(
					SELECT users_id FROM mod_projects2users WHERE mod_projects2users.projects_id=mod_projects.id
					AND mod_projects2users.users_id='".Serval::call('Auth')->ID."'
				) OR mod_projects.users_id=".Serval::call('Auth')->ID.")"
		);
		$result = array();
		switch(Serval::call('Auth')->Data['type']){
			case 'admin':
				$res = Serval::call('db')->Select("mod_scan, mod_projects",
							"mod_scan.id,  mod_scan.project_id, mod_scan.date, mod_scan.status, mod_scan.error_msg,  mod_scan.new_c, mod_scan.change_c, mod_scan.delete_c,
								mod_projects.domain, mod_projects.users_id, 
								mod_scan.status AS pStatus, mod_scan.error_msg AS pError_msg,
								(SELECT fio FROM mod_users WHERE mod_users.id=mod_projects.users_id LIMIT 1) AS createUser",
							implode(" AND ",$where),"ORDER BY mod_scan.date DESC");
			break;
			default:
				$res = Serval::call('db')->Select("mod_scan, mod_projects",
					"mod_scan.id,  mod_scan.project_id, mod_scan.date, mod_scan.status, mod_scan.error_msg,  mod_scan.new_c, mod_scan.change_c, mod_scan.delete_c,
								mod_projects.domain, mod_projects.users_id, 
								mod_scan.status AS pStatus, mod_scan.error_msg AS pError_msg,
						(SELECT fio FROM mod_users WHERE mod_users.id=mod_projects.users_id LIMIT 1) AS createUser",
					implode(" AND ",$where),"ORDER BY mod_scan.date DESC");
			break;
		}

		if($res){
			foreach($res as $val){
				$result[$val['project_id']]['project_id'] = $val['project_id'];
				$result[$val['project_id']]['users_id'] 	= $val['users_id'];
				$result[$val['project_id']]['domain'] 		= $val['domain'];
				$result[$val['project_id']]['createUser']	= $val['createUser'];
				$result[$val['project_id']]['status'] 		= $val['pStatus'];
				$result[$val['project_id']]['error_msg'] 	= $val['pError_msg'];
				$result[$val['project_id']]['_'.$val['status']]+=1;
				if(empty($result[$val['project_id']]['date'])){
					$result[$val['project_id']]['date']				= $val['date'];	
				}
				$result[$val['project_id']]['_log'][] = $val;
			}	
			unset($res);		
		}
		return $result;
	}
	
	function deleteProject($id){
		Serval::call('db')->run("DELETE FROM mod_projects WHERE id='".(int)$id."'");
		Serval::call('db')->run("DELETE FROM mod_projects2users WHERE projects_id='".(int)$id."'");
		Serval::call('db')->run("DELETE FROM mod_scan WHERE project_id='".(int)$id."'");
		Serval::call('db')->run("DELETE FROM mod_scan_log WHERE project_id='".(int)$id."'");
		Serval::call('db')->run("DELETE FROM mod_scan_dir WHERE project_id='".(int)$id."'");
		
		return array('status'=>'ok');
	}
	
	function getLogList($param = array()){
		$where = array(
			"project_id=".(int)$param['project_id'],
			"mod_scan.status IN('warning','error')"
		);
		return Serval::call('db')->SelectSet("mod_scan","",implode(" AND ",$where),"ORDER BY date DESC",20,$param['page']);
	}
	
	function getLogInfo($project_id,$scan_id){
		if($get = Serval::call("db")->SelectRecord('mod_scan',"","project_id='".(int)$project_id."' AND id=".(int)$scan_id) ){
			
			$status = array('new','change','delete');
			
			$list = array(
				'project_id'=>$project_id,
				'scan_id'=>$scan_id,
				'is_verified'=>$get['is_verified'],
			);

			foreach($status as $val){
				if($log = $this->getLogInfoPage(array('status'=>$val,'scan_id'=>$scan_id,'project_id'=>$project_id))){
					$list['list'][$val] = $log;
				}
			}
			return $list;
		}
		return false;
	}
	
	function getLogInfoPage($param){
		$limit = 100;
		$page = (int)$param['page']>0 ? (int)$param['page'] : 1;
		return Serval::call('db')->SelectSet("mod_scan_log","","status='{$param['status']}' AND scan_id='".(int)$param['scan_id']."' AND project_id='".$param['project_id']."'","",$limit,$page);
	}
	
	function getLogInfoFull($project_id,$scan_id){
		if($get = Serval::call("db")->SelectRecord('mod_scan',"","project_id='".(int)$project_id."' AND id=".(int)$scan_id) ){
			if($log = Serval::call("db")->Select("mod_scan_log","","scan_id='".(int)$scan_id."' AND status!='ok' AND project_id='".(int)$project_id."'")){
				$list = array();
				$list['project_id'] = $project_id;
				$list['scan_id'] = $scan_id;
				$list['is_verified'] = $get['is_verified'];
				foreach($log as $val){
					$list['list'][$val['status']][] = $val; 
				}
				unset($log);
				return $list;
			}
		}
		return false;
	}

}
?>