private static void AbortRequestFromBannedIP(HttpContext context)
 {
     context.Items["BanCurrentRequest"] = true;
     context.ApplicationInstance.CompleteRequest();
     log.Info("BannedIPBlockingHttpModule blocked request from banned ip address " + SiteUtils.GetIP4Address());
 }
Exemple #2
0
 private static string GetEditLink(int newsId)
 {
     return("<a title='" + Resources.NewsResources.NewsEditLink
            + "' class='edit-link' href='" + SiteUtils.GetNavigationSiteRoot() + "/News/NewsEdit.aspx?NewsID=" + newsId
            + "'> <i class='fa fa-pencil'></i></a>");
 }
Exemple #3
0
        public void ProcessRequest(HttpContext context)
        {
            base.Initialize(context);

            if (!UserCanEditModule(ModuleId, XmlConfiguration.FeatureGuid))
            {
                log.Info("User has no edit permission so returning 404");
                Response.StatusCode = 404;
                return;
            }

            if (CurrentSite == null)
            {
                log.Info("CurrentSite is null so returning 404");
                Response.StatusCode = 404;
                return;
            }

            if (CurrentUser == null)
            {
                log.Info("CurrentUser is null so returning 404");
                Response.StatusCode = 404;
                return;
            }

            // this feature only uses the actual system.io file system
            //if (FileSystem == null)
            //{
            //    log.Info("FileSystem is null so returning 404");
            //    Response.StatusCode = 404;
            //    return;
            //}

            if (Request.Files.Count == 0)
            {
                log.Info("Posted File Count is zero so returning 404");
                Response.StatusCode = 404;
                return;
            }

            module = GetModule(ModuleId, XmlConfiguration.FeatureGuid);

            if (module == null)
            {
                log.Info("Module is null so returning 404");
                Response.StatusCode = 404;
                return;
            }

            Hashtable moduleSettings = ModuleSettings.GetModuleSettings(ModuleId);

            config = new XmlConfiguration(moduleSettings);

            HttpPostedFile file = Request.Files[0]; // only expecting one file per post

            string newFileName = Path.GetFileName(file.FileName).ToCleanFileName(WebConfigSettings.ForceLowerCaseForUploadedFiles);

            string ext = Path.GetExtension(file.FileName).ToLowerInvariant();

            if (!SiteUtils.IsAllowedUploadBrowseFile(ext, ".xml|.xsl"))
            {
                log.Info("file extension was " + ext + " so returning 404");
                Response.StatusCode = 404;

                return;
            }

            context.Response.ContentType = "text/plain";//"application/json";
            var r = new System.Collections.Generic.List <UploadFilesResult>();
            JavaScriptSerializer js = new JavaScriptSerializer();


            string destPath;

            switch (ext)
            {
            case ".xml":
                string xmlBasePath = "~/Data/Sites/" + CurrentSite.SiteId.ToInvariantString() + "/xml/";
                destPath = Server.MapPath(xmlBasePath + newFileName);

                if (File.Exists(destPath))
                {
                    File.Delete(destPath);
                }

                file.SaveAs(destPath);

                break;

            case ".xsl":
                string xslBasePath = "~/Data/Sites/" + CurrentSite.SiteId.ToInvariantString() + "/xsl/";
                destPath = Server.MapPath(xslBasePath + newFileName);

                if (File.Exists(destPath))
                {
                    File.Delete(destPath);
                }

                file.SaveAs(destPath);

                break;
            }

            r.Add(new UploadFilesResult()
            {
                //Thumbnail_url =
                Name   = newFileName,
                Length = file.ContentLength,
                Type   = file.ContentType
            });

            var uploadedFiles = new
            {
                files = r.ToArray()
            };

            var jsonObj = js.Serialize(uploadedFiles);

            context.Response.Write(jsonObj.ToString());
        }
Exemple #4
0
        protected override void Render(HtmlTextWriter writer)
        {
            if (HttpContext.Current == null)
            {
                // TODO: show a bmp or some other design time thing?
                writer.Write("[" + this.ID + "]");
            }
            else
            {
                SiteSettings siteSettings = CacheHelper.GetCurrentSiteSettings();
                if (siteSettings == null || String.IsNullOrEmpty(siteSettings.Logo))
                {
                    return;
                }

                string urlToUse   = "~/";
                string titleToUse = siteSettings.SiteName;
                string imageUrlToUse;

                if (WebConfigSettings.SiteLogoUseMediaFolder)
                {
                    imageUrlToUse = Page.ResolveUrl("~/Data/Sites/")
                                    + siteSettings.SiteId.ToString()
                                    + "/media/logos/" + siteSettings.Logo;
                }
                else
                {
                    imageUrlToUse = Page.ResolveUrl("~/Data/Sites/")
                                    + siteSettings.SiteId.ToString()
                                    + "/logos/" + siteSettings.Logo;
                }



                string siteRoot = SiteUtils.GetNavigationSiteRoot(siteSettings);

                if (siteSettings.SiteFolderName.Length > 0)
                {
                    //urlToUse = siteSettings.SiteRoot + "/Default.aspx";
                    urlToUse = siteRoot + "/Default.aspx";
                }

                if (useH1)
                {
                    writer.Write("<h1 class='{0}'>", h1CssClass);
                }

                if (overrideUrl.Length > 0)
                {
                    if (siteSettings.SiteFolderName.Length > 0)
                    {
                        overrideUrl = siteRoot + overrideUrl.Replace("~/", "/");
                    }
                    urlToUse = overrideUrl;
                }

                if (overrideImageUrl.Length > 0)
                {
                    imageUrlToUse = Page.ResolveUrl(overrideImageUrl);
                }

                if (overrideTitle.Length > 0)
                {
                    titleToUse = overrideTitle;
                }
                //if (cssClass == string.Empty) cssClass = "sitelogo";
                if (useUrl)
                {
                    writer.Write("<a href='{0}' title='{1}' class='{4}'><img class='{3}' alt='{1}' src='{2}' /></a>",
                                 Page.ResolveUrl(urlToUse),
                                 titleToUse,
                                 imageUrlToUse,
                                 imageCssClass,
                                 linkCssClass);
                }
                else
                {
                    writer.Write("<img class='{0}' alt='{1}' src='{2}' />",
                                 imageCssClass,
                                 titleToUse,
                                 imageUrlToUse);
                }

                if (useH1)
                {
                    writer.Write("</h1>");
                }
            }
        }
        void btnCreateUser_Click(object sender, EventArgs e)
        {
            Page.Validate("profile");
            if (!Page.IsValid)
            {
                return;
            }

            if (hdnIdentifier.Value.Length == 0)
            {               // form manipulation if this is missing
                Response.Redirect(SiteRoot + "/Secure/Register.aspx");
                return;
            }

            string email = txtEmail.Text;

            if (email.Length == 0)
            {
                if ((hdnEmail.Value.Length > 0) && (!SiteUser.EmailExistsInDB(siteSettings.SiteId, hdnEmail.Value)))
                {
                    email = hdnEmail.Value;
                }
            }

            string loginName = string.Empty;

            if ((hdnPreferredUsername.Value.Length > 0) && (!SiteUser.LoginExistsInDB(siteSettings.SiteId, hdnPreferredUsername.Value)))
            {
                loginName = hdnPreferredUsername.Value;
            }

            if (loginName.Length == 0)
            {
                loginName = SiteUtils.SuggestLoginNameFromEmail(siteSettings.SiteId, email);
            }

            string name = loginName;

            if (hdnDisplayName.Value.Length > 0)
            {
                name = hdnDisplayName.Value;
            }


            if (SiteUser.EmailExistsInDB(siteSettings.SiteId, email))
            {
                lblError.Text = Resource.RegisterDuplicateEmailMessage;
            }
            else
            {
                bool     emailIsVerified = false;
                SiteUser newUser         = CreateUser(
                    hdnIdentifier.Value,
                    email,
                    loginName,
                    name,
                    emailIsVerified);

                SignInUser(newUser, true);
            }
        }
 private void LoadSettings()
 {
     //siteSettings = CacheHelper.GetCurrentSiteSettings();
     SiteRoot = SiteUtils.GetNavigationSiteRoot();
 }
        private void LoadSettings()
        {
            //avatarPath = Page.ResolveUrl("~/Data/Sites/" + siteSettings.SiteId.ToInvariantString() + "/useravatars/");

            UntrustedContent2.TrustedImageUrlPattern = allowedImageUrlRegexPattern;

            allowView  = WebUser.IsInRoles(siteSettings.RolesThatCanViewMemberList);
            userID     = WebUtils.ParseInt32FromQueryString("userid", true, userID);
            timeOffset = SiteUtils.GetUserTimeOffset();
            timeZone   = SiteUtils.GetUserTimeZone();
            userGuid   = WebUtils.ParseGuidFromQueryString("u", Guid.Empty);

            if (userID > -1)
            {
                siteUser = new SiteUser(siteSettings, userID);
                if (siteUser.UserGuid == Guid.Empty)
                {
                    siteUser = null;
                }
            }
            else if (userGuid != Guid.Empty)
            {
                siteUser = new SiteUser(siteSettings, userGuid);
                if (siteUser.UserGuid == Guid.Empty)
                {
                    siteUser = null;
                }
            }

            switch (siteSettings.AvatarSystem)
            {
            case "gravatar":
                allowGravatars = true;
                disableAvatars = false;
                break;

            case "internal":
                allowGravatars = false;
                disableAvatars = false;

                break;

            case "none":
            default:
                allowGravatars = false;
                disableAvatars = true;
                break;
            }

            if (displaySettings.OverrideAvatarLabel.Length > 0)
            {
                lblAvatar.ConfigKey = displaySettings.OverrideAvatarLabel;
            }

            if (displaySettings.HidePostCount)
            {
                divForumPosts.Visible = false;
            }

            AddClassToBody("profileview");
        }
        private void PopulateControls()
        {
            if (order == null)
            {
                return;
            }

            Title           = SiteUtils.FormatPageTitle(siteSettings, " - " + WebStoreResources.OrderDetailHeader + " - " + order.OrderGuid.ToString());
            lblOrderId.Text = order.OrderGuid.ToString();

            litOrderDate.Text     = order.Completed.AddHours(timeOffset).ToShortDateString();
            litSubTotal.Text      = order.SubTotal.ToString("c", currencyCulture);
            litDiscount.Text      = order.Discount.ToString("c", currencyCulture);
            litShippingTotal.Text = order.ShippingTotal.ToString("c", currencyCulture);
            litTaxTotal.Text      = order.TaxTotal.ToString("c", currencyCulture);
            litOrderTotal.Text    = order.OrderTotal.ToString("c", currencyCulture);

            pnlDiscount.Visible      = (order.Discount > 0);
            pnlShippingTotal.Visible = (order.ShippingTotal > 0);
            pnlTaxTotal.Visible      = (order.TaxTotal > 0);

            if ((order.ShippingTotal == 0) && (order.TaxTotal == 0) && (order.Discount == 0))
            {
                pnlSubTotal.Visible = false;
            }

            //using (IDataReader reader = order.GetProducts())
            //{
            //    rptOrderItems.DataSource = reader;
            //    rptOrderItems.DataBind();
            //}

            dsOffers             = Order.GetOrderOffersAndProducts(store.Guid, orderGuid);
            rptOffers.DataSource = dsOffers;
            rptOffers.DataBind();
            // once payment has cleared, status will be fullfillable or fullfilled
            // pending payments are common for echeck or overseas accounts
            // lets not give them the ability to download until payment has cleared
            if (order.StatusGuid == OrderStatus.OrderStatusReceivedGuid)
            {
                lblPaymentPending.Text = WebStoreResources.PaymentPendingMessage;
            }
            else
            {
                downloadTickets = order.GetDownloadTickets();
                if (downloadTickets.Count > 0)
                {
                    if ((siteUser != null) && (order.UserGuid == siteUser.UserGuid))
                    {
                        pnlDownloadItems.Visible    = true;
                        rptDownloadItems.DataSource = downloadTickets;
                        rptDownloadItems.DataBind();
                    }
                    else
                    {
                        if (siteUser == null)
                        {
                            lblMustSignInToDownload.Visible = true;
                        }
                    }
                }
            }

            PopulateCustomerInfo();
            DoGoogleAnalyticsTracking();
        }
        private void PopulateCustomerInfo()
        {
            if (order == null)
            {
                return;
            }
            if (siteUser == null)
            {
                return;
            }
            if (siteUser.UserGuid != order.UserGuid)
            {
                return;
            }
            // don't show customer information in the page ifnot using ssl
            if (!SiteUtils.IsSecureRequest() && !commerceConfig.PaymentGatewayUseTestMode)
            {
                return;
            }

            pnlCustomer.Visible = true;

            litBillingName.Text = order.BillingFirstName + " " + order.BillingLastName + "<br />";

            if (order.BillingCompany.Length > 0)
            {
                litBillingCompany.Text = order.BillingCompany + "<br />";
            }

            litBillingAddress1.Text = order.BillingAddress1 + "<br />";

            if (order.BillingAddress2.Length > 0)
            {
                litBillingAddress2.Text = order.BillingAddress2 + "<br />";
            }

            if (order.BillingSuburb.Length > 0)
            {
                litBillingSuburb.Text = order.BillingSuburb + "<br />";
            }

            litBillingCity.Text       = order.BillingCity + ",&nbsp;";
            litBillingState.Text      = order.BillingState + "&nbsp;&nbsp;";
            litBillingPostalCode.Text = order.BillingPostalCode + "<br />";
            litBillingCountry.Text    = order.BillingCountry + "<br />";

            if (order.HasShippingProducts())
            {
                pnlShippingAddress.Visible = true;

                litShippingName.Text = order.DeliveryFirstName + " " + order.DeliveryLastName + "<br />";

                if (order.DeliveryCompany.Length > 0)
                {
                    litShippingCompany.Text = order.DeliveryCompany + "<br />";
                }

                litShippingAddress1.Text = order.DeliveryAddress1 + "<br />";

                if (order.DeliveryAddress2.Length > 0)
                {
                    litShippingAddress2.Text = order.DeliveryAddress2 + "<br />";
                }

                if (order.DeliverySuburb.Length > 0)
                {
                    litShippingSuburb.Text = order.DeliverySuburb + "<br />";
                }

                litShippingCity.Text       = order.DeliveryCity + ",&nbsp;";
                litShippingState.Text      = order.DeliveryState + "&nbsp;&nbsp;";
                litShippingPostalCode.Text = order.DeliveryPostalCode + "<br />";
                litShippingCountry.Text    = order.DeliveryCountry + "<br />";
            }
        }
