<%@ LANGUAGE = JavaScript %>
<% /*
     $Revision$
     $Id$

    File:               upploadform_save.asp
    Description:        Opvangscript van uploadform.asp
    Parameters:
        extfilter       extensie filter
        pkey            ALG_RUIMTE_KEY of ...
        pModule         "ALG" of ...
        pKenmerk_key    ALG_KENMERK_KEY of ...
    Context:            Vanuit uploadform.asp
    Note:               Na submit sluiten we onzelf
                        Met TAMPER bescherming!
*/

if (Server.ScriptTimeout < 600) Server.ScriptTimeout = 600; // 10 minuten moet echt genoeg zijn
%>

<!-- #include file="../Shared/common.inc" -->
<!-- #include file="./flexfiles.inc" -->
<!-- #include file="../Shared/upload.inc" -->
<!-- #include file='../cad/cad_scan_dwf.inc' -->

<%
protectQS.verify(); // tamper check

FCLTHeader.Requires({ plugins:["jQuery"]
                    });

var pKey = getQParamInt("key", -1);
var pNiveau = getQParamSafe("niveau", "");
var pModule = getQParamSafe("module");
var pKenmerk_key = getQParamInt("kenmerk_key", -1);

var params = flexProps(pModule, pKey, String(pKenmerk_key), pNiveau);

if (params.extFilter)
{
  // extFilter="pdf,tiff" of "pdf tiff" of "pdf;tiff"
  var regFilter = params.extFilter;
  regFilter = regFilter.replace(/( |,|;)/g,"|"); // Altijd | karakter
  regFilter = ".*\\." + "(" + regFilter + ")$"; // er moet een punt voor en extensie is aan het einde
}

function jslog(str) // VB Vindt de twee underscores niet leuk
{
    __Log(str)
}
%>

<html>
  <head>
<%  FCLTHeader.Generate();

  __Log("Opslaan onder: " + params.AttachPath);

  var VB_result = VB_savefile(regFilter, params.AttachPath, (params.encrypt? 1 : 0));
  var result = { message: VB_result("message"),
                 safefilename: VB_result("safefilename")
               };

  if (!result.message && params.forcesingle)
  {
      // Verwijder alle andere bestanden.
      var fso = Server.CreateObject("Scripting.FileSystemObject")
      var f = fso.GetFolder(params.AttachPath);
      for (fc = new Enumerator(f.files); !fc.atEnd(); fc.moveNext())
      {
          var vFileName = fc.item().Name;
          if (vFileName != VB_result("safefilename"))
          {
              __Log("Autodelete: " + params.AttachPath + vFileName)
              DeleteFile(params.AttachPath + vFileName);
          }
      }
  }


  if (result.message != "")
  {
      result.message = L("lcl_shared_upload_error_start") + result.message + L("lcl_shared_upload_error_end");
  }
  else
  {
      checkWebconfig(params.AttachRootPath);

      // Eerst Resize/crop
      if (params.regexp && result.safefilename.match(/\.(png|jpg|jpeg)$/i))
      {
        var Format = params.regexp.match(/^([RrCc])(\d*)x(\d*)$/i); // P800x600
        if (Format && Format.length == 4)
        {
            var oIMG = new ActiveXObject("SLNKDWF.ImageConvert");
            try
            {
                oIMG.Open(params.AttachPath + result.safefilename);
            }
            catch(e)
            {
                result.message = L("lcl_shared_thumbnail_error") + e.description;
                // Gewoon opruimen
                DeleteFile(params.AttachPath + result.safefilename);
            }

            var RrCc = Format[1];
            var h0 = h = parseInt(Format[2], 10);
            var w0 = w = parseInt(Format[3], 10);
            if (RrCc == "R" || RrCc == "r") // Dan niet croppen maar aspect ratio behouden
            {
               if (oIMG.Width * h > w * oIMG.Height)
                   h = oIMG.Height / oIMG.Width * w;
               else
                   w = oIMG.Width / oIMG.Height * h;
            }

            if (oIMG.Height < h || oIMG.Width < w) // Zou er iets vergroot gaan worden.
            {
                if (RrCc == "R" || RrCc == "C") // Dan zijn we streng en eisen we minimale afmeting
                {
                    result.message = L("lcl_shared_photo_small").format(h0, w0, oIMG.Height, oIMG.Width);
                    DeleteFile(params.AttachPath + result.safefilename);
                }
                else // Dan maar niet, we vergtoten niet.
                {
                    h = oIMG.Height;
                    w = oIMG.Width;
                }
            }
            if (!result.message && (oIMG.Height != h || oIMG.Width != w))
            {
                try {
                    __Log("Resize/Cropping from w=" + oIMG.Width + " h=" + oIMG.Height + " to w=" + w + " h=" + h);
                    oIMG.Width = w;
                    oIMG.Height = h;
                    oIMG.SaveAs(params.AttachPath + result.safefilename);
                }
                catch (e)
                {
                   result.message = L("lcl_shared_thumbnail_error") + e.description;
                   // Gewoon opruimen
                   DeleteFile(params.AttachPath + result.safefilename);
                }
            }
         }
      }

      if (!result.message)
      switch(pModule)
      {
        case "SML": // Thumb altijd
           try {
               maxThumbW = 60;
               maxThumbH = 80;
               if (oIMG.Width / oIMG.Height > maxThumbW / maxThumbH)
               {
                 oIMG.Height = oIMG.Height / oIMG.Width * maxThumbW;
                 oIMG.Width = maxThumbW;
               }
               else
               {
                 oIMG.Width = oIMG.Width / oIMG.Height * maxThumbH;
                 oIMG.Height = maxThumbH;
               }
               CreateFullPath(params.AttachPath + "thumb/");
               oIMG.SaveAs(params.AttachPath + "thumb/" + result.safefilename);
           }
           catch (e)
           {
              result.message = L("lcl_shared_thumbnail_error") + e.description;
              DeleteFile(params.AttachPath + "thumb/" + result.safefilename);
           }
           break;
        case "FGII":
           // Direct scannen nu, indien dwf bestand. Tekening kan vaker gebruikt worden.
           var sql = "SELECT cad_tekening_key"
                   + " FROM cad_tekening"
                   + " WHERE cad_tekening_filenaam || '.dwf' = " + safe.quoted_sql(result.safefilename);
           var oRs = Oracle.Execute(sql);
           while (!oRs.eof)
           {
             var cad_tek_key = oRs("cad_tekening_key").value;
             result.message = scanDWF(cad_tek_key, 1);
             oRs.MoveNext();
           }
           break;
      }
    }
    %><script>
        <% if (result.message) { %>
            alert("<%=safe.jsstring(result.message)%>");
        <% } %>
        parent.uploadDone("<%=safe.jsstring(result.safefilename)%>"); // Zoo fout....
      </script>
    <%
    Response.End;
