<?php
class ArchiveRoutine { 
	function deleteDir($dirPath) {
		if (! is_dir($dirPath)) {
			throw new InvalidArgumentException("$dirPath must be a directory");
		}
		if (substr($dirPath, strlen($dirPath) - 1, 1) != '/') {
			$dirPath .= '/';
		}
		$files = glob($dirPath . '*', GLOB_MARK);
		foreach ($files as $file) {
			if (is_dir($file)) {
				self::deleteDir($file);
			} else {
				unlink($file);
			}
		}
		$handle = opendir($dirPath);
		closedir($handle);
		rmdir($dirPath);
	}

	function isDirEmpty($dirPath) {
		if (!is_readable($dirPath)){
			return NULL; 
		} else {
			return (count(scandir($dirPath)) == 2);
		} 
	}

	function copyDirectory($source, $dest) {
		$sourceHandle = opendir($source);
	
		if (!$sourceHandle) {
		return false;
		}
	
		while ($file = readdir($sourceHandle)) {
			if ($file == '.' || $file == '..')
				continue;

			if (is_dir($source . '/' . $file)) {
				if (!file_exists($dest . '/' . $file)) {
					mkdir($dest . '/' . $file, 0755);
				}
			self::copyDirectory($source . '/' . $file, $dest . '/' . $file, $excludeSvnFolders);
			} else {
				copy($source . '/' . $file, $dest . '/' . $file);
			}
		}
		
		return true;
	}
}

function createPollObjectArc($cn, $skpollingobject, $iduser, $skipIfArcFolderExists = FALSE){

	if (getSetting('portal','polls.createarchive',0) != 1) {
		//если опция создания архива отключена
		return true;
	}

	$arRoutine = new ArchiveRoutine; 
	$pobj = db_getPollingObject($cn, $skpollingobject);
	if ($pobj === NULL || sizeof($pobj) == 0 || sizeof($pobj[0]) == 0){
		logmessage('Create pollobject archiev : Error - for object '.$skpollingobject.' not exists data in DB');
		return false;
	}
	try {
		$hash = $pobj[0]['objectversionhash'];
		$arcroot = getSetting('storage','arcroot',realpath(dirname(__FILE__).'/../').'/arc/');
		$arcrootfolder = $arcroot.'/'.$hash.'/';
		if (!file_exists($arcrootfolder)) {
			if (!mkdir($arcrootfolder, 0777, true)){
				logmessage('Create pollobject archiev : Error folder create - '.$arcrootfolder);
				return false;
			}
		}

		$idpollingobjectarchive = db_createPollingObjectsArchive($cn, $skpollingobject, $iduser, TRUE, FALSE); 
		if (!isset($idpollingobjectarchive)){
			logmessage('Create pollobject archiev : Error in call db_createPollingObjectsArchive - $idpollingobjectarchive was NULL');
			return false;
		} else {
			db_createPollingObjectsArchiveResourcesForObject($cn, $idpollingobjectarchive);
			db_createPollingObjectsArchiveResourcesForReport($cn, $idpollingobjectarchive);		
		}

		// already arc was created
		if (!$arRoutine->isDirEmpty($arcrootfolder) && $skipIfArcFolderExists) {
			return true;
		}
			
		$idbranch = db_getIDBranch($cn,$pobj[0]['skbranch']);
		$flroot = getSetting('storage','fileroot',realpath(dirname(__FILE__).'/../').'/data/');
		$langs = db_getlanguagesForReport($cn, $pobj[0]['r_guid'], $pobj[0]['skbranch'] );
		for($i=0; $i<sizeof($langs); $i++){
			if (!file_exists($arcrootfolder.(strlen($langs[$i]['lang_short']) == 0 ? '' : '/'.$langs[$i]['lang_short'].'/'))) {
				if (!mkdir($arcrootfolder.(strlen($langs[$i]['lang_short']) == 0 ? '' : '/'.$langs[$i]['lang_short'].'/'), 0777, true)){
					logmessage('Create pollobject archiev : Error folder create - '.$arcrootfolder.(strlen($langs[$i]['lang_short']) == 0 ? '' : '/'.$langs[$i]['lang_short'].'/'));
				}
			}

			$fname = $flroot.'/'.$idbranch.'/'.(strlen($langs[$i]['lang_short']) == 0 ? '' : '/'.$langs[$i]['lang_short'].'/').$pobj[0]['o_guid'].'_'.$pobj[0]['r_guid'];
		
			if (!is_readable($fname.'.htm')) {
				logmessage('Create pollobject archiev : Error reading file - '.$fname);
			} else {
				if (!copy($fname.'.htm', $arcrootfolder.(strlen($langs[$i]['lang_short']) == 0 ? '' : '/'.$langs[$i]['lang_short'].'/').$pobj[0]['o_guid'].'_'.$pobj[0]['r_guid'].'.htm')){
					logmessage('Create pollobject archiev : Error copy file - '.$fname.'.htm');
				}
				if (file_exists($fname.'.files')){
					if (!mkdir($arcrootfolder.(strlen($langs[$i]['lang_short']) == 0 ? '' : '/'.$langs[$i]['lang_short'].'/').$pobj[0]['o_guid'].'_'.$pobj[0]['r_guid'].'.files', 0777, true)){
						logmessage('Create pollobject archiev : Error folder create - '.$arcrootfolder.(strlen($langs[$i]['lang_short']) == 0 ? '' : '/'.$langs[$i]['lang_short'].'/').$pobj[0]['o_guid'].'_'.$pobj[0]['r_guid'].'.files');
					}
					if(!$arRoutine->copyDirectory($fname.'.files', $arcrootfolder.(strlen($langs[$i]['lang_short']) == 0 ? '' : '/'.$langs[$i]['lang_short'].'/').$pobj[0]['o_guid'].'_'.$pobj[0]['r_guid'].'.files')){
						logmessage('Create pollobject archiev : Error folder copy - '.$fname.'.files');
					}
				}
			}
		}
		$delete = db_deletePollingObjectsArchivesBySetupDepth($cn, $skpollingobject);
		for($i=0; $i<sizeof($delete); $i++){
			$hash = $pobj[0]['objectversionhash'];
			$arcroot = getSetting('storage','arcroot',realpath(dirname(__FILE__).'/../').'/arc/');
			$arcrootfolder = $arcroot.'/'.$hash.'/';
			if (file_exists($arcrootfolder)) {
				$arRoutine->deleteDir($arcrootfolder);
				logmessage('delete polling objec arhiev was successful for dir '.$arcrootfolder);
			}
		}
	} catch (Exception $e) {
		logmessage("Create pollobject archiev : Error -  ".$e->getMessage());
	}
	
}

function deletePollObjectArc($cn, $skpollingobject, $idpolltype){
	try {
		$arRoutine = new ArchiveRoutine; 
		db_deletePollingObjectsArchive($cn, $skpollingobject, $idpolltype);
		$poar = db_getPollingObjectsArchivesToDelete($cn, $skpollingobject, $idpolltype);
		for($p=0; $p<sizeof($poar); $p++){
				$hash = $pobj[0]['objectversionhash'];
				$arcroot = getSetting('storage','arcroot',realpath(dirname(__FILE__).'/../').'/arc/');
				$arcrootfolder = $arcroot.'/'.$hash.'/';
				if (file_exists($arcrootfolder)) {
					$arRoutine->deleteDir($arcrootfolder);
					logmessage('delete polling objec arhiev was successful for dir '.$arcrootfolder);
				}
		}	
	} catch (Exception $e) {
		logmessage("function deletePollObjectArc: Error ".$e->getMessage());
	}
}

?>