Exemple #10
0
        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);

            if (HttpContext.Current == null)
            {
                return;
            }

            //if (useDefaultDimensions)
            //{
            //    //if (Width == Unit.Empty) { Width = Unit.Pixel(600); }
            //    //if (Height == Unit.Empty) { Height = Unit.Pixel(400); }
            //}

            // zero these out so they are not automatically added
            // we will add it manually with Atrributes.Add
            Width = Unit.Empty;
            //Height = Unit.Empty;

            if (
                (!mapWidth.EndsWith("px")) &&
                (!mapWidth.EndsWith("%"))
                )
            {
                mapWidth += "px";
            }

            //if (
            //    (!mapHeight.EndsWith("px"))
            //    && (!mapHeight.EndsWith("%"))
            //)
            //{
            //    mapHeight += "px";
            //}

            if (SiteUtils.UseMobileSkin())
            {
                //Width = Unit.Percentage(98);
                mapWidth = "98%";
            }

            Attributes.Add("style", "width:" + mapWidth + ";height:" + Height.ToString() + ";");

            if (CssClass.Length == 0)
            {
                CssClass = "bmap";
            }

            if (autoSetMarket)
            {
                market = GetMarket();
            }

            if (SiteUtils.IsSecureRequest())
            {
                protocol      = "https";
                securityParam = "&amp;s=1";
            }

            SetupScripts();
        }
        private void Page_Load(object sender, EventArgs e)
        {
            if (SiteUtils.SslIsAvailable() && (siteSettings.UseSslOnAllPages || CurrentPage.RequireSsl))
            {
                SiteUtils.ForceSsl();
            }
            else
            {
                SiteUtils.ClearSsl();
            }
            LoadParams();

            if (!UserCanViewPage(moduleId, Blog.FeatureGuid))
            {
                if (!Request.IsAuthenticated)
                {
                    SiteUtils.RedirectToLoginPage(this, Request.RawUrl);
                    return;
                }

                SiteUtils.RedirectToAccessDeniedPage(this);
                return;
            }

            LoadSettings();


            if (!IsPostBack)
            {
                if ((moduleId > -1) && (categoryId > -1))
                {
                    using (IDataReader reader = Blog.GetCategory(categoryId))
                    {
                        if (reader.Read())
                        {
                            this.category = reader["Category"].ToString();
                        }
                    }

                    string prefixLabel = BlogResources.BlogCategoriesPrefixLabel;
                    if (displaySettings.OverrideCategoryPrefixLabel.Length > 0)
                    {
                        prefixLabel = displaySettings.OverrideCategoryPrefixLabel;
                    }

                    heading.Text = Page.Server.HtmlEncode(prefixLabel + category);

                    if (blogModule != null)
                    {
                        Title = SiteUtils.FormatPageTitle(siteSettings,
                                                          blogModule.ModuleTitle + " - " + prefixLabel + category);

                        MetaDescription = string.Format(CultureInfo.InvariantCulture,
                                                        BlogResources.CategoryMetaDescriptionFormat,
                                                        blogModule.ModuleTitle, category);
                    }
                }
            }

            LoadSideContent(config.ShowLeftContent, config.ShowRightContent);
            LoadAltContent(BlogConfiguration.ShowTopContent, BlogConfiguration.ShowBottomContent);
            AnalyticsSection = ConfigHelper.GetStringProperty("AnalyticsBlogSection", "blog");
        }
        private void LoadSettings()
        {
            if (siteSettings == null)
            {
                return;
            }

            TimeOffset      = SiteUtils.GetUserTimeOffset();
            timeZone        = SiteUtils.GetUserTimeZone();
            showUserRevenue = (WebConfigSettings.ShowRevenueInForums && isCommerceReportViewer);
            currencyCulture = ResourceHelper.GetCurrencyCulture(siteSettings.GetCurrency().Code);
            filterContentFromTrustedUsers = ForumConfiguration.FilterContentFromTrustedUsers;
            if (ForumConfiguration.AllowExternalImages)
            {
                allowedImageUrlRegexPattern = SecurityHelper.RegexAnyImageUrlPatern;
            }

            IsModerator = isEditable;

            if (forum != null)
            {
                if (WebUser.IsInRoles(forum.RolesThatCanModerate))
                {
                    IsModerator = true;
                }
            }

            switch (siteSettings.AvatarSystem)
            {
            case "gravatar":
                allowGravatars = true;
                disableAvatars = false;
                break;

            case "internal":
                allowGravatars = false;
                disableAvatars = false;
                break;

            case "none":
            default:
                allowGravatars = false;
                disableAvatars = true;
                break;
            }

            if (displaySettings.HideAvatars)
            {
                allowGravatars = false;
                disableAvatars = true;
            }

            notificationUrl = SiteRoot + "/Forums/EditSubscriptions.aspx?mid="
                              + moduleId.ToInvariantString()
                              + "&pageid=" + PageId.ToInvariantString() + "#forum" + ItemId.ToInvariantString();

            pnlNotify.Visible = (!isSubscribedToForum) && !displaySettings.HideNotificationLinkOnPostList;
            if (!Request.IsAuthenticated)
            {
                pnlNotify.Visible = false;
            }

            if (WebConfigSettings.LoginPageRelativeUrl.Length > 0)
            {
                lnkLogin.NavigateUrl       = SiteRoot + WebConfigSettings.LoginPageRelativeUrl + "?returnurl=" + Server.UrlEncode(Request.RawUrl);
                lnkLoginBottom.NavigateUrl = SiteRoot + WebConfigSettings.LoginPageRelativeUrl + "?returnurl=" + Server.UrlEncode(Request.RawUrl);
            }
            else
            {
                lnkLogin.NavigateUrl       = SiteRoot + "/Secure/Login.aspx?returnurl=" + Server.UrlEncode(Request.RawUrl);
                lnkLoginBottom.NavigateUrl = SiteRoot + "/Secure/Login.aspx?returnurl=" + Server.UrlEncode(Request.RawUrl);
            }
        }
