Beispiel #1
0
        /// <summary>
        /// Esplode un M7m infocert nelle sue due compomenti (un p7m e un tsr)
        /// </summary>
        /// <param name="fileContents">bytearray contente il messaggio m7m</param>
        public void explode(byte[] fileContents)
        {
            int posi = BusinessLogic.Documenti.DigitalSignature.Helpers.IndexOfInArray(fileContents, System.Text.ASCIIEncoding.ASCII.GetBytes("Mime-Version:"));

            if (posi == 0) //E' un mime m7m
            {
                using (MemoryStream ms = new MemoryStream(fileContents))
                {
                    anmar.SharpMimeTools.SharpMessage sm = new anmar.SharpMimeTools.SharpMessage(ms);
                    if (sm.Attachments.Count > 0)
                    {
                        foreach (anmar.SharpMimeTools.SharpAttachment att in sm.Attachments)
                        {
                            if (System.IO.Path.GetExtension(att.Name).ToLower().Contains("p7m"))
                            {
                                att.Stream.Position = 0;
                                BinaryReader sr = new BinaryReader(att.Stream);
                                _p7m = new CryptoFile {
                                    Content = sr.ReadBytes((int)att.Size), MessageFileType = CryptoFile.mapType(att.ContentTransferEncoding), Name = att.Name
                                };
                            }

                            if (System.IO.Path.GetExtension(att.Name).ToLower().Contains("tsr"))
                            {
                                att.Stream.Position = 0;
                                BinaryReader sr = new BinaryReader(att.Stream);
                                _tsr.Add(new CryptoFile {
                                    Content = sr.ReadBytes((int)att.Size), MessageFileType = CryptoFile.mapType(att.ContentTransferEncoding), Name = att.Name
                                });
                            }
                        }
                    }
                }
            }
        }
