+1-888-365-2779
Try Now
More in this section

Forums / General Discussions / Spam protection (CAPTCHA)

Spam protection (CAPTCHA)

38 posts, 0 answered
  1. Ivan Dimitrov
    Ivan Dimitrov avatar
    16072 posts
    Registered:
    25 Nov 2016
    07 Sep 2012
    Link to this post
    Hi,

    You have to validate whether the page is valid. Please take a look at this demo.

    All the best,
    Ivan Dimitrov
    the Telerik team
    Do you want to have your say in the Sitefinity development roadmap? Do you want to know when a feature you requested is added or when a bug fixed? Explore the Telerik Public Issue Tracking system and vote to affect the priority of the items
  2. Jochem Bökkers
    Jochem Bökkers avatar
    787 posts
    Registered:
    13 Aug 2007
    07 Sep 2012
    Link to this post
    Since there are no Sweeds in the thread, I'm just going to say it:

    Blonde question but how do you envision this kind of validation on a Sitefinity form ?

    On content>forms you can't add this validation. On the Forms widget you can't add extra validation.

    So the only way something like that could work is by dropping a Javascript widget on the page where you drop the widget and mimic the code inside that script block.

    Which is fun since that totally negates the re-use of forms as a widget because you'd manually need to add script widgets for each page where you post a form and it means the end-user can never create a new page with a form...

    Or am I missing something here?

    Jochem


  3. Steve
    Steve avatar
    3037 posts
    Registered:
    03 Dec 2008
    07 Sep 2012
    Link to this post
    You have to use a custom control (until they can just implement this...) that inherits from the regular forms control and then check the captcha on the BeforeFormSave event

    I based mine on Georges Forms Notification Control, but you can just as easily cut out the important bits.

    So use jochems method to copy the radcaptcha into the forms controls toolbox then it searches through the controls on the form and finds the captcha, then validates on submit!

    I have this active on my site and it's been working flawlessly since implimented.  However it'd be nice if telerik implemented it core.

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Linq;
    using System.Net;
    using System.Net.Mail;
    using System.Text;
    using System.Text.RegularExpressions;
    using Telerik.Microsoft.Practices.EnterpriseLibrary.Logging;
    using Telerik.Sitefinity.Configuration;
    using Telerik.Sitefinity.Modules.Forms;
    using Telerik.Sitefinity.Modules.Forms.Web.UI;
    using Telerik.Sitefinity.Modules.Forms.Web.UI.Fields;
    using Telerik.Sitefinity.Services;
    using Telerik.Sitefinity.Web.UI;
    using Telerik.Sitefinity.Web.UI.Fields;
    using Telerik.Web.UI;
     
    namespace FormsNotification
    {
        [Telerik.Sitefinity.Web.UI.ControlDesign.ControlDesigner(typeof(FormsControlCustomDesigner))]
        public class FormsControlCustom : FormsControl
        {
            private const string LAYOUT_TEMPLATE_NAME = "FormsNotification.Resources.FormsControl.ascx";
            private const string CLIENT_EMAIL_SUBJECT = "Form Submission";
            private string _clientEmailField;
     
            protected override void InitializeControls(GenericContainer container)
            {
                if (!SystemManager.IsDesignMode)
                {
                    //Hide the form if JS is disabled, it'll let them bypass the required fields.
                    base.InitializeControls(container);
                    this.BeforeFormSave += new EventHandler<CancelEventArgs>(FormsControlCustom_BeforeFormSave);
                }
            }
     
     
            #region EVENTS
            protected void FormsControlCustom_BeforeFormSave(object sender, CancelEventArgs e)
            {
                bool canSendEmail = true;
     
                if (this.MyCaptcha != null)
                {
                    if (!this.MyCaptcha.IsValid)
                    {
                        e.Cancel = true;
                        this.MyCaptcha.ErrorMessage = this.CaptchaErrorMessage;
                        canSendEmail = false;
                    }
                }
     
                if (canSendEmail)
                    SendEmail();
            }
            /*
            /// <summary>
            /// Handles the submit button click event.
            /// </summary>
            /// <param name="control">The submit control.</param>
            /// <param name="validationGroup">The validation group.</param>
            protected override void ConfigureSubmitButton(System.Web.UI.Control control, string validationGroup)
            {
                //var submit = control as FormSubmitButton;
                //submit.Click += new EventHandler(OnSubmitButton_Click);
                base.ConfigureSubmitButton(control, validationGroup);
            }
            */
            /*
            /// <summary>
            /// The submit button click event handler.
            /// </summary>
            /// <param name="sender">Calling control.</param>
            /// <param name="e">Event arguments.</param>
            void OnSubmitButton_Click(object sender, EventArgs e)
            {
                SendEmail();
            }
             * */
       
            private void SendEmail()
            {
                try
                {
                    //String to hold the message content
                    var msgContent = new StringBuilder();
     
                    if (!string.IsNullOrEmpty(Message))
                        msgContent.Append(string.Format("<p>{0}</p>", Message));
     
                    if (IncludeFields)
                    {
                        //Start reading fields controls starting with the built-in types then the custom or generic types)
                        foreach (var fieldControl in this.FieldControls)
                        {
                            if (fieldControl is FormTextBox)
                            {
                                msgContent.Append(String.Format("<p><strong>{0}:</strong> {1}</p>",
                                    ((FormTextBox)fieldControl).Title,
                                    ((FormTextBox)fieldControl).Value));
     
                                if (fieldControl.MetaField.FieldName.ToLower().Contains("email"))
                                {
                                    _clientEmailField = ((FormTextBox)fieldControl).Value.ToString().Trim();
                                }
                            }
                            else if (fieldControl is FormParagraphTextBox)
                            {
                                msgContent.Append(String.Format("<p><strong>{0}:</strong> {1}</p>",
                                    ((FormParagraphTextBox)fieldControl).Title,
                                    ((FormParagraphTextBox)fieldControl).Value));
                            }
                            else if (fieldControl is FormCheckboxes)
                            {
                                string choices = ((List<String>)((FormCheckboxes)fieldControl).Value).Aggregate(string.Empty,
                                    (current, item) =>
                                                      current +
                                                      String.Format(
                                                          "{0},",
                                                          item));
                                msgContent.Append(String.Format("<p><strong>{0}:</strong> {1}</p>",
                                    ((FormCheckboxes)fieldControl).Title, choices));
                            }
                            else if (fieldControl is FormChoiceField)
                            {
                                msgContent.Append(String.Format("<p><strong>{0}:</strong> {1}</p>",
                                    ((FormChoiceField)fieldControl).Title,
                                    ((FormChoiceField)fieldControl).Value));
                            }
                            else if (fieldControl is FieldControl)
                            {
                                var fldControl = fieldControl as FieldControl;
     
                                msgContent.Append(String.Format("<p><strong>{0}:</strong> {1}</p>", fldControl.Title,
                                    fldControl.Value));
                            }
                        }
                    }
                    else
                    {
                        foreach (var fieldControl in FieldControls.OfType<FormTextBox>().Where(fieldControl => fieldControl.MetaField.FieldName.ToLower().Contains("email")))
                        {
                            _clientEmailField = (fieldControl).Value.ToString().Trim();
                        }
                    }
     
                    try
                    {
                        //Finally attempt to send the email(s)
                        var isMsgSent = SendEmailMsg(FromAddress, ToAddresses, CCAddresses, Subject, msgContent.ToString());
     
                        if (!isMsgSent)
                        {
                            //TODO: add action when the email was not sent.
                        }
                    }
                    catch (Exception ex)
                    {
                        if (EnableLogging)
                        {
                            Logger.Writer.Write(CreateLogEntry(ex));
                        }
                    }
                }
                catch (Exception ex)
                {
                    Logger.Writer.Write(CreateLogEntry(ex));
                }
            }
     
            private LogEntry CreateLogEntry(Exception ex, string title = "Email on form submission failed")
            {
                var logEntry = new LogEntry();
                logEntry.Categories.Add("ErrorLog");
                logEntry.Message = ex.ToString();
                logEntry.Title = title;
                return logEntry;
            }
     
            #endregion
     
            #region METHODS
            /// <summary>
            /// Determines whether the email address provided is valid using regular expression.
            /// </summary>
            /// <param name="email">Email address to validate</param>
            /// <returns>True if valid, false otherwise</returns>
            private bool IsValidEmail(string email)
            {
                //regular expression pattern for valid email
                var pattern = @"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*";
                //Regular expression object
                var check = new Regex(pattern, RegexOptions.IgnorePatternWhitespace);
                //boolean variable to return to calling method
                var valid = false;
     
                //make sure an email address was provided
                valid = !string.IsNullOrEmpty(email) && check.IsMatch(email);
     
                //return the value to the calling method
                return valid;
            }
     
            /// <summary>
            /// Attempts to sends an email message.  If success, returns true.  Else returns false.
            /// </summary>
            /// <param name="fromAddr">Who the email is from</param>
            /// <param name="toAddr">Who the email is to (comma separate if more than one)</param>
            /// <param name="ccAddr">Who should be cc'ed (comma separate if more than one)</param>
            /// <param name="subject">Subject line of the email</param>
            /// <param name="msgBody">content of the email</param>
            /// <returns></returns>
            private bool SendEmailMsg(string fromAddr, string toAddr, string ccAddr, string subject, string msgBody)
            {
                if (!string.IsNullOrEmpty(fromAddr) && !string.IsNullOrEmpty(toAddr))
                {
                    var mailServer = new SmtpClient();
                    var mailMsg = new MailMessage();
     
                    var clientMailMsg = new MailMessage();
     
                    var smtpSettings = Config.Get<SystemConfig>().SmtpSettings;
     
                    if (!smtpSettings.Host.IsNullOrWhitespace())
                    {
                        mailServer.Host = smtpSettings.Host;
                        mailServer.Port = smtpSettings.Port;
                        mailServer.EnableSsl = smtpSettings.EnableSSL;
                        mailServer.Timeout = smtpSettings.Timeout;
     
                        if (!string.IsNullOrEmpty(smtpSettings.UserName))
                        {
                            mailServer.UseDefaultCredentials = false;
                            mailServer.Credentials = new NetworkCredential(smtpSettings.UserName, smtpSettings.Password);
                        }
                    }
     
                    if (IsValidEmail(fromAddr))
                    {
                        mailMsg.From = new MailAddress(fromAddr);
                        clientMailMsg.From = new MailAddress(fromAddr);
                    }
     
                    //Split the addresses into an array and check whether the specified addresses are valid
     
                    var arrToAddr = toAddr.Split(new string[] { ",", ";" }, StringSplitOptions.RemoveEmptyEntries);
                    var arrCCAddr = ccAddr.Split(new string[] { ",", ";" }, StringSplitOptions.RemoveEmptyEntries);
     
                    foreach (var emailAddr in arrToAddr.Select(s => s.Trim()).Where(IsValidEmail))
                    {
                        mailMsg.To.Add(new MailAddress(emailAddr));
                    }
     
                    foreach (var emailAddr in arrCCAddr.Select(s => s.Trim()).Where(IsValidEmail))
                    {
                        mailMsg.CC.Add(new MailAddress(emailAddr));
                    }
     
                    mailMsg.IsBodyHtml = true;
                    mailMsg.Subject = subject;
                    mailMsg.Body = "<div style='font-family: verdana;font-size: .8em;'>" + msgBody + "</div>";
     
                    if (SendEmailToClient && IsValidEmail(_clientEmailField))
                    {
                        clientMailMsg.To.Add(_clientEmailField);
                        clientMailMsg.IsBodyHtml = true;
                        clientMailMsg.Subject = CLIENT_EMAIL_SUBJECT;
                        clientMailMsg.Body = ClientMailMessage;
                    }
     
                    try
                    {
                        mailServer.Send(mailMsg);
     
                        if (SendEmailToClient && IsValidEmail(_clientEmailField))
                        {
                            mailServer.Send(clientMailMsg);
                        }
                    }
                    catch (Exception ex)
                    {
                        if (EnableLogging)
                        {
                            Logger.Writer.Write(CreateLogEntry(ex));
                        }
     
                        return false;
                    }
                }
     
                return true;
            }
     
            #endregion
     
            #region Properties
            private RadCaptcha _captcha = null;
            protected RadCaptcha MyCaptcha
            {
                get
                {
                    if (!SystemManager.IsDesignMode)
                    {
                        foreach (var control in this.FormControls.Controls[1].Controls)
                        {
                            if (control.GetType() == typeof(RadCaptcha))
                            {
                                _captcha = control as RadCaptcha;
                                break;
                            }
                        }
                    }
     
                    return _captcha;
                }
            }
     
            private string _captchaErrorMessage = "Invalid Code, please try again";
            public string CaptchaErrorMessage
            {
                 
                get{
                    return _captchaErrorMessage;
                }
                set
                {
                    _captchaErrorMessage = value;
                }
            }
     
            /// <summary>
            /// Gets or Sets the layout template name for the control.
            /// </summary>
            protected override string LayoutTemplateName
            {
                get
                {
                    return FormsControlCustom.LAYOUT_TEMPLATE_NAME;
                }
            }
     
            /// <summary>
            /// Gets or Sets the address(es) to which the email will be delivered.
            /// </summary>
            [Category("Email Options")]
            public string Subject
            {
                get
                {
                    var propertyValue = string.Empty;
     
                    object obj = ViewState["Subject"];
     
                    if (obj != null)
                        propertyValue = obj.ToString();
                    else
                    {
                        var formId = this.FormId;
                        var formMgr = new FormsManager();
                        var formDescr = formMgr.GetForm(formId);
                        propertyValue = String.Format("{0} {1} - Submission", formDescr.ApplicationName.TrimEnd('/'), formDescr.Title);
                    }
     
                    return propertyValue;
                }
                set
                {
                    ViewState["Subject"] = value;
                }
            }
     
            /// <summary>
            /// Gets or Sets the message that is included in the body.
            /// </summary>
            [Category("Email Options")]
            public string Message
            {
                get
                {
                    var propertyValue = string.Empty;
     
                    object obj = ViewState["Message"];
     
                    if (obj != null)
                        propertyValue = obj.ToString();
                    else
                    {
                        var formId = this.FormId;
                        var formMgr = new FormsManager();
                        var formDescr = formMgr.GetForm(formId);
                        propertyValue = String.Format("A {0} has been submitted, login to your CMS to view the results", formDescr.Title);
                    }
     
                    return propertyValue;
                }
                set
                {
                    ViewState["Message"] = value;
                }
            }
     
     
            /// <summary>
            /// Gets or Sets the address(es) to which the email will be delivered.
            /// </summary>
            [Category("Email Options")]
            public string ToAddresses
            {
                get
                {
                    var propertyValue = string.Empty;
                    object obj = ViewState["ToAddresses"];
                    if (obj != null)
                        propertyValue = obj.ToString();
                    return propertyValue.Trim();
                }
                set
                {
                    ViewState["ToAddresses"] = value;
                }
            }
     
            /// <summary>
            /// Gets or Sets the address from which the email will be delivered.
            /// </summary>
            [Category("Email Options")]
            public String FromAddress
            {
                get
                {
                    var propertyValue = string.Empty;
                    var obj = ViewState["FromAddress"];
                    if (obj != null)
                        propertyValue = obj.ToString();
     
                    else
                    {
                        var smtpSettings = Config.Get<SystemConfig>().SmtpSettings;
     
                        if (string.IsNullOrEmpty(propertyValue) && !string.IsNullOrEmpty(smtpSettings.DefaultSenderEmailAddress))
                        {
                            propertyValue = smtpSettings.DefaultSenderEmailAddress;
                        }
                    }
     
                    return propertyValue.Trim();
                }
     
                set { ViewState["FromAddress"] = value; }
            }
     
            /// <summary>
            /// Gets or Sets the address(es) of the CC to which the email will be delivered.
            /// </summary>
            [Category("Email Options")]
            public String CCAddresses
            {
                get
                {
                    var propertyValue = string.Empty;
                    object obj = ViewState["CCAddresses"];
                    if (obj != null)
                        propertyValue = obj.ToString();
     
                    return propertyValue.Trim();
                }
                set
                {
                    ViewState["CCAddresses"] = value;
                }
            }
     
            /// <summary>
            /// Gets or Sets the flag indicating whether error will be logged.
            /// </summary>
            [Category("Additional")]
            public bool EnableLogging
            {
                get
                {
                    var propertyValue = false;
                    object obj = ViewState["EnableLogging"];
                    if (obj != null)
                        propertyValue = (bool)obj;
                    return propertyValue;
                }
                set
                {
                    ViewState["EnableLogging"] = value;
                }
            }
     
            /// <summary>
            /// Gets or Sets the flag indicating whether field names and values are included in the email
            /// </summary>
            [Category("Additional")]
            public bool IncludeFields
            {
                get
                {
                    var propertyValue = true;
                    object obj = ViewState["IncludeFields"];
                    if (obj != null)
                        propertyValue = (bool)obj;
                    return propertyValue;
                }
                set
                {
                    ViewState["IncludeFields"] = value;
                }
            }
     
            /// <summary>
            /// Gets or Sets the flag indicating whether an email will be sent to the client after submission.
            /// </summary>
            [Category("Additional")]
            public bool SendEmailToClient
            {
                get
                {
                    var propertyValue = false;
                    object obj = ViewState["SendEmailToClient"];
                    if (obj != null)
                        propertyValue = (bool)obj;
                    return propertyValue;
                }
                set
                {
                    ViewState["SendEmailToClient"] = value;
                }
            }
     
            /// <summary>
            /// Gets or Sets the message that is included in the body of the email that is sent to the client after submission.
            /// </summary>
            [Category("Email Options")]
            public string ClientMailMessage
            {
                get
                {
                    var propertyValue = string.Empty;
     
                    object obj = ViewState["ClientMailMessage"];
     
                    if (obj != null)
                        propertyValue = obj.ToString();
     
                    return propertyValue;
                }
                set
                {
                    ViewState["ClientMailMessage"] = value;
                }
            }
            #endregion
        }
    }

  4. Jochem Bökkers
    Jochem Bökkers avatar
    787 posts
    Registered:
    13 Aug 2007
    07 Sep 2012
    Link to this post
    @Steve,

    You've certainly earned your nickname today! Thanks for sharing, can't wait to see this in v5.2!

    Jochem
  5. Markus
    Markus avatar
    2763 posts
    Registered:
    25 Nov 2005
    08 Sep 2012
    Link to this post
    How importent CAPTCHAS are show this forum. anotheür 4 pages full of the same spam. I would $be embarresed as Telerik.
    Markus
  6. Bart Welch
    Bart Welch avatar
    64 posts
    Registered:
    10 Jul 2009
    17 May 2013 in reply to michaelroper
    Link to this post
    I just added the RadCaptcha control to the Forms toolbox as well.  How do you force it to require and validate the captcha?  
  7. Mark
    Mark avatar
    147 posts
    Registered:
    01 Jun 2010
    26 Jul 2013
    Link to this post
    It looks like the solution in this thread have been outdated by the new forms subscription model. Does anyone have a workable captcha solution for 6.x? 

    I've asked support and was referred to this thread and this blog post that does not work when javascript has been turned off.
  8. Stefani Tacheva
    Stefani Tacheva avatar
    718 posts
    Registered:
    06 Dec 2016
    31 Jul 2013
    Link to this post
    Hello,

    I would suggest you to check the Akismet(http://akismet.com/) integration sample from the Sitefinity SDK.
    Furthermore you could review this forum post:

    http://www.sitefinity.com/developer-network/forums/developing-with-sitefinity-/how-to-add-captcha-in-custom-sitefinity-form-builder-


    Regards,
    Stefani Tacheva
    Telerik
    Do you want to have your say in the Sitefinity development roadmap? Do you want to know when a feature you requested is added or when a bug fixed? Explore the Telerik Public Issue Tracking system and vote to affect the priority of the items
38 posts, 0 answered
1 2