Exemple #13
0
        private void PopulateLabels()
        {
            Title = SiteUtils.FormatPageTitle(siteSettings, MyPageResources.MyPageLink);

            MetaDescription = string.Format(CultureInfo.InvariantCulture,
                                            MyPageResources.MetaDescriptionMyPageFormat, siteSettings.SiteName);


            cmdCatalogView.Visible = isAutheticated;
            cmdPersonalizationModeToggle.Visible = (isAdmin || isSiteEditor);
            cmdCatalogView.ImageUrl      = ImageSiteRoot + "/Data/SiteImages/add.png";
            cmdCatalogView.AlternateText = MyPageResources.WebPartManagerCatalogTooltip;
            cmdCatalogView.ToolTip       = MyPageResources.WebPartManagerCatalogTooltip;

            cmdResetPersonalization.Visible       = isAutheticated;
            cmdResetPersonalization.ImageUrl      = ImageSiteRoot + "/Data/SiteImages/FeatureIcons/trash.gif";
            cmdResetPersonalization.AlternateText = MyPageResources.WebPartManagerResetButton;
            cmdResetPersonalization.ToolTip       = MyPageResources.WebPartManagerResetButton;

            //cmdPersonalizationModeToggle.AlternateText
            //    = Resource.MyPageToggleScopeLabel;

            WebPartManager1.DeleteWarning = MyPageResources.MyPageDeleteWarning;

            LeftWebPartZone.CloseVerb.Text           = MyPageResources.WebPartCloseVerbText;
            LeftWebPartZone.CloseVerb.Description    = MyPageResources.WebPartCloseVerbDescription;
            LeftWebPartZone.CloseVerb.ImageUrl       = ImageSiteRoot + "/Data/SiteImages/close.png";
            LeftWebPartZone.DeleteVerb.Text          = MyPageResources.WebPartDeleteVerbText;
            LeftWebPartZone.DeleteVerb.Description   = MyPageResources.WebPartDeleteVerbDescription;
            LeftWebPartZone.DeleteVerb.ImageUrl      = ImageSiteRoot + "/Data/SiteImages/del.png";
            LeftWebPartZone.MinimizeVerb.Text        = MyPageResources.WebPartMinimizeVerbText;
            LeftWebPartZone.MinimizeVerb.Description = MyPageResources.WebPartMinimizeVerbDescription;
            LeftWebPartZone.MinimizeVerb.ImageUrl    = ImageSiteRoot + "/Data/SiteImages/min.png";
            LeftWebPartZone.RestoreVerb.Text         = MyPageResources.WebPartRestoreVerbText;
            LeftWebPartZone.RestoreVerb.Description  = MyPageResources.WebPartRestoreVerbDescription;
            LeftWebPartZone.RestoreVerb.ImageUrl     = ImageSiteRoot + "/Data/SiteImages/max.png";
            LeftWebPartZone.EditVerb.Text            = MyPageResources.WebPartEditVerbText;
            LeftWebPartZone.EditVerb.Description     = MyPageResources.WebPartEditVerbDescription;
            LeftWebPartZone.EditVerb.ImageUrl        = ImageSiteRoot + "/Data/SiteImages/editsettings.png";

            LeftWebPartZone.HelpVerb.Text          = MyPageResources.WebPartHelpVerbText;
            LeftWebPartZone.HelpVerb.Description   = MyPageResources.WebPartHelpVerbDescription;
            LeftWebPartZone.ExportVerb.Text        = MyPageResources.WebPartExportVerbText;
            LeftWebPartZone.ExportVerb.Description = MyPageResources.WebPartExportVerbDescription;
            LeftWebPartZone.EditVerb.Text          = MyPageResources.WebPartEditVerbText;
            LeftWebPartZone.EditVerb.Description   = MyPageResources.WebPartEditVerbDescription;
            LeftWebPartZone.TitleBarVerbButtonType = ButtonType.Image;
            LeftWebPartZone.EmptyZoneText          = MyPageResources.WebPartEmptyZoneText;

            CenterWebPartZone.CloseVerb.Text           = MyPageResources.WebPartCloseVerbText;
            CenterWebPartZone.CloseVerb.Description    = MyPageResources.WebPartCloseVerbDescription;
            CenterWebPartZone.CloseVerb.ImageUrl       = ImageSiteRoot + "/Data/SiteImages/close.png";
            CenterWebPartZone.DeleteVerb.Text          = MyPageResources.WebPartDeleteVerbText;
            CenterWebPartZone.DeleteVerb.Description   = MyPageResources.WebPartDeleteVerbDescription;
            CenterWebPartZone.DeleteVerb.ImageUrl      = ImageSiteRoot + "/Data/SiteImages/del.png";
            CenterWebPartZone.MinimizeVerb.Text        = MyPageResources.WebPartMinimizeVerbText;
            CenterWebPartZone.MinimizeVerb.Description = MyPageResources.WebPartMinimizeVerbDescription;
            CenterWebPartZone.MinimizeVerb.ImageUrl    = ImageSiteRoot + "/Data/SiteImages/min.png";
            CenterWebPartZone.RestoreVerb.Text         = MyPageResources.WebPartRestoreVerbText;
            CenterWebPartZone.RestoreVerb.Description  = MyPageResources.WebPartRestoreVerbDescription;
            CenterWebPartZone.RestoreVerb.ImageUrl     = ImageSiteRoot + "/Data/SiteImages/max.png";
            CenterWebPartZone.EditVerb.Text            = MyPageResources.WebPartEditVerbText;
            CenterWebPartZone.EditVerb.Description     = MyPageResources.WebPartEditVerbDescription;
            CenterWebPartZone.EditVerb.ImageUrl        = ImageSiteRoot + "/Data/SiteImages/editsettings.png";
            CenterWebPartZone.HelpVerb.Text            = MyPageResources.WebPartHelpVerbText;
            CenterWebPartZone.HelpVerb.Description     = MyPageResources.WebPartHelpVerbDescription;
            CenterWebPartZone.ExportVerb.Text          = MyPageResources.WebPartExportVerbText;
            CenterWebPartZone.ExportVerb.Description   = MyPageResources.WebPartExportVerbDescription;
            CenterWebPartZone.EditVerb.Text            = MyPageResources.WebPartEditVerbText;
            CenterWebPartZone.EditVerb.Description     = MyPageResources.WebPartEditVerbDescription;
            CenterWebPartZone.TitleBarVerbButtonType   = ButtonType.Image;
            CenterWebPartZone.EmptyZoneText            = MyPageResources.WebPartEmptyZoneText;

            RightWebPartZone.CloseVerb.Text           = MyPageResources.WebPartCloseVerbText;
            RightWebPartZone.CloseVerb.Description    = MyPageResources.WebPartCloseVerbDescription;
            RightWebPartZone.CloseVerb.ImageUrl       = ImageSiteRoot + "/Data/SiteImages/close.png";
            RightWebPartZone.DeleteVerb.Text          = MyPageResources.WebPartDeleteVerbText;
            RightWebPartZone.DeleteVerb.Description   = MyPageResources.WebPartDeleteVerbDescription;
            RightWebPartZone.DeleteVerb.ImageUrl      = ImageSiteRoot + "/Data/SiteImages/del.png";
            RightWebPartZone.MinimizeVerb.Text        = MyPageResources.WebPartMinimizeVerbText;
            RightWebPartZone.MinimizeVerb.Description = MyPageResources.WebPartMinimizeVerbDescription;
            RightWebPartZone.MinimizeVerb.ImageUrl    = ImageSiteRoot + "/Data/SiteImages/min.png";
            RightWebPartZone.RestoreVerb.Text         = MyPageResources.WebPartRestoreVerbText;
            RightWebPartZone.RestoreVerb.Description  = MyPageResources.WebPartRestoreVerbDescription;
            RightWebPartZone.RestoreVerb.ImageUrl     = ImageSiteRoot + "/Data/SiteImages/max.png";
            RightWebPartZone.EditVerb.Text            = MyPageResources.WebPartEditVerbText;
            RightWebPartZone.EditVerb.Description     = MyPageResources.WebPartEditVerbDescription;
            RightWebPartZone.EditVerb.ImageUrl        = ImageSiteRoot + "/Data/SiteImages/editsettings.png";
            RightWebPartZone.HelpVerb.Text            = MyPageResources.WebPartHelpVerbText;
            RightWebPartZone.HelpVerb.Description     = MyPageResources.WebPartHelpVerbDescription;
            RightWebPartZone.ExportVerb.Text          = MyPageResources.WebPartExportVerbText;
            RightWebPartZone.ExportVerb.Description   = MyPageResources.WebPartExportVerbDescription;
            RightWebPartZone.EditVerb.Text            = MyPageResources.WebPartEditVerbText;
            RightWebPartZone.EditVerb.Description     = MyPageResources.WebPartEditVerbDescription;
            RightWebPartZone.TitleBarVerbButtonType   = ButtonType.Image;
            RightWebPartZone.EmptyZoneText            = MyPageResources.WebPartEmptyZoneText;

            CatalogZone1.HeaderCloseVerb.Visible = false;
            CatalogZone1.CloseVerb.Visible       = false;

            CatalogZone1.AddVerb.Text        = MyPageResources.WebPartAddVerbText;
            CatalogZone1.AddVerb.Description = MyPageResources.WebPartAddVerbDescription;
            CatalogZone1.EmptyZoneText       = MyPageResources.WebPartEmptyCatalogZoneText;
            CatalogZone1.InstructionText     = String.Empty;
            //CatalogZone1.SelectTargetZoneText =

            EditorZone1.HeaderText      = MyPageResources.WebPartEditorHeaderText;
            EditorZone1.InstructionText = MyPageResources.WebPartEditorInstructionsText;

            EditorZone1.ApplyVerb.Text              = MyPageResources.WebPartEditorApplyVerbText;
            EditorZone1.ApplyVerb.Description       = MyPageResources.WebPartEditorApplyVerbDescription;
            EditorZone1.CancelVerb.Text             = MyPageResources.WebPartEditorCancelVerbText;
            EditorZone1.CancelVerb.Description      = MyPageResources.WebPartEditorCancelVerbDescription;
            EditorZone1.HeaderCloseVerb.Text        = MyPageResources.WebPartEditorHeaderCloseVerbText;
            EditorZone1.HeaderCloseVerb.Description = MyPageResources.WebPartEditorHeaderCloseVerbDescription;
            EditorZone1.OKVerb.Text        = MyPageResources.WebPartEditorOKVerbText;
            EditorZone1.OKVerb.Description = MyPageResources.WebPartEditorOKVerbDescription;


            PageCatalogPart1 = (PageCatalogPart)CatalogZone1.FindControl("PageCatalogPart1");
            if (PageCatalogPart1 != null)
            {
                PageCatalogPart1.Description = MyPageResources.WebPartPageCatalogTitle;
                PageCatalogPart1.Title       = MyPageResources.WebPartPageCatalogDescription;
            }



            if (WebPartManager1.Personalization.Scope == PersonalizationScope.User)
            {
                cmdPersonalizationModeToggle.ImageUrl = ImageSiteRoot
                                                        + "/Data/SiteImages/scope_user.png";

                cmdPersonalizationModeToggle.AlternateText = MyPageResources.WebPartManagerToggleFromUserModeTooltip;
                cmdPersonalizationModeToggle.ToolTip       = MyPageResources.WebPartManagerToggleFromUserModeTooltip;
            }
            else
            {
                cmdPersonalizationModeToggle.ImageUrl = ImageSiteRoot
                                                        + "/Data/SiteImages/scope_shared.png";

                cmdPersonalizationModeToggle.AlternateText = MyPageResources.WebPartManagerToggleToUserModeTooltip;
                cmdPersonalizationModeToggle.ToolTip       = MyPageResources.WebPartManagerToggleToUserModeTooltip;
            }


            btnNewPage.Text          = MyPageResources.MyPageNewPageButton;
            btnCancelAddPage.Text    = MyPageResources.MyPageCancelNewPageButton;
            btnChangeName.Text       = MyPageResources.MyPageRenamePageButton;
            btnCancelChangeName.Text = MyPageResources.MyPageCancelRenamePageButton;
        }