Beispiel #2
0
        /// <summary>
        /// Verifiy of CRL
        /// </summary>
        /// <param name="fileContents">byte Array file contents</param>
        /// <param name="endPoint">not used </param>
        /// <param name="args">1) Datetime? data verifica / string cachePath / string (bool) nocache</param>
        /// <returns></returns>
        public EsitoVerifica VerificaByteEV(byte[] fileContents, string endPoint, Object[] args)
        {
            //string ID = String.Format("{0}-{1}", Environment.GetEnvironmentVariable("APP_POOL_ID").Replace(" ", ""), AppDomain.CurrentDomain.BaseDirectory);
            bool forceDownload = false;
            //end point lo usiamo per forzare il download

            string p7mSignAlgorithm = null;

            //string p7mSignHash = null;
            DocsPaVO.documento.Internal.SignerInfo[] certSignersInfo;

            EsitoVerifica ev = new EsitoVerifica();

            DateTime?dataverificaDT = null;
            string   cachePath      = string.Empty;

            if (args == null)
            {
                logger.Debug("Args (Date) is null, settign current");
                dataverificaDT = DateTime.Now;
            }
            if (args.Length > 0)
            {
                dataverificaDT = args[0] as DateTime?;
                if (dataverificaDT == null)
                {
                    logger.Debug("Date is null, settign current");
                    dataverificaDT = DateTime.Now;
                }
                cachePath = args[1] as string;

                string fdl = args[2] as string;
                if (!String.IsNullOrEmpty(fdl))
                {
                    Boolean.TryParse(endPoint, out forceDownload);
                }
            }

            int posi = IndexOfInArray(fileContents, System.Text.ASCIIEncoding.ASCII.GetBytes("Mime-Version:"));

            if (posi == 0) //E' un mime m7m
            {
                using (MemoryStream ms = new MemoryStream(fileContents))
                {
                    anmar.SharpMimeTools.SharpMessage sm = new anmar.SharpMimeTools.SharpMessage(ms);
                    if (sm.Attachments.Count > 0)
                    {
                        foreach (anmar.SharpMimeTools.SharpAttachment att in sm.Attachments)
                        {
                            if (System.IO.Path.GetExtension(att.Name).ToLower().Contains("p7m"))
                            {
                                att.Stream.Position = 0;
                                BinaryReader sr = new BinaryReader(att.Stream);
                                fileContents = sr.ReadBytes((int)att.Size);
                            }
                        }
                    }
                }
            }

            // Ce provo....
            posi = -1;
            posi = IndexOfInArray(fileContents, System.Text.ASCIIEncoding.ASCII.GetBytes("%PDF"));
            if (posi == 0)    //E' un pdf
            {
                PdfReader pdfReader = isPdf(fileContents);
                try
                {
                    AcroFields    af        = pdfReader.AcroFields;
                    List <string> signNames = af.GetSignatureNames();

                    if (signNames.Count == 0) //Firma non è presente
                    {
                        ev.status    = EsitoVerificaStatus.ErroreGenerico;
                        ev.message   = "Il file PDF da verificare non contiene nessuna firma";
                        ev.errorCode = "1458";
                        return(ev);
                    }

                    List <DocsPaVO.documento.Internal.SignerInfo> siList = new List <DocsPaVO.documento.Internal.SignerInfo>();
                    foreach (string name in signNames)
                    {
                        PdfPKCS7 pk = af.VerifySignature(name);
                        p7mSignAlgorithm = pk.GetHashAlgorithm();

                        Org.BouncyCastle.X509.X509Certificate[] certs = pk.Certificates;
                        foreach (X509Certificate cert in certs)
                        {
                            DocsPaVO.documento.Internal.SignerInfo si = GetCertSignersInfo(cert);

                            VerificaValiditaTemporaleCertificato(ev, dataverificaDT, cert, p7mSignAlgorithm);
                            si = ControlloCRL(forceDownload, ev, cachePath, cert, si);

                            siList.Add(si);
                        }
                        bool result = pk.Verify();
                        if (!result)
                        {
                            ev.status    = EsitoVerificaStatus.ErroreGenerico;
                            ev.message   = "La verifica della firma è fallita (File is Tampered)";
                            ev.errorCode = "1450";
                        }
                    }

                    /*
                     * if (
                     *  (pdfReader.PdfVersion.ToString() != "4")||
                     *  (pdfReader.PdfVersion.ToString() != "7"))
                     * {
                     *  ev.status = EsitoVerificaStatus.ErroreGenerico;
                     *  ev.message = "Il file da verificare non è conforme allo standard PDF 1.4 o pdf 1.7";
                     *  ev.errorCode = "1457";
                     * }
                     */

                    List <DocsPaVO.documento.Internal.PKCS7Document> p7docsLst = new List <DocsPaVO.documento.Internal.PKCS7Document>();

                    DocsPaVO.documento.Internal.PKCS7Document p7doc = new DocsPaVO.documento.Internal.PKCS7Document
                    {
                        SignersInfo      = siList.ToArray(),
                        DocumentFileName = null,
                        Level            = 0
                    };
                    p7docsLst.Add(p7doc);

                    ev.VerifySignatureResult = ConvertToVerifySignatureResult(ev.status, p7docsLst.ToArray());
                    ev.content = fileContents;
                }
                catch (Exception e)
                {
                    ev.status    = EsitoVerificaStatus.ErroreGenerico;
                    ev.message   = "Error verifying pdf message :" + e.Message;
                    ev.errorCode = "1402";

                    return(ev);
                }
            }
            else //PKCS7
            {
                try
                {
                    int doclevel = 0;
                    List <DocsPaVO.documento.Internal.PKCS7Document> p7docsLst = new List <DocsPaVO.documento.Internal.PKCS7Document>();
                    do
                    {
                        //questa Estrazione serve solo per capire se uscire dal ciclo ricorsivo e ritornare il content
                        try
                        {
                            ev.content = extractSignedContent(fileContents);
                        }
                        catch
                        {
                            break;
                        }

                        //Ciclo per file firmato
                        Asn1Sequence        sequenza   = Asn1Sequence.GetInstance(fileContents);
                        DerObjectIdentifier tsdOIDFile = sequenza[0] as DerObjectIdentifier;
                        if (tsdOIDFile != null)
                        {
                            if (tsdOIDFile.Id == CmsObjectIdentifiers.timestampedData.Id)   //TSD
                            {
                                logger.Debug("Found TSD file");
                                DerTaggedObject taggedObject = sequenza[1] as DerTaggedObject;
                                if (taggedObject != null)
                                {
                                    Asn1Sequence    asn1seq = Asn1Sequence.GetInstance(taggedObject, true);
                                    TimeStampedData tsd     = TimeStampedData.GetInstance(asn1seq);
                                    fileContents = tsd.Content.GetOctets();
                                }
                            }

                            if (tsdOIDFile.Id == CmsObjectIdentifiers.SignedData.Id)   //p7m
                            {
                                logger.Debug("Found P7M file");
                            }
                        }


                        CmsSignedData cms = new CmsSignedData(fileContents);
                        //controllaCrlFileP7m(cms);

                        IX509Store             store   = cms.GetCertificates("Collection");
                        SignerInformationStore signers = cms.GetSignerInfos();

                        SignedData da = SignedData.GetInstance(cms.ContentInfo.Content.ToAsn1Object());

                        Asn1Sequence DigAlgAsn1 = null;
                        if (da.DigestAlgorithms.Count > 0)
                        {
                            DigAlgAsn1 = da.DigestAlgorithms[0].ToAsn1Object() as Asn1Sequence;
                        }

                        if (DigAlgAsn1 != null)
                        {
                            p7mSignAlgorithm = Org.BouncyCastle.Security.DigestUtilities.GetAlgorithmName(AlgorithmIdentifier.GetInstance(DigAlgAsn1).ObjectID);
                        }

                        certSignersInfo = new DocsPaVO.documento.Internal.SignerInfo[signers.GetSigners().Count];
                        int i = 0;

                        foreach (SignerInformation signer in signers.GetSigners())
                        {
                            bool fileOK = false;
                            Org.BouncyCastle.X509.X509Certificate cert1 = GetCertificate(signer, store);
                            certSignersInfo[i] = GetCertSignersInfo(cert1);
                            VerificaValiditaTemporaleCertificato(ev, dataverificaDT, cert1, p7mSignAlgorithm);

                            fileOK = VerificaNonRepudiation(ev, fileOK, cert1);
                            if (!fileOK)
                            {
                                certSignersInfo[i].CertificateInfo.messages = ev.errorCode + " " + ev.message;
                            }

                            try
                            {
                                fileOK = VerificaCertificato(ev, signer, fileOK, cert1);
                            }
                            catch (Exception e)
                            {
                                ev.status    = EsitoVerificaStatus.ErroreGenerico;
                                ev.message   = "Error verifying 2, message :" + e.Message;
                                ev.errorCode = "1450";
                            }


                            if (fileOK)
                            {
                                certSignersInfo[i] = ControlloCRL(forceDownload, ev, cachePath, cert1, certSignersInfo[i]);
                            }

                            //p7mSignHash = BitConverter.ToString(Org.BouncyCastle.Security.DigestUtilities.CalculateDigest(Org.BouncyCastle.Security.DigestUtilities.GetAlgorithmName(AlgorithmIdentifier.GetInstance(DigAlgAsn1).ObjectID), (byte[])cms.SignedContent.GetContent())).Replace("-", "");
                        }

                        /*
                         * if (cms.SignedContent != null)
                         * {
                         *  //CmsProcessable signedContent = cms.SignedContent;
                         *  //ev.content = (byte[])signedContent.GetContent();
                         *
                         *  ev.content = extractMatrioskaFile(fileContents);
                         *
                         *
                         *
                         * }
                         */


                        DocsPaVO.documento.Internal.PKCS7Document p7doc = new DocsPaVO.documento.Internal.PKCS7Document
                        {
                            SignersInfo      = certSignersInfo,
                            DocumentFileName = null,
                            Level            = doclevel++
                        };
                        p7docsLst.Add(p7doc);
                        try
                        {
                            fileContents = extractSignedContent(fileContents);
                        }
                        catch
                        {
                            break;
                        }
                    } while (true);

                    ev.VerifySignatureResult = ConvertToVerifySignatureResult(ev.status, p7docsLst.ToArray());;
                }
                catch (Exception e)
                {
                    ev.status    = EsitoVerificaStatus.ErroreGenerico;
                    ev.message   = "Error verifying 1, message :" + e.Message;
                    ev.errorCode = "1402";

                    return(ev);
                }
            }
            return(ev);
        }
