public async Task <IActionResult> Edit(Samorzad modelReturned, List <IFormFile> files)
        {
            Samorzad dataBase = repository.Samorzads.FirstOrDefault();

            dataBase.Tresc = HtmlUtility.RemoveInvalidHtmlTags(modelReturned.Tresc);
            repository.SaveSamorzad(dataBase);
            if (files != null)
            {
                long size     = files.Sum(f => f.Length);
                var  filePath = "";
                foreach (var formFile in files)
                {
                    filePath = Path.Combine(fileDirectory, formFile.FileName);
                    if (formFile.Length > 0)
                    {
                        using (var stream = new FileStream(filePath, FileMode.Create))
                        {
                            await formFile.CopyToAsync(stream);
                        }
                    }
                }
            }
            return(RedirectToAction(nameof(Index)));
        }
Ejemplo n.º 2
0
        protected string RenderLastUpdates()
        {
            if (Topic.RecentPostID == 0)
            {
                return("");
            }

            var recentPostURL = _settings.LinkProvider.RecentPost(Topic.RecentPostID, Topic.ID, Topic.PostCount);

            var sb = new StringBuilder();

            var fullText = HtmlUtility.GetText(Topic.RecentPostText);
            var text     = HtmlUtility.GetText(Topic.RecentPostText, 20);

            sb.Append("<div style='margin-bottom:5px;'><a class = 'link' title=\"" + HttpUtility.HtmlEncode(fullText) + "\" href=\"" + recentPostURL + "\">" + HttpUtility.HtmlEncode(text) + "</a></div>");

            sb.Append("<div class = 'link' style='overflow: hidden; max-width: 180px;'>" + ASC.Core.Users.StudioUserInfoExtension.RenderCustomProfileLink(CoreContext.UserManager.GetUsers(Topic.RecentPostAuthorID), _settings.ProductID, "describe-text", "link gray") + "</div>");
            sb.Append("<div style='margin-top:5px;'>");
            sb.Append(DateTimeService.DateTime2StringTopicStyle(Topic.RecentPostCreateDate));
            sb.Append("<a href=\"" + recentPostURL + "\"><img hspace=\"5\" align=\"absmiddle\" alt=\"&raquo;\" title=\"&raquo;\" border=\"0\" src=\"" + WebImageSupplier.GetAbsoluteWebPath("goto.png", _settings.ImageItemID) + "\"/></a>");
            sb.Append("</div>");

            return(sb.ToString());
        }
Ejemplo n.º 3
0
        /// <summary>
        /// 照片圈人积分
        /// </summary>
        public void PhotoLabelEventModule_After(PhotoLabel photoLabel, CommonEventArgs eventArgs)
        {
            string pointItemKey       = string.Empty;
            string eventOperationType = string.Empty;

            //加积分
            if (eventArgs.EventOperationType == EventOperationType.Instance().Create())
            {
                pointItemKey       = PointItemKeys.Instance().Photo_BeLabelled();
                eventOperationType = EventOperationType.Instance().Create();
            }
            //减积分
            if (eventArgs.EventOperationType == EventOperationType.Instance().Delete())
            {
                pointItemKey       = PointItemKeys.Instance().Photo_BeLabelled_Delete();
                eventOperationType = EventOperationType.Instance().Delete();
            }

            if (!string.IsNullOrEmpty(pointItemKey))
            {
                string description = string.Format("照片圈人", "", HtmlUtility.TrimHtml(photoLabel.Description, 64));
                pointService.GenerateByRole(photoLabel.ObjetId, pointItemKey, description);
            }
        }
Ejemplo n.º 4
0
        public static ArticleList ParseList(string Html, string Pattern, string Url = null, bool RecogNextPage = true)
        {
            //输入检查
            if (string.IsNullOrWhiteSpace(Html) || string.IsNullOrWhiteSpace(Pattern))
            {
                return(null);
            }

            //检查 Pattern 的格式,判断是否符合要求
            XpathPattern xpathPattern = null;

            try {
                xpathPattern = JsonConvert.DeserializeObject <XpathPattern>(Pattern);
            }
            catch (Exception ex)
            {
                Logger.Error(string.Format("Pattern 的格式不符合 Xpath Parser 的定义,请检查!Url:{0}, Pattern:{1}.", Url, Pattern), ex);
            }

            ArticleList articleList = new ArticleList();

            List <Article> articles = new List <Article>();

            #region Article 集合
            HashSet <string> ItemIDs  = new HashSet <string>();
            HtmlNode         htmlNode = HtmlUtility.getSafeHtmlRootNode(Html, true, true);

            articles = ExtractItemFromList(Url, htmlNode, xpathPattern);
            #endregion Item集合


            articleList.Articles = articles;
            articleList.Count    = articleList?.Count ?? 0;

            return(articleList);
        }
Ejemplo n.º 5
0
        public AjaxResponse AddComment(string parrentCommentID, long bookmarkID, string text, string pid)
        {
            var resp = new AjaxResponse {
                rs1 = parrentCommentID
            };

            var comment = new Comment
            {
                Content  = HtmlUtility.GetFull(text),
                Datetime = ASC.Core.Tenants.TenantUtil.DateTimeNow(),
                UserID   = SecurityContext.CurrentAccount.ID
            };

            var parentID = Guid.Empty;

            try
            {
                if (!string.IsNullOrEmpty(parrentCommentID))
                {
                    parentID = new Guid(parrentCommentID);
                }
            }
            catch
            {
                parentID = Guid.Empty;
            }
            comment.Parent     = parentID.ToString();
            comment.BookmarkID = bookmarkID;
            comment.ID         = Guid.NewGuid();

            _serviceHelper.AddComment(comment);

            resp.rs2 = GetOneCommentHtmlWithContainer(comment);

            return(resp);
        }
Ejemplo n.º 6
0
        /// <summary>
        /// 内容过滤
        /// </summary>
        /// <param name="body">待过滤内容</param>
        /// <param name="isBanned">是否禁止提交</param>
        private string TextFilter(string body, out bool isBanned)
        {
            isBanned = false;
            if (string.IsNullOrEmpty(body))
            {
                return(body);
            }

            string           temBody = body;
            WordFilterStatus staus   = WordFilterStatus.Replace;

            temBody = WordFilter.SensitiveWordFilter.Filter(body, out staus);

            if (staus == WordFilterStatus.Banned)
            {
                isBanned = true;
                return(body);
            }

            body = temBody;
            HtmlUtility.CleanHtml(body, TrustedHtmlLevel.Basic);

            return(body);
        }