Exemple #14
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if ((SiteUtils.SslIsAvailable()) && (WebConfigSettings.UseSslForMyPage))
            {
                SiteUtils.ForceSsl();
            }
            else
            {
                SiteUtils.ClearSsl();
            }

            if (!siteSettings.EnableMyPageFeature)
            {
                allowView = false;
            }
            if (!WebConfigSettings.MyPageIsInstalled)
            {
                allowView = false;
            }

            if (!WebUser.IsInRoles(siteSettings.RolesThatCanViewMyPage))
            {
                allowView = false;
            }

            if (!allowView)
            {
                SiteUtils.RedirectToAccessDeniedPage();
                return;
            }


            //WebPartManager1 = WebPartManager.GetCurrentWebPartManager(Page);

            if (Request.IsAuthenticated)
            {
                currentUser = SiteUtils.GetCurrentSiteUser();

                isAutheticated = true;
                if (WebUser.IsAdminOrContentAdmin)
                {
                    isAdmin = true;
                }
                isSiteEditor = SiteUtils.UserIsSiteEditor();
            }

            SetupCss();
            EnsureUserPage();
            PopulateLabels();

            if (Request.IsAuthenticated)
            {
                // TODO: to support anonymous session
                // personalization need to figure out how thy are doing it
                // at pageflakes to enable edit mode when unauthenticated
                if (!IsPostBack)
                {
                    BindUserMenu();
                    WebPartManager1.DisplayMode = WebPartManager.EditDisplayMode;

                    // I don't want the zone titles to display unless
                    // in catalog view. If set to String.Emtpy it doesn't
                    // make them blank but shows the server side id instead
                    // setting to a space works for clearing it
                    LeftWebPartZone.HeaderText   = " ";
                    CenterWebPartZone.HeaderText = " ";
                    RightWebPartZone.HeaderText  = " ";
                    CatalogZone1.HeaderText      = " ";
                }
            }

            if (!IsPostBack)
            {
                this.pnlAddPage.Visible    = false;
                this.pnlChangeName.Visible = false;
            }
        }
Exemple #15
0
        private void btnUpdate_Click(object sender, EventArgs e)
        {
            Page.Validate("feeds");
            if (!Page.IsValid)
            {
                return;
            }

            RssFeed feed = new RssFeed(ModuleId, ItemId);

            feed.ModuleId = ModuleId;
            feed.Author   = txtAuthor.Text;
            feed.Url      = txtWebSite.Text;
            feed.RssUrl   = txtRssUrl.Text;
            feed.ImageUrl = txtImageUrl.Text;
            int sortRank = 500;

            int.TryParse(txtSortRank.Text, out sortRank);
            feed.SortRank = sortRank;

            SiteUser siteUser = SiteUtils.GetCurrentSiteUser();

            if (siteUser == null)
            {
                return;
            }

            Module module = new Module(ModuleId);

            feed.ModuleGuid       = module.ModuleGuid;
            feed.UserId           = siteUser.UserId;
            feed.UserGuid         = siteUser.UserGuid;
            feed.LastModUserGuid  = siteUser.UserGuid;
            feed.PublishByDefault = chkPublishByDefault.Checked;

            if (feed.Save())
            {
                CurrentPage.UpdateLastModifiedTime();

                FeedCache.RefreshFeed(
                    feed,
                    ModuleId,
                    module.ModuleGuid,
                    _maxDaysOld,
                    _maxEntriesPerFeed,
                    EnableSelectivePublishing);


                String rssFriendlyUrl = "aggregator" + ModuleId.ToString(CultureInfo.InvariantCulture) + "rss.aspx";
                if (!FriendlyUrl.Exists(siteSettings.SiteId, rssFriendlyUrl))
                {
                    FriendlyUrl friendlyUrl = new FriendlyUrl();
                    friendlyUrl.SiteId   = siteSettings.SiteId;
                    friendlyUrl.SiteGuid = siteSettings.SiteGuid;
                    friendlyUrl.Url      = rssFriendlyUrl;
                    friendlyUrl.RealUrl  = "~/FeedManager/FeedAggregate.aspx?mid=" + ModuleId.ToString(CultureInfo.InvariantCulture);
                    friendlyUrl.Save();
                }

                if (hdnReturnUrl.Value.Length > 0)
                {
                    WebUtils.SetupRedirect(this, hdnReturnUrl.Value);
                    return;
                }

                WebUtils.SetupRedirect(this, SiteUtils.GetCurrentPageUrl());
            }
        }
        void app_Error(object sender, EventArgs e)
        {
            HttpApplication app = sender as HttpApplication;

            if (app == null)
            {
                return;
            }

            if (
                (app.Request.Path.EndsWith(".gif", StringComparison.InvariantCultureIgnoreCase)) ||
                (app.Request.Path.EndsWith(".js", StringComparison.InvariantCultureIgnoreCase)) ||
                (app.Request.Path.EndsWith(".png", StringComparison.InvariantCultureIgnoreCase)) ||
                (app.Request.Path.EndsWith(".jpg", StringComparison.InvariantCultureIgnoreCase)) ||
                (app.Request.Path.EndsWith(".css", StringComparison.InvariantCultureIgnoreCase)) ||
                (app.Request.Path.EndsWith(".axd", StringComparison.InvariantCultureIgnoreCase)) ||
                (app.Request.Path.EndsWith(".ashx", StringComparison.InvariantCultureIgnoreCase))
                )
            {
                // don't handle 404 errors for images and javascript files and web services
                return;
            }

            Exception ex = null;

            try
            {
                Exception rawException = app.Server.GetLastError();
                if (rawException != null)
                {
                    if (rawException.InnerException != null)
                    {
                        ex = rawException.InnerException;
                    }
                    else
                    {
                        ex = rawException;
                    }
                }

                // too bad 404 errors don't throw FileNotFoundException, this is ugly but works
                if (ex is HttpException)
                {
                    if (
                        (ex.Message.Contains(aspnet404ErrorMarker)) ||
                        (ex.Message.Contains(mono404ErrorMarker)) ||
                        (ex.StackTrace.Contains(aspnet404StackTraceMarker)) ||
                        (ex.StackTrace.Contains(mono404StackTraceMarker))
                        )
                    {
                        log.Error(SiteUtils.GetIP4Address() + "  PageNotFoundHttpModule handled error.", ex);
                        app.Server.ClearError();
#if !MONO
                        // this solves the IIS 7 issue where the standard 404 page was returned
                        //http://www.west-wind.com/weblog/posts/745738.aspx
                        app.Context.Response.TrySkipIisCustomErrors = true;
#endif
                        app.Context.Response.StatusCode = 404;
                        app.Context.Response.Write(GetCustom404Html());
                        app.Context.Response.End();
                    }
                    else
                    {
                        if (WebConfigSettings.LogErrorsFrom404Handler)
                        {
                            log.Info("PageNotFoundHttpModule ignoring error ", ex);
                        }
                    }
                }
            }
            catch (Exception ex2)
            {
                log.Info("PageNotFoundHttpModule swallowed error", ex2);
            }
        }
        private void SetToolBar()
        {
            string siteRoot = SiteUtils.GetNavigationSiteRoot();

            switch (toolBar)
            {
            case ToolBar.Full:

                Editor.FileManagerUrl    = siteRoot + WebConfigSettings.FileDialogRelativeUrl;
                Editor.EnableFileBrowser = true;
                Editor.StylesJsonUrl     = siteRoot + "/Services/CKeditorStyles.ashx?cb=" + Guid.NewGuid().ToString().Replace("-", string.Empty);
                Editor.DropFileUploadUrl = siteRoot + "/Services/FileService.ashx?cmd=uploadfromeditor&rz=true&ko=" + WebConfigSettings.KeepFullSizeImagesDroppedInEditor.ToString().ToLower()
                                           + "&t=" + Global.FileSystemToken.ToString();

                break;

            case ToolBar.FullWithTemplates:


                //string sRoot = SiteUtils.GetNavigationSiteRoot();
                Editor.FileManagerUrl    = siteRoot + WebConfigSettings.FileDialogRelativeUrl;
                Editor.EnableFileBrowser = true;
                //string navRoot = SiteUtils.GetNavigationSiteRoot();
                Editor.TemplatesJsonUrl = siteRoot + "/Services/CKeditorTemplates.ashx?cb=" + Guid.NewGuid().ToString();     //prevent caching with a guid param
                //Editor.TemplatesXmlUrl = navRoot + "/Services/HtmlTemplates.ashx?cb=" + Guid.NewGuid().ToString();
                Editor.StylesJsonUrl = siteRoot + "/Services/CKeditorStyles.ashx?cb=" + Guid.NewGuid().ToString().Replace("-", string.Empty);
                //Editor.StylesJsonUrl =  "/ckstyles.js";
                Editor.DropFileUploadUrl = siteRoot + "/Services/FileService.ashx?cmd=uploadfromeditor&rz=true&ko=" + WebConfigSettings.KeepFullSizeImagesDroppedInEditor.ToString().ToLower()
                                           + "&t=" + Global.FileSystemToken.ToString();

                break;

            case ToolBar.Newsletter:

                Editor.FileManagerUrl    = siteRoot + WebConfigSettings.FileDialogRelativeUrl;
                Editor.EnableFileBrowser = true;
                Editor.FullPageMode      = true;
                //Editor.CustomConfigPath = "~/ClientScript/ckeditor-mojo-newsletterconfig.js";


                break;

            case ToolBar.ForumWithImages:


                Editor.FileManagerUrl        = siteRoot + WebConfigSettings.FileDialogRelativeUrl;
                Editor.EnableFileBrowser     = true;
                Editor.ForcePasteAsPlainText = true;

                break;

            case ToolBar.Forum:


                Editor.ForcePasteAsPlainText = true;


                break;



            case ToolBar.AnonymousUser:



                break;

            case ToolBar.SimpleWithSource:



                break;
            }
        }