Beispiel #3
0
        /// <summary>
        ///
        /// </summary>
        protected void mainInterface(anmar.SharpWebMail.CTNInbox inbox)
        {
            this.newattachmentPH                      = (System.Web.UI.WebControls.PlaceHolder) this.SharpUI.FindControl("newattachmentPH");
            this.attachmentsPH                        = (System.Web.UI.WebControls.PlaceHolder) this.SharpUI.FindControl("attachmentsPH");
            this.confirmationPH                       = (System.Web.UI.WebControls.PlaceHolder) this.SharpUI.FindControl("confirmationPH");
            this.newMessagePH                         = (System.Web.UI.WebControls.PlaceHolder) this.SharpUI.FindControl("newMessagePH");
            this.newMessageWindowAttachFile           = (System.Web.UI.HtmlControls.HtmlInputFile) this.SharpUI.FindControl("newMessageWindowAttachFile");
            this.newMessageWindowAttachmentsList      = (System.Web.UI.WebControls.CheckBoxList) this.SharpUI.FindControl("newMessageWindowAttachmentsList");
            this.newMessageWindowAttachmentsAddedList = (System.Web.UI.WebControls.DataList) this.SharpUI.FindControl("newMessageWindowAttachmentsAddedList");

            this.FCKEditor = (FredCK.FCKeditorV2.FCKeditor) this.SharpUI.FindControl("FCKEditor");
            this.fromname  = (System.Web.UI.HtmlControls.HtmlInputText) this.SharpUI.FindControl("fromname");
            this.fromemail = (System.Web.UI.HtmlControls.HtmlInputText) this.SharpUI.FindControl("fromemail");
            this.subject   = (System.Web.UI.HtmlControls.HtmlInputText) this.SharpUI.FindControl("subject");
            this.toemail   = (System.Web.UI.HtmlControls.HtmlInputText) this.SharpUI.FindControl("toemail");

#if MONO
            System.Web.UI.WebControls.RequiredFieldValidator rfv = (System.Web.UI.WebControls.RequiredFieldValidator) this.SharpUI.FindControl("ReqbodyValidator");
            rfv.Enabled = false;
            this.Validators.Remove(rfv);
#endif

            this.newMessageWindowConfirmation = (System.Web.UI.WebControls.Label) this.SharpUI.FindControl("newMessageWindowConfirmation");

            this.SharpUI.refreshPageImageButton.Click += new System.Web.UI.ImageClickEventHandler(refreshPageButton_Click);

            // Disable PlaceHolders
            this.attachmentsPH.Visible  = false;
            this.confirmationPH.Visible = false;

            // Disable some things
            this.SharpUI.nextPageImageButton.Enabled = false;
            this.SharpUI.prevPageImageButton.Enabled = false;
            // Get mode
            if (Page.Request.QueryString["mode"] != null)
            {
                try {
                    this._message_mode = (anmar.SharpWebMail.UI.MessageMode)System.Enum.Parse(typeof(anmar.SharpWebMail.UI.MessageMode), Page.Request.QueryString["mode"], true);
                } catch (System.Exception) {}
            }
            // Get message ID
            System.String msgid = System.Web.HttpUtility.HtmlEncode(Page.Request.QueryString["msgid"]);
            System.Guid   guid  = System.Guid.Empty;
            if (msgid != null)
            {
                guid = new System.Guid(msgid);
            }
            if (!this.IsPostBack && !guid.Equals(System.Guid.Empty))
            {
                System.Object[] details = inbox[guid];
                if (details != null)
                {
                    if (this._message_mode.Equals(anmar.SharpWebMail.UI.MessageMode.None))
                    {
                        this._message_mode = anmar.SharpWebMail.UI.MessageMode.reply;
                    }
                    this._headers = (anmar.SharpMimeTools.SharpMimeHeader)details[13];
                    if (!this.IsPostBack)
                    {
                        bool html_content = this.FCKEditor.CheckBrowserCompatibility();

                        this.subject.Value = System.String.Concat(this.SharpUI.LocalizedRS.GetString(System.String.Concat(this._message_mode, "Prefix")), ":");
                        if (details[10].ToString().ToLower().IndexOf(this.subject.Value.ToLower()) != -1)
                        {
                            this.subject.Value = details[10].ToString().Trim();
                        }
                        else
                        {
                            this.subject.Value = System.String.Concat(this.subject.Value, " ", details[10]).Trim();
                        }
                        // Get the original message
                        inbox.CurrentFolder = details[18].ToString();
                        System.IO.MemoryStream            ms      = inbox.GetMessage((int)details[1], msgid);
                        anmar.SharpMimeTools.SharpMessage message = null;
                        if (ms != null && ms.CanRead)
                        {
                            System.String path = null;
                            if (this._message_mode.Equals(anmar.SharpWebMail.UI.MessageMode.forward))
                            {
                                path = Session["sharpwebmail/read/message/temppath"].ToString();
                                path = System.IO.Path.Combine(path, msgid);
                                path = System.IO.Path.GetFullPath(path);
                            }
                            bool attachments = false;
                            if (this._message_mode.Equals(anmar.SharpWebMail.UI.MessageMode.forward))
                            {
                                attachments = (bool)Application["sharpwebmail/send/message/forwardattachments"];
                            }
                            message = new anmar.SharpMimeTools.SharpMessage(ms, attachments, html_content, path);
                            ms.Close();
                        }
                        ms = null;
                        if (this._message_mode.Equals(anmar.SharpWebMail.UI.MessageMode.reply))
                        {
                            // From name if present on original message's To header
                            // and we don't have it already
                            if (Session["DisplayName"] == null)
                            {
                                foreach (anmar.SharpMimeTools.SharpMimeAddress address in (System.Collections.IEnumerable)details[8])
                                {
                                    if (address["address"] != null && address["address"].Equals(User.Identity.Name) &&
                                        address["name"].Length > 0 && !address["address"].Equals(address["name"]))
                                    {
                                        this.fromname.Value = address["name"];
                                        break;
                                    }
                                }
                            }
                            // To addresses
                            foreach (anmar.SharpMimeTools.SharpMimeAddress address in (System.Collections.IEnumerable)details[9])
                            {
                                if (address["address"] != null && !address["address"].Equals(User.Identity.Name))
                                {
                                    if (this.toemail.Value.Length > 0)
                                    {
                                        this.toemail.Value += ", ";
                                    }
                                    this.toemail.Value += address["address"];
                                }
                            }
                        }
                        else if (this._message_mode.Equals(anmar.SharpWebMail.UI.MessageMode.forward))
                        {
                            // If the original message has attachments, preserve them
                            if (message != null && message.Attachments != null && message.Attachments.Count > 0)
                            {
                                this.bindAttachments();
                                foreach (anmar.SharpMimeTools.SharpAttachment attachment in message.Attachments)
                                {
                                    if (attachment.SavedFile == null)
                                    {
                                        continue;
                                    }
                                    this.AttachmentSelect(System.IO.Path.Combine(attachment.SavedFile.Directory.Name, attachment.SavedFile.Name));
                                }
                                this.Attach_Click(this, null);
                            }
                        }
                        // Preserve the original body and some properties
                        if (message != null)
                        {
                            System.Text.StringBuilder sb_body  = new System.Text.StringBuilder();
                            System.String             line_end = null;
                            if (html_content)
                            {
                                line_end = "<br />\r\n";
                            }
                            else
                            {
                                line_end = "\r\n";
                            }
                            sb_body.Append(this.SharpUI.LocalizedRS.GetString(System.String.Concat(this._message_mode, "PrefixBody")));
                            sb_body.Append(line_end);
                            sb_body.Append(this.SharpUI.LocalizedRS.GetString("newMessageWindowFromNameLabel"));
                            sb_body.Append(" ");
                            sb_body.Append(message.From);
                            sb_body.Append(" [mailto:");
                            sb_body.Append(message.FromAddress);
                            sb_body.Append("]");
                            sb_body.Append(line_end);
                            sb_body.Append(this.SharpUI.LocalizedRS.GetString("newMessageWindowDateLabel"));
                            sb_body.Append(" ");
                            sb_body.Append(message.Date.ToString());
                            sb_body.Append(line_end);
                            sb_body.Append(this.SharpUI.LocalizedRS.GetString("newMessageWindowToEmailLabel"));
                            sb_body.Append(" ");
                            if (html_content)
                            {
                                sb_body.Append(System.Web.HttpUtility.HtmlEncode(message.To.ToString()));
                            }
                            else
                            {
                                sb_body.Append(message.To);
                            }
                            sb_body.Append(line_end);
                            sb_body.Append(this.SharpUI.LocalizedRS.GetString("newMessageWindowSubjectLabel"));
                            sb_body.Append(" ");
                            sb_body.Append(message.Subject);
                            sb_body.Append(line_end);
                            sb_body.Append(line_end);
                            if (!message.HasHtmlBody && html_content)
                            {
                                sb_body.Append("<pre>");
                            }
                            sb_body.Append(message.Body);
                            if (!message.HasHtmlBody && html_content)
                            {
                                sb_body.Append("</pre>");
                            }
                            if (this._message_mode.Equals(anmar.SharpWebMail.UI.MessageMode.reply))
                            {
                                if (html_content)
                                {
                                    sb_body.Insert(0, System.String.Concat("<blockquote style=\"", Application["sharpwebmail/send/message/replyquotestyle"], "\">"));
                                    sb_body.Append("</blockquote>");
                                }
                                else
                                {
                                    sb_body.Insert(0, Application["sharpwebmail/send/message/replyquotechar"].ToString());
                                    sb_body.Replace("\n", System.String.Concat("\n", Application["sharpwebmail/send/message/replyquotechar"]));
                                }
                            }
                            sb_body.Insert(0, line_end);
                            sb_body.Insert(0, " ");
                            this.FCKEditor.Value = sb_body.ToString();
                        }
                    }
                    details = null;
                }
            }
            else if (!this.IsPostBack)
            {
                System.String to = Page.Request.QueryString["to"];
                if (to != null && to.Length > 0)
                {
                    this.toemail.Value = to;
                }
            }
            if (this.fromname.Value.Length > 0 || this.IsPostBack)
            {
                Session["DisplayName"] = this.fromname.Value;
            }
            if (this.fromname.Value.Length == 0 && Session["DisplayName"] != null)
            {
                this.fromname.Value = Session["DisplayName"].ToString();
            }
            if (this.fromemail.Value.Length > 0 || this.IsPostBack)
            {
                Session["DisplayEmail"] = this.fromemail.Value;
            }
        }
