Exemplo n.º 1
0
        private static bool InitializeBlacklist(IBlackList referrerBlacklist, string path)
        {
            ILoggingDataService loggingService = LoggingDataServiceFactory.GetService(SiteConfig.GetLogPathFromCurrentContext());

            try
            {
                referrerBlacklist.Initialize(path);
                BlacklistUpdateState updateState = referrerBlacklist.UpdateBlacklist();

                if (updateState == BlacklistUpdateState.Failed)
                {
                    loggingService.AddEvent(
                        new EventDataItem(EventCodes.Error, referrerBlacklist.ToString() + " could not be updated: ", "InitializeBlacklist"));
                }
                else if (updateState == BlacklistUpdateState.Updated)
                {
                    loggingService.AddEvent(
                        new EventDataItem(EventCodes.ApplicationStartup, referrerBlacklist.ToString() + " updated: ", "InitializeBlacklist"));
                }

                return(true);
            }
            catch (Exception ex)
            {
                loggingService.AddEvent(new EventDataItem(EventCodes.Error, referrerBlacklist.ToString() + " could not be initialized: " + ex.ToString(), "InitializeBlacklist"));
            }

            return(false);
        }
Exemplo n.º 2
0
        /// <summary>
        /// Report-Mailer runs in background thread and this is the thread function.
        /// </summary>
        public void Run()
        {
            IBlogDataService    dataService       = null;
            ILoggingDataService loggingService    = null;
            DateTime            lastReportDateUTC = DateTime.Now.ToUniversalTime();


            SiteConfig siteConfig = SiteConfig.GetSiteConfig(configPath);

            loggingService = LoggingDataServiceFactory.GetService(logPath);
            dataService    = BlogDataServiceFactory.GetService(contentPath, loggingService);

            ErrorTrace.Trace(System.Diagnostics.TraceLevel.Info, "ReportMailer thread spinning up");
            loggingService.AddEvent(new EventDataItem(EventCodes.ReportMailerServiceStart, "", ""));

            do
            {
                try
                {
                    // reload on every cycle to get the current settings
                    siteConfig     = SiteConfig.GetSiteConfig(configPath);
                    loggingService = LoggingDataServiceFactory.GetService(logPath);
                    dataService    = BlogDataServiceFactory.GetService(contentPath, loggingService);

                    if (siteConfig.EnableDailyReportEmail)
                    {
                        if (siteConfig.SmtpServer != null && siteConfig.SmtpServer.Length > 0 &&
                            lastReportDateUTC.Day != DateTime.Now.ToUniversalTime().Day)
                        {
                            // It's a new day so send the report
                            SendEmailReport(lastReportDateUTC, siteConfig, dataService, loggingService);
                            // and update the cached date to today
                            lastReportDateUTC = DateTime.Now.ToUniversalTime();
                        }
                    }

                    // tick again in an hour
                    Thread.Sleep(TimeSpan.FromSeconds(3600));
                }

                catch (ThreadAbortException abortException)
                {
                    ErrorTrace.Trace(System.Diagnostics.TraceLevel.Info, abortException);
                    loggingService.AddEvent(new EventDataItem(EventCodes.ReportMailerServiceShutdown, "", ""));
                    break;
                }
                catch (Exception e)
                {
                    // if the siteConfig can't be read, stay running regardless
                    // default wait time is 60 minutes in that case
                    ErrorTrace.Trace(System.Diagnostics.TraceLevel.Error, e);
                    loggingService.AddEvent(new EventDataItem(EventCodes.ReportMailerServiceError, e.ToString().Replace("\n", "<br />"), null, null));
                    Thread.Sleep(TimeSpan.FromSeconds(3600));
                }
            }while (true);

            ErrorTrace.Trace(System.Diagnostics.TraceLevel.Info, "ReportMailer thread terminating");
            loggingService.AddEvent(new EventDataItem(EventCodes.ReportMailerServiceShutdown, "", ""));
        }
Exemplo n.º 3
0
        private static void LogSuccess(string userName)
        {
            ILoggingDataService loggingService = LoggingDataServiceFactory.GetService(SiteConfig.GetLogPathFromCurrentContext());

            if (HttpContext.Current == null)
            {
                loggingService.AddEvent(new EventDataItem(EventCodes.SecuritySuccess, userName, "non-web"));
            }
            else
            {
                loggingService.AddEvent(new EventDataItem(EventCodes.SecuritySuccess, userName, HttpContext.Current.Request.UserHostAddress));
            }
        }
Exemplo n.º 4
0
        public void SendEmailReport(DateTime reportDate, SiteConfig siteConfig, IBlogDataService dataService, ILoggingDataService loggingService)
        {
            MailMessage emailMessage = new MailMessage();

            if (siteConfig.NotificationEMailAddress != null && siteConfig.NotificationEMailAddress.Length > 0)
            {
                emailMessage.To.Add(siteConfig.NotificationEMailAddress);
            }
            else
            {
                emailMessage.To.Add(siteConfig.Contact);
            }

            emailMessage.Subject      = String.Format("Weblog Daily Activity Report for '{0}'", reportDate.ToLongDateString());
            emailMessage.Body         = GenerateReportEmailBody(reportDate);
            emailMessage.IsBodyHtml   = true;
            emailMessage.BodyEncoding = System.Text.Encoding.UTF8;
            emailMessage.From         = new MailAddress(siteConfig.Contact);

            SendMailInfo sendMailInfo = new SendMailInfo(emailMessage, siteConfig.SmtpServer,
                                                         siteConfig.EnableSmtpAuthentication, siteConfig.UseSSLForSMTP, siteConfig.SmtpUserName, siteConfig.SmtpPassword, siteConfig.SmtpPort);

            dataService.AddTracking(null, sendMailInfo); // use this with null tracking object, just to get the email sent
            loggingService.AddEvent(new EventDataItem(EventCodes.ReportMailerReportSent, "", ""));
        }
Exemplo n.º 5
0
        public void SetUpForTests()
        {
            // This method will be run each and every time a test method is run.
            // Place common initialization steps here that should be run before
            // every test.

            DirectoryInfo root = new DirectoryInfo(ReflectionHelper.CodeBase());

            testContent = new DirectoryInfo(Path.Combine(root.Parent.FullName, "TestContent"));
            Assert.IsTrue(testContent.Exists);

            testLogs = new DirectoryInfo(Path.Combine(root.Parent.FullName, "TestLogs"));
            Assert.IsTrue(testLogs.Exists);

            loggingService = LoggingDataServiceFactory.GetService(
                testLogs.FullName);
            Assert.IsNotNull(loggingService);

            blogService = BlogDataServiceFactory.GetService(
                testContent.FullName,
                loggingService);
            Assert.IsNotNull(blogService);

            loggingService.AddEvent(new EventDataItem(EventCodes.ApplicationStartup, "", ""));
        }
Exemplo n.º 6
0
        public void SetUpForTests()
        {
            // This method will be run each and every time a test method is run.
            // Place common initialization steps here that should be run before
            // every test.

            DirectoryInfo root = new DirectoryInfo(ReflectionHelper.CodeBase());

            testContent = new DirectoryInfo(Path.Combine(root.Parent.FullName, "TestContent"));
            Assert.IsTrue(testContent.Exists);

            testLogs = new DirectoryInfo(Path.Combine(root.Parent.FullName, "TestLogs"));
            Assert.IsTrue(testLogs.Exists);

            loggingService = LoggingDataServiceFactory.GetService(
                testLogs.FullName);
            Assert.IsNotNull(loggingService);

            blogService = BlogDataServiceFactory.GetService(
                testContent.FullName,
                loggingService);
            Assert.IsNotNull(blogService);

            loggingService.AddEvent(new EventDataItem(EventCodes.ApplicationStartup, "", ""));
        }
Exemplo n.º 7
0
        public void ProcessRequest(HttpContext context)
        {
            ILoggingDataService logService = LoggingDataServiceFactory.GetService(SiteConfig.GetLogPathFromCurrentContext());

            try
            {
                IBlogDataService dataService = BlogDataServiceFactory.GetService(SiteConfig.GetContentPathFromCurrentContext(), logService);
                SiteConfig       siteConfig  = SiteConfig.GetSiteConfig();

                string languageFilter = context.Request.Headers["Accept-Language"];
                if (SiteSecurity.IsInRole("admin"))
                {
                    languageFilter = "";
                }

                EntryCollection entries = dataService.GetEntriesForDay(DateTime.UtcNow, siteConfig.GetConfiguredTimeZone(), languageFilter, 1, 1, String.Empty);

                if (entries != null && entries.Count > 0)
                {
                    Entry e = entries[0];
                    context.Response.Write(e.Title);
                }
            }
            catch (Exception ex)
            {
                logService.AddEvent(new EventDataItem(EventCodes.Error, "Error generating Microsummary: " + ex.ToString(), String.Empty));
            }
        }
        public void ProcessRequest(HttpContext context)
        {
            SiteConfig siteConfig = SiteConfig.GetSiteConfig();

            string sourceId;
            string referrerUrl;

            /*
             * This service is a bit diffent from the other handlers, because
             * the "bugs" are out in the wild regardless of whether the service is
             * enabled. So the service must yield a valid result, regardless of
             * whetr
             */
            if (siteConfig.EnableCrossposts)
            {
                sourceId    = context.Request.QueryString["id"];
                referrerUrl = context.Request.UrlReferrer != null?context.Request.UrlReferrer.ToString() : "";

                try
                {
                    ILoggingDataService logService  = LoggingDataServiceFactory.GetService(SiteConfig.GetLogPathFromCurrentContext());
                    IBlogDataService    dataService = BlogDataServiceFactory.GetService(SiteConfig.GetContentPathFromCurrentContext(), logService);

                    Entry entry = dataService.GetEntry(sourceId);
                    if (entry != null)
                    {
                        // we'll check whether the entry exists just to avoid trash in the DB
                        logService.AddCrosspostReferrer(
                            new LogDataItem(
                                SiteUtilities.GetPermaLinkUrl(siteConfig, sourceId), referrerUrl, context.Request.UserAgent, context.Request.UserHostName));
                    }
                    else
                    {
                        StackTrace st = new StackTrace();
                        logService.AddEvent(new EventDataItem(EventCodes.Error, "Entry was not found: " + sourceId + " " + st.ToString(), ""));
                    }
                }
                catch (Exception exc)
                {
                    // absorb
                    ErrorTrace.Trace(System.Diagnostics.TraceLevel.Error, exc);
                }
            }

            context.Response.OutputStream.Write(aggBugBitmap, 0, aggBugBitmap.Length);
            context.Response.ContentType = "image/gif";
            context.Response.StatusCode  = 200;
            context.Response.End();
        }