Exemple #18
0
        public void ProcessRequest(HttpContext context)
        {
            base.Initialize(context);

            if (!UserCanEditModule(ModuleId, Gallery.FeatureGuid))
            {
                log.Info("User has no edit permission so returning 404");
                Response.StatusCode = 404;
                return;
            }

            if (CurrentSite == null)
            {
                log.Info("CurrentSite is null so returning 404");
                Response.StatusCode = 404;
                return;
            }

            if (CurrentUser == null)
            {
                log.Info("CurrentUser is null so returning 404");
                Response.StatusCode = 404;
                return;
            }

            if (FileSystem == null)
            {
                log.Info("FileSystem is null so returning 404");
                Response.StatusCode = 404;
                return;
            }

            if (Request.Files.Count == 0)
            {
                log.Info("Posted File Count is zero so returning 404");
                Response.StatusCode = 404;
                return;
            }

            if (Request.Files.Count > GalleryConfiguration.MaxFilesToUploadAtOnce)
            {
                log.Info("Posted File Count is higher than allowed so returning 404");
                Response.StatusCode = 404;
                return;
            }

            module = GetModule(ModuleId, Gallery.FeatureGuid);

            if (module == null)
            {
                log.Info("Module is null so returning 404");
                Response.StatusCode = 404;
                return;
            }

            itemId = WebUtils.ParseInt32FromQueryString("ItemID", itemId);

            //if (Request.Form.Count > 0)
            //{
            //    string submittedContent = Server.UrlDecode(Request.Form.ToString()); // this gets the full content of the post
            //    log.Info("submitted data: " + submittedContent);
            //}


            Hashtable moduleSettings = ModuleSettings.GetModuleSettings(ModuleId);

            config = new GalleryConfiguration(moduleSettings);

            string imageFolderPath;
            string fullSizeImageFolderPath;

            if (WebConfigSettings.ImageGalleryUseMediaFolder)
            {
                imageFolderPath = "~/Data/Sites/" + CurrentSite.SiteId.ToInvariantString() + "/media/GalleryImages/" + ModuleId.ToInvariantString() + "/";
            }
            else
            {
                imageFolderPath = "~/Data/Sites/" + CurrentSite.SiteId.ToInvariantString() + "/GalleryImages/" + ModuleId.ToInvariantString() + "/";
            }

            fullSizeImageFolderPath = imageFolderPath + "FullSizeImages/";
            string thumbnailPath = imageFolderPath + "Thumbnails/";

            context.Response.ContentType = "text/plain";//"application/json";
            var r = new System.Collections.Generic.List <UploadFilesResult>();
            JavaScriptSerializer js = new JavaScriptSerializer();

            for (int f = 0; f < Request.Files.Count; f++)
            {
                HttpPostedFile file = Request.Files[f];

                string ext = Path.GetExtension(file.FileName);
                if (SiteUtils.IsAllowedUploadBrowseFile(ext, ".jpg|.gif|.png|.jpeg"))
                {
                    GalleryImage galleryImage;

                    if ((itemId > -1) && (Request.Files.Count == 1))
                    {
                        galleryImage = new GalleryImage(ModuleId, itemId);
                    }
                    else
                    {
                        galleryImage = new GalleryImage(ModuleId);
                    }

                    galleryImage.ModuleGuid      = module.ModuleGuid;
                    galleryImage.WebImageHeight  = config.WebSizeHeight;
                    galleryImage.WebImageWidth   = config.WebSizeWidth;
                    galleryImage.ThumbNailHeight = config.ThumbnailHeight;
                    galleryImage.ThumbNailWidth  = config.ThumbnailWidth;
                    galleryImage.UploadUser      = CurrentUser.Name;

                    galleryImage.UserGuid = CurrentUser.UserGuid;

                    string newFileName  = Path.GetFileName(file.FileName).ToCleanFileName(WebConfigSettings.ForceLowerCaseForUploadedFiles);
                    string newImagePath = VirtualPathUtility.Combine(fullSizeImageFolderPath, newFileName);

                    if (galleryImage.ImageFile == newFileName)
                    {
                        // an existing gallery image delete the old one
                        FileSystem.DeleteFile(newImagePath);
                    }
                    else
                    {
                        // this is a new galleryImage instance, make sure we don't use the same file name as any other instance
                        int i = 1;
                        while (FileSystem.FileExists(VirtualPathUtility.Combine(fullSizeImageFolderPath, newFileName)))
                        {
                            newFileName = i.ToInvariantString() + newFileName;
                            i          += 1;
                        }
                    }

                    newImagePath = VirtualPathUtility.Combine(fullSizeImageFolderPath, newFileName);


                    using (Stream s = file.InputStream)
                    {
                        FileSystem.SaveFile(newImagePath, s, file.ContentType, true);
                    }


                    galleryImage.ImageFile     = newFileName;
                    galleryImage.WebImageFile  = newFileName;
                    galleryImage.ThumbnailFile = newFileName;
                    galleryImage.Save();
                    GalleryHelper.ProcessImage(galleryImage, FileSystem, imageFolderPath, file.FileName, config.ResizeBackgroundColor);

                    r.Add(new UploadFilesResult()
                    {
                        Thumbnail_url = WebUtils.ResolveServerUrl(thumbnailPath + newFileName),
                        Name          = newFileName,
                        Length        = file.ContentLength,
                        Type          = file.ContentType,
                        ReturnValue   = galleryImage.ItemId.ToInvariantString()
                    });
                }
            }

            var uploadedFiles = new
            {
                files = r.ToArray()
            };
            var jsonObj = js.Serialize(uploadedFiles);

            context.Response.Write(jsonObj.ToString());
        }
Exemple #19
0
        /// <summary>
        /// Catchall handler when errors are thrown outside the MVC pipeline
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Application_Error(object sender, EventArgs e)
        {
            var ex          = Server.GetLastError();
            var contextBase = new HttpContextWrapper(Context);

            try
            {
                if ((ex as HttpException).GetHttpCode() == 404)
                {
                    var s = "~/Home/Redir" + contextBase.Request.FilePath;
                    contextBase.RewritePath(s, false);
                    contextBase.Server.TransferRequest(s);
                }
            }
            catch {}

            if (Context.Items["ErrorID"] != null)
            {
                return;  //this one has already been handled in one of the MVC error filters
            }
            if (ex.InnerException != null)
            {
                ex = ex.InnerException;
            }

            Server.ClearError();
            if (ex == null)
            {
                return;
            }
            var code = (ex is HttpException) ? (ex as HttpException).GetHttpCode() : 500;

            var bAjax    = IsAjaxRequest();
            var sMessage = (bAjax) ? "AJAX call error" : "";
            var eid      = Logging.WriteDebugInfoToErrorLog(sMessage, ex);

            Context.Items.Add("ErrorID", eid);  //to keep us from doing this again in the same call

            Response.Clear();

            if (bAjax)
            {
                //this is a json call; tryskip will return our IDs in response.write, 500 will throw in jquery
                Response.TrySkipIisCustomErrors = true;
                Response.StatusCode             = 500;
                Response.StatusDescription      = String.Format("{0} Application Error", Utils.ApplicationName);
                Response.ContentType            = "application/json";
                Response.Write(JsonConvert.SerializeObject(new ErrResponsePoco {
                    DbErrorId = eid
                }));
                Response.End();
            }
            else
            {
                try
                {
                    SiteUtils.ReturnViaCode(contextBase, code);
                }
                // ReSharper disable once EmptyGeneralCatchClause
                catch (Exception) { }
            }
        }