Beispiel #4
0
 private void decodeMessage(anmar.SharpMimeTools.SharpMessage message, System.Web.UI.WebControls.PlaceHolder entity)
 {
     System.Web.UI.HtmlControls.HtmlGenericControl body = new System.Web.UI.HtmlControls.HtmlGenericControl("span");
     // RFC 2392
     message.SetUrlBase(System.String.Concat("download.aspx?msgid=", Server.UrlEncode(msgid), "&name=[Name]&i=1"));
     // Html body
     if (message.HasHtmlBody)
     {
         body.Attributes["class"] = "XPFormText";
         if ((int)Application["sharpwebmail/read/message/sanitizer_mode"] == 1)
         {
             body.InnerHtml = anmar.SharpWebMail.BasicSanitizer.SanitizeHTML(message.Body, anmar.SharpWebMail.SanitizerMode.CommentBlocks | anmar.SharpWebMail.SanitizerMode.RemoveEvents);
         }
         else
         {
             body.InnerHtml = message.Body;
         }
         // Text body
     }
     else
     {
         body.TagName   = "pre";
         body.InnerText = message.Body;
     }
     entity.Controls.Add(body);
     // Attachments
     if (message.Attachments != null)
     {
         bool inline_added = false;
         foreach (anmar.SharpMimeTools.SharpAttachment item in message.Attachments)
         {
             if (item.SavedFile == null)
             {
                 continue;
             }
             System.Web.UI.HtmlControls.HtmlAnchor attachment = new System.Web.UI.HtmlControls.HtmlAnchor();
             attachment.Attributes["class"] = "XPDownload";
             attachment.Title     = System.String.Concat(item.SavedFile.Name, " (", item.Size, " bytes)");
             attachment.InnerText = attachment.Title;
             System.String urlstring = System.String.Concat("download.aspx?msgid=", Server.UrlEncode(msgid),
                                                            "&name=", Server.UrlEncode(item.SavedFile.Name), "&i=");
             attachment.HRef = urlstring;
             this.readMessageWindowAttachmentsHolder.Controls.Add(attachment);
             // Inline attachment
             if (item.Inline)
             {
                 if (item.MimeTopLevelMediaType == anmar.SharpMimeTools.MimeTopLevelMediaType.image &&
                     (item.MimeMediaSubType == "gif" || item.MimeMediaSubType == "jpg" || item.MimeMediaSubType == "png"))
                 {
                     System.Web.UI.HtmlControls.HtmlImage image = new System.Web.UI.HtmlControls.HtmlImage();
                     image.Src = System.String.Concat(urlstring, "1");
                     image.Alt = attachment.Name;
                     if (!inline_added)
                     {
                         entity.Controls.Add(new System.Web.UI.HtmlControls.HtmlGenericControl("hr"));
                         inline_added = true;
                     }
                     entity.Controls.Add(image);
                 }
             }
         }
     }
 }