Exemplo n.º 9
0
        protected void buttonTestSMTP_Click(object sender, EventArgs e)
        {
            SharedBasePage requestPage = Page as SharedBasePage;
            SiteConfig     siteConfig  = requestPage.SiteConfig;

            if (textSmtpServer.Text != "" & textNotificationEmailAddress.Text != "")
            {
                MailMessage emailMessage = new MailMessage();

                emailMessage.To.Add(textNotificationEmailAddress.Text);
                emailMessage.Subject = String.Format("dasBlog test message");
                emailMessage.Body    =
                    String.Format("This is a test message from dasBlog. If you are reading this then everything is working properly.");
                emailMessage.IsBodyHtml   = false;
                emailMessage.BodyEncoding = Encoding.UTF8;
                emailMessage.From         = new MailAddress(siteConfig.Contact);
                SendMailInfo sendMailInfo = new SendMailInfo(emailMessage, textSmtpServer.Text,
                                                             checkEnableSmtpAuthentication.Checked, checkUseSSLForSMTP.Checked,
                                                             textSmtpUsername.Text, textSmtpPassword.Text,
                                                             int.Parse(textSmtpPort.Text));

                try
                {
                    sendMailInfo.SendMyMessage();
                }
                catch (Exception ex)
                {
                    //RyanG: Decode the real reason the error occured by looking at the inner exceptions
                    StringBuilder exceptionMessage = new StringBuilder();
                    Exception     lastException    = ex;
                    while (lastException != null)
                    {
                        if (exceptionMessage.Length > 0)
                        {
                            exceptionMessage.Append("; ");
                        }
                        exceptionMessage.Append(lastException.Message);
                        lastException = lastException.InnerException;
                    }

                    ILoggingDataService logService = requestPage.LoggingService;
                    logService.AddEvent(
                        new EventDataItem(EventCodes.SmtpError, "", exceptionMessage.ToString()));

                    Response.Redirect("FormatPage.aspx?path=SiteConfig/pageerror.format.html", true);
                }
            }
        }
Exemplo n.º 10
0
        public static void RemoveBlacklist(Type type)
        {
            ILoggingDataService loggingService = LoggingDataServiceFactory.GetService(SiteConfig.GetLogPathFromCurrentContext());

            if (blacklists.ContainsKey(type.Name) == true)
            {
                try
                {
                    blacklists.Remove(type.Name);
                }
                catch (Exception ex)
                {
                    loggingService.AddEvent(new EventDataItem(EventCodes.Error, type.Name.ToString() + " could not be removed: " + ex.ToString(), ""));
                }
            }
        }
Exemplo n.º 11
0
        private static bool TryCreateControl(Type editControlType, out EditControlAdapter editControl)
        {
            editControl = null;

            try
            {
                editControl = (EditControlAdapter)Activator.CreateInstance(editControlType);
                return(true);
            }
            catch (Exception exc)
            {
                // prevents the editentry page from failing when the configured editor is not (or no longer) supported
                ILoggingDataService loggingService = LoggingDataServiceFactory.GetService(SiteConfig.GetLogPathFromCurrentContext());
                string message = String.Format("Failed to load configured editor type. \"{0}\" Exception: \"{1}\"", editControlType, exc);
                loggingService.AddEvent(new EventDataItem(EventCodes.Error, message, HttpContext.Current.Request.Url.ToString()));
            }

            return(false);
        }
Exemplo n.º 12
0
        public string Invoke(Stream requestStream)
        {
            try
            {
                var xmlRpcSerializer = new XmlRpcSerializer();

                var xmlRpcServiceAttribute = (XmlRpcServiceAttribute)Attribute.GetCustomAttribute(this.GetType(), typeof(XmlRpcServiceAttribute));
                if (xmlRpcServiceAttribute != null)
                {
                    if (xmlRpcServiceAttribute.XmlEncoding != null)
                    {
                        xmlRpcSerializer.XmlEncoding = Encoding.GetEncoding(xmlRpcServiceAttribute.XmlEncoding);
                    }
                    xmlRpcSerializer.UseIntTag      = xmlRpcServiceAttribute.UseIntTag;
                    xmlRpcSerializer.UseStringTag   = xmlRpcServiceAttribute.UseStringTag;
                    xmlRpcSerializer.UseIndentation = xmlRpcServiceAttribute.UseIndentation;
                    xmlRpcSerializer.Indentation    = xmlRpcServiceAttribute.Indentation;
                }

                var bodyStream = new StreamReader(requestStream);
                bodyStream.BaseStream.Seek(0, SeekOrigin.Begin);

                var    request  = xmlRpcSerializer.DeserializeRequest(bodyStream, this.GetType());
                var    response = Invoke(request);
                Stream stream   = new MemoryStream();
                xmlRpcSerializer.SerializeResponse(stream, response);
                stream.Seek(0L, SeekOrigin.Begin);

                var reader = new StreamReader(stream);
                return(reader.ReadToEnd());
            }
            catch (Exception ex)
            {
                loggingDataService.AddEvent(new EventDataItem(EventCodes.Error, ex.Message, "XmlRpcManager.Invoke"));

                var    faultEx           = (!(ex is XmlRpcException)) ? ((!(ex is XmlRpcFaultException)) ? new XmlRpcFaultException(0, ex.Message) : ((XmlRpcFaultException)ex)) : new XmlRpcFaultException(0, ((XmlRpcException)ex).Message);
                var    xmlRpcSerializer2 = new XmlRpcSerializer();
                Stream stream2           = new MemoryStream();
                xmlRpcSerializer2.SerializeFaultResponse(stream2, faultEx);
                stream2.Seek(0L, SeekOrigin.Begin);

                var reader2 = new StreamReader(stream2);
                return(reader2.ReadToEnd());
            }
        }
Exemplo n.º 13
0
        public IActionResult BloggerPost()
        {
            var blogger = string.Empty;

            try
            {
                using (var mem = new MemoryStream())
                {
                    Request.Body.CopyTo(mem);
                    blogger = xmlRpcManager.Invoke(mem);
                }
            }
            catch (Exception ex)
            {
                loggingDataService.AddEvent(new EventDataItem(EventCodes.Error, ex.Message, "FeedController.BloggerPost"));
            }

            BreakSiteCache();

            return(Content(blogger));
        }
Exemplo n.º 14
0
        private static bool TryGetType(string typeName, out Type type)
        {
            type = null;

            if (string.IsNullOrEmpty(typeName))
            {
                return(false);
            }

            try
            {
                type = Type.GetType(typeName, /* throw on error */ true, /* ignore case */ true);
                return(true);
            }
            catch (Exception exc)
            {
                // prevents the editentry page from failing when the configured editor is not (or no longer) supported
                ILoggingDataService loggingService = LoggingDataServiceFactory.GetService(SiteConfig.GetLogPathFromCurrentContext());
                string message = String.Format("Failed to load configured editor type. \"{0}\" Exception: \"{1}\"", typeName, exc);
                loggingService.AddEvent(new EventDataItem(EventCodes.Error, message, HttpContext.Current.Request.Url.ToString()));
            }

            return(false);
        }
Exemplo n.º 15
0
        /// <summary>
        /// Deletes an entry, including comments enclosures etc.
        /// </summary>
        /// <remarks>Admins can delete all, contributors only their own.</remarks>
        /// <param name="entryId">The entry to delete.</param>
        /// <param name="siteConfig"></param>
        /// <param name="logService"></param>
        /// <param name="dataService"></param>
        public static void DeleteEntry(string entryId, SiteConfig siteConfig, ILoggingDataService logService, IBlogDataService dataService)
        {
            try
            {
                IPrincipal user = HttpContext.Current.User;
                Entry entry = dataService.GetEntry(entryId);
                //fix: admins can delete all, contributors only their own
                if (!CanEdit(user, entry))
                {
                    throw new SecurityException("Current user is not allowed to delete this entry!");
                }

                string permalink = SiteUtilities.GetPermaLinkUrl(entry.EntryId);
                //string[] categories = entry.GetSplitCategories();

                dataService.DeleteEntry(entryId, siteConfig.CrosspostSites);

                BreakCache(siteConfig, entry.GetSplitCategories());

                // give the XSS upstreamer a hint that things have changed
                //FIX:    XSSUpstreamer.TriggerUpstreaming();

                // TODO: when we add support for more than just enclosures, we can't delete the entire folder
                DirectoryInfo enclosuresPath = new DirectoryInfo((Path.Combine(SiteConfig.GetBinariesPathFromCurrentContext(), entryId)));
                if (enclosuresPath.Exists) enclosuresPath.Delete(true);

                logService.AddEvent(
                    new EventDataItem(
                    EventCodes.EntryDeleted, entry.Title,
                    permalink));
            }
            catch (SecurityException)
            {
                throw;
            }
            catch (Exception ex)
            {
                StackTrace st = new StackTrace();
                logService.AddEvent(
                    new EventDataItem(EventCodes.Error, ex.ToString() + Environment.NewLine + st.ToString(), HttpContext.Current.Request.RawUrl));

                // DESIGN: We should rethrow the exception for the calling class, but this break too much for this point release.
            }
        }
