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

    File:               UploadForm_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 BijlagenForm.asp.asp
    Note:               Na submit sluiten we onzelf
                        Met TAMPER bescherming!
*/

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

var JSON_Result = true;

var pKey = getQParamInt("key", -1);
var pModule = getQParamSafe("module");
var pNiveau = getQParamSafe("niveau", "");
if (pModule == "MLD" && pNiveau == "M")
    var LOCKED_USER_OK = { "xmlnode": "melding", "key": pKey };
else if (pModule == "MLD" && pNiveau == "O")
    var LOCKED_USER_OK = { "xmlnode": "opdracht", "key": pKey };
else if (pModule === "ORDN") {
    var LOCKED_USER_OK = { "xmlnode": "opdracht", "key": getQParam("opdr_key", -1) };
}
%>

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

<%
if (getQParamInt("skiptampercheck", 0) == 1)
{
    user.checkAutorisation("WEB_FACFAC"); // klapt er uit als je dat niet hebt
}
else
{
    protectQS.verify({ allowparams: ["clientresize"]}); // tamper check
}

FCLTHeader.Requires({ plugins:["jQuery"]
                    });
var deleteTransit = buildTransitParam(["key", "module", "opdr_key", "mld_key"]);

var pKenmerk_key = getQParamInt("kenmerk_key", -1);
var pAlgLevel = getQParam("kenmerk_module", "");
var imp_exp_key = getQParamInt("imp_exp_key", -1);
var pCanDelete = getQParamInt("candelete", 1) == 1;
var clientresize = getQParamInt("clientresize", 0); // Client heeft het al gedaan, hoeft niet serverside ook nog een keer
                                                    // We moeten mogelijk nog wel een thumbnail maken

var params = flexProps(pModule, pKey, String(pKenmerk_key), pNiveau, {alglevel: pAlgLevel, imp_exp_key: imp_exp_key});
var doEncrypt = (params.encrypt? 1 : 0);
var regFilter = null;
if (params.extFilter)
{
  // extFilter="pdf,tiff" of "pdf tiff" of "pdf;tiff"
  regFilter = params.extFilter;
  regFilter = regFilter.replace(/( |,|;)/g,"|"); // Altijd | karakter
  regFilter = ".*\\.(" + regFilter + ")$"; // er moet een punt voor en extensie is aan het einde
}
var fso = Server.CreateObject("Scripting.FileSystemObject")

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

  var found_files = [];
  var found_fields = {};

  function js_add_file(name, data, contenttype, counter)
  {
    var safename = safe.filename(name.split("\\")[name.split("\\").length - 1]); // eventuele padnaam eraf
    __Log("Upload file: " + name + " is safe: " + safename);

    // iPad/IPhone uploaden directe foto altijd als 'Image.jpg' wat erg lastig is
    var newfilename = renameIphoneIpadFiles(safename, counter);
    if (newfilename)
    {
      safename = newfilename;
    }

    found_files.push({ name: safename, data: data, contenttype: contenttype});
  }

  function js_add_field(name, data)
  {
      found_fields[name] = data;
  }