Beispiel #5
0
 protected void Page_PreRender(System.Object sender, System.EventArgs args)
 {
     if (msgid != null)
     {
         bool deleted = false;
         System.IO.MemoryStream ms = null;
         if (delete)
         {
             deleted = this.SharpUI.Inbox.DeleteMessage(msgid);
             if (deleted)
             {
                 this.SharpUI.setVariableLabels();
             }
         }
         // Setup some options for later use
         System.String tmppath = null;
         anmar.SharpMimeTools.MimeTopLevelMediaType types   = anmar.SharpMimeTools.MimeTopLevelMediaType.text | anmar.SharpMimeTools.MimeTopLevelMediaType.multipart | anmar.SharpMimeTools.MimeTopLevelMediaType.message;
         anmar.SharpMimeTools.SharpDecodeOptions    options = anmar.SharpMimeTools.SharpDecodeOptions.AllowHtml;
         if (Session["sharpwebmail/read/message/temppath"] != null)
         {
             tmppath  = System.IO.Path.Combine(Session["sharpwebmail/read/message/temppath"].ToString(), msgid);
             options |= anmar.SharpMimeTools.SharpDecodeOptions.AllowAttachments | anmar.SharpMimeTools.SharpDecodeOptions.DecodeTnef | anmar.SharpMimeTools.SharpDecodeOptions.CreateFolder;
             types   |= anmar.SharpMimeTools.MimeTopLevelMediaType.application | anmar.SharpMimeTools.MimeTopLevelMediaType.audio | anmar.SharpMimeTools.MimeTopLevelMediaType.image | anmar.SharpMimeTools.MimeTopLevelMediaType.video;
         }
         // Delete messaged, we have to commit changes
         if (deleted && (bool)Application["sharpwebmail/read/inbox/commit_ondelete"])
         {
             this.SharpUI.Inbox.Client.PurgeInbox(this.SharpUI.Inbox, false);
             Response.Redirect("default.aspx");
         }
         else
         {
             // We retrieve the message body
             this.SharpUI.Inbox.CurrentFolder = this.SharpUI.Inbox.GetMessageFolder(msgid);
             ms = this.SharpUI.Inbox.GetMessage(msgid);
         }
         if (ms != null)
         {
             System.Object[] details = this.SharpUI.Inbox[msgid];
             // Disable delete button if message is already deleted
             if (details[15].Equals(true) || deleted)
             {
                 ((System.Web.UI.WebControls.ImageButton) this.SharpUI.FindControl("msgtoolbarDelete")).Enabled = false;
             }
             this.readMessageWindowDateTextLabel.Text    = System.Web.HttpUtility.HtmlEncode(details[14].ToString());
             this.readMessageWindowFromTextLabel.Text    = System.Web.HttpUtility.HtmlEncode(details[6].ToString());
             this.readMessageWindowToTextLabel.Text      = System.Web.HttpUtility.HtmlEncode(details[8].ToString());
             this.readMessageWindowSubjectTextLabel.Text = System.Web.HttpUtility.HtmlEncode(details[10].ToString());
             this.newMessageWindowTitle.Text             = System.Web.HttpUtility.HtmlEncode(details[10].ToString());
             if (this.newMessageWindowTitle.Text.Equals(System.String.Empty))
             {
                 this.newMessageWindowTitle.Text = this.SharpUI.LocalizedRS.GetString("noSubject");
             }
             if (ms != null && ms.CanRead)
             {
                 anmar.SharpMimeTools.SharpMessage mm = new anmar.SharpMimeTools.SharpMessage(ms, types, options, tmppath, null);
                 this.readMessageWindowCcTextLabel.Text = System.Web.HttpUtility.HtmlEncode(mm.Cc.ToString());
                 this.decodeMessage(mm, this.readMessageWindowBodyTextHolder);
                 mm = null;
                 this.SharpUI.Inbox.readMessage(msgid);
             }
             details = null;
         }
         if (ms != null && ms.CanRead)
         {
             ms.Close();
         }
         ms = null;
     }
 }
