<?php

class FlushHandler {
	
	private $ScriptFilePath;
	private $FlushUsername;
	private $FlushPassword;
	private $FlushPaths = array();
	private $FlushPathsCount = 0;
	private $Emails = array();
	private $FilePaths = array();
	private $Unique;
	private $FlushFileMaxSize = '30000';// Bytes
	private $PathsMaxCountInFlushFile = '512';// Strings (URLs)
	private $RequestResult = array();
	private $Errors = array();
	
	public function FlushHandler() {
		GLOBAL $COMMON_VARS;
		$this->setScriptFilePath($COMMON_VARS['flush_script_filepath']);
		$this->setFlushUsername($COMMON_VARS['flush_username']);
		$this->setFlushPassword($COMMON_VARS['flush_password']);
		$this->Unique = getUnique32();
	}
	
	public function getScriptFilePath() {
		return $this->ScriptFilePath;
	}
	
	public function setScriptFilePath($filepath) {
		GLOBAL $TOOLS_PATH, $COMMON_VARS, $ROOT_PATH;
		chdir($ROOT_PATH);
		if(file_exists($filepath)){
			include_once($TOOLS_PATH.'/File.functions.inc');
			if(substr($filepath, 0, 1) == '/') $filepath = substr($filepath, 1);
			$fileinfo = getFileDirInfo($filepath, false, true, true, false, false, false);
			$perm = isset($COMMON_VARS['special_rights_engine_path'][$filepath]) ? $COMMON_VARS['special_rights_engine_path'][$filepath] : $COMMON_VARS['default_rights_engine'];
			if($fileinfo['type'] == 'file'){
				if(checkFileDirPerms($perm, $fileinfo['perm'])) {
					$this->ScriptFilePath = $filepath;
					return true;
				}
				else return $this->returnError('Script file path "'.$filepath.'" permissions are not valid');
			}
			else return $this->returnError('Script file path "'.$filepath.'" is not a file');
		}
		else return $this->returnError('Script file path "'.$filepath.'" doesn\'t exist');
	}
	
	public function setFlushUsername($username) {
		if(empty($username)) return $this->returnError('Flush username is empty');
		if(!is_string($username)) return $this->returnError('Flush Username "'.$username.'" is not valid');
		$this->FlushUsername = $username;
		return true;
	}
	
	public function setFlushPassword($password) {
		if(empty($password)) return $this->returnError('Flush password is empty');
		if(!is_string($password) && !is_integer($password)) return $this->returnError('Flush password "'.$password.'" is not valid');
		$this->FlushPassword = $password;
		return true;
	}
	
	public function setFlushPaths($paths, $check = false) {
		if(!is_array($paths)) return $this->returnError('Flush paths are not an array');
		if(empty($paths)) return $this->returnError('Flush paths array is empty');
		$paths = array_values($paths);
		$count = count($paths);
		if($check) {
			for ($i = 0; $i < $count; $i++) {
				if(empty($paths[$i])) return $this->returnError('Flush path "'.$paths[$i].'" is not string');
				if(!is_string($paths[$i])) return $this->returnError('Flush path "'.$paths[$i].'" is not string');
				$path = checkURL($paths[$i]);
				if($path != $paths[$i]) return $this->returnError('Flush path "'.$paths[$i].'" is not valid');
			}
		}
		$this->FlushPaths = $paths;
		$this->FlushPathsCount = $count;
		return true;
	}
	
	public function setEmails($emails, $check = false) {
		if(!is_array($emails)) return $this->returnError('Emails are not an array');
		if($check){
			foreach($emails as $email)
				if(!is_Email($email)) return $this->returnError('Email "'.$email.'" is not valid');
		}
		$this->Emails = $emails;
		return true;
	}
	