Exemplo n.º 16
0
        public static bool IsBlockedReferrer(string referrer, string entryTitle)
        {
            HttpContext context = HttpContext.Current;

            if (referrer == null || referrer.Length == 0 || context == null)
            {
                return(false);
            }

            SiteConfig siteConfig = SiteConfig.GetSiteConfig();

            // return if this is a local page
            // bail if we are getting a local referral from our website
            if (context.Request.UrlReferrer != null &&
                SiteUtilities.ReferralFromSelf(siteConfig, context.Request.UrlReferrer.ToString()) == true)
            {
                return(false);
            }

            ILoggingDataService loggingService = LoggingDataServiceFactory.GetService(SiteConfig.GetLogPathFromCurrentContext());
            bool  retVal = false;
            Match match  = null;

            foreach (IBlackList referralBlacklist in ReferralBlackListFactory.Lists)
            {
                try
                {
                    match = referralBlacklist.IsBlacklisted(referrer);
                    if (match != null)
                    {
                        retVal = match.Success;
                        if (retVal)
                        {
                            break;
                        }
                    }
                }
                catch (Exception ex)
                {
                    loggingService.AddEvent(new EventDataItem(EventCodes.Error, ex.ToString(), referralBlacklist.ToString() + " Regular Expression"));
                    return(false);
                }
            }

            // if either Blacklist has a return value of true, we block the referral and log the event
            if (context != null && retVal == true)
            {
                if (siteConfig.LogBlockedReferrals)
                {
                    if (entryTitle != null && entryTitle != "")
                    {
                        loggingService.AddEvent(new EventDataItem(EventCodes.ItemReferralBlocked, context.Request.UserHostAddress + " because of \"" + match.Value + "\"", context.Request.RawUrl, referrer, entryTitle));
                    }
                    else
                    {
                        loggingService.AddEvent(new EventDataItem(EventCodes.ReferralBlocked, context.Request.UserHostAddress + " because of \"" + match.Value + "\"", context.Request.RawUrl, referrer));
                    }
                }

                if (siteConfig.EnableReferralUrlBlackList404s == true)
                {
                    context.Response.StatusCode      = 404;
                    context.Response.SuppressContent = true;
                    context.Response.End();
                }
            }

            return(retVal);
        }
Exemplo n.º 17
0
        public void Run()
        {
            SiteConfig          siteConfig     = SiteConfig.GetSiteConfig(configPath);
            ILoggingDataService loggingService = LoggingDataServiceFactory.GetService(logPath);
            IBlogDataService    dataService    = BlogDataServiceFactory.GetService(contentPath, loggingService);


            loggingService.AddEvent(new EventDataItem(EventCodes.XSSServiceStart, "", ""));

            do
            {
                try
                {
                    // reload on every cycle to get the current settings
                    siteConfig     = SiteConfig.GetSiteConfig(configPath);
                    loggingService = LoggingDataServiceFactory.GetService(logPath);
                    dataService    = BlogDataServiceFactory.GetService(contentPath, loggingService);

                    SyndicationServiceImplementation syndicator = new SyndicationServiceImplementation(siteConfig, dataService, loggingService);

                    if (siteConfig.EnableXSSUpstream &&
                        siteConfig.XSSUpstreamPassword != null &&
                        siteConfig.XSSUpstreamUsername != null)
                    {
                        try
                        {
                            MemoryStream  memoryStream = new MemoryStream();
                            StreamWriter  streamWriter = new StreamWriter(memoryStream, System.Text.Encoding.UTF8);
                            XmlSerializer ser          = new XmlSerializer(typeof(RssRoot));
                            RssRoot       root         = syndicator.GetRss();
                            ser.Serialize(streamWriter, root);



                            XmlStorageSystemClientProxy xssProxy = new XmlStorageSystemClientProxy();
                            if (siteConfig.XSSUpstreamEndpoint != null && siteConfig.XSSUpstreamEndpoint.Length > 0)
                            {
                                xssProxy.Url = siteConfig.XSSUpstreamEndpoint;
                            }

                            string rssFileName = "rss-dasblog.xml";
                            if (siteConfig.XSSRSSFilename != null && siteConfig.XSSRSSFilename.Length > 0)
                            {
                                rssFileName = siteConfig.XSSRSSFilename;
                            }

                            // the buffer is longer than the output and must be shortened
                            // by copying into a new buffer
                            byte[] rssBuffer          = new byte[memoryStream.Position];
                            byte[] memoryStreamBuffer = memoryStream.GetBuffer();
                            for (int l = 0; l < rssBuffer.Length; l++)
                            {
                                rssBuffer[l] = memoryStreamBuffer[l];
                            }


                            XSSSaveMultipleFilesReply reply =
                                xssProxy.SaveMultipleFiles(
                                    siteConfig.XSSUpstreamUsername,
                                    XmlStorageSystemClientProxy.EncodePassword(siteConfig.XSSUpstreamPassword),
                                    new string[] { rssFileName },
                                    new byte[][] { rssBuffer });

                            if (reply.flError)
                            {
                                loggingService.AddEvent(
                                    new EventDataItem(
                                        EventCodes.XSSUpstreamError, reply.message, null, null));
                            }
                            else
                            {
                                loggingService.AddEvent(
                                    new EventDataItem(
                                        EventCodes.XSSUpstreamSuccess, reply.message, rssFileName, xssProxy.Url));
                            }
                        }
                        catch (Exception e)
                        {
                            loggingService.AddEvent(
                                new EventDataItem(
                                    EventCodes.XSSUpstreamError, e.Message, e.StackTrace, null));
                        }
                    }

                    upstreamTrigger.WaitOne(TimeSpan.FromSeconds(siteConfig.XSSUpstreamInterval), false);

                    // introduce a little time offset to limit competition for the files.
                    Thread.Sleep(500);
                }
                catch (ThreadAbortException abortException)
                {
                    ErrorTrace.Trace(System.Diagnostics.TraceLevel.Info, abortException);
                    loggingService.AddEvent(new EventDataItem(EventCodes.XSSServiceShutdown, "", ""));
                    break;
                }
                catch (Exception e)
                {
                    // if the siteConfig can't be read, stay running regardless
                    // default wait time is 4 minutes in that case
                    Thread.Sleep(TimeSpan.FromSeconds(240));
                    ErrorTrace.Trace(System.Diagnostics.TraceLevel.Error, e);
                }
            }while (true);
            loggingService.AddEvent(new EventDataItem(EventCodes.XSSServiceShutdown, "", ""));
        }
Exemplo n.º 18
0
        protected void Application_Start(Object sender, EventArgs e)
        {
            //We clear out the Cache on App Restart...
            CacheFactory.GetCache().Clear();

            ILoggingDataService loggingService = null;

            loggingService = LoggingDataServiceFactory.GetService(SiteConfig.GetLogPathFromCurrentContext());
            loggingService.AddEvent(new EventDataItem(EventCodes.ApplicationStartup, "", ""));

            SiteConfig siteConfig = SiteConfig.GetSiteConfig(SiteConfig.GetConfigFilePathFromCurrentContext());

            //if (siteConfig.EnableReportMailer)
            {
                reportMailer = new ReportMailer(
                    SiteConfig.GetConfigFilePathFromCurrentContext(),
                    SiteConfig.GetContentPathFromCurrentContext(),
                    SiteConfig.GetLogPathFromCurrentContext()
                    );

                reportMailerThread              = new Thread(new ThreadStart(reportMailer.Run));
                reportMailerThread.Name         = "ReportMailer";
                reportMailerThread.IsBackground = true;
                reportMailerThread.Start();
            }

            if (siteConfig.EnablePop3)
            {
                mailToWeblog = new MailToWeblog(
                    SiteConfig.GetConfigFilePathFromCurrentContext(),
                    SiteConfig.GetContentPathFromCurrentContext(),
                    SiteConfig.GetBinariesPathFromCurrentContext(),
                    SiteConfig.GetLogPathFromCurrentContext(),
                    new Uri(new Uri(SiteConfig.GetSiteConfig().Root), SiteConfig.GetSiteConfig().BinariesDirRelative)
                    );

                mailToWeblogThread              = new Thread(new ThreadStart(mailToWeblog.Run));
                mailToWeblogThread.Name         = "MailToWeblog";
                mailToWeblogThread.IsBackground = true;
                mailToWeblogThread.Start();
            }

            if (siteConfig.EnableXSSUpstream)
            {
                xssUpstreamer = new XSSUpstreamer(
                    SiteConfig.GetConfigFilePathFromCurrentContext(),
                    SiteConfig.GetContentPathFromCurrentContext(),
                    SiteConfig.GetLogPathFromCurrentContext()
                    );

                xssUpstreamerThread              = new Thread(new ThreadStart(xssUpstreamer.Run));
                xssUpstreamerThread.Name         = "XSSUpstreamer";
                xssUpstreamerThread.IsBackground = true;
                xssUpstreamerThread.Start();
            }

            /*
             * if (siteConfig.EnableMovableTypeBlackList)
             * {
             *      ReferralBlackListFactory.AddBlacklist(new MovableTypeBlacklist(), Path.Combine(SiteConfig.GetConfigPathFromCurrentContext(), "blacklist.txt"));
             * }
             */

            if (siteConfig.EnableReferralUrlBlackList && siteConfig.ReferralUrlBlackList.Length != 0)
            {
                ReferralBlackListFactory.AddBlacklist(new ReferralUrlBlacklist(), siteConfig.ReferralUrlBlackList);
            }
        }
