/// <summary>
        /// Updates the preview.
        /// </summary>
        protected void UpdatePreview()
        {
            var templateDoc = new HtmlAgilityPack.HtmlDocument();

            templateDoc.LoadHtml(ceEmailTemplate.Text);

            // only show the template logo uploader if there is a div with id='template-logo'
            // then update the help-message on the loader based on the template-logo's data-instructions attribute and width and height
            // this gets called when the codeeditor is done initializing and when the cursor blurs out of the template code editor
            var templateLogoNode = templateDoc.GetElementbyId("template-logo");

            if (templateLogoNode != null)
            {
                string helpText = null;
                if (templateLogoNode.Attributes.Contains("data-instructions"))
                {
                    helpText = templateLogoNode.Attributes["data-instructions"].Value;
                }

                if (helpText.IsNullOrWhiteSpace())
                {
                    helpText = "The Logo that can be included in the contents of the message";
                }

                string helpWidth  = null;
                string helpHeight = null;
                if (templateLogoNode.Attributes.Contains("width"))
                {
                    helpWidth = templateLogoNode.Attributes["width"].Value;
                }

                if (templateLogoNode.Attributes.Contains("height"))
                {
                    helpHeight = templateLogoNode.Attributes["height"].Value;
                }

                if (helpWidth.IsNotNullOrWhiteSpace() && helpHeight.IsNotNullOrWhiteSpace())
                {
                    helpText += string.Format(" (Image size: {0}px x {1}px)", helpWidth, helpHeight);
                }

                imgTemplateLogo.Help = helpText;
            }

            pnlTemplateLogo.Visible = templateLogoNode != null;

            // take care of the lava fields stuff
            var lavaFieldsNode = templateDoc.GetElementbyId("lava-fields");

            if (lavaFieldsNode == null)
            {
                lavaFieldsNode = templateDoc.CreateElement("noscript");
                lavaFieldsNode.Attributes.Add("id", "lava-fields");
            }
            else if (lavaFieldsNode.ParentNode.Name == "body")
            {
                // if the lava-fields is a in the body (from pre-v9 template), remove it from body, and let it get added to head instead
                lavaFieldsNode.Attributes.Remove("style");
                lavaFieldsNode.Remove();
                lavaFieldsNode.Name = "noscript";
            }

            var templateDocLavaFieldLines = lavaFieldsNode.InnerText.Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.RemoveEmptyEntries).Select(a => a.Trim()).Where(a => a.IsNotNullOrWhiteSpace()).ToList();

            // dictionary of keys and default values from Lava Fields KeyValueList control
            var lavaFieldsDefaultDictionary = kvlMergeFields.Value.AsDictionary();

            // add any new lava fields that were added to the KeyValueList editor
            foreach (var keyValue in lavaFieldsDefaultDictionary)
            {
                string pattern = string.Format(@"{{%\s+assign\s+{0}.*\s+=\s", keyValue.Key);
                if (!templateDocLavaFieldLines.Any(a => Regex.IsMatch(a, pattern)))
                {
                    templateDocLavaFieldLines.Add("{% assign " + keyValue.Key + " = '" + keyValue.Value + "' %}");
                }
            }

            // remove any lava fields that are not in the KeyValueList editor
            foreach (var templateDocLavaFieldLine in templateDocLavaFieldLines.ToList())
            {
                var found = false;
                foreach (var keyValue in lavaFieldsDefaultDictionary)
                {
                    var pattern = string.Format(@"{{%\s+assign\s+{0}.*\s+=\s", keyValue.Key);
                    if (!Regex.IsMatch(templateDocLavaFieldLine, pattern))
                    {
                        continue;
                    }

                    found = true;
                    break;
                }

                // if not found, delete it
                if (!found)
                {
                    templateDocLavaFieldLines.Remove(templateDocLavaFieldLine);
                }
            }

            // dictionary of keys and values from the lava fields in the 'lava-fields' div
            var lavaFieldsTemplateDictionary = new Dictionary <string, string>();

            foreach (var templateDocLavaFieldLine in templateDocLavaFieldLines)
            {
                var match = Regex.Match(templateDocLavaFieldLine, @"{% assign (.*)\=(.*) %}");
                if (match.Groups.Count != 3)
                {
                    continue;
                }

                var key   = match.Groups[1].Value.Trim().RemoveSpaces();
                var value = match.Groups[2].Value.Trim().Trim('\'');

                // If this is a postback, there will be a control that holds the value
                var lavaValueControl = phLavaFieldsControls.FindControl("lavaValue_" + key) as RockTextBox;
                if (lavaValueControl != null && lavaValueControl.Text != value)
                {
                    value = lavaValueControl.Text;
                }

                lavaFieldsTemplateDictionary.Add(key, value);
            }

            if (lavaFieldsTemplateDictionary.Any())
            {
                var lavaAssignsHtml = new StringBuilder();
                lavaAssignsHtml.AppendLine();
                lavaAssignsHtml.AppendLine("    {% comment %}  Lava Fields: Code-Generated from Template Editor {% endcomment %}");
                foreach (var lavaFieldsTemplateItem in lavaFieldsTemplateDictionary)
                {
                    lavaAssignsHtml.AppendLine(string.Format("    {{% assign {0} = '{1}' %}}", lavaFieldsTemplateItem.Key, lavaFieldsTemplateItem.Value));
                }

                lavaAssignsHtml.Append("  ");

                lavaFieldsNode.InnerHtml = lavaAssignsHtml.ToString();

                if (lavaFieldsNode.ParentNode == null)
                {
                    var headNode = templateDoc.DocumentNode.SelectSingleNode("//head");
                    if (headNode != null)
                    {
                        // prepend a linefeed so that it is after the lava node (to make it pretty printed)
                        headNode.PrependChild(templateDoc.CreateTextNode("\r\n"));

                        headNode.PrependChild(lavaFieldsNode);

                        // prepend a indented linefeed so that it ends up prior the lava node (to make it pretty printed)
                        headNode.PrependChild(templateDoc.CreateTextNode("\r\n  "));
                    }
                }
            }
            else if (lavaFieldsNode.ParentNode != null)
            {
                if (lavaFieldsNode.NextSibling != null && lavaFieldsNode.NextSibling.Name == "#text")
                {
                    // remove the extra line endings
                    lavaFieldsNode.NextSibling.InnerHtml = lavaFieldsNode.NextSibling.InnerHtml.TrimStart(' ', '\r', '\n');
                }

                lavaFieldsNode.Remove();
            }

            hfLavaFieldsState.Value = lavaFieldsTemplateDictionary.ToJson(Newtonsoft.Json.Formatting.None);

            ceEmailTemplate.Text = templateDoc.DocumentNode.OuterHtml;

            CreateDynamicLavaValueControls();

            var mergeFields         = Rock.Lava.LavaHelper.GetCommonMergeFields(RockPage);
            var resolvedPreviewHtml = ceEmailTemplate.Text.ResolveMergeFields(mergeFields);

            if (cbCssInliningEnabled.Checked)
            {
                resolvedPreviewHtml = resolvedPreviewHtml.ConvertHtmlStylesToInlineAttributes();
            }

            ifEmailPreview.Attributes["srcdoc"] = resolvedPreviewHtml;
            pnlEmailPreview.Visible             = true;
            upnlEmailPreview.Update();
        }
