<?php

class mDeleteDirectories
{
    private $db;
    private $root;
    private $paths;
    private $deletedPaths;

    function __construct($db, $paths, $root = null)
    {
        $this->db = $db;
        $this->setRootDir($root);

        $this->paths = $paths;
        $this->deletedPaths = Array();
    }

    private function setRootDir($value = null)
    {
		if(!is_null($value))
		{
			$this->root = $value;
			return;
		}

        if(!is_null($this->db))
        {
            $this->db->ChangeDatabase(DB_WARPIT_MAIN);
            $sql = "SELECT cValue FROM _WarpitConfig WHERE prefix = 'paths' AND cName = 'warpit_webprojects'";
            if(!$res = $this->db->SQLexecute($sql))
            {
                $this->root = "/";
                return;
            }
            $row = $this->db->fetchAssoc($res);
            $this->root = $row["cValue"];
        }

        if(is_null($this->root))
        {
            $this->root = "/";
        }
    }

    private function cleanPath($inPath)
    {
        return str_replace("//", "/", $inPath);
    }

    public function executeDelete()
    {
        foreach($this->paths as $path)
        {
            $fullPath = $this->cleanPath($this->root . $path);
            if(file_exists($fullPath))
            {
                if(is_dir($fullPath))
                {
                    $this->deleteDirectoryRecursive($fullPath);
                }
                else
                {
                    $this->deleteFile($fullPath);
                }
            }
            else
            {
                $this->deletedPaths[] = Array("type" => "non-existing", "path" => $fullPath );
            }
        }
    }

    function deleteDirectoryRecursive($path)
    {
        $path = $this->cleanPath($path);
        
		$dir = opendir($path);
        while(false !== ( $file = readdir($dir)) )
        {
            if (( $file != '.' ) && ( $file != '..' ))
            {
                $filePath = $this->cleanPath($path . '/' . $file);
                if ( is_dir($filePath) )
                {
                    $this->deleteDirectoryRecursive($filePath);
                }
                else
                {
                    $this->deleteFile($filePath);
                }
            }
        }
        closedir($dir);

        $this->deleteDirectory($path);
    }

    private function deleteDirectory($path)
    {
        $this->deletedPaths[] = Array("type" => "dir", "path" => $path );
        rmdir($path);
    }

    private function deleteFile($file)
    {
        $this->deletedPaths[] = Array("type" => "file", "path" => $file );
        unlink($file);
    }

    public function getLogString()
    {
        $logString = "";

        $logPaths = array_reverse($this->deletedPaths);
        foreach($logPaths as $deletedPath)
        {
            $logString .= $deletedPath["type"] . ": " . $deletedPath["path"] . "<br />";
        }
        return $logString;
    }
}


class mScriptDeleteProjects
{
	private $db;
	private $projectIds;
	private $executedSqls;

	function __construct($db, $projectIds)
	{
		$this->db = $db;
		$this->projectIds = $projectIds;
		$this->executedSqls = Array();
	}