Exemplo n.º 19
0
        public void ProcessRequest(HttpContext context)
        {
            if (!SiteSecurity.IsValidContributor())
            {
                context.Response.Redirect("~/FormatPage.aspx?path=SiteConfig/accessdenied.format.html");
            }

            SiteConfig siteConfig = SiteConfig.GetSiteConfig();

            string entryId;
            string commentId;
            string referralPermalink;
            string type;
            string redirectUrl = SiteUtilities.GetStartPageUrl();
            bool   reportAsSpam;

            entryId           = context.Request.QueryString["entryId"];
            commentId         = context.Request.QueryString["commentId"];
            referralPermalink = context.Request.QueryString["referralPermalink"];
            type         = context.Request.QueryString["type"];
            reportAsSpam = context.Request.QueryString["report"] != null;

            // make sure the entry param is there
            if (entryId == null || entryId.Length == 0)
            {
                context.Response.Redirect(SiteUtilities.GetStartPageUrl(siteConfig));
                return;
            }
            else
            {
                try
                {
                    ILoggingDataService logService  = LoggingDataServiceFactory.GetService(SiteConfig.GetLogPathFromCurrentContext());
                    IBlogDataService    dataService = BlogDataServiceFactory.GetService(SiteConfig.GetContentPathFromCurrentContext(), logService);

                    Entry entry = dataService.GetEntry(entryId);
                    if (entry != null)
                    {
                        if (commentId != null && commentId.Length > 0)
                        {
                            if (reportAsSpam)
                            {
                                ISpamBlockingService spamBlockingService = siteConfig.SpamBlockingService;
                                if (spamBlockingService != null)
                                {
                                    Comment comment = dataService.GetCommentById(entryId, commentId);
                                    if ((comment != null) && (comment.SpamState != SpamState.Spam))
                                    {
                                        try
                                        {
                                            spamBlockingService.ReportSpam(comment);
                                        }
                                        catch (Exception ex)
                                        {
                                            logService.AddEvent(new EventDataItem(EventCodes.Error, String.Format("Unable to report comment {0} as spam. Original exception: {1}", comment.EntryId, ex), SiteUtilities.GetPermaLinkUrl(entryId)));
                                        }
                                    }
                                }
                            }
                            dataService.DeleteComment(entryId, commentId);

                            logService.AddEvent(
                                new EventDataItem(
                                    EventCodes.CommentDeleted, commentId,
                                    SiteUtilities.GetPermaLinkUrl(entryId)));

                            redirectUrl = SiteUtilities.GetCommentViewUrl(entryId);
                        }
                        else if (referralPermalink != null && referralPermalink.Length > 0)
                        {
                            TrackingType trackingType = TrackingType.Referral;

                            if (type != null && type.Length != 0)
                            {
                                trackingType = (TrackingType)Enum.Parse(typeof(TrackingType), type);
                            }

                            dataService.DeleteTracking(entryId, referralPermalink, trackingType);

                            logService.AddEvent(
                                new EventDataItem(
                                    EventCodes.ItemReferralDeleted, referralPermalink,
                                    SiteUtilities.GetPermaLinkUrl(entryId)));

                            redirectUrl = SiteUtilities.GetPermaLinkUrl(entryId);
                        }
                        else                         // it must be an entry we are deleting
                        {
                            SiteUtilities.DeleteEntry(entryId, siteConfig, logService, dataService);
                            redirectUrl = SiteUtilities.GetStartPageUrl();
                        }
                    }
                }
                catch (Exception exc)
                {
                    // absorb
                    ErrorTrace.Trace(System.Diagnostics.TraceLevel.Error, exc);
                }
            }

            context.Response.Redirect(redirectUrl);
        }
Exemplo n.º 20
0
        public string ping(
            string sourceUri,
            string targetUri)
        {
            if (!siteConfig.EnablePingbackService)
            {
                throw new ServiceDisabledException();
            }

            string returnValue = "0";


            if (ReferralBlackList.IsBlockedReferrer(sourceUri))
            {
                if (siteConfig.EnableReferralUrlBlackList404s)
                {
                    this.Context.Response.StatusCode = 404;
                    this.Context.Response.End();
                    throw new XmlRpcFaultException(404, "not found");
                }
            }


            try
            {
                string entryId = null;

                // OmarS: need to rewrite the URL so w can find the entryId
                Uri    uriTargetUri = new Uri(SiteUtilities.MapUrl(targetUri));
                string query        = uriTargetUri.Query;
                if (query.Length > 0 && query[0] == '?')
                {
                    query = query.Substring(1);
                }
                else
                {
                    return(returnValue);
                }

                string[] queryItems = query.Split('&');
                if (queryItems == null)
                {
                    return(returnValue);
                }

                foreach (string queryItem in queryItems)
                {
                    string[] keyvalue = queryItem.Split('=');
                    if (keyvalue.Length == 2)
                    {
                        string key    = keyvalue[0];
                        string @value = keyvalue[1];

                        if (key == "guid")
                        {
                            entryId = @value;
                            break;
                        }
                    }
                }

                if (entryId != null)
                {
                    Entry entry = dataService.GetEntry(entryId);
                    if (entry != null)
                    {
                        Tracking t = new Tracking();
                        t.PermaLink = sourceUri;
                        t.Referer   = this.Context.Request.UrlReferrer != null?this.Context.Request.UrlReferrer.ToString() : String.Empty;

                        t.RefererBlogName  = sourceUri;
                        t.RefererExcerpt   = String.Empty;
                        t.RefererTitle     = sourceUri;
                        t.TargetEntryId    = entryId;
                        t.TargetTitle      = entry.Title;
                        t.TrackingType     = TrackingType.Pingback;
                        t.RefererIPAddress = this.Context.Request.UserHostAddress;

                        ISpamBlockingService spamBlockingService = siteConfig.SpamBlockingService;
                        if (spamBlockingService != null)
                        {
                            bool isSpam = false;
                            try
                            {
                                isSpam = spamBlockingService.IsSpam(t);
                            }
                            catch (Exception ex)
                            {
                                logDataService.AddEvent(new EventDataItem(EventCodes.Error, String.Format("The external spam blocking service failed for pingback from {0}. Original exception: {1}", sourceUri, ex), targetUri));
                            }
                            if (isSpam)
                            {
                                //TODO: May provide moderation in the future. For now we just ignore the pingback
                                logDataService.AddEvent(new EventDataItem(
                                                            EventCodes.PingbackBlocked,
                                                            "Pingback blocked from " + sourceUri + " because it was considered spam by the external blocking service.",
                                                            targetUri, sourceUri));
                                System.Web.HttpContext.Current.Response.StatusCode = 404;
                                System.Web.HttpContext.Current.Response.End();
                                throw new XmlRpcFaultException(404, "not found");
                            }
                        }

                        if (siteConfig.SendPingbacksByEmail &&
                            siteConfig.SmtpServer != null && siteConfig.SmtpServer.Length > 0)
                        {
                            MailMessage emailMessage = new MailMessage();
                            if (siteConfig.NotificationEMailAddress != null &&
                                siteConfig.NotificationEMailAddress.Length > 0)
                            {
                                emailMessage.To.Add(siteConfig.NotificationEMailAddress);
                            }
                            else
                            {
                                emailMessage.To.Add(siteConfig.Contact);
                            }
                            emailMessage.Subject = String.Format("Weblog pingback by '{0}' on '{1}'", sourceUri, t.TargetTitle);
                            emailMessage.Body    = String.Format("You were pinged back by\n{0}\r\non your weblog entry '{1}'\n({2}\r\n\r\nDelete Trackback: {3})",
                                                                 sourceUri,
                                                                 t.TargetTitle,
                                                                 SiteUtilities.GetPermaLinkUrl(entry),
                                                                 SiteUtilities.GetTrackbackDeleteUrl(entryId, t.PermaLink, t.TrackingType));

                            emailMessage.IsBodyHtml   = false;
                            emailMessage.BodyEncoding = System.Text.Encoding.UTF8;
                            emailMessage.From         = new MailAddress(siteConfig.Contact);
                            SendMailInfo sendMailInfo = new SendMailInfo(emailMessage, siteConfig.SmtpServer,
                                                                         siteConfig.EnableSmtpAuthentication, siteConfig.UseSSLForSMTP, siteConfig.SmtpUserName, siteConfig.SmtpPassword, siteConfig.SmtpPort);
                            dataService.AddTracking(t, sendMailInfo);
                        }
                        else
                        {
                            dataService.AddTracking(t);
                        }

                        logDataService.AddEvent(
                            new EventDataItem(EventCodes.PingbackReceived, entry.Title, targetUri, sourceUri));
                        returnValue = sourceUri;
                    }
                }
            }
            catch (Exception e)
            {
                ErrorTrace.Trace(System.Diagnostics.TraceLevel.Error, e);
                return("0");
            }
            return(returnValue);
        }
Exemplo n.º 21
0
        public static void SaveEntry(Entry entry, string trackbackUrl, CrosspostInfoCollection crosspostList, SiteConfig siteConfig, ILoggingDataService logService, IBlogDataService dataService)
        {
            TrackbackInfoCollection trackbackList = null;
            if (trackbackUrl != null && trackbackUrl.Length > 0)
            {
                trackbackList = new TrackbackInfoCollection();
                trackbackList.Add(new TrackbackInfo(
                    trackbackUrl,
                    SiteUtilities.GetPermaLinkUrl(siteConfig, entry),
                    entry.Title,
                    entry.Description,
                    siteConfig.Title));
            }
            InternalSaveEntry(entry, trackbackList, crosspostList, siteConfig, logService, dataService);

            logService.AddEvent(
                new EventDataItem(
                EventCodes.EntryAdded, entry.Title,
                SiteUtilities.GetPermaLinkUrl(siteConfig, entry.EntryId)));
        }
Exemplo n.º 22
0
        public static void SaveEntry(Entry entry, TrackbackInfoCollection trackbackList, CrosspostInfoCollection crosspostList, SiteConfig siteConfig, ILoggingDataService logService, IBlogDataService dataService)
        {
            InternalSaveEntry(entry, trackbackList, crosspostList, siteConfig, logService, dataService);

            logService.AddEvent(
                new EventDataItem(
                    EventCodes.EntryAdded, entry.Title,
                    SiteUtilities.GetPermaLinkUrl(siteConfig, entry.EntryId)));
        }