Exemple #2
0
        public ActionResult Forgot(FormCollection collection)
        {
            try
            {
                var model = new Models.Passwords.Forgot {
                    Username = collection["Username"], Email = collection["Email"]
                };
                if (!TryValidateModel(model))
                {
                    return(View(model));
                }

                using (var ctx = new Models.Ao3TrackEntities())
                {
                    var user = (from users in ctx.Users
                                where users.username == model.Username
                                select users).FirstOrDefault();

                    if (user == null)
                    {
                        ModelState.AddModelError("Username", "Unknown Username");
                        return(View(model));
                    }

                    if (user.email != model.Email)
                    {
                        ModelState.AddModelError("Email", "Email address does not match database");
                        return(View(model));
                    }

                    var pwrequest = new Models.PWReset {
                        id = Guid.NewGuid(), expires = DateTime.Now.AddDays(1), user = user.id, oldhash = user.hash, complete = false
                    };
                    ctx.PWResets.Add(pwrequest);
                    ctx.SaveChanges();

                    var uri = new Uri(Request.Url, Url.Action("Reset", new { id = pwrequest.id.ToString("N") }));

                    MailMessage message = new MailMessage(new MailAddress("*****@*****.**", "Archive Track Reader"), new MailAddress(user.email));
                    message.Subject = "Archive Track Reader Password Reset Request";

                    var doc  = new HtmlAgilityPack.HtmlDocument();
                    var html = doc.CreateElement("html");
                    doc.DocumentNode.AppendChild(html);

                    var head = doc.CreateElement("head");
                    html.AppendChild(head);

                    var title = doc.CreateElement("title");
                    title.AppendChild(doc.CreateTextNode("Archive Track Reader Password Reset Request"));
                    head.AppendChild(title);


                    var style = doc.CreateElement("style");
                    style.AppendChild(doc.CreateTextNode(@"body {
    color: #191919;
    background: #CCCCCC;
}

h1, h2, h3, h4, h5, h6, h7, h8, a {
    color: #A50000;
}

details p {
    color: #656565;
}"));
                    head.AppendChild(style);

                    var body = doc.CreateElement("body");
                    html.AppendChild(body);

                    var heading = doc.CreateElement("h1");
                    heading.AppendChild(doc.CreateTextNode("Archive Track Reader Password Reset Request"));
                    body.AppendChild(heading);

                    var para = doc.CreateElement("p");
                    para.AppendChild(doc.CreateTextNode("A Password Reset Request was made for the account: " + System.Net.WebUtility.HtmlEncode(user.username)));
                    body.AppendChild(para);

                    para = doc.CreateElement("p");
                    para.AppendChild(doc.CreateTextNode("Follow this link "));
                    var link = doc.CreateElement("a");
                    link.Attributes.Add(doc.CreateAttribute("href", System.Net.WebUtility.HtmlEncode(uri.AbsoluteUri)));
                    link.AppendChild(doc.CreateTextNode(System.Net.WebUtility.HtmlEncode(uri.AbsoluteUri)));
                    para.AppendChild(link);
                    para.AppendChild(doc.CreateTextNode(" to change the account's password."));

                    body.AppendChild(para);
                    para.AppendChild(doc.CreateTextNode("The link will expire at " + pwrequest.expires.ToString("r") + "."));
                    para = doc.CreateElement("p");

                    body.AppendChild(para);

                    var writer = new System.IO.StringWriter();
                    doc.Save(writer);

                    message.Body       = "<!DOCTYPE html>\n" + writer.ToString();
                    message.IsBodyHtml = true;

                    SmtpClient client = new SmtpClient("127.0.0.1");
                    client.Send(message);

                    return(View("ForgotDone", user));
                }
            }
            catch (Exception e)
            {
                ModelState.AddModelError("", e.ToString());

                return(View());
            }
        }