Exemple #20
0
        private void LoadSettings()
        {
            bingApiId = SiteUtils.GetBingApiId();

            AddClassToBody("bingsearch");
        }
        private void PopulateControls()
        {
            if (siteUser != null)
            {
                this.lblCreatedDate.Text = siteUser.DateCreated.AddHours(timeOffset).ToString();
                this.lblTotalPosts.Text  = siteUser.TotalPosts.ToString(CultureInfo.InvariantCulture);

                this.lblUserName.Text = Server.HtmlEncode(siteUser.Name);

                Title = SiteUtils.FormatPageTitle(siteSettings, string.Format(CultureInfo.InvariantCulture,
                                                                              Resource.PageTitleFormatProfilePage, Server.HtmlEncode(siteUser.Name)));

                MetaDescription = string.Format(CultureInfo.InvariantCulture,
                                                Resource.ProfileViewMetaFormat, Server.HtmlEncode(siteUser.Name));

                userAvatar.UseGravatar      = allowGravatars;
                userAvatar.Email            = siteUser.Email;
                userAvatar.UserName         = siteUser.Name;
                userAvatar.UserId           = siteUser.UserId;
                userAvatar.AvatarFile       = siteUser.AvatarUrl;
                userAvatar.MaxAllowedRating = MaxAllowedGravatarRating;
                userAvatar.Disable          = disableAvatars;
                userAvatar.SiteId           = siteSettings.SiteId;
                userAvatar.UseLink          = false;

                if (disableAvatars)
                {
                    divAvatar.Visible = false;
                }


                //if (allowGravatars)
                //{
                //    imgAvatar.Visible = false;
                //    gravatar1.Visible = true;
                //    gravatar1.Email = siteUser.Email;
                //    //gravatar1.MaxAllowedRating = MaxAllowedGravatarRating;
                //}
                //else
                //{
                //    gravatar1.Visible = false;
                //    if (disableAvatars)
                //    {
                //        divAvatar.Visible = false;
                //    }
                //    else
                //    {
                //        if (siteUser.AvatarUrl.Length > 0)
                //        {
                //            imgAvatar.Src = avatarPath + siteUser.AvatarUrl;
                //        }
                //        else
                //        {
                //            imgAvatar.Src = Page.ResolveUrl(WebConfigSettings.DefaultBlankAvatarPath);
                //        }
                //    }
                //}

                lnkUserPosts.UserId     = siteUser.UserId;
                lnkUserPosts.TotalPosts = siteUser.TotalPosts;

                if (siteUser.TimeZoneId.Length > 0)
                {
                    TimeZoneInfo userTz = SiteUtils.GetTimeZone(siteUser.TimeZoneId);
                    if (userTz != null)
                    {
                        pnlTimeZone.Visible = true;

                        if (userTz.IsDaylightSavingTime(DateTime.UtcNow))
                        {
                            lblTimeZone.Text = userTz.DaylightNameWithOffset();
                        }
                        else
                        {
                            lblTimeZone.Text = userTz.DisplayName;
                        }
                    }
                }

                if (WebConfigSettings.UseRelatedSiteMode)
                {
                    // this can't be used in related site mode
                    // because we can't assume forum posts were in this site.
                    divForumPosts.Visible = false;
                }

                if (Request.IsAuthenticated)
                {
                    ShowAuthenticatedProperties(siteUser);
                }
                else
                {
                    ShowAnonymousProperties(siteUser);
                }


                PopulateMessenger();
            }
            else
            {
                this.lblUserName.Text = "User not found";
                divAvatar.Visible     = false;
            }
        }
        public static void ReplaceStaticTokens(
            StringBuilder stringBuilder,
            ModuleConfiguration config,
            bool isEditable,
            SuperFlexiDisplaySettings displaySettings,
            int moduleId,
            PageSettings pageSettings,
            SiteSettings siteSettings,
            out StringBuilder sb)
        {
            sb = stringBuilder;
            string featuredImageUrl = String.IsNullOrWhiteSpace(config.InstanceFeaturedImage) ? string.Empty : WebUtils.GetRelativeSiteRoot() + config.InstanceFeaturedImage;
            string jsonObjName      = "sflexi" + moduleId.ToString() + (config.IsGlobalView ? "Modules" : "Items");
            string currentSkin      = string.Empty;
            string siteRoot         = WebUtils.GetRelativeSiteRoot();

            if (HttpContext.Current != null && HttpContext.Current.Request.Params.Get("skin") != null)
            {
                currentSkin = SiteUtils.SanitizeSkinParam(HttpContext.Current.Request.Params.Get("skin")) + "/";
            }

            Module module = new Module(moduleId);

            if (module != null)
            {
                sb.Replace("$_ModuleTitle_$", module.ShowTitle ? String.Format(displaySettings.ModuleTitleFormat, module.ModuleTitle) : string.Empty);
                sb.Replace("$_RawModuleTitle_$", module.ModuleTitle);
                sb.Replace("$_ModuleGuid_$", module.ModuleGuid.ToString());
                if (String.IsNullOrWhiteSpace(config.ModuleFriendlyName))
                {
                    sb.Replace("$_FriendlyName_$", module.ModuleTitle);
                }

                siteSettings = new SiteSettings(module.SiteGuid);
            }
            if (!String.IsNullOrWhiteSpace(config.ModuleFriendlyName))
            {
                sb.Replace("$_FriendlyName_$", config.ModuleFriendlyName);
            }
            sb.Replace("$_FeaturedImageUrl_$", featuredImageUrl);
            sb.Replace("$_ModuleID_$", moduleId.ToString());
            sb.Replace("$_PageID_$", pageSettings.PageId.ToString());
            sb.Replace("$_PageUrl_$", siteRoot + pageSettings.Url.Replace("~/", ""));
            sb.Replace("$_PageName_$", siteRoot + pageSettings.PageName);
            sb.Replace("$_ModuleLinks_$", isEditable ? SuperFlexiHelpers.GetModuleLinks(config, displaySettings, moduleId, pageSettings.PageId) : string.Empty);
            sb.Replace("$_JSONNAME_$", jsonObjName);
            sb.Replace("$_ModuleClass_$", SiteUtils.IsMobileDevice() && !String.IsNullOrWhiteSpace(config.MobileInstanceCssClass) ? config.MobileInstanceCssClass : config.InstanceCssClass);
            sb.Replace("$_ModuleTitleElement_$", module.HeadElement);
            sb.Replace("$_SiteID_$", siteSettings.SiteId.ToString());
            sb.Replace("$_SiteRoot_$", String.IsNullOrWhiteSpace(siteRoot) ? "/" : siteRoot);
            sb.Replace("$_SitePath_$", String.IsNullOrWhiteSpace(siteRoot) ? "/" : WebUtils.GetApplicationRoot() + "/Data/Sites/" + CacheHelper.GetCurrentSiteSettings().SiteId.ToInvariantString());
            sb.Replace("$_SkinPath_$", SiteUtils.DetermineSkinBaseUrl(currentSkin));
            sb.Replace("$_CustomSettings_$", config.CustomizableSettings); //this needs to be enhanced, a lot, right now we just dump the 'settings' where ever this token exists.
            sb.Replace("$_EditorType_$", siteSettings.EditorProviderName);
            sb.Replace("$_EditorSkin_$", siteSettings.EditorSkin.ToString());
            sb.Replace("$_EditorBasePath_$", WebUtils.ResolveUrl(ConfigurationManager.AppSettings["CKEditor:BasePath"]));
            sb.Replace("$_EditorConfigPath_$", WebUtils.ResolveUrl(ConfigurationManager.AppSettings["CKEditor:ConfigPath"]));
            sb.Replace("$_EditorToolbarSet_$", mojoPortal.Web.Editor.ToolBar.FullWithTemplates.ToString());
            sb.Replace("$_EditorTemplatesUrl_$", siteRoot + "/Services/CKeditorTemplates.ashx?cb=" + Guid.NewGuid().ToString());
            sb.Replace("$_EditorStylesUrl_$", siteRoot + "/Services/CKeditorStyles.ashx?cb=" + Guid.NewGuid().ToString().Replace("-", string.Empty));
            sb.Replace("$_DropFileUploadUrl_$", siteRoot + "/Services/FileService.ashx?cmd=uploadfromeditor&rz=true&ko=" + WebConfigSettings.KeepFullSizeImagesDroppedInEditor.ToString().ToLower()
                       + "&t=" + Global.FileSystemToken.ToString());
            sb.Replace("$_FileBrowserUrl_$", siteRoot + WebConfigSettings.FileDialogRelativeUrl);
            sb.Replace("$_HeaderContent_$", config.HeaderContent);
            sb.Replace("$_FooterContent_$", config.FooterContent);
        }
        private void SignInUser(SiteUser user, bool isNewUser)
        {
            if (
                (siteSettings.UseSecureRegistration) &&
                (user.RegisterConfirmGuid != Guid.Empty)
                )
            {
                Notification.SendRegistrationConfirmationLink(
                    SiteUtils.GetSmtpSettings(),
                    ResourceHelper.GetMessageTemplate("RegisterConfirmEmailMessage.config"),
                    siteSettings.DefaultEmailFromAddress,
                    siteSettings.DefaultFromEmailAlias,
                    user.Email,
                    siteSettings.SiteName,
                    SiteRoot + "/ConfirmRegistration.aspx?ticket=" +
                    user.RegisterConfirmGuid.ToString());


                log.Info("User " + user.Name + " tried to login but email address is not confirmed.");

                lblError.Text = Resource.RegistrationRequiresEmailConfirmationMessage;
                litInfoNeededMessage.Visible         = false;
                pnlRequiredProfileProperties.Visible = false;
                btnCreateUser.Visible = false;

                return;
            }

            if (user.IsLockedOut)
            {
                log.Info("User " + user.Name + " tried to login but account is locked.");

                lblError.Text = Resource.LoginAccountLockedMessage;

                return;
            }

            if ((siteSettings.RequireApprovalBeforeLogin) && (!user.ApprovedForLogin))
            {
                log.Info("User " + user.Name + " tried to login but account is not approved yet.");

                lblError.Text = Resource.LoginNotApprovedMessage;

                return;
            }


            if (siteSettings.UseEmailForLogin)
            {
                FormsAuthentication.SetAuthCookie(user.Email, true);
            }
            else
            {
                FormsAuthentication.SetAuthCookie(user.LoginName, true);
            }

            if (WebConfigSettings.UseFoldersInsteadOfHostnamesForMultipleSites)
            {
                string cookieName = "siteguid" + siteSettings.SiteGuid;
                CookieHelper.SetCookie(cookieName, user.UserGuid.ToString(), true);
            }

            if (user.UserId > -1 && siteSettings.AllowUserSkins && user.Skin.Length > 0)
            {
                SiteUtils.SetSkinCookie(user);
            }

            user.UpdateLastLoginTime();

            // track user ip address
            UserLocation userLocation = new UserLocation(user.UserGuid, SiteUtils.GetIP4Address());

            userLocation.SiteGuid = siteSettings.SiteGuid;
            userLocation.Hostname = Request.UserHostName;
            userLocation.Save();

            UserSignInEventArgs u = new UserSignInEventArgs(user);

            OnUserSignIn(u);

            if (CookieHelper.CookieExists(returnUrlCookieName))
            {
                returnUrl = CookieHelper.GetCookieValue(returnUrlCookieName);
                CookieHelper.ExpireCookie(returnUrlCookieName);
            }
            string requestedReturnUrl = SiteUtils.GetReturnUrlParam(Page, SiteRoot);

            returnUrl = requestedReturnUrl;

            if (isNewUser)
            {
                if (WebConfigSettings.PageToRedirectToAfterRegistration.Length > 0)
                {
                    returnUrl = SiteRoot + WebConfigSettings.PageToRedirectToAfterRegistration;
                }
            }

            if (String.IsNullOrEmpty(returnUrl) ||
                returnUrl.Contains("AccessDenied") ||
                returnUrl.Contains("Login") ||
                returnUrl.Contains("SignIn") ||
                returnUrl.Contains("ConfirmRegistration.aspx") ||
                returnUrl.Contains("OpenIdRpxHandler.aspx") ||
                returnUrl.Contains("RecoverPassword.aspx") ||
                returnUrl.Contains("Register")
                )
            {
                returnUrl = SiteRoot;
            }

            if (returnUrl.Length > 0)
            {
                if (SiteUtils.IsSecureRequest())
                {
                    if (returnUrl.StartsWith("http:"))
                    {
                        returnUrl = returnUrl.Replace("http:", "https:");
                    }
                }

                WebUtils.SetupRedirect(this, returnUrl);
                return;
            }

            if (SiteUtils.IsSecureRequest())
            {
                if (SiteRoot.StartsWith("http:"))
                {
                    WebUtils.SetupRedirect(this, SiteRoot.Replace("http:", "https:"));
                    return;
                }
            }


            WebUtils.SetupRedirect(this, SiteRoot);
            return;
        }