Exemplo n.º 23
0
        /// <summary>
        /// Mail-To-Weblog runs in background thread and this is the thread function.
        /// </summary>
        public void Run()
        {
            IBlogDataService    dataService    = null;
            ILoggingDataService loggingService = null;

            SiteConfig siteConfig = SiteConfig.GetSiteConfig(configPath);

            loggingService = LoggingDataServiceFactory.GetService(logPath);
            dataService    = BlogDataServiceFactory.GetService(contentPath, loggingService);


            ErrorTrace.Trace(System.Diagnostics.TraceLevel.Info, "MailToWeblog thread spinning up");

            loggingService.AddEvent(new EventDataItem(EventCodes.Pop3ServiceStart, "", ""));

            do
            {
                try
                {
                    // reload on every cycle to get the current settings
                    siteConfig     = SiteConfig.GetSiteConfig(configPath);
                    loggingService = LoggingDataServiceFactory.GetService(logPath);
                    dataService    = BlogDataServiceFactory.GetService(contentPath, loggingService);


                    if (siteConfig.EnablePop3 &&
                        siteConfig.Pop3Server != null && siteConfig.Pop3Server.Length > 0 &&
                        siteConfig.Pop3Username != null && siteConfig.Pop3Username.Length > 0)
                    {
                        Pop3 pop3 = new Pop3();


                        try
                        {
                            pop3.host     = siteConfig.Pop3Server;
                            pop3.userName = siteConfig.Pop3Username;
                            pop3.password = siteConfig.Pop3Password;

                            pop3.Connect();
                            pop3.Login();
                            pop3.GetAccountStat();

                            for (int j = pop3.messageCount; j >= 1; j--)
                            {
                                Pop3Message message = pop3.GetMessage(j);

                                string messageFrom;
                                // [email protected] 1-MAR-04
                                // only delete those messages that are processed
                                bool messageWasProcessed = false;

                                // E-Mail addresses look usually like this:
                                // My Name <*****@*****.**> or simply
                                // [email protected]. This block handles
                                // both variants.
                                Regex getEmail   = new Regex(".*\\<(?<email>.*?)\\>.*");
                                Match matchEmail = getEmail.Match(message.from);
                                if (matchEmail.Success)
                                {
                                    messageFrom = matchEmail.Groups["email"].Value;
                                }
                                else
                                {
                                    messageFrom = message.from;
                                }

                                // Only if the subject of the message is prefixed (case-sensitive) with
                                // the configured subject prefix, we accept the message
                                if (message.subject.StartsWith(siteConfig.Pop3SubjectPrefix))
                                {
                                    Entry entry = new Entry();
                                    entry.Initialize();
                                    entry.Title      = message.subject.Substring(siteConfig.Pop3SubjectPrefix.Length);
                                    entry.Categories = "";
                                    entry.Content    = "";
                                    entry.Author     = messageFrom;                                 //store the email, what we have for now...

                                    // Grab the categories. Categories are defined in square brackets
                                    // in the subject line.
                                    Regex categoriesRegex = new Regex("(?<exp>\\[(?<cat>.*?)\\])");
                                    foreach (Match match in categoriesRegex.Matches(entry.Title))
                                    {
                                        entry.Title       = entry.Title.Replace(match.Groups["exp"].Value, "");
                                        entry.Categories += match.Groups["cat"].Value + ";";
                                    }
                                    entry.Title = entry.Title.Trim();

                                    string   categories = "";
                                    string[] splitted   = entry.Categories.Split(';');
                                    for (int i = 0; i < splitted.Length; i++)
                                    {
                                        categories += splitted[i].Trim() + ";";
                                    }
                                    entry.Categories = categories.TrimEnd(';');


                                    entry.CreatedUtc = RFC2822Date.Parse(message.date);

                                    #region PLain Text
                                    // plain text?
                                    if (message.contentType.StartsWith("text/plain"))
                                    {
                                        entry.Content += message.body;
                                    }
                                    #endregion

                                    #region Just HTML
                                    // Luke Latimer 16-FEB-2004 ([email protected])
                                    // HTML only emails were not appearing
                                    else if (message.contentType.StartsWith("text/html"))
                                    {
                                        string messageText = "";

                                        // Note the email may still be encoded
                                        //messageText = QuotedCoding.DecodeOne(message.charset, "Q", message.body);
                                        messageText = message.body;

                                        // Strip the <body> out of the message (using code from below)
                                        Regex bodyExtractor = new Regex("<body.*?>(?<content>.*)</body>", RegexOptions.IgnoreCase | RegexOptions.Singleline);
                                        Match match         = bodyExtractor.Match(messageText);
                                        if (match != null && match.Success && match.Groups["content"] != null)
                                        {
                                            entry.Content += match.Groups["content"].Value;
                                        }
                                        else
                                        {
                                            entry.Content += messageText;
                                        }
                                    }
                                    #endregion

                                    // HTML/Text with attachments ?
                                    else if (
                                        message.contentType.StartsWith("multipart/alternative") ||
                                        message.contentType.StartsWith("multipart/related") ||
                                        message.contentType.StartsWith("multipart/mixed"))
                                    {
                                        Hashtable embeddedFiles = new Hashtable();
                                        ArrayList attachedFiles = new ArrayList();

                                        foreach (Attachment attachment in message.attachments)
                                        {
                                            // just plain text?
                                            if (attachment.contentType.StartsWith("text/plain"))
                                            {
                                                entry.Content += StringOperations.GetString(attachment.data);
                                            }

                                            // Luke Latimer 16-FEB-2004 ([email protected])
                                            // Allow for html-only attachments
                                            else if (attachment.contentType.StartsWith("text/html"))
                                            {
                                                // Strip the <body> out of the message (using code from below)
                                                Regex  bodyExtractor = new Regex("<body.*?>(?<content>.*)</body>", RegexOptions.IgnoreCase | RegexOptions.Singleline);
                                                string htmlString    = StringOperations.GetString(attachment.data);
                                                Match  match         = bodyExtractor.Match(htmlString);

                                                //NOTE: We will BLOW AWAY any previous content in this case.
                                                // This is because most mail clients like Outlook include
                                                // plain, then HTML. We will grab plain, then blow it away if
                                                // HTML is included later.
                                                if (match != null && match.Success && match.Groups["content"] != null)
                                                {
                                                    entry.Content = match.Groups["content"].Value;
                                                }
                                                else
                                                {
                                                    entry.Content = htmlString;
                                                }
                                            }

                                            // or alternative text ?
                                            else if (attachment.contentType.StartsWith("multipart/alternative"))
                                            {
                                                bool   contentSet  = false;
                                                string textContent = null;
                                                foreach (Attachment inner_attachment in attachment.attachments)
                                                {
                                                    // we prefer HTML
                                                    if (inner_attachment.contentType.StartsWith("text/plain"))
                                                    {
                                                        textContent = StringOperations.GetString(inner_attachment.data);
                                                    }
                                                    else if (inner_attachment.contentType.StartsWith("text/html"))
                                                    {
                                                        Regex  bodyExtractor = new Regex("<body.*?>(?<content>.*)</body>", RegexOptions.IgnoreCase | RegexOptions.Singleline);
                                                        string htmlString    = StringOperations.GetString(inner_attachment.data);
                                                        Match  match         = bodyExtractor.Match(htmlString);
                                                        if (match != null && match.Success && match.Groups["content"] != null)
                                                        {
                                                            entry.Content += match.Groups["content"].Value;
                                                        }
                                                        else
                                                        {
                                                            entry.Content += htmlString;
                                                        }
                                                        contentSet = true;
                                                    }
                                                }
                                                if (!contentSet)
                                                {
                                                    entry.Content += textContent;
                                                }
                                            }
                                            // or text with embeddedFiles (in a mixed message only)
                                            else if ((message.contentType.StartsWith("multipart/mixed") || message.contentType.StartsWith("multipart/alternative")) &&
                                                     attachment.contentType.StartsWith("multipart/related"))
                                            {
                                                foreach (Attachment inner_attachment in attachment.attachments)
                                                {
                                                    // just plain text?
                                                    if (inner_attachment.contentType.StartsWith("text/plain"))
                                                    {
                                                        entry.Content += StringOperations.GetString(inner_attachment.data);
                                                    }

                                                    else if (inner_attachment.contentType.StartsWith("text/html"))
                                                    {
                                                        Regex  bodyExtractor = new Regex("<body.*?>(?<content>.*)</body>", RegexOptions.IgnoreCase | RegexOptions.Singleline);
                                                        string htmlString    = StringOperations.GetString(inner_attachment.data);
                                                        Match  match         = bodyExtractor.Match(htmlString);
                                                        if (match != null && match.Success && match.Groups["content"] != null)
                                                        {
                                                            entry.Content += match.Groups["content"].Value;
                                                        }
                                                        else
                                                        {
                                                            entry.Content += htmlString;
                                                        }
                                                    }

                                                    // or alternative text ?
                                                    else if (inner_attachment.contentType.StartsWith("multipart/alternative"))
                                                    {
                                                        bool   contentSet  = false;
                                                        string textContent = null;
                                                        foreach (Attachment inner_inner_attachment in inner_attachment.attachments)
                                                        {
                                                            // we prefer HTML
                                                            if (inner_inner_attachment.contentType.StartsWith("text/plain"))
                                                            {
                                                                textContent = StringOperations.GetString(inner_inner_attachment.data);
                                                            }
                                                            else if (inner_inner_attachment.contentType.StartsWith("text/html"))
                                                            {
                                                                Regex  bodyExtractor = new Regex("<body.*?>(?<content>.*)</body>", RegexOptions.IgnoreCase | RegexOptions.Singleline);
                                                                string htmlString    = StringOperations.GetString(inner_inner_attachment.data);
                                                                Match  match         = bodyExtractor.Match(htmlString);
                                                                if (match != null && match.Success && match.Groups["content"] != null)
                                                                {
                                                                    entry.Content += match.Groups["content"].Value;
                                                                }
                                                                else
                                                                {
                                                                    entry.Content += htmlString;
                                                                }
                                                                contentSet = true;
                                                            }
                                                        }
                                                        if (!contentSet)
                                                        {
                                                            entry.Content += textContent;
                                                        }
                                                    }
                                                    // any other inner_attachment
                                                    else if (inner_attachment.data != null &&
                                                             inner_attachment.fileName != null &&
                                                             inner_attachment.fileName.Length > 0)
                                                    {
                                                        if (inner_attachment.contentID.Length > 0)
                                                        {
                                                            embeddedFiles.Add(inner_attachment.contentID, StoreAttachment(inner_attachment, binariesPath));
                                                        }
                                                        else
                                                        {
                                                            attachedFiles.Add(StoreAttachment(inner_attachment, binariesPath));
                                                        }
                                                    }
                                                }
                                            }
                                            // any other attachment
                                            else if (attachment.data != null &&
                                                     attachment.fileName != null &&
                                                     attachment.fileName.Length > 0)
                                            {
                                                if (attachment.contentID.Length > 0 && message.contentType.StartsWith("multipart/related"))
                                                {
                                                    embeddedFiles.Add(attachment.contentID, StoreAttachment(attachment, binariesPath));
                                                }
                                                else
                                                {
                                                    attachedFiles.Add(StoreAttachment(attachment, binariesPath));
                                                }
                                            }
                                        }


                                        // check for orphaned embeddings
                                        string[] embeddedKeys = new string[embeddedFiles.Keys.Count];
                                        embeddedFiles.Keys.CopyTo(embeddedKeys, 0);
                                        foreach (string key in embeddedKeys)
                                        {
                                            if (entry.Content.IndexOf("cid:" + key.Trim('<', '>')) == -1)
                                            {
                                                object file = embeddedFiles[key];
                                                embeddedFiles.Remove(key);
                                                attachedFiles.Add(file);
                                            }
                                        }


                                        // now fix up the URIs

                                        if (siteConfig.Pop3InlineAttachedPictures)
                                        {
                                            foreach (string fileName in attachedFiles)
                                            {
                                                string fileNameU = fileName.ToUpper();
                                                if (fileNameU.EndsWith(".JPG") || fileNameU.EndsWith(".JPEG") ||
                                                    fileNameU.EndsWith(".GIF") || fileNameU.EndsWith(".PNG") ||
                                                    fileNameU.EndsWith(".BMP"))
                                                {
                                                    bool scalingSucceeded = false;

                                                    if (siteConfig.Pop3InlinedAttachedPicturesThumbHeight > 0)
                                                    {
                                                        try
                                                        {
                                                            string absoluteFileName  = Path.Combine(binariesPath, fileName);
                                                            string thumbBaseFileName = Path.GetFileNameWithoutExtension(fileName) + "-thumb.dasblog.JPG";
                                                            string thumbFileName     = Path.Combine(binariesPath, thumbBaseFileName);
                                                            Bitmap sourceBmp         = new Bitmap(absoluteFileName);
                                                            if (sourceBmp.Height > siteConfig.Pop3InlinedAttachedPicturesThumbHeight)
                                                            {
                                                                Bitmap targetBmp = new Bitmap(sourceBmp, new Size(
                                                                                                  Convert.ToInt32(Math.Round((((double)sourceBmp.Width) * (((double)siteConfig.Pop3InlinedAttachedPicturesThumbHeight) / ((double)sourceBmp.Height))), 0)),
                                                                                                  siteConfig.Pop3InlinedAttachedPicturesThumbHeight));

                                                                ImageCodecInfo    codecInfo     = GetEncoderInfo("image/jpeg");
                                                                Encoder           encoder       = Encoder.Quality;
                                                                EncoderParameters encoderParams = new EncoderParameters(1);
                                                                long             compression    = 75;
                                                                EncoderParameter encoderParam   = new EncoderParameter(encoder, compression);
                                                                encoderParams.Param[0] = encoderParam;
                                                                targetBmp.Save(thumbFileName, codecInfo, encoderParams);

                                                                string absoluteUri      = new Uri(binariesBaseUri, fileName).AbsoluteUri;
                                                                string absoluteThumbUri = new Uri(binariesBaseUri, thumbBaseFileName).AbsoluteUri;
                                                                entry.Content   += String.Format("<div class=\"inlinedMailPictureBox\"><a href=\"{0}\"><img border=\"0\" class=\"inlinedMailPicture\" src=\"{2}\"></a><br /><a class=\"inlinedMailPictureLink\" href=\"{0}\">{1}</a></div>", absoluteUri, fileName, absoluteThumbUri);
                                                                scalingSucceeded = true;
                                                            }
                                                        }
                                                        catch
                                                        {
                                                        }
                                                    }
                                                    if (!scalingSucceeded)
                                                    {
                                                        string absoluteUri = new Uri(binariesBaseUri, fileName).AbsoluteUri;
                                                        entry.Content += String.Format("<div class=\"inlinedMailPictureBox\"><img class=\"inlinedMailPicture\" src=\"{0}\"><br /><a class=\"inlinedMailPictureLink\" href=\"{0}\">{1}</a></div>", absoluteUri, fileName);
                                                    }
                                                }
                                            }
                                        }

                                        if (attachedFiles.Count > 0)
                                        {
                                            entry.Content += "<p>";
                                        }

                                        foreach (string fileName in attachedFiles)
                                        {
                                            string fileNameU = fileName.ToUpper();
                                            if (!siteConfig.Pop3InlineAttachedPictures ||
                                                (!fileNameU.EndsWith(".JPG") && !fileNameU.EndsWith(".JPEG") &&
                                                 !fileNameU.EndsWith(".GIF") && !fileNameU.EndsWith(".PNG") &&
                                                 !fileNameU.EndsWith(".BMP")))
                                            {
                                                string absoluteUri = new Uri(binariesBaseUri, fileName).AbsoluteUri;
                                                entry.Content += String.Format("Download: <a href=\"{0}\">{1}</a><br />", absoluteUri, fileName);
                                            }
                                        }
                                        if (attachedFiles.Count > 0)
                                        {
                                            entry.Content += "</p>";
                                        }

                                        foreach (string key in embeddedFiles.Keys)
                                        {
                                            entry.Content = entry.Content.Replace("cid:" + key.Trim('<', '>'), new Uri(binariesBaseUri, (string)embeddedFiles[key]).AbsoluteUri);
                                        }
                                    }

                                    loggingService.AddEvent(
                                        new EventDataItem(
                                            EventCodes.Pop3EntryReceived, entry.Title,
                                            SiteUtilities.GetPermaLinkUrl(siteConfig, entry.EntryId), messageFrom));

                                    SiteUtilities.SaveEntry(entry, siteConfig, loggingService, dataService);

                                    ErrorTrace.Trace(System.Diagnostics.TraceLevel.Info,
                                                     String.Format("Message stored. From: {0}, Title: {1} as entry {2}",
                                                                   messageFrom, entry.Title, entry.EntryId));

                                    // give the XSS upstreamer a hint that things have changed
//                                    XSSUpstreamer.TriggerUpstreaming();

                                    // [email protected] (01-MAR-04)
                                    messageWasProcessed = true;
                                }
                                else
                                {
                                    // [email protected] (01-MAR-04)
                                    // logging every ignored email is apt
                                    // to fill up the event page very quickly
                                    // especially if only processed emails are
                                    // being deleted
                                    if (siteConfig.Pop3LogIgnoredEmails)
                                    {
                                        loggingService.AddEvent(
                                            new EventDataItem(
                                                EventCodes.Pop3EntryIgnored, message.subject,
                                                null, messageFrom));
                                    }
                                }
                                // [email protected] (01-MAR-04)
                                if (siteConfig.Pop3DeleteAllMessages || messageWasProcessed)
                                {
                                    if (!messageWasProcessed)
                                    {
                                        loggingService.AddEvent(
                                            new EventDataItem(
                                                EventCodes.Pop3EntryDiscarded, message.subject,
                                                null, messageFrom));
                                    }
                                    pop3.DeleteMessage(j);
                                }
                            }
                        }
                        catch (Exception e)
                        {
                            ErrorTrace.Trace(System.Diagnostics.TraceLevel.Error, e);
                            loggingService.AddEvent(
                                new EventDataItem(
                                    EventCodes.Pop3ServerError, e.ToString().Replace("\n", "<br />"), null, null));
                        }
                        finally
                        {
                            pop3.Close();
                        }
                    }

                    Thread.Sleep(TimeSpan.FromSeconds(siteConfig.Pop3Interval));
                }
                catch (ThreadAbortException abortException)
                {
                    ErrorTrace.Trace(System.Diagnostics.TraceLevel.Info, abortException);
                    loggingService.AddEvent(new EventDataItem(EventCodes.Pop3ServiceShutdown, "", ""));
                    break;
                }
                catch (Exception e)
                {
                    // if the siteConfig can't be read, stay running regardless
                    // default wait time is 4 minutes in that case
                    Thread.Sleep(TimeSpan.FromSeconds(240));
                    ErrorTrace.Trace(System.Diagnostics.TraceLevel.Error, e);
                }
            }while (true);
            ErrorTrace.Trace(System.Diagnostics.TraceLevel.Info, "MailToWeblog thread terminating");
            loggingService.AddEvent(new EventDataItem(EventCodes.Pop3ServiceShutdown, "", ""));
        }