	public function splitFlushPathsToFiles() {
		GLOBAL $ROOT_PATH, $COMMON_VARS;
		if(empty($this->FlushPaths)) return $this->returnError('Flush paths array is empty'); 
		$this->FilePaths = array();
		$indexes = array();
		$offset = 0;
		$size = 0;
		$url_count = 0;
		for ($i = 0; $i < $this->FlushPathsCount; $i++){
			$path_size = strlen($this->FlushPaths[$i]) + 2;
			$size += $path_size;
			$url_count++;
			if($size > $this->FlushFileMaxSize || $url_count >= $this->PathsMaxCountInFlushFile){
				$length = $i - $offset;
				$indexes[$offset] = $length;
				$offset = $i;
				$size = $path_size;
				$url_count = 0;
			}
		}
		if(empty($indexes)) $indexes[0] = $this->FlushPathsCount;
		if((end($indexes) + key($indexes)) != $this->FlushPathsCount) $indexes[$offset] = $this->FlushPathsCount - $offset;
		chdir($ROOT_PATH);
		$ind = 0;
		foreach($indexes as $key => $value){
			$this->FilePaths[$ind] = $COMMON_VARS['temp_dir'].'/flush_'.$this->Unique.'_'.$key.'-'.$value.'.txt';
			$result = file_put_contents ($ROOT_PATH.'/'.$this->FilePaths[$ind], implode("\r\n", array_slice($this->FlushPaths, $key, $value)));
			if($result === false){
				for ($j = 0; $j < $ind; $j++) unlink($ROOT_PATH.'/'.$this->FilePaths[$j]);
				return $this->returnError('Can not create autoflush file "'.$this->FilePaths[$ind].'"');
			}
			$ind++;
		}
		return true;
	}
	
	public function getFilePaths() {
		return $this->FilePaths;
	}
	
	public function launchFlushScript($break_on_error = true) {
		GLOBAL $ROOT_PATH, $TOOLS_PATH;
		if(!empty($this->Errors)) return array(array('message' => $this->getLastError()));
		if(empty($this->FilePaths)){
			if(!$this->splitFlushPathsToFiles()) return false;
		}
		include_once($TOOLS_PATH.'/func.php');
		$count = count($this->FilePaths);
		for ($i = 0; $i < $count; $i++){
			$this->RequestResult[$i]['filepath'] = $this->FilePaths[$i];
			$request = './'.$this->ScriptFilePath.' --user '.$this->FlushUsername.' --pwd '.$this->FlushPassword.' --file '.$this->FilePaths[$i];
			if(!empty($this->Emails)) $request .= ' --email "'.implode(',', $this->Emails).'"';
			$this->RequestResult[$i]['request'] = $request;
			$result = mysystem($request);
			preg_match("/resultCode: [0-9]{1,3}/", $result, $matches);
			if(!empty($matches)) preg_match("/[0-9]{1,3}/", $matches[0], $code);
			$this->RequestResult[$i]['code'] = @$code[0];
			preg_match("/resultMsg: .*/", $result, $matches);
			$this->RequestResult[$i]['message'] = @substr($matches[0], strlen('resultMsg: '));
			preg_match("/estTime: [0-9]{1,5}/", $result, $matches);
			if(!empty($matches)) preg_match("/[0-9]{1,5}/", $matches[0], $time);
			$this->RequestResult[$i]['time'] = @$time[0];
			preg_match("/sessionID: [[:alnum:]]{1,32}/", $result, $matches);
			$this->RequestResult[$i]['session'] = @substr($matches[0], strlen('sessionID: '));
			if($this->RequestResult[$i]['code'] != '100' && $break_on_error) {
				if(empty($this->RequestResult[$i]['message']) && strlen($result) < 100) $this->RequestResult[$i]['message'] = $result;
				break;
			}
		}
		for($i = 0; $i < $count; $i++) unlink($ROOT_PATH.'/'.$this->FilePaths[$i]);
		return $this->RequestResult;
	}
	
	public function getResult() {
		return $this->RequestResult;
	}
	
	private function returnError($error) {
		$this->setError($error);
		return false;
	}
	
	private function setError($error) {
		$this->Errors[] = $error;
	}
	
	public function getErrors() {
		return $this->Errors;
	}
	
	public function getLastError() {
		return end($this->Errors);
	}
	
}

?>