Beispiel #6
0
        /// <summary>
        /// 
        /// </summary>
        protected void mainInterface( anmar.SharpWebMail.CTNInbox inbox )
        {
            this.newattachmentPH=(System.Web.UI.WebControls.PlaceHolder )this.SharpUI.FindControl("newattachmentPH");
            this.attachmentsPH=(System.Web.UI.WebControls.PlaceHolder )this.SharpUI.FindControl("attachmentsPH");
            this.confirmationPH=(System.Web.UI.WebControls.PlaceHolder )this.SharpUI.FindControl("confirmationPH");
            this.newMessagePH=(System.Web.UI.WebControls.PlaceHolder )this.SharpUI.FindControl("newMessagePH");
            this.newMessageWindowAttachFile=( System.Web.UI.HtmlControls.HtmlInputFile )this.SharpUI.FindControl("newMessageWindowAttachFile");
            this.newMessageWindowAttachmentsList=(System.Web.UI.WebControls.CheckBoxList )this.SharpUI.FindControl("newMessageWindowAttachmentsList");
            this.newMessageWindowAttachmentsAddedList=(System.Web.UI.WebControls.DataList )this.SharpUI.FindControl("newMessageWindowAttachmentsAddedList");

            this.FCKEditor = (FredCK.FCKeditorV2.FCKeditor)this.SharpUI.FindControl("FCKEditor");
            this.fromname = (System.Web.UI.HtmlControls.HtmlInputText)this.SharpUI.FindControl("fromname");
            this.fromemail = (System.Web.UI.HtmlControls.HtmlInputText)this.SharpUI.FindControl("fromemail");
            this.subject = (System.Web.UI.HtmlControls.HtmlInputText)this.SharpUI.FindControl("subject");
            this.toemail = (System.Web.UI.HtmlControls.HtmlInputText)this.SharpUI.FindControl("toemail");

            #if MONO
            System.Web.UI.WebControls.RequiredFieldValidator rfv = (System.Web.UI.WebControls.RequiredFieldValidator) this.SharpUI.FindControl("ReqbodyValidator");
            rfv.Enabled=false;
            this.Validators.Remove(rfv);
            #endif

            this.newMessageWindowConfirmation = (System.Web.UI.WebControls.Label)this.SharpUI.FindControl("newMessageWindowConfirmation");

            this.SharpUI.refreshPageImageButton.Click += new System.Web.UI.ImageClickEventHandler(refreshPageButton_Click);

            // Disable PlaceHolders
            this.attachmentsPH.Visible = false;
            this.confirmationPH.Visible = false;

            // Disable some things
            this.SharpUI.nextPageImageButton.Enabled = false;
            this.SharpUI.prevPageImageButton.Enabled = false;
            // Get mode
            if ( Page.Request.QueryString["mode"]!=null ) {
                try {
                    this._message_mode = (anmar.SharpWebMail.UI.MessageMode)System.Enum.Parse(typeof(anmar.SharpWebMail.UI.MessageMode), Page.Request.QueryString["mode"], true);
                } catch ( System.Exception ){}
            }
            // Get message ID
            System.String msgid = System.Web.HttpUtility.HtmlEncode (Page.Request.QueryString["msgid"]);
            System.Guid guid = System.Guid.Empty;
            if ( msgid!=null )
                guid = new System.Guid(msgid);
            if ( !this.IsPostBack && !guid.Equals( System.Guid.Empty) ) {
                System.Object[] details = inbox[ guid ];
                if ( details!=null ) {
                    if ( this._message_mode.Equals(anmar.SharpWebMail.UI.MessageMode.None) )
                        this._message_mode = anmar.SharpWebMail.UI.MessageMode.reply;
                    this._headers = (anmar.SharpMimeTools.SharpMimeHeader) details[13];
                    if ( !this.IsPostBack ) {
                        bool html_content = this.FCKEditor.CheckBrowserCompatibility();

                        this.subject.Value = System.String.Concat (this.SharpUI.LocalizedRS.GetString(System.String.Concat(this._message_mode, "Prefix")), ":");
                        if ( details[10].ToString().ToLower().IndexOf (this.subject.Value.ToLower())!=-1 ) {
                            this.subject.Value = details[10].ToString().Trim();
                        } else {
                            this.subject.Value = System.String.Concat (this.subject.Value, " ", details[10]).Trim();
                        }
                        // Get the original message
                        inbox.CurrentFolder = details[18].ToString();
                        System.IO.MemoryStream ms = inbox.GetMessage((int)details[1], msgid);
                        anmar.SharpMimeTools.SharpMessage message = null;
                        if ( ms!=null && ms.CanRead ) {
                            System.String path = null;
                            if ( this._message_mode.Equals(anmar.SharpWebMail.UI.MessageMode.forward) ) {
                                path = Session["sharpwebmail/read/message/temppath"].ToString();
                                path = System.IO.Path.Combine (path, msgid);
                                path = System.IO.Path.GetFullPath(path);
                            }
                            bool attachments = false;
                            if ( this._message_mode.Equals(anmar.SharpWebMail.UI.MessageMode.forward) )
                                attachments = (bool)Application["sharpwebmail/send/message/forwardattachments"];
                            message = new anmar.SharpMimeTools.SharpMessage(ms, attachments, html_content, path);
                        }
                        if ( this._message_mode.Equals(anmar.SharpWebMail.UI.MessageMode.reply) ) {
                            // From name if present on original message's To header
                            // and we don't have it already
                            if ( Session["DisplayName"]==null ) {
                                foreach ( anmar.SharpMimeTools.SharpMimeAddress address in (System.Collections.IEnumerable) details[8] ) {
                                    if ( address["address"]!=null && address["address"].Equals( User.Identity.Name )
                                        && address["name"].Length>0 && !address["address"].Equals(address["name"]) ) {
                                        this.fromname.Value = address["name"];
                                        break;
                                    }
                                }
                            }
                            // To addresses
                            foreach ( anmar.SharpMimeTools.SharpMimeAddress address in (System.Collections.IEnumerable) details[9] ) {
                                if ( address["address"]!=null && !address["address"].Equals( User.Identity.Name ) ) {
                                    if ( this.toemail.Value.Length >0 )
                                        this.toemail.Value += ", ";
                                    this.toemail.Value += address["address"];
                                }
                            }
                        } else if ( this._message_mode.Equals(anmar.SharpWebMail.UI.MessageMode.forward) ) {
                            // If the original message has attachments, preserve them
                            if ( message!=null && message.Attachments!=null &&  message.Attachments.Count>0 ) {
                                this.bindAttachments();
                                foreach ( anmar.SharpMimeTools.SharpAttachment attachment in message.Attachments ) {
                                    if ( attachment.SavedFile==null )
                                        continue;
                                    this.AttachmentSelect(System.IO.Path.Combine(attachment.SavedFile.Directory.Name, attachment.SavedFile.Name));
                                }
                                this.Attach_Click(this, null);
                            }
                        }
                        // Preserve the original body and some properties
                        if ( message!=null ) {
                            System.Text.StringBuilder sb_body = new System.Text.StringBuilder();
                            System.String line_end = null;
                            if ( html_content )
                                line_end = "<br />\r\n";
                            else
                                line_end = "\r\n";
                            sb_body.Append(this.SharpUI.LocalizedRS.GetString(System.String.Concat(this._message_mode, "PrefixBody")));
                            sb_body.Append(line_end);
                            sb_body.Append(this.SharpUI.LocalizedRS.GetString("newMessageWindowFromNameLabel"));
                            sb_body.Append(" ");
                            sb_body.Append(message.From);
                            sb_body.Append(" [mailto:");
                            sb_body.Append(message.FromAddress);
                            sb_body.Append("]");
                            sb_body.Append(line_end);
                            sb_body.Append(this.SharpUI.LocalizedRS.GetString("newMessageWindowDateLabel"));
                            sb_body.Append(" ");
                            sb_body.Append(message.Date.ToString());
                            sb_body.Append(line_end);
                            sb_body.Append(this.SharpUI.LocalizedRS.GetString("newMessageWindowToEmailLabel"));
                            sb_body.Append(" ");
                            if ( html_content )
                                sb_body.Append(System.Web.HttpUtility.HtmlEncode(message.To.ToString()));
                            else
                                sb_body.Append(message.To);
                            sb_body.Append(line_end);
                            sb_body.Append(this.SharpUI.LocalizedRS.GetString("newMessageWindowSubjectLabel"));
                            sb_body.Append(" ");
                            sb_body.Append(message.Subject);
                            sb_body.Append(line_end);
                            sb_body.Append(line_end);
                            if ( !message.HasHtmlBody &&  html_content )
                                sb_body.Append("<pre>");
                            sb_body.Append(message.Body);
                            if ( !message.HasHtmlBody &&  html_content )
                                sb_body.Append("</pre>");
                            if ( this._message_mode.Equals(anmar.SharpWebMail.UI.MessageMode.reply) ) {
                                if ( html_content ) {
                                    sb_body.Insert(0, System.String.Concat("<blockquote style=\"", Application["sharpwebmail/send/message/replyquotestyle"] ,"\">"));
                                    sb_body.Append("</blockquote>");
                                } else {
                                    sb_body.Insert(0, Application["sharpwebmail/send/message/replyquotechar"].ToString());
                                    sb_body.Replace("\n", System.String.Concat("\n", Application["sharpwebmail/send/message/replyquotechar"]));
                                }
                            }
                            sb_body.Insert(0, line_end);
                            sb_body.Insert(0, " ");
                            this.FCKEditor.Value = sb_body.ToString();
                        }
                    }
                    details = null;
                }
            } else if ( !this.IsPostBack ) {
                System.String to = Page.Request.QueryString["to"];
                if ( to!=null && to.Length>0 ) {
                    this.toemail.Value = to;
                }
            }
            if ( this.fromname.Value.Length>0 || this.IsPostBack )
                Session["DisplayName"] = this.fromname.Value;
            if ( this.fromname.Value.Length==0 && Session["DisplayName"]!=null )
                this.fromname.Value = Session["DisplayName"].ToString();
            if ( this.fromemail.Value.Length>0 || this.IsPostBack )
                Session["DisplayEmail"] = this.fromemail.Value;
        }