Exemplo n.º 24
0
        public static EntrySaveState UpdateEntry(Entry entry, string trackbackUrl, CrosspostInfoCollection crosspostList, SiteConfig siteConfig, ILoggingDataService logService, IBlogDataService dataService)
        {
            EntrySaveState rtn = EntrySaveState.Failed;

            entry.ModifiedLocalTime = DateTime.Now;

            TrackbackInfoCollection trackbackList = null;
            if (trackbackUrl != null && trackbackUrl.Length > 0)
            {
                trackbackList = new TrackbackInfoCollection();
                trackbackList.Add(new TrackbackInfo(
                    trackbackUrl,
                    SiteUtilities.GetPermaLinkUrl(siteConfig, entry),
                    entry.Title,
                    entry.Description,
                    siteConfig.Title));
            }

            rtn = InternalSaveEntry(entry, trackbackList, crosspostList, siteConfig, logService, dataService);

            logService.AddEvent(
                new EventDataItem(
                    EventCodes.EntryChanged, entry.Title,
                    SiteUtilities.GetPermaLinkUrl(entry.EntryId)));

            return rtn;
        }
Exemplo n.º 25
0
        private static EntrySaveState InternalSaveEntry(Entry entry, TrackbackInfoCollection trackbackList, CrosspostInfoCollection crosspostList, SiteConfig siteConfig, ILoggingDataService logService, IBlogDataService dataService)
        {
            EntrySaveState rtn = EntrySaveState.Failed;
            // we want to prepopulate the cross post collection with the crosspost footer
            if (siteConfig.EnableCrossPostFooter && siteConfig.CrossPostFooter != null && siteConfig.CrossPostFooter.Length > 0)
            {
                foreach (CrosspostInfo info in crosspostList)
                {
                    info.CrossPostFooter = siteConfig.CrossPostFooter;
                }
            }

            // now save the entry, passign in all the necessary Trackback and Pingback info.
            try
            {
                // if the post is missing a title don't publish it
                if (entry.Title == null || entry.Title.Length == 0)
                {
                    entry.IsPublic = false;
                }

                // if the post is missing categories, then set the categories to empty string.
                if (entry.Categories == null)
                    entry.Categories = "";

                rtn = dataService.SaveEntry(
                    entry,
                    (siteConfig.PingServices.Count > 0) ?
                        new WeblogUpdatePingInfo(siteConfig.Title, SiteUtilities.GetBaseUrl(siteConfig), SiteUtilities.GetBaseUrl(siteConfig), SiteUtilities.GetRssUrl(siteConfig), siteConfig.PingServices) : null,
                    (entry.IsPublic) ?
                        trackbackList : null,
                    siteConfig.EnableAutoPingback && entry.IsPublic ?
                        new PingbackInfo(
                            SiteUtilities.GetPermaLinkUrl(siteConfig, entry),
                            entry.Title,
                            entry.Description,
                            siteConfig.Title) : null,
                    crosspostList);

                SendEmail(entry, siteConfig, logService);

            }
            catch (Exception ex)
            {
                StackTrace st = new StackTrace();
                logService.AddEvent(
                    new EventDataItem(EventCodes.Error, ex.ToString() + Environment.NewLine + st.ToString(), ""));
            }

            // we want to invalidate all the caches so users get the new post
            BreakCache(siteConfig, entry.GetSplitCategories());

            // give the XSS upstreamer a hint that things have changed
            //FIX:  XSSUpstreamer.TriggerUpstreaming();

            return rtn;
        }
