using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Bitrix.UI;
using System.IO;
using Bitrix.Services;
using System.Reflection;
using Bitrix.Configuration;
using Bitrix.Installer;
using System.Text.RegularExpressions;


public partial class bitrix_install_Step4 : BXWizardStep
{
	bool errors;

	protected void Page_Init(object sender, EventArgs e)
	{
       	TrustLevel.Text = BXInstaller.GetMessage(this, "NA");
       	AjaxVersion.Text = BXInstaller.GetMessage(this, "NotInstalled");
	}

	public override void Activate()
	{
		FillServerVersion();

		FillNetVersion();

		FillRootAccess();

		FillUploadAccess();

		FillPublicAccess();

		FillWebConfigAccess();

		FillAjaxVersion();

		//FillCreateFolder();
        FillFileSystemAccess();

        FillTrustLevel();

		btnNext.Enabled = !errors;
	}

	private void FillWebConfigAccess()
	{
		try
		{
			WebConfigAccess.Text = BXInstaller.GetMessage(this, "FileReadWriteAllowed");
			BXWebConfig config = new BXWebConfig();
			config.Load(MapPath("~/web.config"));
			config.Save();
			WebConfigAccess.Style.Add(HtmlTextWriterStyle.Color, "#009900");
		}
		catch
		{
			WebConfigAccess.Text = BXInstaller.GetMessage(this, "FileWriteNotAllowed");
			WebConfigAccess.Style.Add(HtmlTextWriterStyle.Color, "#ff0000");
			errors = true;
		}
	}

	private void FillPublicAccess()
	{
		try
		{
			PublicAccess.Text = BXInstaller.GetMessage(this, "FolderReadWriteAllowed");
			string fileName = Guid.NewGuid().ToString();
			using (FileStream fs = File.Create(Request.MapPath("~/" + fileName + ".txt")))
			{
				fs.Close();
			}
			PublicAccess.Style.Add(HtmlTextWriterStyle.Color, "#009900");
			File.Delete(Request.MapPath("~/" + fileName + ".txt"));
		}
		catch
		{
			PublicAccess.Text = BXInstaller.GetMessage(this, "FolderWriteNotAllowed");
			PublicAccess.Style.Add(HtmlTextWriterStyle.Color, "#ff0000");
			errors = true;
		}
	}

    /*
	private void FillCreateFolder()
	{
		string folderName = Guid.NewGuid().ToString();
		string path = MapPath("~/" + folderName);
		try
		{
			Directory.CreateDirectory(path);
		}
		catch
		{
			CreateFolder.Text = HttpUtility.HtmlEncode("Не удалось создать папку " + path);
			CreateFolder.Style.Add(HtmlTextWriterStyle.Color, "#ff0000");
			errors = true;
			return;
		}
		finally
		{
			try
			{
				Directory.Delete(path);
			}
			catch
			{
			}
		}
		CreateFolder.Text = "Создание папки прошло успешно.";
		CreateFolder.Style.Add(HtmlTextWriterStyle.Color, "#009900");
	}
    */
    private AspNetHostingPermissionLevel GetCurrentTrustLevelName() 
    {
        foreach (AspNetHostingPermissionLevel trustLevel in
                new AspNetHostingPermissionLevel[] {
                AspNetHostingPermissionLevel.Unrestricted,
                AspNetHostingPermissionLevel.High,
                AspNetHostingPermissionLevel.Medium,
                AspNetHostingPermissionLevel.Low,
                AspNetHostingPermissionLevel.Minimal 
            })
        {
            try
            {
                new AspNetHostingPermission(trustLevel).Demand();
            }
            catch (System.Security.SecurityException)
            {
                continue;
            }

            return trustLevel;
        }
        return AspNetHostingPermissionLevel.None;
    }

    private void FillFileSystemAccess() 
    {
        string folderName = Guid.NewGuid().ToString();
        string testPhysicalPath = System.Web.Hosting.HostingEnvironment.MapPath(string.Concat("~/", folderName));
        try
        {
            Directory.CreateDirectory(testPhysicalPath);
            CreateFolder.Text = BXInstaller.GetMessage(this, "Allowed");
            CreateFolder.Style.Add(HtmlTextWriterStyle.Color, "#009900");
        }
        catch (Exception ex)
        {
            string errorText = string.Empty;
            System.Security.SecurityException securityEx = ex as System.Security.SecurityException;
            if (securityEx != null)
            {
                if (securityEx.PermissionType == typeof(System.Security.Permissions.FileIOPermission))
                    errorText = string.Format(BXInstaller.GetMessage(this, "FolderCreate.FileSystemError"), ex.GetType().ToString());
                else
                    errorText = string.Format(BXInstaller.GetMessage(this, "FolderCreate.SecurityError"), ex.GetType().ToString());
            }
            else
                errorText = string.Format(BXInstaller.GetMessage(this, "FolderCreate.Error"), ex.GetType().ToString());

            CreateFolder.Text = HttpUtility.HtmlEncode(errorText);
            CreateFolder.Style.Add(HtmlTextWriterStyle.Color, "#ff0000");
            errors = true;
        }
        finally
        {
            try
            {
                if (Directory.Exists(testPhysicalPath))
                    Directory.Delete(testPhysicalPath);
            }
            catch (Exception) { }
        }
    }