Exemple #24
0
        private void LoadSettings()
        {
            timeOffset = SiteUtils.GetUserTimeOffset();
            timeZone   = SiteUtils.GetUserTimeZone();
            //lnkAllUsers.NavigateUrl = SiteRoot + "/MemberList.aspx";
            IsAdmin = WebUser.IsAdmin;

            ShowEmailInMemberList     = WebConfigSettings.ShowEmailInMemberList || displaySettings.ShowEmail;
            ShowUserIDInMemberList    = WebConfigSettings.ShowUserIDInMemberList || displaySettings.ShowUserId;
            ShowLoginNameInMemberList = WebConfigSettings.ShowLoginNameInMemberList || displaySettings.ShowLoginName;
            ShowJoinDate = displaySettings.ShowJoinDate;

            // this can't be used in related site mode because we can't assume forum posts were in this site.
            //ShowForumPostColumn = WebConfigSettings.ShowForumPostsInMemberList && displaySettings.ShowForumPosts && !WebConfigSettings.UseRelatedSiteMode;

            allowView = WebUser.IsInRoles(siteSettings.RolesThatCanViewMemberList);

            //if (IsAdmin || WebUser.IsInRoles(siteSettings.RolesThatCanManageUsers))
            //{
            //	canManageUsers = true;
            //	fgpOtherActions.Visible = true;
            //}

            //if (canManageUsers || WebUser.IsInRoles(siteSettings.RolesThatCanCreateUsers))
            //{
            //	fgpOtherActions.Controls.Add(new Literal
            //	{
            //		Text = string.Format(displaySettings.NewUserLinkFormat, SiteRoot + "/Admin/ManageUsers.aspx?userId=-1", Resource.MemberListAddUserTooltip, Resource.MemberListAddUserLabel)
            //	});
            //}

            //if (canManageUsers)
            //         {
            //             fgpIPSearch.Visible = true;
            //	fgpOtherActions.Controls.Add(new Literal
            //	{
            //		Text = string.Format(displaySettings.LockedUsersLinkFormat, SiteRoot + "/MemberList.aspx?locked=true", Resource.ShowLockedOutUsersTooltip, Resource.ShowLockedOutUsers)
            //	});
            //}

            //if (canManageUsers && siteSettings.RequireApprovalBeforeLogin)
            //{
            //	fgpOtherActions.Controls.Add(new Literal
            //	{
            //		Text = string.Format(displaySettings.UnapprovedUsersLinkFormat, SiteRoot + "/MemberList.aspx?needapproval=true", Resource.ShowNotApprovedUsersTooltip, Resource.ShowNotApprovedUsers)
            //	});
            //}

            pageNumber = WebUtils.ParseInt32FromQueryString("pagenumber", 1);

            sortMode = WebUtils.ParseInt32FromQueryString("sd", sortMode);

            if ((sortMode == 0) && (displaySettings.ShowFirstAndLastName))
            {
                sortMode = 2; // lastname, firstname
            }

            if (Request.Params["letter"] != null)
            {
                filterLetter = Request.Params["letter"].Trim();
            }

            if (Request.Params["search"] != null)
            {
                searchText = Request.Params["search"].Trim();
            }
            ipSearchText   = WebUtils.ParseStringFromQueryString("ips", ipSearchText);
            showLocked     = WebUtils.ParseBoolFromQueryString("locked", showLocked);
            showUnApproved = WebUtils.ParseBoolFromQueryString("needapproval", showUnApproved);

            //if (showLocked || showUnApproved || !string.IsNullOrWhiteSpace(searchText) || !string.IsNullOrWhiteSpace(userNameBeginsWith))
            //{
            //	fgpOtherActions.Controls.Add(new Literal
            //	{
            //		Text = string.Format(displaySettings.ShowAllUsersLinkFormat, SiteRoot + "/MemberList.aspx", Resource.MemberListShowAllTooltip, Resource.MemberListShowAllLabel)
            //	});
            //}

            pageSize = WebConfigSettings.MemberListPageSize;

            //mojoProfileConfiguration profileConfig = mojoProfileConfiguration.GetConfig();
            //if (profileConfig != null)
            //{
            //    if (profileConfig.Contains("WebSiteUrl"))
            //    {
            //        mojoProfilePropertyDefinition webSiteUrlProperty = profileConfig.GetPropertyDefinition("WebSiteUrl");
            //        if(
            //            (webSiteUrlProperty.OnlyVisibleForRoles.Length == 0)
            //            || (WebUser.IsInRoles(webSiteUrlProperty.OnlyVisibleForRoles))
            //            )
            //        {
            //            ShowWebSiteColumn = true;
            //        }

            //    }
            //}

            // displaySettings can be configured from theme.skin
            //if (displaySettings.HideWebSiteColumn) { ShowWebSiteColumn = false; }

            //if(displaySettings.TableCssClass.Length > 0)
            //{
            //    tableClassMarkup = " class='" + displaySettings.TableCssClass + "'";
            //}

            //tableAttributes = displaySettings.TableAttributes;

            //if (!ShowWebSiteColumn) { thWebLink.Visible = false; }
            //if (!ShowJoinDate) { thJoinDate.Visible = false; }



            //if (IsAdmin) { pnlAdminCrumbs.Visible = true; }

            //if (!ShowForumPostColumn) { thForumPosts.Visible = false; }

            //this page has no content other than nav
            SiteUtils.AddNoIndexFollowMeta(Page);

            AddClassToBody("memberlist");

            //if (displaySettings.TableCssClass == "jqtable")
            //{
            //    ScriptConfig.IncludeJQTable = true;
            //}
        }
        private SiteUser CreateUser(
            string openId,
            string email,
            string loginName,
            string name,
            bool emailIsVerified)
        {
            SiteUser newUser = new SiteUser(siteSettings);

            newUser.Email = email;

            if (loginName.Length > 50)
            {
                loginName = loginName.Substring(0, 50);
            }

            int i = 1;

            while (SiteUser.LoginExistsInDB(
                       siteSettings.SiteId, loginName))
            {
                loginName += i.ToString();
                if (loginName.Length > 50)
                {
                    loginName = loginName.Remove(40, 1);
                }
                i++;
            }
            if ((name == null) || (name.Length == 0))
            {
                name = loginName;
            }
            newUser.LoginName = loginName;
            newUser.Name      = name;
            //newUser.Password = SiteUser.CreateRandomPassword(7);
            mojoMembershipProvider mojoMembership = (mojoMembershipProvider)Membership.Provider;

            newUser.Password         = mojoMembership.EncodePassword(siteSettings, newUser, SiteUser.CreateRandomPassword(7, WebConfigSettings.PasswordGeneratorChars));
            newUser.PasswordQuestion = Resource.ManageUsersDefaultSecurityQuestion;
            newUser.PasswordAnswer   = Resource.ManageUsersDefaultSecurityAnswer;
            newUser.OpenIdUri        = openId;
            newUser.Save();

            //test
            //emailIsVerified = false;

            if (siteSettings.UseSecureRegistration)
            {
                if (!emailIsVerified)
                {
                    newUser.SetRegistrationConfirmationGuid(Guid.NewGuid());
                }
            }



            mojoProfileConfiguration profileConfig
                = mojoProfileConfiguration.GetConfig();

            // set default values first
            foreach (mojoProfilePropertyDefinition propertyDefinition in profileConfig.PropertyDefinitions)
            {
                // we are using the new TimeZoneInfo list but it doesn't work under Mono
                // this makes us skip the TimeOffsetHours setting from mojoProfile.config which is not used under windows
                if (propertyDefinition.Name == mojoProfilePropertyDefinition.TimeOffsetHoursKey)
                {
                    continue;
                }
                mojoProfilePropertyDefinition.SavePropertyDefault(
                    newUser, propertyDefinition);
            }

            foreach (mojoProfilePropertyDefinition propertyDefinition in profileConfig.PropertyDefinitions)
            {
                // we are using the new TimeZoneInfo list but it doesn't work under Mono
                // this makes us skip the TimeOffsetHours setting from mojoProfile.config which is not used under windows
                if (propertyDefinition.Name == mojoProfilePropertyDefinition.TimeOffsetHoursKey)
                {
                    continue;
                }
                if ((propertyDefinition.RequiredForRegistration) || (propertyDefinition.ShowOnRegistration))
                {
                    mojoProfilePropertyDefinition.SaveProperty(
                        newUser,
                        pnlRequiredProfileProperties,
                        propertyDefinition,
                        timeOffset,
                        timeZone);
                }
            }

            // track user ip address
            UserLocation userLocation = new UserLocation(newUser.UserGuid, SiteUtils.GetIP4Address());

            userLocation.SiteGuid = siteSettings.SiteGuid;
            userLocation.Hostname = Page.Request.UserHostName;
            userLocation.Save();

            UserRegisteredEventArgs u = new UserRegisteredEventArgs(newUser);

            OnUserRegistered(u);

            CacheHelper.ClearMembershipStatisticsCache();

            // we'll map them next time they login
            //OpenIdRpxHelper rpxHelper = new OpenIdRpxHelper(rpxApiKey, rpxBaseUrl);
            //rpxHelper.Map(openId, newUser.UserGuid.ToString());

            DoSubscribe(newUser);

            NewsletterHelper.ClaimExistingSubscriptions(newUser);

            return(newUser);
        }
        protected override void Render(HtmlTextWriter writer)
        {
            if (HttpContext.Current == null)
            {
                writer.Write("[" + this.ID + "]");
                return;
            }

            if (!WebConfigSettings.UseSiteMailFeature)
            {
                return;
            }

            if ((!Page.Request.IsAuthenticated) && (!WebConfigSettings.UseSilverlightSiteOffice))
            {
                return;
            }

            if (renderAsListItem)
            {
                writer.WriteBeginTag("li");
                writer.WriteAttribute("class", listItemCSS);
                writer.Write(HtmlTextWriter.TagRightChar);
            }

            if (leftSeparatorImageUrl.Length > 0)
            {
                writer.Write("<img class='accent' src='" + Page.ResolveUrl(leftSeparatorImageUrl) + "' border='0' /> ");
            }
            else
            {
                if (UseLeftSeparator)
                {
                    writer.Write("<span class='accent'>|</span>");
                }
            }

            string urlToUse = "/SiteOffice/Default.aspx";

            if (WebConfigSettings.UseSilverlightSiteOffice)
            {
                urlToUse = "/app.aspx";
            }

            urlToUse = SiteUtils.GetNavigationSiteRoot() + urlToUse;

            if (Page.Request.IsSecureConnection)
            {
                SiteSettings siteSettings = CacheHelper.GetCurrentSiteSettings();
                if ((siteSettings != null) && (!siteSettings.UseSslOnAllPages) && (!WebConfigSettings.UseSslForSiteOffice))
                {
                    urlToUse = urlToUse.Replace("https", "http");
                }
            }

            if (CssClass.Length == 0)
            {
                CssClass = "sitelink";
            }

            writer.WriteBeginTag("a");
            writer.WriteAttribute("class", CssClass);
            //writer.WriteAttribute("title", Resource.MailboxLink);
            writer.WriteAttribute("href", Page.ResolveUrl(urlToUse));
            writer.Write(HtmlTextWriter.TagRightChar);
            writer.WriteEncodedText(Resource.MailboxLink);
            writer.WriteEndTag("a");

            if (renderAsListItem)
            {
                writer.WriteEndTag("li");
            }
        }