Exemplo n.º 26
0
        public void SendEmailReport(DateTime reportDate, SiteConfig siteConfig, IBlogDataService dataService, ILoggingDataService loggingService)
        {
            MailMessage emailMessage = new MailMessage();
            if ( siteConfig.NotificationEMailAddress != null && siteConfig.NotificationEMailAddress.Length > 0 )
            {
                emailMessage.To.Add(siteConfig.NotificationEMailAddress);
            }
            else
            {
                emailMessage.To.Add(siteConfig.Contact);
            }

            emailMessage.Subject = String.Format("Weblog Daily Activity Report for '{0}'", reportDate.ToLongDateString());
            emailMessage.Body = GenerateReportEmailBody(reportDate);
            emailMessage.IsBodyHtml = true;
            emailMessage.BodyEncoding = System.Text.Encoding.UTF8;
            emailMessage.From = new MailAddress(siteConfig.Contact);

            SendMailInfo sendMailInfo = new SendMailInfo(emailMessage, siteConfig.SmtpServer,
                siteConfig.EnableSmtpAuthentication, siteConfig.UseSSLForSMTP, siteConfig.SmtpUserName, siteConfig.SmtpPassword, siteConfig.SmtpPort);

            dataService.AddTracking(null, sendMailInfo ); // use this with null tracking object, just to get the email sent
            loggingService.AddEvent( new EventDataItem( EventCodes.ReportMailerReportSent,"",""));
        }
Exemplo n.º 27
0
        public EntryCollection SearchEntries(string searchString)
        {
            StringCollection searchWords = new StringCollection();

            string[] splitString = Regex.Split(searchString, @"(""[^""]*"")", RegexOptions.IgnoreCase |
                                               RegexOptions.Compiled);

            for (int index = 0; index < splitString.Length; index++)
            {
                if (splitString[index] != "")
                {
                    if (index == splitString.Length - 1)
                    {
                        foreach (string s in splitString[index].Split(' '))
                        {
                            if (s != "")
                            {
                                searchWords.Add(s);
                            }
                        }
                    }
                    else
                    {
                        searchWords.Add(splitString[index].Substring(1, splitString[index].Length - 2));
                    }
                }
            }

            EntryCollection matchEntries = new EntryCollection();

            foreach (Entry entry in requestPage.DataService.GetEntriesForDay(DateTime.MaxValue.AddDays(-2), new UTCTimeZone(), Request.Headers["Accept-Language"], int.MaxValue, int.MaxValue, null))
            {
                string entryTitle       = entry.Title;
                string entryDescription = entry.Description;
                string entryContent     = entry.Content;

                foreach (string searchWord in searchWords)
                {
                    if (entryTitle != null)
                    {
                        if (searchEntryForWord(entryTitle, searchWord))
                        {
                            if (!matchEntries.Contains(entry))
                            {
                                matchEntries.Add(entry);
                            }
                            continue;
                        }
                    }
                    if (entryDescription != null)
                    {
                        if (searchEntryForWord(entryDescription, searchWord))
                        {
                            if (!matchEntries.Contains(entry))
                            {
                                matchEntries.Add(entry);
                            }
                            continue;
                        }
                    }
                    if (entryContent != null)
                    {
                        if (searchEntryForWord(entryContent, searchWord))
                        {
                            if (!matchEntries.Contains(entry))
                            {
                                matchEntries.Add(entry);
                            }
                            continue;
                        }
                    }
                }
            }

            // log the search to the event log
            ILoggingDataService logService = requestPage.LoggingService;
            string referrer = Request.UrlReferrer != null ? Request.UrlReferrer.AbsoluteUri : Request.ServerVariables["REMOTE_ADDR"];

            logService.AddEvent(
                new EventDataItem(EventCodes.Search, String.Format("{0}", searchString), referrer));

            return(matchEntries);
        }
Exemplo n.º 28
0
        public void ProcessRequest(HttpContext context)
        {
            if (!SiteSecurity.IsValidContributor())
            {
                context.Response.Redirect("~/FormatPage.aspx?path=SiteConfig/accessdenied.format.html");
            }

            SiteConfig siteConfig = SiteConfig.GetSiteConfig();

            string entryId     = "";
            string author      = "";
            string title       = "";
            string textToSave  = "";
            string redirectUrl = SiteUtilities.GetStartPageUrl();


            System.Xml.XmlTextReader xtr = new System.Xml.XmlTextReader(context.Request.InputStream);
            try
            {
                while (!xtr.EOF)
                {
                    xtr.Read();
                    if (xtr.Name == "entryid")
                    {
                        entryId = xtr.ReadInnerXml();
                    }
                    if (xtr.Name == "author")
                    {
                        author = xtr.ReadInnerXml();
                    }
                    if (xtr.Name == "title" && xtr.NodeType == System.Xml.XmlNodeType.Element)
                    {
                        // Ensure this is the start element before moving forward to the CDATA.
                        xtr.Read();                          // Brings us to the CDATA inside "title"
                        title = xtr.Value;
                    }
                    if (xtr.Name == "posttext" && xtr.NodeType == System.Xml.XmlNodeType.Element)
                    {
                        xtr.Read();
                        textToSave = xtr.Value;
                    }
                }
            }
            finally
            {
                xtr.Close();
            }


            // make sure the entry param is there
            if (entryId == null || entryId.Length == 0)
            {
                context.Response.Redirect(SiteUtilities.GetStartPageUrl(siteConfig));
                return;
            }
            else
            {
                ILoggingDataService logService  = LoggingDataServiceFactory.GetService(SiteConfig.GetLogPathFromCurrentContext());
                IBlogDataService    dataService = BlogDataServiceFactory.GetService(SiteConfig.GetContentPathFromCurrentContext(), logService);

                // First, attempt to get the entry.  If the entry exists, then get it for editing
                // and save.  If not, create a brand new entry and save it instead.
                Entry entry = dataService.GetEntry(entryId);
                if (entry != null)
                {
                    entry = dataService.GetEntryForEdit(entryId);
                    Entry modifiedEntry = entry.Clone();
                    modifiedEntry.Content     = textToSave;
                    modifiedEntry.Title       = title;
                    modifiedEntry.Author      = author;
                    modifiedEntry.Syndicated  = false;
                    modifiedEntry.IsPublic    = false;
                    modifiedEntry.ModifiedUtc = DateTime.Now.ToUniversalTime();
                    modifiedEntry.Categories  = "";
                    dataService.SaveEntry(modifiedEntry, null);

                    //context.Request.Form["textbox1"];

                    logService.AddEvent(
                        new EventDataItem(
                            EventCodes.EntryChanged, entryId,
                            context.Request.RawUrl));
                }
                else
                {
                    // This is a brand new entry.  Create the entry and save it.
                    entry             = new Entry();
                    entry.EntryId     = entryId;
                    entry.CreatedUtc  = DateTime.Now.ToUniversalTime();
                    entry.ModifiedUtc = DateTime.Now.ToUniversalTime();
                    entry.Title       = title;
                    entry.Author      = author;
                    entry.Content     = textToSave;
                    entry.Syndicated  = false;
                    entry.IsPublic    = false;
                    dataService.SaveEntry(entry, null);

                    //context.Request.Form["textbox1"];

                    logService.AddEvent(
                        new EventDataItem(
                            EventCodes.EntryAdded, entryId,
                            context.Request.RawUrl));
                }
            }
        }