%>
<script language="VBScript" runat="Server">
Dim UploadRequest
Public Function VB_savefile(regFilter, fullpath, doEncrypt)
    Dim myErr
    Set result = Server.CreateObject("Scripting.Dictionary")

    byteCount = Request.TotalBytes
    if byteCount = 0 then Response.End

    on error resume next
    RequestBin = Request.BinaryRead(byteCount)
    myErr = Err.Description
    on error goto 0
    If myErr <> "" Then
        result.add "message", myErr
        Set VB_savefile = result
        Exit Function
    End If

    Set UploadRequest =  CreateObject("Scripting.Dictionary")
    BuildUploadRequest  RequestBin

    contentType = UploadRequest.Item("imgfile").Item("ContentType")
    filepathname = UploadRequest.Item("imgfile").Item("FileName")

    safefilename = safe.filename(Right(filepathname,Len(filepathname)-InstrRev(filepathname,"\"))) '" //syntaxhighlight correctie

    jslog "File: " & filepathname & " safe: " & safefilename

    Set re = new regexp

    re.Pattern = S("flexAllowedExt")
    re.IgnoreCase = true
    If Not re.test(safefilename) Then
        result.add "message", L("lcl_shared_file_ext_not_allowed")
        Set VB_savefile = result
        Exit Function
    End If

    re.Pattern = regFilter
    re.IgnoreCase = true
    If Not re.test(safefilename) Then
        result.add "message", L("lcl_shared_file_ext_invalid_start") & params.extFilter & L("lcl_shared_file_ext_invalid_end")
        Set VB_savefile = result
        Exit Function
    End If

    value = UploadRequest.Item("imgfile").Item("Value")

    If value = "" Or filepathname = "" Then
        result.add "message", "Empty file or name?"
        Set VB_savefile = result
        Exit Function
    End If

    on error resume next
    CreateFullPath(fullpath)
    myErr = Err.Description
    on error goto 0
    If myErr <> "" Then
        result.add "message", myErr
        Set VB_savefile = result
        Exit Function
    End If

    If doEncrypt = "1" Then ''Encrypting
        Set oZip = Server.CreateObject("SLNKDWF.Zip")
        oZip.New(fullpath & safefilename & ".encrypted")
        call oZip.EncryptFromString(safefilename, value)
    Else
      Set BinaryStream = Server.CreateObject("ADODB.Stream")
      BinaryStream.Type = 1 '' adTypeBinary
      BinaryStream.Open
      on error resume next
   	      BinaryStream.Write MultiByteToBinary(Value)
          ''Save binary data To disk
          jslog("Saving to: " & fullpath & safefilename)
          BinaryStream.SaveToFile fullpath & safefilename, 2 '' adSaveCreateOverWrite
          myErr = Err.Description
      on error goto 0
    End If
    result.add "safefilename", safefilename
    result.add "message", myErr
    Set VB_savefile = result
End Function
</script>