	function deleteProjectsExecute()
	{
		$this->db->ChangeDatabase(DB_WARPIT_WEBCATI_BASE);
		$sql = "SELECT id, proj_name FROM _Projects WHERE id IN (" . implode(",", $this->projectIds) . ")";
		$this->executedSqls[] = $sql;
		
		if(!$projectsToDeleteRes = $this->db->SQLexecute($sql))
		{
			//echo "SQL ERROR IN SCRIPT";
			return;
		}

		if(!$this->db->NumRows($projectsToDeleteRes))
		{
			//echo "No projects with id(s):" . implode(",", $this->projectIds) . " !";
			return;
		}

		while($proj = $this->db->fetchAssoc($projectsToDeleteRes))
		{
			$id = $proj["id"];
			$name = $proj["proj_name"];	
			$projData = $this->db->get('_Projects',$id);	

			$sql = "DELETE from _ProjectsTree WHERE id = $id";
			if(!$this->db->SQLexecute($sql)){return json_encode(Array("success" => FALSE, "STATMENT" => $sql));}
			$sql = "DELETE from _Projects WHERE proj_name = '$name'";
			if(!$this->db->SQLexecute($sql)){return json_encode(Array("success" => FALSE, "STATMENT" => $sql));}
		
			$this->db->ChangeDatabase(DB_WARPIT_WEBCATI);
			$sql = "DROP TABLE IF EXISTS $name";
			if(!$this->db->SQLexecute($sql)){return json_encode(Array("success" => FALSE, "STATMENT" => $sql));}
			$sql = "DROP TABLE IF EXISTS {$name}_tree";
			if(!$this->db->SQLexecute($sql)){return json_encode(Array("success" => FALSE, "STATMENT" => $sql));}
			$sql = "DROP TABLE IF EXISTS {$name}_script";
			if(!$this->db->SQLexecute($sql)){return json_encode(Array("success" => FALSE, "STATMENT" => $sql));}
			$sql = "DROP TABLE IF EXISTS {$name}_language";
			if(!$this->db->SQLexecute($sql)){return json_encode(Array("success" => FALSE, "STATMENT" => $sql));}

			$this->db->ChangeDatabase(DB_WARPIT_WEBCATI_BASE);
			$sqls[] = "DROP TABLE IF EXISTS ".DB_WARPIT_WEBCATI_BASE.".{$name}_statistic";//????

			$sqls[] = "DROP TABLE IF EXISTS ".DB_WARPIT_WEBCATI_BASE.".{$name}_structure";

			$sqls[] = "DROP TABLE IF EXISTS ".DB_WARPIT_WEBCATI_BASE.".{$name}___quotaCalc";
			$sqls[] = "DROP TABLE IF EXISTS ".DB_WARPIT_WEBCATI_BASE.".{$name}___quotaLock";

			$sqls[] = "DROP TABLE IF EXISTS ".DB_WARPIT_WEBCATI_BASE.".{$name}___quotaLimits";
			$sqls[] = "DROP TABLE IF EXISTS ".DB_WARPIT_WEBCATI_BASE.".{$name}___telIndex";

			$sqls[] = "DROP TABLE IF EXISTS ".DB_WARPIT_WEBCATI_BASE.".{$name}___telLog";
			$sqls[] = "DROP TABLE IF EXISTS ".DB_WARPIT_WEBCATI_BASE.".{$name}___EngineLog";

			//clear language table and rotation table!
			$sqls[] = "DELETE FROM  _QuestionRotation WHERE id_project = $id";
			$sqls[] = "DELETE FROM  _LanguageProjects WHERE id_project = $id";

			//clear all intervieweres!
			$sqls[] = "DELETE FROM _www_ids WHERE id_project = $id";
			$sqls[] = "DELETE FROM _www_externalLinks WHERE id_project = $id";

			$sqls[] = "DELETE FROM _ProjectExtraVariables WHERE id_project = $id";

			if(isset($projData['id_telname']) && $projData['id_telname'] && $projData['tel_reserve'])
			{
				$telTable = $this->db->get('_TelephoneTables',$projData['id_telname'],'name');
				$sqls[] = "UPDATE tel___$telTable SET proj_reserved = 0 WHERE proj_reserved = $id";
			}

			foreach ($sqls as $sql) {
				$this->executedSqls[] = $sql;
				if(!$this->db->SQLexecute($sql))
				{
					return FALSE;
				}
			}
		}

		//deletes folder with same name as project if exists
		$deleteDirectoriesScript = new mDeleteDirectories($this->db, Array("/$name"));
		$deleteDirectoriesScript->executeDelete();

		//echo "project with id: $id and name: $name WAS DELETED!";
		return;
	}

	public function getLogString()
    {
        $logString = "<br />";

        $logSqls = $this->executedSqls;
        foreach($logSqls as $sql)
        {
            $logString .= "$sql<br />";
        }
        return $logString;
    }
}


$projectIds = $scriptParams->{"projectIds"};
if($projectIds != null && (count($projectIds) > 0))
{
	$scriptExec = new mScriptDeleteProjects($this->db, $projectIds);
	$scriptExec->deleteProjectsExecute();	
}

?>