Exemplo n.º 29
0
        public void ProcessRequest(HttpContext context)
        {
            SiteConfig siteConfig = SiteConfig.GetSiteConfig();
            string     entryId;
            string     title;
            string     excerpt;
            string     url;
            string     blog_name;

            if (!siteConfig.EnableTrackbackService)
            {
                context.Response.StatusCode = 503;
                context.Response.Status     = "503 Service Unavailable";
                context.Response.End();
                return;
            }

            // Try blocking them once, on the off chance they sent us a referrer
            string referrer = context.Request.UrlReferrer != null?context.Request.UrlReferrer.AbsoluteUri:"";

            if (ReferralBlackList.IsBlockedReferrer(referrer))
            {
                if (siteConfig.EnableReferralUrlBlackList404s)
                {
                    context.Response.StatusCode = 404;
                    context.Response.End();
                    return;
                }
            }

            entryId = context.Request.QueryString["guid"];

            if (context.Request.HttpMethod == "POST")
            {
                title     = context.Request.Form["title"];
                excerpt   = context.Request.Form["excerpt"];
                url       = context.Request.Form["url"];
                blog_name = context.Request.Form["blog_name"];
            }

            /* GET is no longer in the Trackback spec. Keeping
             * this arround for testing. Just uncomment.
             * else if ( context.Request.HttpMethod == "GET" )
             * {
             * title = context.Request.QueryString["title"];
             * excerpt= context.Request.QueryString["excerpt"];
             * url = context.Request.QueryString["url"];
             * blog_name = context.Request.QueryString["blog_name"];
             * }
             */
            else
            {
                context.Response.Redirect(SiteUtilities.GetStartPageUrl(siteConfig));
                return;
            }

            if (url != null && url.Length > 0)
            {
                try
                {
                    // First line of defense, try blocking again with the URL they are tracking us back with
                    if (ReferralBlackList.IsBlockedReferrer(url))
                    {
                        if (siteConfig.EnableReferralUrlBlackList404s)
                        {
                            context.Response.StatusCode = 404;
                            context.Response.End();
                            return;
                        }
                    }

                    ILoggingDataService logService  = LoggingDataServiceFactory.GetService(SiteConfig.GetLogPathFromCurrentContext());
                    IBlogDataService    dataService = BlogDataServiceFactory.GetService(SiteConfig.GetContentPathFromCurrentContext(), logService);

                    Entry entry = dataService.GetEntry(entryId);

                    if (entry != null)
                    {
                        try
                        {
                            string requestBody = null;
                            // see if this is a spammer
                            HttpWebRequest webRequest = WebRequest.Create(url) as HttpWebRequest;
                            webRequest.Method    = "GET";
                            webRequest.UserAgent = SiteUtilities.GetUserAgent();

                            HttpWebResponse response = webRequest.GetResponse() as HttpWebResponse;

                            // now we want to get the page contents of the target body
                            using (StreamReader requestReader = new StreamReader(response.GetResponseStream()))
                            {
                                requestBody = requestReader.ReadToEnd();
                            }

                            response.Close();

                            // the source URL in the page could be URL encoded like the ClickThroughHandler does
                            string urlEncodedBaseUrl = HttpUtility.UrlEncode(SiteUtilities.GetBaseUrl());

                            // check to see if the source's page contains a link to us
                            if (Regex.Match(requestBody, SiteUtilities.GetBaseUrl()).Success == false &&
                                Regex.Match(requestBody, urlEncodedBaseUrl).Success == false)
                            {
                                logService.AddEvent(new EventDataItem(
                                                        EventCodes.TrackbackBlocked,
                                                        context.Request.UserHostAddress + " because it did not contain a link",
                                                        SiteUtilities.GetPermaLinkUrl(entryId),
                                                        url,
                                                        entry.Title
                                                        ));

                                context.Response.StatusCode = 404;
                                context.Response.End();
                                return;
                            }
                        }
                        catch
                        {
                            // trackback url is not even alive
                            logService.AddEvent(new EventDataItem(
                                                    EventCodes.TrackbackBlocked,
                                                    context.Request.UserHostAddress + " because the server did not return a valid response",
                                                    SiteUtilities.GetPermaLinkUrl(entryId),
                                                    url,
                                                    entry.Title
                                                    ));

                            context.Response.StatusCode = 404;
                            context.Response.End();
                            return;
                        }

                        // if we've gotten this far, the trackback is real and valid
                        Tracking t = new Tracking();
                        t.PermaLink = url;
                        t.Referer   = context.Request.UrlReferrer != null?context.Request.UrlReferrer.ToString() : String.Empty;

                        t.RefererBlogName  = blog_name;
                        t.RefererExcerpt   = excerpt;
                        t.RefererTitle     = title;
                        t.RefererIPAddress = context.Request.UserHostAddress;
                        t.TargetEntryId    = entryId;
                        t.TargetTitle      = entry.Title;
                        t.TrackingType     = TrackingType.Trackback;

                        ISpamBlockingService spamBlockingService = siteConfig.SpamBlockingService;
                        if (spamBlockingService != null)
                        {
                            bool isSpam = false;
                            try
                            {
                                isSpam = spamBlockingService.IsSpam(t);
                            }
                            catch (Exception ex)
                            {
                                logService.AddEvent(new EventDataItem(EventCodes.Error, String.Format("The external spam blocking service failed for trackback from {0}. Original exception: {1}", t.PermaLink, ex), SiteUtilities.GetPermaLinkUrl(entryId)));
                            }
                            if (isSpam)
                            {
                                //TODO: maybe we can add a configuration option to moderate trackbacks.
                                // For now, we'll just avoid saving suspected spam
                                logService.AddEvent(new EventDataItem(
                                                        EventCodes.TrackbackBlocked,
                                                        context.Request.UserHostAddress + " because it was considered spam by the external blocking service.",
                                                        SiteUtilities.GetPermaLinkUrl(entryId),
                                                        url,
                                                        entry.Title
                                                        ));
                                context.Response.StatusCode = 404;
                                context.Response.End();
                                return;
                            }
                        }

                        if (siteConfig.SendTrackbacksByEmail &&
                            siteConfig.SmtpServer != null && siteConfig.SmtpServer.Length > 0)
                        {
                            MailMessage emailMessage = new MailMessage();
                            if (siteConfig.NotificationEMailAddress != null &&
                                siteConfig.NotificationEMailAddress.Length > 0)
                            {
                                emailMessage.To.Add(siteConfig.NotificationEMailAddress);
                            }
                            else
                            {
                                emailMessage.To.Add(siteConfig.Contact);
                            }
                            emailMessage.Subject = String.Format("Weblog trackback by '{0}' on '{1}'", t.PermaLink, t.TargetTitle);
                            emailMessage.Body    = String.Format("You were tracked back from\n{0}\r\non your weblog entry '{1}'\n({2}\r\n\r\nDelete Trackback: {3})",
                                                                 t.PermaLink,
                                                                 t.TargetTitle,
                                                                 SiteUtilities.GetPermaLinkUrl(entryId),
                                                                 SiteUtilities.GetTrackbackDeleteUrl(entryId, t.PermaLink, t.TrackingType));


                            emailMessage.IsBodyHtml   = false;
                            emailMessage.BodyEncoding = System.Text.Encoding.UTF8;
                            emailMessage.From         = new MailAddress(siteConfig.Contact);
                            SendMailInfo sendMailInfo = new SendMailInfo(emailMessage, siteConfig.SmtpServer,
                                                                         siteConfig.EnableSmtpAuthentication, siteConfig.UseSSLForSMTP, siteConfig.SmtpUserName, siteConfig.SmtpPassword, siteConfig.SmtpPort);
                            dataService.AddTracking(t, sendMailInfo);
                        }
                        else
                        {
                            dataService.AddTracking(t);
                        }

                        logService.AddEvent(
                            new EventDataItem(
                                EventCodes.TrackbackReceived,
                                entry.Title,
                                SiteUtilities.GetPermaLinkUrl(entryId),
                                url));

                        // return the correct Trackback response
                        // http://www.movabletype.org/docs/mttrackback.html
                        context.Response.Write("<?xml version=\"1.0\" encoding=\"iso-8859-1\"?><response><error>0</error></response>");
                        return;
                    }
                }
                catch (System.Threading.ThreadAbortException ex)
                {
                    // absorb
                    ErrorTrace.Trace(System.Diagnostics.TraceLevel.Error, ex);
                    return;
                }
                catch (Exception exc)
                {
                    // absorb
                    ErrorTrace.Trace(System.Diagnostics.TraceLevel.Error, exc);

                    // return the correct Trackback response
                    // http://www.movabletype.org/docs/mttrackback.html
                    context.Response.Write("<?xml version=\"1.0\" encoding=\"iso-8859-1\"?><response><error>1</error><message>" + exc.ToString() + "</message></response>");
                    return;
                }
            }

            if (entryId != null && entryId.Length > 0)
            {
                context.Response.Redirect(SiteUtilities.GetPermaLinkUrl(siteConfig, entryId));
            }
            else
            {
                context.Response.Redirect(SiteUtilities.GetStartPageUrl(siteConfig));
            }
        }