Ejemplo n.º 7
0
        public ActionResult Detail(string spaceKey, long threadId, int pageIndex = 1, bool onlyLandlord = false, SortBy_BarPost sortBy = SortBy_BarPost.DateCreated, long?postId = null, long?childPostIndex = null)
        {
            BarThread barThread = barThreadService.Get(threadId);

            if (barThread == null)
            {
                return(HttpNotFound());
            }

            GroupEntity group = groupService.Get(spaceKey);

            if (group == null)
            {
                return(HttpNotFound());
            }
            BarSection section = barSectionService.Get(barThread.SectionId);

            if (section == null || section.TenantTypeId != TenantTypeIds.Instance().Group())
            {
                return(HttpNotFound());
            }

            //验证是否通过审核
            long currentSpaceUserId = UserIdToUserNameDictionary.GetUserId(spaceKey);

            if (!authorizer.IsAdministrator(BarConfig.Instance().ApplicationId) && barThread.UserId != currentSpaceUserId &&
                (int)barThread.AuditStatus < (int)(new AuditService().GetPubliclyAuditStatus(BarConfig.Instance().ApplicationId)))
            {
                return(Redirect(SiteUrls.Instance().SystemMessage(TempData, new SystemMessageViewModel
                {
                    Title = "尚未通过审核",
                    Body = "由于当前帖子尚未通过审核,您无法浏览当前内容。",
                    StatusMessageType = StatusMessageType.Hint
                })));
            }


            pageResourceManager.InsertTitlePart(section.Name);
            pageResourceManager.InsertTitlePart(barThread.Subject);

            Category category = categoryService.Get(barThread.CategoryId ?? 0);
            string   keyWords = string.Join(",", barThread.TagNames);

            pageResourceManager.SetMetaOfKeywords(category != null ? category.CategoryName + "," + keyWords : keyWords); //设置Keyords类型的Meta
            pageResourceManager.SetMetaOfDescription(HtmlUtility.TrimHtml(barThread.GetResolvedBody(), 120));            //设置Description类型的Meta

            ViewData["EnableRating"] = barSettings.EnableRating;

            //更新浏览计数
            CountService countService = new CountService(TenantTypeIds.Instance().BarThread());

            countService.ChangeCount(CountTypes.Instance().HitTimes(), barThread.ThreadId, barThread.UserId, 1, false);

            PagingDataSet <BarPost> barPosts = barPostService.Gets(threadId, onlyLandlord, sortBy, pageIndex);

            if (pageIndex > barPosts.PageCount && pageIndex > 1)
            {
                return(Detail(spaceKey, threadId, barPosts.PageCount));
            }
            if (Request.IsAjaxRequest())
            {
                return(PartialView("~/Applications/Bar/Views/Bar/_ListPost.cshtml", barPosts));
            }

            ViewData["barThread"] = barThread;
            ViewData["group"]     = group;
            return(View(barPosts));
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Gets the content of the html.
        /// </summary>
        /// <returns>The html content.</returns>
        /// <param name="bodyText">Body text.</param>
        /// <param name="Title">Title.</param>
        /// <param name="dateTimeStr">Date time string.</param>
        private static string GetHtmlContent(string html, string title, string dateTimeStr)
        {
            HtmlNode itempagenode = HtmlUtility.getSafeHtmlRootNode(html, true, true);

            return(GetHtmlContent(itempagenode, title, dateTimeStr));
        }
Ejemplo n.º 9
0
        /// <summary>
        /// 获取标题
        /// </summary>
        /// <param name="html"></param>
        /// <returns></returns>
        private static string GetTitle(string html)
        {
            HtmlNode itempagenode = HtmlUtility.getSafeHtmlRootNode(html, true, true);

            return(GetTitle(itempagenode));
        }
Ejemplo n.º 10
0
        protected override void RenderContents(HtmlTextWriter writer)
        {
            writer.AddAttribute(HtmlTextWriterAttribute.Class, "tableBase");
            writer.AddAttribute("cellspacing", "0");
            writer.AddAttribute("cellpadding", "8");
            writer.RenderBeginTag(HtmlTextWriterTag.Table);

            writer.RenderBeginTag(HtmlTextWriterTag.Tbody);

            foreach (var searchItemResult in Items.GetRange(0, (MaxCount < Items.Count) ? MaxCount : Items.Count))
            {
                var relativeInfo = searchItemResult.Additional["relativeInfo"].ToString();

                if (String.IsNullOrEmpty(relativeInfo))
                {
                    relativeInfo = searchItemResult.Description.HtmlEncode();
                }
                else
                {
                    relativeInfo = String.Format("<span class='describe-text'>{0}</span> {1}", CRMCommonResource.RelativeTo, relativeInfo.HtmlEncode());
                }

                writer.AddAttribute(HtmlTextWriterAttribute.Class, "search-result-item");
                writer.RenderBeginTag(HtmlTextWriterTag.Tr);

                writer.AddAttribute(HtmlTextWriterAttribute.Class, "borderBase left-column gray-text");
                writer.RenderBeginTag(HtmlTextWriterTag.Td);
                writer.AddAttribute(HtmlTextWriterAttribute.Title, searchItemResult.Additional["typeInfo"].ToString());
                writer.RenderBeginTag(HtmlTextWriterTag.Div);
                writer.Write(searchItemResult.Additional["typeInfo"].ToString());
                writer.RenderEndTag();
                writer.RenderEndTag();

                writer.AddAttribute(HtmlTextWriterAttribute.Class, "borderBase center-column");
                writer.RenderBeginTag(HtmlTextWriterTag.Td);

                writer.AddAttribute(HtmlTextWriterAttribute.Href, searchItemResult.URL);
                writer.AddAttribute(HtmlTextWriterAttribute.Class, "link bold");
                writer.RenderBeginTag(HtmlTextWriterTag.A);
                writer.Write(HtmlUtility.SearchTextHighlight(Text, searchItemResult.Name.HtmlEncode(), false));
                writer.RenderEndTag();

                if (!String.IsNullOrEmpty(relativeInfo))
                {
                    writer.WriteBreak();
                    writer.Write(relativeInfo);
                }

                writer.RenderEndTag();

                writer.AddAttribute(HtmlTextWriterAttribute.Class, "borderBase right-column gray-text");
                writer.RenderBeginTag(HtmlTextWriterTag.Td);
                if (searchItemResult.Date.HasValue)
                {
                    writer.AddAttribute(HtmlTextWriterAttribute.Title, searchItemResult.Date.Value.ToShortDateString());
                    writer.RenderBeginTag(HtmlTextWriterTag.Div);
                    writer.Write(searchItemResult.Date.Value.ToShortDateString());
                    writer.RenderEndTag();
                }
                writer.RenderEndTag();

                writer.RenderEndTag();
            }

            writer.RenderEndTag();
            writer.RenderEndTag();
        }
Ejemplo n.º 11
0
 public string GetPreviewFull(string html)
 {
     return(HtmlUtility.GetFull(html, false));
 }
Ejemplo n.º 12
0
        protected override void RenderContents(System.Web.UI.HtmlTextWriter writer)
        {
            ForumLastUpdatesWidgetSettings widgetSettings = SettingsManager.Instance.LoadSettingsFor <ForumLastUpdatesWidgetSettings>(SecurityContext.CurrentAccount.ID);

            var           topicList = ForumDataProvider.GetLastUpdateTopics(TenantProvider.CurrentTenantID, widgetSettings.MaxTopicCount);
            StringBuilder sb        = new StringBuilder();

            foreach (Topic topic in topicList)
            {
                if (topic.RecentPostID != 0)
                {
                    sb.Append("<div class='clearFix' style='margin-bottom:20px;'>");
                    sb.Append("<table cellspacing='0' cellpadding='0' border='0'><tr valign='top'>");

                    //date
                    sb.Append("<td style='width:30px; text-align:left;'>");
                    sb.Append(DateTimeService.DateTime2StringWidgetStyle(topic.RecentPostCreateDate));
                    sb.Append("</td>");

                    //message
                    sb.Append("<td style='padding-left:10px;'>");
                    string recentPostURL = VirtualPathUtility.ToAbsolute(ForumManager.BaseVirtualPath + "/posts.aspx") + "?t=" + topic.ID;
                    int    pageNum       = Convert.ToInt32(Math.Ceiling(topic.PostCount / (ForumManager.Settings.PostCountOnPage * 1.0)));
                    if (pageNum <= 0)
                    {
                        pageNum = 1;
                    }

                    if (topic.RecentPostID != 0)
                    {
                        recentPostURL = VirtualPathUtility.ToAbsolute(ForumManager.BaseVirtualPath + "/posts.aspx") + "?t=" + topic.ID.ToString() + "&p=" + pageNum.ToString() + "#" + topic.RecentPostID.ToString();
                    }

                    string message = topic.RecentPostText;
                    if (topic.RecentPostFormatter == PostTextFormatter.BBCode)
                    {
                        message = new ASC.Web.Controls.BBCodeParser.Parser(CommonControlsConfigurer.TextConfig).Parse(topic.RecentPostText);
                    }

                    if (widgetSettings.IsCutLongMessage)
                    {
                        message = HtmlUtility.GetText(message, 120, true);
                    }
                    else
                    {
                        message = HtmlUtility.GetText(message, true);
                    }

                    //topic
                    sb.Append("<div>");
                    sb.Append("<a href='" + recentPostURL + "'>" + HttpUtility.HtmlEncode(topic.Title) + "</a>");
                    if (topic.IsNew())
                    {
                        sb.Append("<span style='margin-left:7px;' class='errorText'>(" + topic.PostCount + ")</span>");
                    }
                    else
                    {
                        sb.Append("<span style='margin-left:7px;' class='describeText'>(" + topic.PostCount + ")</span>");
                    }
                    sb.Append("</div>");

                    //thread

                    //post
                    sb.Append("<div style='margin-top:5px;'>");
                    sb.Append(message);
                    sb.Append("</div>");

                    //who
                    sb.Append("<div style='margin-top:5px;'>");
                    sb.Append("<span class='textBigDescribe' style='margin-right:5px;'>" + Resources.ForumResource.PostedBy + ":</span>");
                    sb.Append(topic.RecentPostAuthor.RenderProfileLink(CommunityProduct.ID));

                    sb.Append("</div>");

                    sb.Append("</td>");
                    sb.Append("</tr></table>");
                    sb.Append("</div>");
                }
            }


            if (topicList.Count > 0)
            {
                sb.Append("<div style='margin-top:10px;'>");
                sb.Append("<a href=\"" + VirtualPathUtility.ToAbsolute(ForumManager.BaseVirtualPath + "/default.aspx") + "\">" + Resources.ForumResource.ForumsBreadCrumbs + "</a>");
                sb.Append("</div>");
            }
            else
            {
                sb.Append("<div class=\"empty-widget\" style='text-align:center; padding:40px 0px;'>");

                if (ForumManager.Instance.ValidateAccessSecurityAction(ForumAction.GetAccessForumEditor, null))
                {
                    sb.AppendFormat(
                        Resources.ForumResource.ForumNotCreatedWidgetMessageForAdmin,
                        string.Format("<div style=\"padding-top:3px;\"><a href=\"{0}\">", VirtualPathUtility.ToAbsolute(ForumManager.BaseVirtualPath + "/managementcenter.aspx")),
                        "</a></div>");
                }
                else
                {
                    sb.Append(Resources.ForumResource.ForumNotCreatedWidgetMessage);
                }
                sb.Append("</div>");
            }

            writer.Write(sb.ToString());
        }
Ejemplo n.º 13
0
 public string GetPreview(string htmltext)
 {
     return(HtmlUtility.GetFull(htmltext));
 }
Ejemplo n.º 14
0
        /// <summary>
        /// 转换成BlogThread类型
        /// </summary>
        /// <returns>文章实体</returns>
        public BlogThread AsBlogThread()
        {
            BlogThread blogThread = null;

            //写文章
            if (this.ThreadId <= 0)
            {
                blogThread        = BlogThread.New();
                blogThread.UserId = UserContext.CurrentUser.UserId;
                blogThread.Author = UserContext.CurrentUser.DisplayName;
                if (this.OwnerId.HasValue)
                {
                    blogThread.OwnerId      = this.OwnerId.Value;
                    blogThread.TenantTypeId = TenantTypeIds.Instance().Group();
                }
                else
                {
                    blogThread.OwnerId      = UserContext.CurrentUser.UserId;
                    blogThread.TenantTypeId = TenantTypeIds.Instance().User();
                }
                blogThread.OriginalAuthorId = UserContext.CurrentUser.UserId;
                blogThread.IsDraft          = this.IsDraft;
            }
            //编辑文章
            else
            {
                BlogService blogService = new BlogService();
                blogThread = blogService.Get(this.ThreadId);
                blogThread.LastModified = DateTime.UtcNow;
            }

            blogThread.Subject       = this.Subject;
            blogThread.Body          = this.Body;
            blogThread.IsSticky      = this.IsSticky;
            blogThread.IsLocked      = this.IsLocked;
            blogThread.PrivacyStatus = this.PrivacyStatus;
            blogThread.Keywords      = this.Keywords;
            if (string.IsNullOrEmpty(blogThread.Keywords))
            {
                string[] keywords = ClauseScrubber.TitleToKeywords(this.Subject);
                if (keywords.Length > 0)
                {
                    blogThread.Keywords = string.Join(" ", keywords);
                }
                else
                {
                    blogThread.Keywords = string.Empty;
                }
            }
            blogThread.Summary = this.Summary;
            if (string.IsNullOrEmpty(this.Summary))
            {
                blogThread.Summary = HtmlUtility.TrimHtml(this.Body, 100);
            }

            blogThread.FeaturedImageAttachmentId = this.FeaturedImageAttachmentId;
            if (blogThread.FeaturedImageAttachmentId > 0)
            {
                Attachment attachment = attachmentService.Get(blogThread.FeaturedImageAttachmentId);
                if (attachment != null)
                {
                    blogThread.FeaturedImage = attachment.GetRelativePath() + "\\" + attachment.FileName;
                }
                else
                {
                    blogThread.FeaturedImageAttachmentId = 0;
                }
            }
            else
            {
                blogThread.FeaturedImage = string.Empty;
            }

            return(blogThread);
        }
Ejemplo n.º 15
0
        protected void btnWrite_Click(object sender, EventArgs e)
        {
            //보안 문자를 정확히 입력햇거나, 로그인이 된 상태라면...
            if (IsImageTextCorrect())
            {
                UploadProcess(); //파일 업로드 관련 코드 분리

                Note note = new Note();

                note.Id = Convert.ToInt32(_Id);

                note.Name     = txtName.Text;
                note.Email    = HtmlUtility.Encode(txtEmail.Text);
                note.Homepage = txtHomepage.Text;
                note.Title    = HtmlUtility.Encode(txtTitle.Text);
                note.Content  = txtContent.Text;
                note.FileName = _FileName;
                note.FileSize = _FileSize;
                note.Password = txtPassword.Text;
                note.PostIp   = Request.UserHostAddress;
                note.Encoding = rdoEncoding.SelectedValue;

                NoteRepository repository = new NoteRepository();

                switch (FormType)
                {
                case BoardWriteFormType.Write:
                    repository.Add(note);
                    Response.Redirect("BoardList.aspx");
                    break;

                case BoardWriteFormType.Modify:
                    note.ModifyIp = Request.UserHostAddress;
                    note.FileName = ViewState["FileName"].ToString();
                    note.FileSize = Convert.ToInt32(ViewState["FileSize"]);
                    int r = repository.UpdateNote(note);
                    if (r > 0)     //업데이트 완료
                    {
                        Response.Redirect($"BoardView.aspx?Id={_Id}");
                    }
                    else
                    {
                        lblError.Text = "업데이트가 되지 않았습니다. 암호를 확인하세요.";
                    }
                    break;

                case BoardWriteFormType.Reply:
                    note.ParentNum = Convert.ToInt32(_Id);
                    repository.ReplyNote(note);
                    Response.Redirect("BoardList.aspx");
                    break;

                default:
                    repository.Add(note);
                    Response.Redirect("BoardList.aspx");
                    break;
                }
            }
            else
            {
                lblError.Text = "보안코드가 틀립니다. 다시 입력하세요.";
            }
        }
Ejemplo n.º 16
0
        /// <summary>
        /// Creates the aspNET EmailMessage object based on mail information
        /// we've alread got. Construct the message from html, and then spesify
        /// that the images should be attached inline.
        /// </summary>
        /// <param name="mailInfo">Mail info.</param>
        /// <returns></returns>
        private EmailMessage CreateMessage(MailInformation mailInfo)
        {
            if (_log.IsDebugEnabled())
                _log.Debug("Begin CreateMessage. Base Url: {0}", mailInfo.BaseUrl);

            EmailMessage email = new EmailMessage();
            HtmlUtility utility = new HtmlUtility(email);

            // Swallow exceptions if configured
            if (Configuration.NewsLetterConfiguration.DisableExceptionsInMailRendering == true)
                email.ThrowException = false;

            // Troubleshooting needs logging
            if (Configuration.NewsLetterConfiguration.ExtendedLogFile != null)
            {
                // Be careful with logging, it will generate large amounts of log data
                email.LogInMemory = false;
                email.LogPath = EPiServer.Global.BaseDirectory + Configuration.NewsLetterConfiguration.ExtendedLogFile;
                email.LogDebugStatements = true;
                email.LogBody = true;
                email.Logging = true;
            }

            // set all relative links contained in the html to this url
            string baseUrl = SiteDefinition.Current.SiteUrl.ToString();

            if (string.IsNullOrEmpty(mailInfo.BaseUrl) == false)
                baseUrl = mailInfo.BaseUrl;

            // Resolves Hrefs to their absolute value, this means
            // no urls in the html will be relative (which can be a pain
            // depending on the markup
            utility.ResolveHrefs = true;

            // Clean html, remove tags and content we do not want or need
            utility.HtmlRemovalOptions = HtmlRemovalOptions.AppletTag |
                                        HtmlRemovalOptions.EmbedTag |
                                        HtmlRemovalOptions.NoScriptTag |
                                        HtmlRemovalOptions.ObjectTag |
                                        HtmlRemovalOptions.ParamTag |
                                        HtmlRemovalOptions.Scripts |
                                        HtmlRemovalOptions.ViewState |
                                        HtmlRemovalOptions.EventArgument |
                                        HtmlRemovalOptions.EventTarget;

            // Load the html mail
            utility.LoadString(mailInfo.BodyHtml, baseUrl);

            // Set the UrlContent base
            utility.SetUrlContentBase = false;

            // Set the basetag in the html
            utility.SetHtmlBaseTag = true;

            // Embed the images into the email message, using the
            // content id as a src reference. Change this if you do
            // not want images to be part of the message
            utility.EmbedImageOption = EmbedImageOption.ContentId;

            // If you have problems loading images, disable exceptions
            // if (utility.ParentMessage != null)
            //    utility.ParentMessage.ThrowException = false;

            //render the Html so it is properly formatted for email
            utility.Render();

            //render an EmailMessage with appropriate text and html parts
            email = utility.ToEmailMessage();

            //load remaining properties from web.config
            email.LoadFromConfig();

            // Try to get these encodings correct
            email.ContentTransferEncoding = MailEncoding.QuotedPrintable;

            // Using utf-8 would have been nice, but utf-8 is not widely
            // adopted by email clients it seems.
            // email.CharSet = "utf-8";

            // Using iso 8859-1 hotmail will show Norwegian characters
            // even if the user runs with english settings
            // Hotmail needs this
            email.CharSet = "iso-8859-1";

            // Override with our own values
            email.Subject = mailInfo.Subject;
            email.From = mailInfo.From;
            email.TextBodyPart = mailInfo.BodyText;

            if (_log.IsDebugEnabled())
                _log.Debug("Rendered Mail Message: {0}", email.Subject);

            return email;
        }
Ejemplo n.º 17
0
        public virtual ActionResult EditPost(EditPostModel postModel)
        {
            if (!ModelState.IsValid)
            {
                return(PartialView(MVC.Admin.Shared.Views._ValidationSummery));
            }

            postModel.ModifiedDate = DateAndTime.GetDateTime();
            postModel.EditedByUser = _userService.GetUserByUserName(User.Identity.Name);
            postModel.Labels       = _labelService.GetLabelsById(postModel.LabelsId);

            // _downloadLinkService.RemoveByPostId(postModel.PostId);

            _uow.SaveChanges();

            //if (!string.IsNullOrEmpty(postModel.Links.DownloadLink1.Link))
            //{
            //    postModel.DownloadLinks.Add(postModel.Links.DownloadLink1);
            //}
            //if (!string.IsNullOrEmpty(postModel.Links.DownloadLink2.Link))
            //{
            //    postModel.DownloadLinks.Add(postModel.Links.DownloadLink2);
            //}
            //if (!string.IsNullOrEmpty(postModel.Links.DownloadLink3.Link))
            //{
            //    postModel.DownloadLinks.Add(postModel.Links.DownloadLink3);
            //}
            //if (!string.IsNullOrEmpty(postModel.Links.DownloadLink4.Link))
            //{
            //    postModel.DownloadLinks.Add(postModel.Links.DownloadLink4);
            //}

            //postModel.Book.Description = postModel.Book.Description.ToSafeHtml();
            postModel.PostBody = postModel.PostBody.ToSafeHtml();

            UpdatePostStatus status = _postService.UpdatePost(postModel);

            if (status == UpdatePostStatus.Successfull)
            {
                _uow.SaveChanges();

                #region Indexing updated Post by Lucene.NET
                new LucenePostSearch(_postService);
                //Index updated book lucene.NET
                LucenePostSearch.ClearLuceneIndexRecord(postModel.PostId);
                Post currentPost = _postService.Find(postModel.PostId);
                LucenePostSearch.AddUpdateLuceneIndex(new LucenePostModel
                {
                    Labels      = string.Join(" , ", currentPost.Labels.Select(l => l.Name).ToArray()),
                    Body        = HtmlUtility.RemoveHtmlTags(currentPost.Body),
                    Description = currentPost.Description,
                    Keywords    = currentPost.Keyword,
                    PostId      = currentPost.Id,
                    Title       = currentPost.Title
                });

                #endregion

                return(PartialView(MVC.Admin.Shared.Views._Alert,
                                   new Alert {
                    Message = "اطلاعات با موفقیت به روز رسانی شد", Mode = AlertMode.Success
                }));
            }

            return(PartialView(MVC.Admin.Shared.Views._Alert, new Alert
            {
                Message = "خطا در به روز رسانی اطلاعات",
                Mode = AlertMode.Error
            }));
        }
Ejemplo n.º 18
0
 public string GetDiscussionPreview(string html)
 {
     return(HtmlUtility.GetFull(html));
 }
        internal static string GenerateBasePageHtml(string gridName, IMVCGridDefinition def, object pageParameters)
        {
            string definitionJson = GenerateClientDefinitionJson(gridName, def, pageParameters);

            StringBuilder sbHtml = new StringBuilder();

            sbHtml.AppendFormat("<div id='{0}' class='{1}'>", HtmlUtility.GetContainerHtmlId(gridName), HtmlUtility.ContainerCssClass);

            sbHtml.AppendFormat("<input type='hidden' name='MVCGridName' value='{0}' />", gridName);
            sbHtml.AppendFormat("<div id='MVCGrid_{0}_JsonData' style='display: none'>{1}</div>", gridName, definitionJson);

            sbHtml.AppendFormat("<div id='MVCGrid_ErrorMessage_{0}' style='display: none;'>", gridName);
            if (String.IsNullOrWhiteSpace(def.ErrorMessageHtml))
            {
                sbHtml.Append("An error has occured.");
            }
            else
            {
                sbHtml.Append(def.ErrorMessageHtml);
            }
            sbHtml.Append("</div>");

            bool renderLoadingDiv = def.GetAdditionalSetting <bool>(RenderLoadingDivSettingName, true);

            if (renderLoadingDiv)
            {
                sbHtml.AppendFormat("<div id='MVCGrid_Loading_{0}' class='text-center' style='visibility: hidden'>", gridName);
                sbHtml.AppendFormat("&nbsp;&nbsp;&nbsp;<img src='{0}/ajaxloader.gif' alt='{1}' style='width: 15px; height: 15px;' />", HtmlUtility.GetHandlerPath(), def.ProcessingMessage);
                sbHtml.AppendFormat("&nbsp;{0}...", def.ProcessingMessage);
                sbHtml.Append("</div>");
            }

            sbHtml.AppendFormat("<div id='{0}'>", HtmlUtility.GetTableHolderHtmlId(gridName));
            sbHtml.Append("%%PRELOAD%%");
            sbHtml.Append("</div>");

            sbHtml.AppendLine("</div>");

            return(sbHtml.ToString());
        }
Ejemplo n.º 20
0
        private static HtmlUtility HtmlUtilityReturn(EmailSendDetail emailSendDetail)
        {
            var email =
                new EmailMessage(true, false)
                    {
                        To = emailSendDetail.PreviewEmailSend,
                        Subject = emailSendDetail.Subject
                    };

            var utility =
                new HtmlUtility(email)
                    {
                        CssOption = CssOption.None

                    };

            utility.LoadUrl(emailSendDetail.EmailUrl ?? "http://pkellner.site44.com/");

            utility.SetUrlContentBase = false;
            utility.SetHtmlBaseTag = false;
            utility.EmbedImageOption = EmbedImageOption.None;

            utility.Render();
            return utility;

            // note from dave on removing objects embedded image collection
            //If you are using utility.ToEmailMessage(), it should be created for you, automatically. If not, then I need to do some quick testing.

            //As far as the embedded images, there is a msg.EmbeddedObjects collection.

            //You can loop through that collection, check image names, and simply remove them. Off the top of my head:

            //If( msg.EmbeddedObjects != null ) && ( msg.EmbeddedObjects.Count > 0) ){
            //For( int i=msg.EmbeddedObjects.Count -1;i>=0;i--)
            //{
            //EmbeddedObject eo = msg.EmbeddedObjects[i] as EmbeddedObject.
            //If( eo.Name == “Whatever”)
            //{
            //  //remove the object
            //Msg.EmbeddedObjects.RemoveAt(i);
            //}
            //}
            //}
        }
Ejemplo n.º 21
0
 protected string GetDiscussionText()
 {
     return(HtmlUtility.GetFull(Discussion.Content, ProductEntryPoint.ID));
 }
Ejemplo n.º 22
0
        public string Process(string body, string tenantTypeId, long associateId, long userId)
        {
            //if (string.IsNullOrEmpty(body) || !body.Contains("[attach:"))
            //    return body;

            //List<long> attachmentIds = new List<long>();

            //Regex rg = new Regex(@"\[attach:(?<id>[\d]+)\]", RegexOptions.Multiline | RegexOptions.Singleline);
            //MatchCollection matches = rg.Matches(body);

            //if (matches != null)
            //{
            //    foreach (Match m in matches)
            //    {
            //        if (m.Groups["id"] == null || string.IsNullOrEmpty(m.Groups["id"].Value))
            //            continue;
            //        long attachmentId = 0;
            //        long.TryParse(m.Groups["id"].Value, out attachmentId);
            //        if (attachmentId > 0 && !attachmentIds.Contains(attachmentId))
            //            attachmentIds.Add(attachmentId);
            //    }
            //}

            //IEnumerable<ContentAttachment> attachments = new ContentAttachmentService().Gets(attachmentIds);

            //if (attachments != null && attachments.Count() > 0)
            //{
            //    IList<BBTag> bbTags = new List<BBTag>();
            //    string htmlTemplate = "<div class=\"tn-annexinlaid\"><a href=\"{3}\" rel=\"nofollow\">{0}</a>(<em>{1}</em>,<em>下载次数:{2}</em>)<a href=\"{3}\" rel=\"nofollow\">下载</a> </div>";

            //    //解析文本中附件
            //    foreach (var attachment in attachments)
            //    {
            //        bbTags.Add(AddBBTag(htmlTemplate, attachment));
            //    }

            //    body = HtmlUtility.BBCodeToHtml(body, bbTags);
            //}

            //解析at用户
            AtUserService atUserService = new AtUserService(tenantTypeId);

            body = atUserService.ResolveBodyForDetail(body, associateId, userId, AtUserTagGenerate);

            AttachmentService        attachmentService = new AttachmentService(tenantTypeId);
            IEnumerable <Attachment> attachments       = attachmentService.GetsByAssociateId(associateId);

            if (attachments != null && attachments.Count() > 0)
            {
                IList <BBTag> bbTags       = new List <BBTag>();
                string        htmlTemplate = "<div class=\"tn-annexinlaid\"><a href=\"{3}\" rel=\"nofollow\">{0}</a>(<em>{1}</em>,<em>下载次数:{2}</em>)<a href=\"{3}\" rel=\"nofollow\">下载</a> </div>";

                //解析文本中附件
                IEnumerable <Attachment> attachmentsFiles = attachments.Where(n => n.MediaType != MediaType.Image);
                foreach (var attachment in attachmentsFiles)
                {
                    bbTags.Add(AddBBTag(htmlTemplate, attachment));
                }

                body = HtmlUtility.BBCodeToHtml(body, bbTags);
            }

            body = new EmotionService().EmoticonTransforms(body);
            body = DIContainer.Resolve <ParsedMediaService>().ResolveBodyForHtmlDetail(body, ParsedMediaTagGenerate);



            return(body);
        }
Ejemplo n.º 23
0
        /// <summary>
        /// 日志详细页
        /// </summary>
        public ActionResult Detail(string spaceKey, long threadId)
        {
            BlogThread blogThread = blogService.Get(threadId);

            if (blogThread == null)
            {
                return(HttpNotFound());
            }

            if (!authorizer.BlogThread_View(blogThread))
            {
                return(Redirect(SiteUrls.Instance().SystemMessage(TempData, new SystemMessageViewModel
                {
                    Title = "没有权限",
                    Body = "由于空间主人的权限设置,您无法浏览当前内容。",
                    StatusMessageType = StatusMessageType.Hint
                })));
            }

            long currentSpaceUserId = UserIdToUserNameDictionary.GetUserId(spaceKey);

            if (!authorizer.IsAdministrator(BlogConfig.Instance().ApplicationId) && blogThread.UserId != currentSpaceUserId &&
                (int)blogThread.AuditStatus < (int)(new AuditService().GetPubliclyAuditStatus(BlogConfig.Instance().ApplicationId)))
            {
                return(Redirect(SiteUrls.Instance().SystemMessage(TempData, new SystemMessageViewModel
                {
                    Title = "尚未通过审核",
                    Body = "由于当前日志尚未通过审核,您无法浏览当前内容。",
                    StatusMessageType = StatusMessageType.Hint
                })));
            }

            //附件信息
            IEnumerable <Attachment> attachments = attachmentService.GetsByAssociateId(threadId);

            if (attachments != null && attachments.Count() > 0)
            {
                ViewData["attachments"] = attachments.Where(n => n.MediaType == MediaType.Other);
            }

            //更新浏览计数
            CountService countService = new CountService(TenantTypeIds.Instance().BlogThread());

            countService.ChangeCount(CountTypes.Instance().HitTimes(), blogThread.ThreadId, blogThread.UserId, 1, false);

            //设置SEO信息
            pageResourceManager.InsertTitlePart(blogThread.Author);
            pageResourceManager.InsertTitlePart(blogThread.ResolvedSubject);

            List <string> keywords = new List <string>();

            keywords.AddRange(blogThread.TagNames);
            keywords.AddRange(blogThread.OwnerCategoryNames);
            string keyword = string.Join(" ", keywords.Distinct());

            if (!string.IsNullOrEmpty(blogThread.Keywords))
            {
                keyword += " " + blogThread.Keywords;
            }

            pageResourceManager.SetMetaOfKeywords(keyword);

            if (!string.IsNullOrEmpty(blogThread.Summary))
            {
                pageResourceManager.SetMetaOfDescription(HtmlUtility.StripHtml(blogThread.Summary, true, false));
            }


            return(View(blogThread));
        }
Ejemplo n.º 24
0
        private void FillSelectedPage(List <Post> posts, BlogsEngine engine)
        {
            var currentUser = CoreContext.UserManager.GetUsers(SecurityContext.CurrentAccount.ID);

            if (posts == null || posts.Count == 0)
            {
                var emptyScreenControl = new EmptyScreenControl
                {
                    ImgSrc   = WebImageSupplier.GetAbsoluteWebPath("blog_icon.png", ASC.Blogs.Core.Constants.ModuleId),
                    Header   = BlogsResource.EmptyScreenBlogCaption,
                    Describe = BlogsResource.EmptyScreenBlogText
                };

                if (CommunitySecurity.CheckPermissions(new PersonalBlogSecObject(currentUser), ASC.Blogs.Core.Constants.Action_AddPost) &&
                    string.IsNullOrEmpty(UserID) && string.IsNullOrEmpty(Search))
                {
                    emptyScreenControl.ButtonHTML = String.Format("<a class='link underline blue plus' href='addblog.aspx'>{0}</a>", BlogsResource.EmptyScreenBlogLink);
                }

                placeContent.Controls.Add(emptyScreenControl);
                return;
            }

            placeContent.Controls.Add(new Literal {
                Text = "<div>"
            });

            var post_with_comments = engine.GetPostsCommentsCount(posts);

            if (!String.IsNullOrEmpty(UserID))
            {
                var post = post_with_comments[0].Item1;
                var st   = new StringBuilder();

                st.Append("<div class=\"BlogsHeaderBlock header-with-menu\" style=\"margin-bottom:16px;\">");
                st.Append("<span class=\"header\">" + CoreContext.UserManager.GetUsers(post.UserID).DisplayUserName() + "</span>");
                st.Append("</div>");

                placeContent.Controls.Add(new Literal {
                    Text = st.ToString()
                });
            }

            for (var i = 0; i < post_with_comments.Count; i++)
            {
                var post         = post_with_comments[i].Item1;
                var commentCount = post_with_comments[i].Item2;
                var sb           = new StringBuilder();
                var user         = CoreContext.UserManager.GetUsers(post.UserID);

                sb.Append("<div class=\"container-list\">");
                sb.Append("<div class=\"header-list\">");

                sb.Append("<div class=\"avatar-list\">");
                sb.Append("<a href=\"viewblog.aspx?blogid=" + post.ID.ToString() + "\">" + ImageHTMLHelper.GetHTMLUserAvatar(user.ID) + "</a>");
                sb.Append("</div><div class=\"describe-list\">");
                sb.Append("<div class=\"title-list\">");
                sb.Append("<a href=\"viewblog.aspx?blogid=" + post.ID.ToString() + "\">" + HttpUtility.HtmlEncode(post.Title) + "</a>");
                sb.Append("</div>");

                sb.Append("<div class=\"info-list\">");
                sb.Append("<span class=\"caption-list\">" + BlogsResource.PostedTitle + ":</span>");
                sb.Append(user.RenderCustomProfileLink("name-list", "link"));
                sb.Append("</div>");

                if (String.IsNullOrEmpty(UserID))
                {
                    sb.Append("<div class=\"info-list\">");
                    sb.Append("<a class=\"link gray-text\" href=\"" + VirtualPathUtility.ToAbsolute(ASC.Blogs.Core.Constants.BaseVirtualPath) + "?userid=" + post.UserID + "\">" + BlogsResource.AllRecordsOfTheAutor + "</a>");
                    sb.Append("</div>");
                }

                sb.Append("<div class=\"date-list\">");
                sb.AppendFormat("{0}<span class=\"time-list\">{1}</span>", post.Datetime.ToString("d"), post.Datetime.ToString("t"));
                sb.Append("</div></div></div>");

                sb.Append("<div class=\"content-list\">");

                sb.Append(HtmlUtility.GetFull(post.Content, false));
                sb.Append("<div id=\"postIndividualLink\" class=\"display-none\">viewblog.aspx?blogid=" + post.ID.ToString() + "</div>");
                sb.Append("<div class=\"comment-list\">");
                sb.Append("<a href=\"viewblog.aspx?blogid=" + post.ID + "#comments\">" + BlogsResource.CommentsTitle + ": " + commentCount.ToString() + "</a>");
                if (!currentUser.IsOutsider())
                {
                    sb.Append("<a href=\"viewblog.aspx?blogid=" + post.ID + "#addcomment\">" + BlogsResource.CommentsAddButtonTitle + "</a>");
                }
                sb.Append("</div></div></div>");

                placeContent.Controls.Add(new Literal {
                    Text = sb.ToString()
                });
            }

            placeContent.Controls.Add(new Literal {
                Text = "</div>"
            });
        }
Ejemplo n.º 25
0
        private static void NotifyFeed(Feed feed, bool isEdit, FeedType type)
        {
            var initatorInterceptor = new InitiatorInterceptor(new DirectRecipient(feed.Creator, ""));

            try
            {
                NewsNotifyClient.NotifyClient.AddInterceptor(initatorInterceptor);
                var replyToTag = GetReplyToTag(feed, null);
                if (type == FeedType.Poll && feed is FeedPoll)
                {
                    NewsNotifyClient.NotifyClient.SendNoticeAsync(
                        NewsConst.NewFeed, null, null,
                        new TagValue(NewsConst.TagFEED_TYPE, "poll"),
                        new TagValue(NewsConst.TagAnswers, ((FeedPoll)feed).Variants.ConvertAll(v => v.Name)),
                        new TagValue(NewsConst.TagCaption, feed.Caption),
                        new TagValue(NewsConst.TagText, HtmlUtility.GetFull(feed.Text)),
                        new TagValue(NewsConst.TagDate, feed.Date.ToShortString()),
                        new TagValue(NewsConst.TagURL,
                                     CommonLinkUtility.GetFullAbsolutePath(
                                         "~/products/community/modules/news/?docid=" + feed.Id)),
                        new TagValue(NewsConst.TagUserName,
                                     DisplayUserSettings.GetFullUserName(SecurityContext.CurrentAccount.ID)),
                        new TagValue(NewsConst.TagUserUrl,
                                     CommonLinkUtility.GetFullAbsolutePath(
                                         CommonLinkUtility.GetUserProfile(SecurityContext.CurrentAccount.ID))),
                        replyToTag
                        );
                }
                else
                {
                    NewsNotifyClient.NotifyClient.SendNoticeAsync(
                        NewsConst.NewFeed, null, null,
                        new TagValue(NewsConst.TagFEED_TYPE, "feed"),
                        new TagValue(NewsConst.TagCaption, feed.Caption),
                        new TagValue(NewsConst.TagText,
                                     HtmlUtility.GetFull(feed.Text)),
                        new TagValue(NewsConst.TagDate, feed.Date.ToShortString()),
                        new TagValue(NewsConst.TagURL,
                                     CommonLinkUtility.GetFullAbsolutePath(
                                         "~/products/community/modules/news/?docid=" + feed.Id)),
                        new TagValue(NewsConst.TagUserName,
                                     DisplayUserSettings.GetFullUserName(SecurityContext.CurrentAccount.ID)),
                        new TagValue(NewsConst.TagUserUrl,
                                     CommonLinkUtility.GetFullAbsolutePath(
                                         CommonLinkUtility.GetUserProfile(SecurityContext.CurrentAccount.ID))),
                        replyToTag
                        );
                }

                // subscribe to new comments
                var subsciber = NewsNotifySource.Instance.GetSubscriptionProvider();
                var me        = (IDirectRecipient)NewsNotifySource.Instance.GetRecipientsProvider().GetRecipient(SecurityContext.CurrentAccount.ID.ToString());
                if (me != null && !subsciber.IsUnsubscribe(me, NewsConst.NewComment, feed.Id.ToString(CultureInfo.InvariantCulture)))
                {
                    subsciber.Subscribe(NewsConst.NewComment, feed.Id.ToString(CultureInfo.InvariantCulture), me);
                }
            }
            finally
            {
                NewsNotifyClient.NotifyClient.RemoveInterceptor(initatorInterceptor.Name);
            }
        }
Ejemplo n.º 26
0
        public static string GetOneCommentHtml(
            CommentInfo comment,
            bool odd,
            Func <string, string> userProfileLink,
            string jsObjName,
            string editCommentLink,
            string responseCommentLink,
            string removeCommentLink,
            string inactiveMessage,
            string confirmRemoveCommentMessage,
            string javaScriptRemoveCommentFunctionName,
            string PID)
        {
            var sb = new StringBuilder();

            sb.Append("<div class='blockComments " + (odd ? OddClass : EvenClass) + "' id=\"comment_" + comment.CommentID + "\" style='" + (odd ? OddStyle : EvenStyle) + " padding: 8px 5px 8px 15px;'><a name=\"" + comment.CommentID + "\"></a>");
            if (comment.Inactive)
            {
                sb.AppendFormat("<div  style=\"padding:10px;\">{0}</div>", inactiveMessage);
            }
            else
            {
                sb.Append("<table width='100%' cellpadding=\"0\" style='table-layout:fixed;' cellspacing=\"0\" border=\"0\" >");
                sb.Append("<tr><td valign=\"top\" width='90'>");
                sb.Append(comment.UserAvatar);
                sb.Append("</td><td valign=\"top\"><div style=\"min-height:55px;\"><div>");
                sb.Append("<a style=\"margin-left:10px;\" class=\"link bold\" href=\"" + userProfileLink(comment.UserID.ToString()) + "\">" + comment.UserFullName + "</a>");
                sb.Append("&nbsp;&nbsp;");
                sb.Append("<span class=\"text-medium-describe\" style='padding-left:5px;'>" + (String.IsNullOrEmpty(comment.TimeStampStr) ? comment.TimeStamp.ToLongDateString() : comment.TimeStampStr) + "</span>");

                sb.Append("</div>");

                if (!string.IsNullOrEmpty(comment.UserPost))
                {
                    sb.AppendFormat("<div style=\"padding-top:2px;padding-left:10px;\" class='describe-text'>{0}</div>", comment.UserPost.HtmlEncode());
                }

                sb.AppendFormat("<div id='content_{0}' style='padding-top:8px;padding-left:10px;' class='longWordsBreak'>", comment.CommentID);
                sb.Append(HtmlUtility.GetFull(comment.CommentBody));
                sb.Append("</div>");

                if (comment.Attachments != null && comment.Attachments.Count > 0)
                {
                    sb.Append("<div id='attacments_" + comment.CommentID + "' style=\"padding-top:10px;padding-left:15px;\">");
                    var k = 0;
                    foreach (var attach in comment.Attachments)
                    {
                        if (k != 0)
                        {
                            sb.Append(", ");
                        }

                        sb.Append("<a class=\"linkDescribe\" href=\"" + attach.FilePath + "\">" + attach.FileName.HtmlEncode() + "</a>");
                        sb.Append("<input name='attacment_name_" + comment.CommentID + "' type='hidden' value='" + attach.FileName + "' />");
                        sb.Append("<input name='attacment_path_" + comment.CommentID + "' type='hidden' value='" + attach.FilePath + "' />");
                        k++;
                    }
                    sb.Append("</div>");
                }
                sb.Append("</div>");
                sb.Append("<div clas='clearFix' style=\"margin: 10px 0px 0px 10px; height:19px;\" >");

                var drowSplitter = false;

                if (comment.IsResponsePermissions)
                {
                    sb.AppendFormat("<div style='float:left;'><a class=\"link dotline gray\" id=\"response_{0}\" href=\"javascript:void(0);\" onclick=\"javascript:CommentsManagerObj.ResponseToComment(this, '{0}');return false;\" >{1}</a></div>",
                                    comment.CommentID, responseCommentLink);
                }

                sb.Append("<div style='float:right;'>");

                if (comment.IsEditPermissions)
                {
                    sb.AppendFormat("<div style='float:right;'><a class=\"link dotline gray\" id=\"edit_{0}\" href=\"javascript:void(0);\" onclick=\"javascript:CommentsManagerObj.EditComment(this, '{0}');return false;\" >{1}</a>",
                                    comment.CommentID, editCommentLink);
                    drowSplitter = true;
                }

                if (comment.IsEditPermissions)
                {
                    if (drowSplitter)
                    {
                        sb.Append("<span class=\"text-medium-describe  splitter\"> </span>");
                    }

                    sb.AppendFormat(
                        "<a class=\"link dotline gray\" id=\"remove_{0}\" href=\"javascript:void(0);\" onclick=\"javascript:AjaxPro.onLoading = function(b){{}}; " +
                        "StudioConfirm.OpenDialog('', function() {{{3}('{0}'," + (String.IsNullOrEmpty(PID) ? "" : "'" + PID + "' ,") + "CommentsManagerObj.callbackRemove)}}); return false;\" >{1}</a>",
                        comment.CommentID, removeCommentLink, confirmRemoveCommentMessage, javaScriptRemoveCommentFunctionName);
                }
                sb.Append("</div>");

                sb.Append("</div>");
                sb.Append("</td></tr></table>");
            }
            sb.Append("</div>");

            return(sb.ToString());
        }
Ejemplo n.º 27
0
        /// <summary>
        /// 获取文章发布日期
        /// </summary>
        /// <param name="html"></param>
        /// <returns></returns>
        private static string GetPublishDate(string html)
        {
            HtmlNode htmlNode = HtmlUtility.getSafeHtmlRootNode(html, true, true);

            return(GetPublishDate(htmlNode));
        }
Ejemplo n.º 28
0
        private void ShowBlogDetails(Post post)
        {
            if (post == null)
            {
                return;
            }

            var sb   = new StringBuilder();
            var user = CoreContext.UserManager.GetUsers(post.UserID);

            if (IsPreview)
            {
                sb.Append("<div style='margin-bottom: 20px'>");
                sb.Append("<div id=\"previewTitle\" class='containerHeaderBlock' style='padding: 0 8px;'>" + HttpUtility.HtmlEncode(post.Title) + "</div>");
            }
            else
            {
                sb.Append("<div>");
            }

            sb.Append("<table class='MainBlogsTable' cellspacing='0' cellpadding='8' border='0'>");
            sb.Append("<tr>");
            sb.Append("<td valign='top' class='avatarContainer'>");
            sb.Append("<div>" + ImageHTMLHelper.GetHTMLUserAvatar(post.UserID) + "</div>");
            sb.Append("</td>");

            sb.Append("<td valign='top'>");

            sb.Append("<div class=\"author-title describe-text\">" + BlogsResource.PostedTitle + ":</div>");
            sb.Append("<div class=\"author-name\">");
            sb.AppendFormat("<a class='linkMedium' href=\"{0}\">{1}</a>", user.GetUserProfilePageURL(), user.DisplayUserName());
            sb.Append("</div>");
            sb.Append("<div>");
            sb.AppendFormat("<a class='linkMedium gray-text' href='{0}?userid={1}'>{2}</a>",
                            VirtualPathUtility.ToAbsolute(ASC.Blogs.Core.Constants.BaseVirtualPath),
                            user.ID,
                            BlogsResource.AllRecordsOfTheAutor);
            sb.Append("</div>");
            sb.Append("<div class='describe-text' style='margin-top:10px'>");
            sb.AppendFormat("{0}<span style='margin-left:20px'>{1}</span>", post.Datetime.ToString("d"), post.Datetime.ToString("t"));
            sb.Append("</div>");

            if (!IsPreview)
            {
                sb.Append("<div id=\"blogActionsMenuPanel\" class=\"studio-action-panel\">");
                sb.Append("<ul class=\"dropdown-content\">");
                if (CommunitySecurity.CheckPermissions(post, ASC.Blogs.Core.Constants.Action_EditRemovePost))
                {
                    sb.Append("<li><a class=\"dropdown-item\" href=\"editblog.aspx?blogid=" + Request.QueryString["blogid"] + "\" >" + BlogsResource.EditBlogLink + "</a></li>");
                    sb.Append("<li><a class=\"dropdown-item\" onclick=\"javascript:return confirm('" + BlogsResource.ConfirmRemovePostMessage + "');\" href=\"editblog.aspx?blogid=" + Request.QueryString["blogid"] + "&action=delete\" >" + BlogsResource.DeleteBlogLink + "</a></li>");
                }
                sb.Append("</ul>");
                sb.Append("</div>");
            }
            sb.Append("</td></tr></table>");

            sb.Append("<div id='previewBody' class='longWordsBreak ContentMainBlog'>");

            sb.Append(HtmlUtility.GetFull(post.Content));

            sb.Append("</div>");

            if (!IsPreview)
            {
                sb.Append("<div  class='clearFix'>");
                if (post.TagList.Count > 0)
                {
                    sb.Append("<div class=\"text-medium-describe TagsMainBlog\">");
                    sb.Append("<img class=\"TagsImgMainBlog\" src=\"" + WebImageSupplier.GetAbsoluteWebPath("tags.png", BlogsSettings.ModuleID) + "\">");

                    var j = 0;
                    foreach (var tag in post.TagList)
                    {
                        if (j != 0)
                        {
                            sb.Append(", ");
                        }
                        j++;
                        sb.Append("<a style='margin-left:5px;' class=\"linkMedium gray-text\" href=\"./?tagname=" + HttpUtility.UrlEncode(tag.Content) + "\">" + HttpUtility.HtmlEncode(tag.Content) + "</a>");
                    }

                    sb.Append("</div>");
                }

                sb.Append("</div>");
            }

            sb.Append("</div>");

            ltrContent.Text = sb.ToString();
        }
        protected string RenderRecentUpdate(Thread thread)
        {
            if (thread.RecentPostID == 0)
            {
                return("");
            }

            var sb = new StringBuilder();

            sb.Append("<div><a title=\"" + HttpUtility.HtmlEncode(thread.RecentTopicTitle) + "\" href=\"" + _settings.LinkProvider.PostList(thread.RecentTopicID) + "\">" + HttpUtility.HtmlEncode(HtmlUtility.GetText(thread.RecentTopicTitle, 20)) + "</a></div>");

            sb.Append("<div style='margin-top:5px;overflow: hidden;width: 180px;'>" + ASC.Core.Users.StudioUserInfoExtension.RenderProfileLink(CoreContext.UserManager.GetUsers(thread.RecentPosterID), _settings.ProductID) + "</div>");
            sb.Append("<div style='margin-top:5px;'>");
            sb.Append("<span class='textSmallDescribe'>" + DateTimeExtension.AgoSentence(thread.RecentPostCreateDate) + "</span>");
            sb.Append("<a href=\"" + _settings.LinkProvider.RecentPost(thread.RecentPostID, thread.RecentTopicID, thread.RecentTopicPostCount) + "\"><img hspace=\"3\" align=\"absmiddle\" alt=\"&raquo;\" title=\"&raquo;\" border=\"0\" src=\"" + WebImageSupplier.GetAbsoluteWebPath("goto.png", _settings.ImageItemID) + "\"/></a>");
            sb.Append("</div>");

            return(sb.ToString());
        }
Ejemplo n.º 30
0
        protected override void RenderContents(HtmlTextWriter writer)
        {
            writer.AddAttribute("class", "tableBase");
            writer.AddAttribute("cellspacing", "0");
            writer.AddAttribute("cellpadding", "7");
            writer.RenderBeginTag(HtmlTextWriterTag.Table);

            writer.RenderBeginTag(HtmlTextWriterTag.Tbody);


            foreach (var searchItemResult in Items.GetRange(0, (MaxCount < Items.Count) ? MaxCount : Items.Count))
            {
                var relativeInfo = searchItemResult.Additional["relativeInfo"].ToString();

                if (String.IsNullOrEmpty(relativeInfo))
                {
                    relativeInfo = searchItemResult.Description.HtmlEncode();
                }
                else
                {
                    relativeInfo = String.Format("<span class='textBigDescribe'>{0}</span> {1}", CRMCommonResource.RelativeTo,
                                                 relativeInfo.HtmlEncode());
                }

                writer.RenderBeginTag(HtmlTextWriterTag.Tr);

                writer.AddStyleAttribute("white-space", "nowrap");
                writer.AddAttribute("class", "borderBase img");
                writer.RenderBeginTag(HtmlTextWriterTag.Td);

                writer.AddAttribute("title", searchItemResult.Additional["typeInfo"].ToString());
                writer.AddAttribute("alt", searchItemResult.Additional["typeInfo"].ToString());
                writer.AddAttribute("src", searchItemResult.Additional["imageRef"].ToString());
                writer.RenderBeginTag(HtmlTextWriterTag.Img);
                writer.RenderEndTag();

                writer.RenderEndTag();

                writer.AddStyleAttribute("width", "100%");
                writer.AddAttribute("class", "borderBase");
                writer.RenderBeginTag(HtmlTextWriterTag.Td);

                writer.AddAttribute(HtmlTextWriterAttribute.Href, searchItemResult.URL);
                writer.AddAttribute("class", "title linkHeaderMedium");
                writer.RenderBeginTag(HtmlTextWriterTag.A);
                writer.Write(HtmlUtility.SearchTextHighlight(Text, searchItemResult.Name.HtmlEncode(), false));
                writer.RenderEndTag();

                if (!String.IsNullOrEmpty(relativeInfo))
                {
                    writer.WriteBreak();
                    writer.Write(relativeInfo);
                }

                writer.RenderEndTag();


                writer.AddAttribute("class", "borderBase");
                writer.AddStyleAttribute("white-space", "nowrap");
                writer.RenderBeginTag(HtmlTextWriterTag.Td);

                writer.AddAttribute("class", "textBigDescribe");
                writer.RenderBeginTag(HtmlTextWriterTag.Span);
                writer.Write(searchItemResult.Date.Value.ToShortDateString());
                writer.RenderEndTag();


                writer.RenderEndTag();

                writer.RenderEndTag();
            }

            writer.RenderEndTag();
            writer.RenderEndTag();
        }
Ejemplo n.º 31
0
        protected override void RenderContents(HtmlTextWriter writer)
        {
            writer.AddAttribute(HtmlTextWriterAttribute.Class, "tableBase");
            writer.AddAttribute("cellspacing", "0");
            writer.AddAttribute("cellpadding", "8");
            writer.RenderBeginTag(HtmlTextWriterTag.Table);

            writer.RenderBeginTag(HtmlTextWriterTag.Tbody);

            foreach (var srGroup in Items.GetRange(0, (MaxCount < Items.Count) ? MaxCount : Items.Count))
            {
                writer.AddAttribute(HtmlTextWriterAttribute.Class, "search-result-item");
                writer.RenderBeginTag(HtmlTextWriterTag.Tr);

                writer.AddAttribute(HtmlTextWriterAttribute.Class, "borderBase left-column gray-text");
                writer.RenderBeginTag(HtmlTextWriterTag.Td);
                writer.AddAttribute(HtmlTextWriterAttribute.Title, srGroup.Additional["Hint"].ToString());
                writer.RenderBeginTag(HtmlTextWriterTag.Div);
                writer.Write(srGroup.Additional["Hint"].ToString());
                writer.RenderEndTag();
                writer.RenderEndTag();

                writer.AddAttribute(HtmlTextWriterAttribute.Class, "borderBase center-column");
                writer.RenderBeginTag(HtmlTextWriterTag.Td);

                writer.AddAttribute(HtmlTextWriterAttribute.Href, srGroup.URL);
                writer.AddAttribute(HtmlTextWriterAttribute.Class, "link bold");
                writer.RenderBeginTag(HtmlTextWriterTag.A);
                writer.Write(HtmlUtility.SearchTextHighlight(Text, srGroup.Name.HtmlEncode(), false));
                writer.RenderEndTag();

                writer.WriteBreak();

                if ((EntityType)(Enum.Parse(typeof(EntityType), (srGroup.Additional["Type"]).ToString())) == EntityType.Project)
                {
                    writer.AddAttribute(HtmlTextWriterAttribute.Class, "describe-text");
                    writer.RenderBeginTag(HtmlTextWriterTag.Span);
                    writer.Write(CheckEmptyValue(HtmlUtility.SearchTextHighlight("", HttpUtility.HtmlEncode(HtmlUtility.GetText(srGroup.Description, 100)))));
                    writer.RenderEndTag();
                }
                else
                {
                    writer.AddAttribute(HtmlTextWriterAttribute.Class, "describe-text");
                    writer.RenderBeginTag(HtmlTextWriterTag.Span);
                    writer.Write(Resources.ProjectsCommonResource.InProject);
                    writer.RenderEndTag();
                    writer.Write("&nbsp;");
                    writer.RenderBeginTag(HtmlTextWriterTag.Span);
                    writer.Write(srGroup.Additional["ProjectName"].ToString().HtmlEncode());
                    writer.RenderEndTag();
                }

                writer.RenderEndTag();

                writer.AddAttribute(HtmlTextWriterAttribute.Class, "borderBase right-column gray-text");
                writer.RenderBeginTag(HtmlTextWriterTag.Td);
                if (srGroup.Date.HasValue)
                {
                    writer.AddAttribute(HtmlTextWriterAttribute.Title, srGroup.Date.Value.ToShortDateString());
                    writer.RenderBeginTag(HtmlTextWriterTag.Div);
                    writer.Write(srGroup.Date.Value.ToShortDateString());
                    writer.RenderEndTag();
                }
                writer.RenderEndTag();

                writer.RenderEndTag();
            }

            writer.RenderEndTag();
            writer.RenderEndTag();
        }
Ejemplo n.º 32
0
        public virtual ActionResult AddPost(AddPostModel postModel)
        {
            if (!ModelState.IsValid)
            {
                return(PartialView(MVC.Admin.Shared.Views._ValidationSummery));
            }

            postModel.PostBody = postModel.PostBody.ToSafeHtml();
            //postModel.Book.Description = postModel.Book.Description.ToSafeHtml();

            var post = new Post
            {
                Body          = postModel.PostBody,
                CommentStatus = postModel.PostCommentStatus,
                CreatedDate   = DateAndTime.GetDateTime(),
                Description   = postModel.PostDescription,
                Keyword       = postModel.PostKeyword,
                Picture       = postModel.PostPicture,
                Status        = postModel.PostStatus.ToString().ToLower(),
                Title         = postModel.PostTitle,
            };

            #region Comment
            //var book = new Book
            //{
            //    Author = postModel.Book.Author,
            //    Description = postModel.Book.Description,
            //    ISBN = postModel.Book.ISBN,
            //    Language = postModel.Book.Language,
            //    Name = postModel.Book.Name,
            //    Year = postModel.Book.Year,
            //    Publisher = postModel.Book.Publisher,
            //    Page = postModel.Book.Page
            //};

            //var bookImage = new BookImage
            //{
            //    Path = postModel.BookImage.Path,
            //    Title = postModel.BookImage.Title,
            //    Description = postModel.BookImage.Description,
            //    UploadedDate = DateAndTime.GetDateTime()
            //};

            //var links = new List<DownloadLink>();

            //if (!string.IsNullOrEmpty(postModel.DownloadLinks.DownloadLink1.Link))
            //{
            //    links.Add(postModel.DownloadLinks.DownloadLink1);
            //}
            //if (!string.IsNullOrEmpty(postModel.DownloadLinks.DownloadLink2.Link))
            //{
            //    links.Add(postModel.DownloadLinks.DownloadLink2);
            //}
            //if (!string.IsNullOrEmpty(postModel.DownloadLinks.DownloadLink3.Link))
            //{
            //    links.Add(postModel.DownloadLinks.DownloadLink3);
            //}
            //if (!string.IsNullOrEmpty(postModel.DownloadLinks.DownloadLink4.Link))
            //{
            //    links.Add(postModel.DownloadLinks.DownloadLink4);
            //}

            //post.Book = book;
            //post.DownloadLinks = links;
            //post.Book.Image = bookImage;
            #endregion
            post.User   = _userService.GetUserByUserName(User.Identity.Name);
            post.Labels = _labelService.GetLabelsById(postModel.LabelId);

            _postService.AddPost(post);
            _uow.SaveChanges();

            #region Indexing new Post by Lucene.NET

            //Index the new Post lucene.NET
            new LucenePostSearch(_postService);
            Post lastPost = _postService.Find(post.Id);
            LucenePostSearch.AddUpdateLuceneIndex(new LucenePostModel
            {
                Labels      = string.Join(" , ", lastPost.Labels.Select(l => l.Name).ToArray()),
                Body        = HtmlUtility.RemoveHtmlTags(lastPost.Body),
                Description = lastPost.Description,
                Keywords    = lastPost.Keyword,
                PostId      = lastPost.Id,
                Title       = lastPost.Title
            });

            #endregion

            return(PartialView(MVC.Admin.Shared.Views._Alert,
                               new Alert {
                Message = "دانشنامه جدید با موقیت در سیستم ثبت شد", Mode = AlertMode.Success
            }));
        }