<%@ language = "JavaScript" %>
<% /*
     $Revision$
     $Id$

     File:          api_hmail.asp
     Description:   API voor opvangen van hMailserver e-mails

     Parameters:    Een xml
     Status:
     Context:       1-op-1 met \UTILS\mail_receive\EventHandlers.js
     Notes:         Deze API krijgen we XML binnen, en geven JSON terug.
                    Dat was het eenvoudigst
*/
    JSON_Result = true;
    THIS_FILE = "appl/api/api_hmail.asp";
%>
<!-- #include file="../Shared/common.inc" -->
<!-- #include file="../Shared/json2.js" -->
<!-- #include file="../Shared/xml_converter.inc" -->
<!-- #include file="../Shared/flexfiles.inc" -->
<!-- #include file="../Shared/upload.inc" -->
<!-- #include file="../api/api.inc" -->
<%

var API = new API_func();

function abortRejectMail(tekst, maillog)
{
    var result = { success: false,
                   message: tekst,
                   maillog: maillog||tekst
                 }
    __Log(result.maillog); // komt altijd ook in hmail log
    Response.Write(JSON.stringify(result));
    Response.End;
}
function stripHtml(html)
{
    // verwijder html-tags
    html = (html||"").replace(/(<([^>]+)>)/ig,"");
    // &nbsp; naar spatie
    html = html.replace(/\&nbsp\;/ig, " ");
    //verwijder leading spaces and tabs
    html = html.replace(/^[ \t]+/gm,"");
    // verwijder lege regels
    html = html.replace(/[(\n\r)]+/g,"\n\r");
    // zet een regel die begint met : maar achter de vorige
    html = html.replace(/(\n\r:)/g,":");
    return html;
}

// puur intern gebruik dus geen stylesheet conversie nodig
var xmlReq = Server.CreateObject("MSXML2.DOMDocument.6.0");
xmlReq.load(Request);
if (xmlReq.parseError.errorCode != 0)
{
     abortRejectMail("Error " + xmlReq.parseError.reason);
}

if (API.apidata.loglevel)
    __Log2File(xmlReq.xml, API.APIname + "_IN");

var Subject  = XMLval(xmlReq, "subject");
var fromAddr = XMLval(xmlReq, "from");
var toAddr   = XMLval(xmlReq, "to");
var htmlBody = XMLval(xmlReq, "htmlbody");
var Body     = XMLval(xmlReq, "body");

__Log("Subject: " + Subject);
__Log("From: " + fromAddr);
__Log("To: " + toAddr);
__Log("htmlBody: " + htmlBody);
__Log("body: " + Body);

var mailuser = toAddr.split("@")[0];

sql = "SELECT fac_email_setting_action,"
    + "       fac_email_setting_expire,"
    + "       fac_email_setting_from,"
    + "       fac_email_setting_attachpath"
    + "  FROM fac_email_setting"
    + " WHERE upper(fac_email_setting_user) = upper("+safe.quoted_sql(mailuser)+")";

var oRs = Oracle.Execute(sql);
if (oRs.Eof)
{
    abortRejectMail(L("lcl_fac_hmail_unknown_user"), "E-mail user niet ontvankelijk: " + mailuser);
}
__Log("E-mail user ontvankelijk: " + mailuser);
if (oRs("fac_email_setting_expire").Value != null)
{
    var expire = new Date(oRs("fac_email_setting_expire").Value);
    if (expire.getTime() < (new Date).getTime())
    {
        abortRejectMail(L("lcl_fac_hmail_expired"), "Te laat, moest voor: " + expire);
    }
}
var shouldFrom = oRs("fac_email_setting_from").Value;
if (shouldFrom)
{
    if (String(shouldFrom).toUpperCase() != String(fromAddr).toUpperCase())
    {
        abortRejectMail(L("lcl_fac_hmail_wrong_sender"), "Foute afzender. Verwacht: " + shouldFrom + ", kreeg: " + fromAddr);
    }
}
var action = oRs("fac_email_setting_action").Value; // Package aanroep
var path = oRs("fac_email_setting_attachpath").Value;
oRs.Close();

var result = { success: true, path: path, attachments: [] };