Exemple #27
0
        public static void SendApprovalRequestNotification(
            SmtpSettings smtpSettings,
            SiteSettings siteSettings,
            int workflowId,
            SiteUser submittingUser,
            News draftNews
            )
        {
            if (!draftNews.StateId.HasValue)
            {
                return;
            }

            WorkflowState workflowState = WorkflowHelper.GetWorkflowState(workflowId, draftNews.StateId.Value);

            if (workflowState == null || workflowState.StateId == -1)
            {
                return;
            }

            if (workflowState.ReviewRoles.Length == 0 ||
                workflowState.NotifyTemplate.Length == 0)                //"ApprovalRequestNotification"
            {
                return;
            }

            string approvalRoles = workflowState.ReviewRoles;

            gbSiteMapNode gbNode = SiteUtils.GetSiteMapNodeByZoneId(draftNews.ZoneID);

            if (gbNode != null)
            {
                List <string> authorizedRoles = gbNode.AuthorizedRoles.SplitOnCharAndTrim(';');
                List <string> reviewRoles     = workflowState.ReviewRoles.SplitOnCharAndTrim(';');

                if (authorizedRoles.Count > 0 && reviewRoles.Count > 0)
                {
                    approvalRoles = string.Empty;

                    foreach (string reviewRole in reviewRoles)
                    {
                        foreach (string role in authorizedRoles)
                        {
                            if (reviewRole.ToLower() == role.ToLower())
                            {
                                approvalRoles += reviewRole + ";";
                            }
                        }
                    }
                }
            }

            List <string> emailAddresses = SiteUser.GetEmailAddresses(siteSettings.SiteId, approvalRoles);

            int queuedMessageCount = 0;

            EmailTemplate template        = EmailTemplate.Get(siteSettings.SiteId, workflowState.NotifyTemplate);
            string        subject         = template.Subject.Replace("{SiteName}", siteSettings.SiteName);
            string        messageTemplate = template.HtmlBody;

            List <string> emailTo = (template.ToAddresses.Length > 0 ? ";" + template.ToAddresses : "").SplitOnCharAndTrim(';');

            string emailToAddress = string.Empty;

            foreach (string email in emailAddresses)
            {
                if (WebConfigSettings.EmailAddressesToExcludeFromAdminNotifications.IndexOf(email,
                                                                                            StringComparison.InvariantCultureIgnoreCase) > -1)
                {
                    continue;
                }
                if (!Email.IsValidEmailAddressSyntax(email))
                {
                    continue;
                }

                if (!emailToAddress.Contains(email + ";"))
                {
                    emailToAddress += email + ";";
                }
            }
            foreach (string email in emailTo)
            {
                if (WebConfigSettings.EmailAddressesToExcludeFromAdminNotifications.IndexOf(email,
                                                                                            StringComparison.InvariantCultureIgnoreCase) > -1)
                {
                    continue;
                }
                if (!Email.IsValidEmailAddressSyntax(email))
                {
                    continue;
                }

                if (!emailToAddress.Contains(email + ";"))
                {
                    emailToAddress += email + ";";
                }
            }

            string replyEmail = submittingUser.Email;

            if (template.ReplyToAddress.Length > 0)
            {
                replyEmail += ";" + template.ReplyToAddress;
            }

            string fromEmailAlias = (template.FromName.Length > 0 ? template.FromName : siteSettings.DefaultFromEmailAlias);

            StringBuilder message = new StringBuilder();

            message.Append(messageTemplate);
            message.Replace("{Title}", draftNews.Title);
            message.Replace("{SubmittedDate}", DateTimeHelper.GetLocalTimeString(draftNews.ApprovedUtc, SiteUtils.GetUserTimeZone(),
                                                                                 SiteUtils.GetUserTimeOffset()));
            message.Replace("{SubmittedBy}", submittingUser.Name);
            message.Replace("{ContentUrl}", NewsHelper.FormatNewsUrl(draftNews.Url, draftNews.NewsID, draftNews.ZoneID));

            EmailMessageTask messageTask = new EmailMessageTask(smtpSettings);

            messageTask.SiteGuid       = siteSettings.SiteGuid;
            messageTask.EmailFrom      = siteSettings.DefaultEmailFromAddress;
            messageTask.EmailFromAlias = fromEmailAlias;
            messageTask.EmailReplyTo   = replyEmail;
            messageTask.EmailTo        = emailToAddress;
            messageTask.EmailCc        = template.CcAddresses;
            messageTask.EmailBcc       = template.BccAddresses;
            messageTask.UseHtml        = true;
            messageTask.Subject        = subject;
            messageTask.HtmlBody       = message.ToString();
            messageTask.QueueTask();
            queuedMessageCount += 1;

            //Email.Send(
            //        smtpSettings,
            //        siteSettings.DefaultEmailFromAddress,
            //        siteSettings.DefaultFromEmailAlias,
            //        submittingUser.Email,
            //        email,
            //        string.Empty,
            //        string.Empty,
            //        messageSubject,
            //        message.ToString(),
            //        false,
            //        Email.PriorityNormal);

            WebTaskManager.StartOrResumeTasks();
        }
Exemple #28
0
        private void LoadSettings()
        {
            pageId      = WebUtils.ParseInt32FromQueryString("pageid", pageId);
            moduleId    = WebUtils.ParseInt32FromQueryString("mid", moduleId);
            itemId      = WebUtils.ParseInt32FromQueryString("ItemID", itemId);
            commentGuid = WebUtils.ParseGuidFromQueryString("c", commentGuid);
            if (commentGuid == Guid.Empty)
            {
                return;
            }


            module = GetModule(moduleId, CommentsConfiguration.FeatureGuid);

            if (module == null)
            {
                return;
            }

            commentRepository = new CommentRepository();



            comment = commentRepository.Fetch(commentGuid);
            if ((comment.ContentGuid != module.ModuleGuid) || (comment.ModuleGuid != module.ModuleGuid))
            {
                module = null;
                return;
            }

            moduleSettings = ModuleSettings.GetModuleSettings(moduleId);

            config = new CommentsConfiguration(moduleSettings);

            currentUser = SiteUtils.GetCurrentSiteUser();

            userCanEdit = UserCanEditComment();

            commentEditor.SiteGuid       = CurrentSite.SiteGuid;
            commentEditor.SiteId         = CurrentSite.SiteId;
            commentEditor.SiteRoot       = SiteRoot;
            commentEditor.CommentsClosed = !config.AllowComments;
            //commentEditor.CommentUrl = Request.RawUrl;
            commentEditor.ContentGuid = module.ModuleGuid;
            //commentEditor.DefaultCommentTitle = defaultCommentTitle;
            commentEditor.FeatureGuid = CommentsConfiguration.FeatureGuid;
            commentEditor.ModuleGuid  = module.ModuleGuid;
            //commentEditor.NotificationAddresses = notificationAddresses;
            //commentEditor.NotificationTemplateName = notificationTemplateName;
            commentEditor.RequireCaptcha  = false;
            commentEditor.UserCanModerate = userCanEdit;
            //commentEditor.Visible = !commentsClosed;
            commentEditor.CurrentUser    = currentUser;
            commentEditor.UserComment    = comment;
            commentEditor.ShowRememberMe = false;

            commentEditor.UseCommentTitle = config.AllowCommentTitle;
            commentEditor.ShowUserUrl     = config.AllowWebSiteUrlForComments;

            //commentEditor.IncludeIpAddressInNotification = includeIpAddressInNotification;
            //commentEditor.ContainerControl = this;
        }
Exemple #29
0
        void btnUpload_Click(object sender, EventArgs e)
        {
            // if javascript is available this method will not be called
            // the file upload will happen by ajax post to /Services/FileService.ashx
            // from jquery file uploaded
            // this is fallback implementation

            if ((hdnFolder.Value.Length > 0) && (hdnFolder.Value != rootDirectory))
            {
                currentDir = hdnFolder.Value;
            }
            if (!canEdit)
            {
                WebUtils.SetupRedirect(this, navigationRoot + "/Dialog/FileDialog.aspx?ed=" + editorType + "&type=" + browserType + "&dir=" + currentDir);
                return;
            }

            if (uploader.HasFile)
            {
                //bool doUpload = true;

                long contentLength = uploader.FileBytes.Length;

                if (contentLength > fileSystem.Permission.MaxSizePerFile)
                {
                    //doUpload = false;
                    lblError.Text = Resource.FileSystemFileTooLargeError;
                    return;
                }

                if (fileSystem.CountAllFiles() >= fileSystem.Permission.MaxFiles)
                {
                    //doUpload = false;
                    lblError.Text = Resource.FileSystemFileCountQuotaReachedError;
                    return;
                }

                if (fileSystem.GetTotalSize() + contentLength >= fileSystem.Permission.Quota)
                {
                    //doUpload = false;
                    lblError.Text = Resource.FileSystemStorageQuotaError;
                    return;
                }


                string currentDirectory = GetCurrentDirectory();
                if (!fileSystem.FolderExists(currentDirectory))
                {
                    fileSystem.CreateFolder(currentDirectory);
                }

                string destPath = VirtualPathUtility.Combine(
                    currentDirectory,
                    Path.GetFileName(uploader.FileName).ToCleanFileName(WebConfigSettings.ForceLowerCaseForUploadedFiles));

                string ext = Path.GetExtension(uploader.FileName);


                if (SiteUtils.IsAllowedUploadBrowseFile(ext, allowedExtensions))
                {
                    using (Stream s = uploader.FileContent)
                    {
                        fileSystem.SaveFile(destPath, s, IOHelper.GetMimeType(ext), true);
                    }

                    if (SiteUtils.IsImageFileExtension(ext))
                    {
                        if (chkConstrainImageSize.Checked)
                        {
                            mojoPortal.Web.ImageHelper.ResizeImage(
                                destPath,
                                IOHelper.GetMimeType(ext),
                                resizeWidth,
                                resizeHeight,
                                WebConfigSettings.DefaultResizeBackgroundColor);
                        }
                    }
                }
            }

            WebUtils.SetupRedirect(this, GetRedirectUrl());
        }
Exemple #30
0
        private void PopulateControls()
        {
            DateTime?startDate = null;

            if (txtDays.Text.Length > 0)
            {
                int days = -1;
                int.TryParse(txtDays.Text, out days);

                if (days > 0)
                {
                    DateTime localTime = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 0, 0, 0).AddDays(-days);

                    if (timeZone != null)
                    {
                        startDate = localTime.ToUtc(timeZone);
                    }
                    else
                    {
                        startDate = localTime.AddHours(-timeOffset);
                    }
                }
            }

            List <OrderItem> lstOrderItems = OrderItem.GetPageBySearch(siteSettings.SiteId, -1, -1, -1, -1, startDate, null, null, null,
                                                                       siteUser.UserGuid, null, pageNumber, pageSize);

            if (lstOrderItems.Count > 0)
            {
                string productGuids = string.Empty;
                string attribute    = string.Empty;
                foreach (OrderItem orderItem in lstOrderItems)
                {
                    productGuids += orderItem.ProductGuid.ToString() + ";";

                    string tmp = orderItem.AttributesXml;
                    if (tmp.Length > 0)
                    {
                        tmp += ";";
                    }

                    //if (orderItem.AttributeDescription.Length > 0)
                    //    tmp += orderItem.AttributeDescription + ";";

                    attribute += tmp;
                }

                if (attribute.Length > 0)
                {
                    lstOptions = CustomFieldOption.GetByOptionIds(siteSettings.SiteId, attribute);
                }

                List <Product> lstProducts = Product.GetByGuids(siteSettings.SiteId, productGuids, -1, WorkingCulture.LanguageId);

                XmlDocument doc = new XmlDocument();

                doc.LoadXml("<ProductList></ProductList>");
                XmlElement root = doc.DocumentElement;

                lstOrderItems.ForEach(orderItem => {
                    Product product = ProductHelper.GetProductFromList(lstProducts, orderItem.ProductId);

                    if (product != null)
                    {
                        XmlElement productXml = doc.CreateElement("Product");
                        root.AppendChild(productXml);

                        ProductHelper.BuildProductDataXml(doc, productXml, product, null);

                        // Order detail
                        XmlHelper.AddNode(doc, productXml, "OrderCode", orderItem.Order.OrderCode);
                        XmlHelper.AddNode(doc, productXml, "OrderDate", FormatDate(orderItem.Order.CreatedUtc, "dd/MM/yyyy"));
                        XmlHelper.AddNode(doc, productXml, "OrderStatus", ProductHelper.GetOrderStatus(orderItem.Order.OrderStatus));
                        XmlHelper.AddNode(doc, productXml, "OrderTotal",
                                          ProductHelper.FormatPrice(orderItem.Quantity * orderItem.Price - orderItem.DiscountAmount, true));
                    }
                });

                XmlHelper.XMLTransform(xmlTransformer, SiteUtils.GetXsltBasePath("Product", "PurchaseHistory.xslt"), doc);
            }
        }