var oorzaak_bekend = false;
  function check_filename(pinfo)
  {
      var filename = safe.filename(pinfo.name);
      var msg = "";
      if (pinfo.data == "")
      {
          msg = L("lcl_shared_file_empty");
      }
      else if (filename == "")
      {
          msg = L("lcl_shared_file_invalid");
      }
      else if (regFilter && (!new RegExp(regFilter, "ig").test(filename)))
      {
          msg = L("lcl_shared_file_ext_invalid_start") + params.extFilter + L("lcl_shared_file_ext_invalid_end");
      }
      else if (!new RegExp(S("flexAllowedExt"), "ig").test(filename))
      {
          msg = L("lcl_shared_file_ext_not_allowed");
      }
      if (msg !== "") { oorzaak_bekend = true; }
      return (msg ? filename +": " + msg : "");
  }

  var VB_result = VB_getfiles();
  var result = { message: VB_result("message") || "",
                 safefilename: [],
                 deepUrl: [],
                 deleteUrl: [],
                 filesize: [],
                 digest: []
               };

  //__Log(found_fields);
  //__Log(found_files);
  if (!result.message) // dikke kans dat dan het token er ook niet is
  {
      protectRequest.validateToken(found_fields["RVT_token"]);
      var fso = Server.CreateObject("Scripting.FileSystemObject");

      // Obscuur: hier geen 'i' gebruiken omdat upload.inc/ getString die ook al gebruikt
      //          Je krijgt daar dan 'Illegal Assignment', ik verzin het niet
      for (var j = 0; j < found_files.length; j++)
      {
          var finfo = found_files[j];
          var safefilename = safe.filename(finfo.name);
          var msg = check_filename(finfo);

          if (msg == "")
          {
              try
              {
                  CreateFullPath(params.AttachPath);
                  if (doEncrypt)
                  {
                      var savedfilename = safefilename + ".encrypted";
                      var oZip = Server.CreateObject("SLNKDWF.Zip");
                      __Log("Encrypting to: " + params.AttachPath + savedfilename);
                      oZip.New(params.AttachPath + savedfilename);
                      oZip.EncryptFromString(safefilename, finfo.data);
                      oZip.Close();
                  }
                  else
                  {
                      var savedfilename = safefilename;
                      if ("linkImmediate" in params) { // Deze willen we niet overschrijven omdat meerdere instanties 1 map delen
                          savedfilename = uniqueFileName(params.AttachPath, savedfilename);
                      }
                      var BinaryStream = Server.CreateObject("ADODB.Stream");
                      BinaryStream.Type = 1; // adTypeBinary
                      BinaryStream.Open();
                      BinaryStream.Write(finfo.data);
                      // Save binary data To disk
                      __Log("Saving to: " + params.AttachPath + savedfilename);
                      if (params.keephistory && fso.FileExists(params.AttachPath + savedfilename))
                      {
                        var jsDate = new Date();
                        var backupTime = String(jsDate.getFullYear()) + padout(jsDate.getMonth() + 1) + padout(jsDate.getDate()) + "_"
                                       + padout(jsDate.getHours()) + padout(jsDate.getMinutes())+ padout(jsDate.getSeconds());
                        // backupTime vlak voor de extensie plakken
                        var backupName = savedfilename.replace(/(\.[a-z]*)$/i, "_" + backupTime + "$1");
                        __Log("Moving old file to: " + params.AttachPath + backupName);
                        fso.MoveFile(params.AttachPath + savedfilename, params.AttachPath + backupName);
                        __DoLog("Replaced {0}, previous version in {1}".format(params.AttachPath + savedfilename, backupName));
                      }
                      BinaryStream.SaveToFile(safe.UNC(params.AttachPath + savedfilename), (pCanDelete ? 2 : 1)); // adSaveCreateOverWrite
                  }
                  result.safefilename.push(savedfilename);
                  var attachfile = params.AttachPath + savedfilename;
                  if (fso.FileExists(attachfile))
                  {
                    var f = fso.GetFile(attachfile);
                    result.filesize.push(fso.GetFile(attachfile).Size);
                    var oCrypto = new ActiveXObject("SLNKDWF.Crypto");
                    result.digest.push(oCrypto.hex_sha1_file(attachfile));
                    if (getQParamInt("usenow", 0) == 1) {
                        var deepurl = HTTP.urlzelf() + "/appl/shared/BijlagenStream.asp?module=" + pModule + "&key=" + pKey + "&filename=" + Server.URLencode(savedfilename);
                        result.deepUrl.push(protectQS.create(deepurl));
                    }
                    result.deleteUrl.push(protectQS.create(rooturl + "/appl/Shared/Bijlagenform_delete.asp?DoDelete=" + Server.URLEncode(savedfilename) + deleteTransit));
                    var linkedFilename = savedfilename;
                    if (pModule.indexOf("FGII") === 0) {
                        linkedFilename = linkedFilename.replace(/\.dwf$/, "");
                    }
                    if ("linkImmediate" in params && pKey > 0) { // Link dit bestand direct aan de entiteit waar het bij hoor in de DB
                        updateLinkedFilename(pKey, params, linkedFilename);
                    }
                  }
              }
              catch(e)
              {
                  result.message += "Saving {0} failed: {1} ".format(safefilename, e.description);
                  __DoLog("Saving to {0} failed: {1}".format(params.AttachPath + safefilename, e.description), "#f0f");
              }
          }
          else
            result.message += msg;
      }
      //__Log(result);

      params.niveau = pNiveau;
      // Toevoegen bijlage/bestand tracken.
      trackBijlagen(pModule, pKey, params, result, "upload");
      for (var i=0; i<result.safefilename.length; i++)
      {
          result_safefilename = result.safefilename[i];
          result_digest = result.digest[i];
          switch(pModule)
          {   // Thumbnail altijd voor onderstaanden
              case "RESPHD":
              case "INSPHD":
              case "SML":
              case "NEWS":
                   // Eerst Resize/crop
                   var resize_params = { resizecode: clientresize?null:params.regexp // Als clientresize dan alleen nog voor thumb
                                       , attachpath: params.AttachPath
                                       , filename:   result_safefilename
                                       , safename:   result_safefilename
                                       , digest:     result_digest
                                       , module:     pModule
                                       , isupload:   true
                                       };
                   var resize_result = resizePicture(resize_params);
                   result.message = resize_result.message;

                   if (resize_result.newsize && (resize_result.newsize > 0))
                   {
                        __Log("filesize: " + result.filesize[i] + " --> " + resize_result.newsize);
                        result.filesize[i] = resize_result.newsize;
                        if (pModule === "NEWS") { /* Vervang het origineel door de resized */
                            if (fso.fileExists(resize_result.file_resized)) {
                                try {
                                    CreateFullPath(params.AttachPath);
                                    fso.CopyFile(resize_result.file_resized, params.AttachPath + savedfilename, true); /* Kopieren, want daarmee kunnen we overschrijven */
                                    fso.DeleteFile(resize_result.file_resized);  /* En verwijder de eerste */
                                } catch(e) {
                                    __DoLog("Replace original by resized file failed: " + e.description);
                                }
                            }
                        }
                   }
                   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.inform = scanDWF(cad_tek_key, 1);
                        oRs.MoveNext();
                   }
                   break;
        }
        if (params.fac_bijlagen)
        {
            var sql = "BEGIN "
                    + "  flx.setflexbijlage"
                            + "(" + safe.quoted_sql(pModule)    // MLD | RES | ....
                            + ", " + pKenmerk_key
                            + ", " + pKey
                            + ", " + safe.quoted_sql(params.AttachSubPath)
                            + ", " + "NULL"
                            + ", " + safe.quoted_sql(result.safefilename[i])
                            + ", " + result.filesize[i]
                            + ", " + "SYSDATE"
                            + ", " + safe.quoted_sql(result.digest[i])
                            + ");"
                    + " END;";
            Oracle.Execute(sql);
        }
      }
  }

  if (!result.message && params.forcesingle)
  {   // Er mag maar 1 bestand bestaan.
      // Verwijder alle andere bestanden.
      if (result.safefilename.length>1)
      {
          result.message += L("lcl_shared_upload_toomany");
      }
      else
      {
          // Verwijder alle andere bestanden behalve die zojuist is toegevoegd.
          var f = fso.GetFolder(params.AttachPath);
          for (fc = new Enumerator(f.files); !fc.atEnd(); fc.moveNext())
          {
              var vFileName = fc.item().Name;
              if (vFileName != result.safefilename[0])
              {
                  __Log("Autodelete: " + params.AttachPath + vFileName)
                  DeleteFile(params.AttachPath + vFileName, params);
              }
          }
      }
  }
  if (result.message && result.message != "")
  {
      result.message = (oorzaak_bekend ? L("lcl_shared_upload_error_start_known") : L("lcl_shared_upload_error_start")) + result.message + L("lcl_shared_upload_error_end");
  }
  else
  {
    result.success = true;
  }
    Response.Write(JSON.stringify(result));
    Response.End;