var psession_id = Session.SessionID;
// verwijder entries in de FAC_RESULT table zodat de action nieuwe resultaten kan schrijven
var sql = "DELETE fac_result WHERE fac_result_sessionid = " + safe.quoted_sql(psession_id);
Oracle.Execute(sql);

if (action) // Bijv "fac.processemail" of "uwva.closeorder-sample"
{
    if (!Body || Body == "") // Voorkeur voor plaintekst
    {
        var v_body = L("lcl_fac_hmail_empty_body") + stripHtml(htmlBody);
    }
    else
    {
        var v_body = Body;
    }
    sql = "BEGIN " + action + " (" + safe.quoted_sql(fromAddr)    + ","
                                   + safe.quoted_sql(toAddr)      + ","
                                   + safe.quoted_sql(Subject || L("lcl_fac_hmail_no_subject"))  + "," // de actions kunnen slecht tegen lege subject
                                   + safe.quoted_sql(v_body, 3990) + "," // HSLE#33588 10 karakters speling
                                   + safe.quoted_sql(psession_id) + ","
                                   + user_key + ");"
        + "END;";
    Oracle.Execute(sql);

    sql = "SELECT fac_result_waarde"
        + "  FROM fac_result"
        + " WHERE fac_result_naam = 'errormsg'"
        + "   AND fac_result_sessionid = " + safe.quoted_sql(psession_id);
    var oRs = Oracle.Execute(sql);
    if (!oRs.Eof)
    {
        abortRejectMail(oRs("fac_result_waarde").Value);
    }
    oRs.Close();

    sql = "SELECT fac_result_waarde"
        + "  FROM fac_result"
        + " WHERE fac_result_naam = 'kenmerkpath'"
        + "   AND fac_result_sessionid = " + safe.quoted_sql(psession_id);
    var oRs = Oracle.Execute(sql);
    if (!oRs.Eof)
    {
       result.path = result.path + oRs("fac_result_waarde").Value;
    }
    oRs.Close();

    // Nog iets specifieks terug te melden voor de logging?
    sql = "SELECT fac_result_waarde"
        + "  FROM fac_result"
        + " WHERE fac_result_naam = 'maillog'"
        + "   AND fac_result_sessionid = " + safe.quoted_sql(psession_id);
    var oRs = Oracle.Execute(sql);
    if (!oRs.Eof)
    {
       result.maillog = oRs("fac_result_waarde").Value;
    }
    else
       result.maillog = "E-mail afgehandeld via: " + action;
    oRs.Close();
}
else
    result.maillog = "Verder geen e-mail action gedefinieerd";

// opruimen
var sql = "DELETE fac_result WHERE fac_result_sessionid = " + safe.quoted_sql(psession_id);
Oracle.Execute(sql);

if (result.path)
{
    var Attachments = xmlReq.getElementsByTagName("attachment");
    for (i=0; i < Attachments.length; i++)
    {
       var safefilename = safe.filename(XMLval(Attachments[i], "filename"));
       var attsize = parseInt(XMLval(Attachments[i], "size"), 10);
       if (safefilename == 'tmpl_logo.gif')
       { // Waarschijnlijk een FACILITOR bon gereply'd
         __Log("Bijlage {0} genegeerd.".format(safefilename));
       }
       else if (attsize < S("flex_min_size"))
       {
         __Log("Bijlage {0} genegeerd, te klein met {1} bytes.".format(safefilename, attsize));
       }
       else if (!new RegExp(S("flexallowedext"), "ig").test(safefilename))
       {
         // TODO: Misschien ook terugkoppelen aan zender?
         __DoLog("Onbekende extensie e-mail bijlage: {0} ({1} bytes). Bestand is niet opgeslagen.".format(safefilename, attsize));
       }
       else
       {
         __Log('{0} bijlage ({1} bytes) mag naar {2}'.format(safefilename, attsize, result.path));
         CreateFullPath(result.path); // Hoeft hMailserver dat niet meer te doen. Eist wel dat hMail op 'onze' webserver draait
         result.attachments.push ({ sequence: i,
                                    safefilename: result.path + safefilename
                                 })
       }
    }
}

Response.Write(JSON.stringify(result));
Response.End;
%>