	private void FillUploadAccess()
	{
		try
		{
			UploadAccess.Text = BXInstaller.GetMessage(this, "FolderReadWriteAllowed");
			string fileName = Guid.NewGuid().ToString();
			using (FileStream fs = File.Create(Request.MapPath("~/upload/" + fileName + ".txt")))
			{
				fs.Close();
			}
			UploadAccess.Style.Add(HtmlTextWriterStyle.Color, "#009900");
			File.Delete(Request.MapPath("~/upload/" + fileName + ".txt"));
		}
		catch
		{
			UploadAccess.Text = BXInstaller.GetMessage(this, "FolderWriteNotAllowed");
			UploadAccess.Style.Add(HtmlTextWriterStyle.Color, "#ff0000");
			errors = true;
		}
	}

	private void FillRootAccess()
	{
		try
		{
			RootAccess.Text = BXInstaller.GetMessage(this, "FolderReadWriteAllowed");
			string fileName = Guid.NewGuid().ToString();
			using (FileStream fs = File.Create(Request.MapPath("~/bitrix/" + fileName + ".txt")))
			{
				fs.Close();
			}
			RootAccess.Style.Add(HtmlTextWriterStyle.Color, "#009900");
			File.Delete(Request.MapPath("~/bitrix/" + fileName + ".txt"));
		}
		catch
		{
			RootAccess.Text = BXInstaller.GetMessage(this, "FolderWriteNotAllowed");
			RootAccess.Style.Add(HtmlTextWriterStyle.Color, "#ff0000");
			errors = true;
		}
	}

	private void FillNetVersion()
	{
		NetVersion.Text = System.Environment.Version.ToString();
		if (System.Environment.Version.Major < 2)
		{
			NetVersion.Style.Add(HtmlTextWriterStyle.Color, "#ff0000");
			errors = true;
		}
		else
		{
			NetVersion.Style.Add(HtmlTextWriterStyle.Color, "#009900");
		}
	}

	private void FillServerVersion()
	{
		string serverVersion = Request.ServerVariables["SERVER_SOFTWARE"] ?? "";
		Match m = Regex.Match(serverVersion, @"microsoft-iis/(\d+(?:\.\d+(?:\.\d+)?)?)", RegexOptions.IgnoreCase);
		if (m.Success)
		{
			Version v = new Version(m.Groups[1].Value);
			if (v.Major < 5 || v.Major == 5 && v.Minor < 1)
			{
				ServerVersion.Text = BXInstaller.GetMessage(this, "IIS50");
				ServerVersion.Style.Add(HtmlTextWriterStyle.Color, "#ff0000");
				errors = true;
			}
			else
			{
				ServerVersion.Text = v.ToString();
				ServerVersion.Style.Add(HtmlTextWriterStyle.Color, "#009900");
			}
		}
		else
		{
			ServerVersion.Text = string.Format(BXInstaller.GetMessage(this, "UnknownVersion"), serverVersion);
			ServerVersion.Style.Add(HtmlTextWriterStyle.Color, "Olive");
		}
	}

	private void FillAjaxVersion()
	{
		try
		{
			Assembly ajax = Assembly.Load("System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35");
			if (ajax != null)
			{
				AjaxVersion.Text = BXInstaller.GetMessage(this, "AJAX35");
				AjaxVersion.Style.Add(HtmlTextWriterStyle.Color, "#009900");
				return;
			}
		}
		catch
		{
		}

		try
		{
			Assembly ajax = Assembly.Load("System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35");
			if (ajax != null)
			{
				AjaxVersion.Text = BXInstaller.GetMessage(this, "AJAX10");
				AjaxVersion.Style.Add(HtmlTextWriterStyle.Color, "#009900");
				return;
			}
		}
		catch
		{
		}

		errors = true;
	}

    private void FillTrustLevel() 
    {
        try 
        {
            AspNetHostingPermissionLevel trustLevel = GetCurrentTrustLevelName();
            TrustLevel.Text = Enum.GetName(typeof(AspNetHostingPermissionLevel), trustLevel);
            if (trustLevel == AspNetHostingPermissionLevel.Medium || trustLevel == AspNetHostingPermissionLevel.High || trustLevel == AspNetHostingPermissionLevel.Unrestricted)
                TrustLevel.Style.Add(HtmlTextWriterStyle.Color, "#009900");
            else
            {
                TrustLevel.Style.Add(HtmlTextWriterStyle.Color, "#ff0000");
                errors = true;
            }
        }
        catch{}
    }
}