%>
<script language="VBScript" runat="Server">
Dim UploadRequest

'' // Vult via de (JavaScript) functie js_add_file de globale found_files
'' // Verder doen we echt zo veel mogelijk in JavaScript
Public Function VB_getfiles()
    Dim myErr
    Set result = Server.CreateObject("Scripting.Dictionary")

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

    on error resume next
    '' Error "Operation not Allowed" op de volgende regel betekent meestal dat de upload te groot is
    RequestBin = Request.BinaryRead(byteCount)
    myErr = Err.Description
    on error goto 0
    If myErr <> "" Then
        result.add "message", myErr
        Set VB_getfiles = result
        Exit Function
    End If

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

    '' // Vul via de (Javascipt) functie js_add_field de globale found_fields
    '' // met de hidden form-fields uit de header
    Dim ur_key, i, var_naam, var_waarde, var_filename, var_data
    ur_key  = UploadRequest.Keys
    for i = 0 To UploadRequest.Count -1
        var_naam = ur_key(i)
        if UploadRequest.Item(var_naam).Exists("ContentType") then
            var_waarde = UploadRequest.Item(var_naam).Item("FileName")
            '' // En dan nu nog de bestanden..
            contentType = UploadRequest.Item(var_naam).Item("ContentType")
            filepathname = UploadRequest.Item(var_naam).Item("FileName")
            var_data = MultiByteToBinary(UploadRequest.Item(var_naam).Item("Value"))
            js_add_file filepathname, var_data, contentType, i
        else
            var_waarde = UploadRequest.Item(var_naam).Item("Value")
        end if
        js_add_field var_naam, var_waarde
    next

    Set VB_getfiles = result
End Function

</script>
<%
    // De ASPPAGE_END wordt mogelijk uitgevoerd *voordat* VB-script aan de beurt is. Daardoor is de
    // Oracle connection al gesloten en krijg je een (fout)melding 'Operation is not allowed when the
    // object is closed.' op een this.RealConnection.Execute
    // ASPPAGE_END();
%>
