public ActionResult Create(int subforumID, int userID, string threadTitle, string threadContent)
        {
            if (!SessionHandler.Logon)
                return RedirectToAction("Index", "Login");

            User user = db.Users.SingleOrDefault(i => i.id == SessionHandler.UID);

            if (user.is_banned)
                return View("Error", new ArgumentException("You cannot add new threads or posts while banned."));

            ForumThread ft = new ForumThread();
            ft.author_id = userID;
            ft.datetime_posted = DateTime.Now;
            ft.num_hits = 1;
            ft.title = SecurityHelper.StripHTML(threadTitle);
            ft.subforum_id = subforumID;

            db.ForumThreads.Add(ft);

            db.SaveChanges();

            ForumPost fp = new ForumPost();
            fp.author_id = userID;
            fp.datetime_posted = DateTime.Now;
            fp.thread_id = ft.id;
            fp.text = SecurityHelper.StripHTMLExceptAnchor(threadContent);

            db.ForumPosts.Add(fp);

            db.SaveChanges();

            return RedirectToAction("Index", "Posts", new { threadID = ft.id });
        }
Exemplo n.º 2
0
        public static List<ForumPost> GetPostIdsPages()
        {
            List<ForumPost> postInfoList = new List<ForumPost>();
            using (SqlConnection con = new SqlConnection(connectstring))
            {
                try
                {                    
                    con.Open();
                    SqlCommand cmd = con.CreateCommand();
                    cmd.CommandText = @"select distinct ThreadID,PageCount from [dbo].[FirstPostTemp] where PageCount>1";
                    SqlDataReader reader = cmd.ExecuteReader();
                    while (reader.Read())
                    {
                        ForumPost post = new ForumPost();
                        post.ThreadID = int.Parse(reader["ThreadID"].ToString());
                        post.PageCount = int.Parse(reader["PageCount"].ToString());
                        postInfoList.Add(post);
                    }

                }
                catch (SqlException e)
                {
                    throw e;
                }
                finally
                {
                    con.Close();
                    con.Dispose();
                }
                return postInfoList;
            }
        }
Exemplo n.º 3
0
        private void addPost( object[] args, object target ) {

            OpenComment comment = args[0] as OpenComment;
            if (comment == null || comment.Id <= 0) return;

            // 只监控论坛评论,其他所有评论跳过
            if (comment.TargetDataType != typeof( ForumTopic ).FullName) return;

            // 附属信息
            ForumTopic topic = commentService.GetTarget( comment ) as ForumTopic;
            User creator = comment.Member;
            IMember owner = getOwner( topic );
            IApp app = ForumApp.findById( topic.AppId );

            // 内容
            ForumPost post = new ForumPost();

            post.ForumBoardId = topic.ForumBoard.Id;
            post.TopicId = topic.Id;
            post.ParentId = getParentId( comment, topic );
            post.Title = "re:" + topic.Title;
            post.Content = comment.Content;
            post.Ip = comment.Ip;


            // 保存
            // 因为comment本身已有通知,所以论坛不再发通知
            postService.InsertNoNotification( post, creator, owner, app );

            // 同步表
            CommentSync objSync = new CommentSync();
            objSync.Post = post;
            objSync.Comment = comment;
            objSync.insert();
        }
Exemplo n.º 4
0
 public static String GetPostEdit( List<ForumBoard> boards, ForumPost post, MvcContext ctx )
 {
     StringBuilder sb = getBuilder( boards, ctx );
     sb.AppendFormat( "<span style=\"margin-left:5px;\">" + alang( ctx, "pPostEdit" ) + ": <a href=\"{0}\">{1}</a></span>", alink.ToAppData( post ), post.Title );
     sb.Append( "</div></div>" );
     return sb.ToString();
 }
Exemplo n.º 5
0
 private Boolean boardError( ForumPost post ) {
     if (ctx.GetLong( "boardId" ) != post.ForumBoardId) {
         echoRedirect( lang( "exNoPermission" ) + ": borad id error" );
         return true;
     }
     return false;
 }
        public ActionResult AddPost(int parentThread, string postContent)
        {
            //checks if the user has been authenticated
            if (!SessionHandler.Logon)
                return RedirectToAction("Index", "Login");

            //checks if the user is banned
            User user = _db.Users.SingleOrDefault(i => i.id == SessionHandler.UID);

            if (user.is_banned)
                return View("Error", new ArgumentException("You cannot add new threads or posts while banned."));

            //creates a new forum posts and adds it to the database
            ForumPost fp = new ForumPost();
            fp.thread_id = parentThread;
            fp.author_id = SessionHandler.UID;
            fp.text = SecurityHelper.StripHTMLExceptAnchor(postContent);
            fp.datetime_posted = DateTime.Now;

            _db.ForumPosts.Add(fp);

            _db.SaveChanges();

            return RedirectToAction("Index", new { threadID = parentThread });
        }
Exemplo n.º 7
0
        private Boolean hasAdminPermission( ForumPost post )
        {
            ForumBoard board = boardService.GetById( post.ForumBoardId, ctx.owner.obj );

            IList adminCmds = PermissionUtil.GetTopicAdminCmds( (User)ctx.viewer.obj, board, ctx );

            return adminCmds.Count > 0;
        }
Exemplo n.º 8
0
        public string AddDiscussionAjax(int topicid = 0, string addtitle = "", string post = "", string name = "", string email = "", string company = "", bool notify = false, string recaptcha_challenge_field = "", string recaptcha_response_field = "")
        {
            CurtDevDataContext db = new CurtDevDataContext();
            JavaScriptSerializer js = new JavaScriptSerializer();
            #region trycatch
            try {
                string remoteip = (Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null) ? Request.ServerVariables["HTTP_X_FORWARDED_FOR"] : Request.ServerVariables["REMOTE_ADDR"];
                if (!(Models.ReCaptcha.ValidateCaptcha(recaptcha_challenge_field, recaptcha_response_field, remoteip))) {
                    throw new Exception("The Captcha was incorrect. Try again please!");
                }
                if (topicid == 0) { throw new Exception("The topic was invalid."); }
                if (addtitle.Trim() == "") { throw new Exception("Title is required."); }
                if (post.Trim() == "") { throw new Exception("Post is required"); }
                if (email.Trim() != "" && (!IsValidEmail(email.Trim()))) { throw new Exception("Your email address was not a valid address."); }
                if (notify == true && email.Trim() == "") { throw new Exception("You cannot be notified by email without an email address."); }
                if(checkIPAddress(remoteip)) { throw new Exception("You cannot post because your IP Address is blocked by our server."); }

                bool moderation = Convert.ToBoolean(ConfigurationManager.AppSettings["ForumModeration"]);

                ForumThread t = new ForumThread {
                    topicID = topicid,
                    active = true,
                    closed = false,
                    createdDate = DateTime.Now,
                };

                db.ForumThreads.InsertOnSubmit(t);
                db.SubmitChanges();

                ForumPost p = new ForumPost {
                    threadID = t.threadID,
                    title = addtitle,
                    post = post,
                    name = name,
                    email = email,
                    notify = notify,
                    approved = !moderation,
                    company = company,
                    createdDate = DateTime.Now,
                    flag = false,
                    active = true,
                    IPAddress = remoteip,
                    parentID = 0,
                    sticky = false
                };

                db.ForumPosts.InsertOnSubmit(p);
                db.SubmitChanges();

                Post newpost = ForumModel.GetPost(p.postID);
                return js.Serialize(newpost);

            } catch (Exception e) {
                return "{\"error\": \"" + e.Message + "\"}";
            }
            #endregion
        }
Exemplo n.º 9
0
        private string getTopicLastPage( ForumPost post ) {
            String lnk = to( new wojilu.Web.Controller.Forum.TopicController().Show, post.TopicId );
            int pageNo = postService.GetPageCount( post.TopicId, getPageSize( ctx.app.obj ) );
            lnk = PageHelper.AppendNo( lnk, pageNo );

            lnk = lnk + "?rd=" + getRandomStr() + "#post" + post.Id;

            return lnk;
        }
Exemplo n.º 10
0
    private string getPostHTML(ForumPost post)
    {
        String HTML = "<h1>" + post.topic.title + "</h1>";
        List<Comment> comments = post.comments;
        foreach (Comment c in comments)
        {
            HTML += getCommentHTML(c);
        }

        return HTML;
    }
Exemplo n.º 11
0
        private static void updatePost( ForumPost post ) {

            if (post.OwnerType != typeof( Site ).FullName) return;

            IMember owner = Site.Instance;
            int appId = post.AppId;

            IndexViewCacher.Update( owner, appId );
            BoardViewCacher.Update( owner, appId, post.ForumBoardId, 1 );
            RecentViewCacher.Update( owner, appId, "Post" );
        }
Exemplo n.º 12
0
        public void BanPost( ForumPost post )
        {
            // post 所在分页列表失效
            String turl = controller.to( new TopicController().Show, post.TopicId );
            int pageNumber = getPostPage( post.Id, post.TopicId, 10 ); // 所属主题详细页的分页页面失效
            if (pageNumber > 1) {
                turl = Link.AppendPage( turl, pageNumber );
            }
            removeCacheSingle( turl );

            String url = controller.to( new PostController().Show, post.Id );
            removeCacheSingle( url );
        }
Exemplo n.º 13
0
        public ActionResult AddPost(int id = 0, string titlestr = "", string post = "", bool sticky = false)
        {
            string remoteip = (Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null) ? Request.ServerVariables["HTTP_X_FORWARDED_FOR"] : Request.ServerVariables["REMOTE_ADDR"];
            try {
                if (id == 0) throw new Exception("Topic is required.");
                if (titlestr.Trim().Length == 0) throw new Exception("Title is required.");
                if (post.Trim().Length == 0) throw new Exception("Post content is required.");
                CurtDevDataContext db = new CurtDevDataContext();

                ForumThread t = new ForumThread {
                    topicID = id,
                    active = true,
                    closed = false,
                    createdDate = DateTime.Now
                };
                db.ForumThreads.InsertOnSubmit(t);
                db.SubmitChanges();
                user u = Users.GetUser(Convert.ToInt32(Session["userID"]));

                ForumPost p = new ForumPost {
                    threadID = t.threadID,
                    title = titlestr,
                    post = post,
                    IPAddress = remoteip,
                    createdDate = DateTime.Now,
                    approved = true,
                    active = true,
                    flag = false,
                    notify = false,
                    parentID = 0,
                    name = u.fname + " " + u.lname,
                    company = "CURT Manufacturing",
                    email = u.email,
                    sticky = sticky
                };
                db.ForumPosts.InsertOnSubmit(p);
                db.SubmitChanges();

                return RedirectToAction("threads", new { id = id });

            } catch (Exception e) {
                FullTopic topic = ForumModel.GetTopic(id);
                ViewBag.topic = topic;
                ViewBag.error = e.Message;
                ViewBag.titlestr = titlestr;
                ViewBag.post = post;
                ViewBag.sticky = sticky;
                return View();
            }
        }
        public int Create(string title, string content, int categoryId, string userId)
        {
            ForumPost newPost = new ForumPost()
            {
                Title = title,
                Content = content,
                CategoryId = categoryId,
                CreatedOn = DateTime.Now,
                UserId = userId,
            };

            this.forumRepository.Add(newPost);
            this.forumRepository.Save();

            return newPost.Id;
        }
Exemplo n.º 15
0
        private void bindPostOne( IBlock block, ForumPost post )
        {
            String title = post.Title;

            if (strUtil.IsNullOrEmpty( title )) {

                ForumTopic topic = topicService.GetByPost( post.Id );
                if (topic == null) return;

                title = "re:" + topic.Title;
            }

            block.Set( "p.Titile", title );
            block.Set( "p.Url", Link.To( post.OwnerType, post.OwnerUrl, new PostController().Show, post.Id, post.AppId ) );

            block.Set( "p.CreateTime", post.Created );

            block.Next();
        }
Exemplo n.º 16
0
        // 创建回帖
        public void CreatePost( ForumPost post )
        {
            ForumTopic topic = topicService.GetById( post.TopicId, owner );

            List<String> urls = new List<String>();
            urls.Add( controller.to( new ForumController().Index ) ); // 论坛首页失效

            ForumBoard bd = boardService.GetById( topic.ForumBoard.Id, owner );
            addBoardUrl( urls, bd, 0 ); // 所在版块失效(帖子被顶到前面)

            removeCacheList( urls );

            //-------------------------------------------------
            // 修改 forum 和 topic 的 timestamp,让论坛最新主题、所有主题的回帖列表失效
            String forumKey = "forum_" + controller.ctx.app.Id;
            cacheHelper.SetTimestamp( forumKey, DateTime.Now );

            String topicKey = "forumtopic_" + topic.Id;
            cacheHelper.SetTimestamp( topicKey, DateTime.Now );
        }
Exemplo n.º 17
0
        public virtual Result InsertNoNotification( ForumPost post, User creator, IMember owner, IApp app )
        {
            post.AppId = app.Id;
            post.Creator = creator;
            post.CreatorUrl = creator.Url;
            post.OwnerId = owner.Id;
            post.OwnerUrl = owner.Url;
            post.OwnerType = owner.GetType().FullName;
            post.EditTime = DateTime.Now;

            Result result = db.insert( post );

            if (result.IsValid) {

                updateCount( post, creator, owner, app );

                String msg = string.Format( "回复帖子 <a href=\"{0}\">{1}</a>,得到奖励", alink.ToAppData( post ), post.Title );
                incomeService.AddIncome( creator, UserAction.Forum_ReplyTopic.Id, msg );
                addFeedInfo( post );

            }
            return result;
        }
        public static MvcHtmlString Print(this HtmlHelper helper, ForumThread thread)
        {
            var url = Global.UrlHelper();

            ForumThreadLastRead lastRead = null;
            DateTime?           lastTime = null;

            if (Global.Account != null)
            {
                lastRead = Global.Account.ForumThreadLastReads.FirstOrDefault(x => x.ForumThreadID == thread.ForumThreadID);
            }
            if (lastRead != null)
            {
                lastTime = lastRead.LastRead;
            }
            ForumPost post = null;

            if (lastTime != null)
            {
                post = thread.ForumPosts.FirstOrDefault(x => x.Created > lastTime);
            }
            int page = post != null?ZeroKWeb.Controllers.ForumController.GetPostPage(post.ForumPostID) : (thread.PostCount - 1) / GlobalConst.ForumPostsPerPage;

            string link;

            if (page > 0)
            {
                link = url.Action("Thread", "Forum", new { id = thread.ForumThreadID, page = page });
            }
            else
            {
                link = url.Action("Thread", "Forum", new { id = thread.ForumThreadID });
            }
            link = string.Format("<a href='{0}' title='$thread${1}'>", link, thread.ForumThreadID);

            string format;

            if (lastRead == null)
            {
                format = "<span>{0}<img src='/img/mail/mail-unread.png' height='15' /><i>{1}</i></a></span>";
            }
            else
            {
                if (lastRead.LastRead >= thread.LastPost)
                {
                    format = "<span>{0}<img src='/img/mail/mail-read.png' height='15' />{1}</a></span>";
                }
                else
                {
                    if (lastRead.LastPosted != null)
                    {
                        format = "<span>{0}<img src='/img/mail/mail-new.png' height='15' /><b>{1}</b></a></span>";
                    }
                    else
                    {
                        format = "<span>{0}<img src='/img/mail/mail-unread.png' height='15' />{1}</a></span>";
                    }
                }
            }

            return(new MvcHtmlString(string.Format(format, link, HttpUtility.HtmlEncode(thread.Title))));
        }
Exemplo n.º 19
0
        public virtual void DeleteToTrash( ForumPost post, User creator, String ip )
        {
            post.Status = TopicStatus.Delete;
            post.update( "Status" );

            ForumTopic topic = topicService.GetByPost( post.Id );
            topic.Replies = topicService.CountReply( topic.Id );
            topic.update( "Replies" );

            // 积分规则中本身定义的是负值,所以此处用AddIncome
            AddAuthorIncome( post, UserAction.Forum_PostDeleted.Id, "删除" );

            forumLogService.AddPost( creator, post.AppId, post.Id, ForumLogAction.Delete, ip );
        }
Exemplo n.º 20
0
        public ActionResult SubmitPost(
            int?threadID,
            int?categoryID,
            int?resourceID,
            int?missionID,
            int?springBattleID,
            int?clanID,
            int?planetID,
            string text,
            string title,
            string wikiKey,
            int?forumPostID)
        {
            if (threadID == null && missionID == null && resourceID == null && springBattleID == null && clanID == null && planetID == null &&
                forumPostID == null && string.IsNullOrWhiteSpace(title))
            {
                return(Content("Cannot post new thread with blank title"));
            }
            if (string.IsNullOrWhiteSpace(text))
            {
                return(Content("Please type some text :)"));
            }

            var penalty = Punishment.GetActivePunishment(Global.AccountID, Request.UserHostAddress, 0, x => x.BanForum);

            if (penalty != null)
            {
                return
                    (Content(
                         string.Format("You cannot post while banned from forum!\nExpires: {0} UTC\nReason: {1}", penalty.BanExpires, penalty.Reason)));
            }

            var db = new ZkDataContext();

            using (var scope = new TransactionScope())
            {
                var thread   = db.ForumThreads.SingleOrDefault(x => x.ForumThreadID == threadID);
                var category = thread?.ForumCategory;
                if (category == null && categoryID != null)
                {
                    category = db.ForumCategories.FirstOrDefault(x => x.ForumCategoryID == categoryID);
                }
                string currentTitle = null;

                // update title
                if (thread != null && !string.IsNullOrEmpty(title))
                {
                    currentTitle   = thread.Title;
                    thread.Title   = title;
                    thread.WikiKey = wikiKey;
                }
                if (thread != null && planetID != null)
                {
                    var planet = db.Planets.Single(x => x.PlanetID == planetID);
                    thread.Title = "Planet " + planet.Name;
                }
                if (thread != null && clanID != null)
                {
                    var clan = db.Clans.Single(x => x.ClanID == clanID);
                    thread.Title = "Clan " + clan.ClanName;
                }
                if (thread != null && missionID != null)
                {
                    var mission = db.Missions.Single(x => x.MissionID == missionID);
                    thread.Title = "Mission " + mission.Name;
                }
                if (thread != null && resourceID != null)
                {
                    var map = db.Resources.Single(x => x.ResourceID == resourceID);
                    thread.Title = "Map " + map.InternalName;
                }

                if (threadID == null && category != null) // new thread
                {
                    if (category.IsLocked)
                    {
                        return(Content("Thread is locked"));
                    }

                    if (category.ForumMode == ForumMode.Wiki)
                    {
                        if (string.IsNullOrEmpty(wikiKey) || !Account.IsValidLobbyName(wikiKey))
                        {
                            return(Content("You need to set a valid wiki key"));
                        }
                        if (db.ForumThreads.Any(y => y.WikiKey == wikiKey))
                        {
                            return(Content("This wiki key already exists"));
                        }
                    }

                    if (string.IsNullOrEmpty(title))
                    {
                        return(Content("Title cannot be empty"));
                    }
                    thread = new ForumThread();
                    thread.CreatedAccountID = Global.AccountID;
                    thread.Title            = title;
                    thread.WikiKey          = wikiKey;
                    thread.ForumCategoryID  = category.ForumCategoryID;
                    db.ForumThreads.InsertOnSubmit(thread);
                }

                if (thread == null && resourceID != null) // non existing thread, we posted new post on map
                {
                    var res = db.Resources.Single(x => x.ResourceID == resourceID);
                    if (res.ForumThread != null)
                    {
                        return(Content("Double post"));
                    }
                    thread = new ForumThread
                    {
                        Title             = "Map " + res.InternalName,
                        CreatedAccountID  = Global.AccountID,
                        LastPostAccountID = Global.AccountID
                    };
                    thread.ForumCategory = db.ForumCategories.FirstOrDefault(x => x.ForumMode == ForumMode.Maps);
                    res.ForumThread      = thread;
                    db.ForumThreads.InsertOnSubmit(thread);
                }

                if (thread == null && springBattleID != null) // non existing thread, we posted new post on battle
                {
                    var bat = db.SpringBattles.Single(x => x.SpringBattleID == springBattleID);
                    if (bat.ForumThread != null)
                    {
                        return(Content("Double post"));
                    }
                    thread = new ForumThread {
                        Title = bat.FullTitle, CreatedAccountID = Global.AccountID, LastPostAccountID = Global.AccountID
                    };
                    thread.ForumCategory = db.ForumCategories.FirstOrDefault(x => x.ForumMode == ForumMode.SpringBattles);
                    bat.ForumThread      = thread;
                    db.ForumThreads.InsertOnSubmit(thread);
                }

                if (thread == null && clanID != null)
                {
                    var clan = db.Clans.Single(x => x.ClanID == clanID);
                    if (clan.ForumThread != null)
                    {
                        return(Content("Double post"));
                    }
                    thread = new ForumThread
                    {
                        Title             = "Clan " + clan.ClanName,
                        CreatedAccountID  = Global.AccountID,
                        LastPostAccountID = Global.AccountID
                    };
                    thread.ForumCategory = db.ForumCategories.FirstOrDefault(x => x.ForumMode == ForumMode.Clans);
                    clan.ForumThread     = thread;
                    thread.Clan          = clan;
                    db.ForumThreads.InsertOnSubmit(thread);
                }

                if (thread == null && planetID != null)
                {
                    var planet = db.Planets.Single(x => x.PlanetID == planetID);
                    if (planet.ForumThread != null)
                    {
                        return(Content("Double post"));
                    }
                    thread = new ForumThread
                    {
                        Title             = "Planet " + planet.Name,
                        CreatedAccountID  = Global.AccountID,
                        LastPostAccountID = Global.AccountID
                    };
                    thread.ForumCategory = db.ForumCategories.FirstOrDefault(x => x.ForumMode == ForumMode.Planets);
                    planet.ForumThread   = thread;
                    db.ForumThreads.InsertOnSubmit(thread);
                }


                if (thread == null)
                {
                    return(Content("Thread not found"));
                }
                if (thread.IsLocked)
                {
                    return(Content("Thread is locked"));
                }
                if (thread.RestrictedClanID != null && thread.RestrictedClanID != Global.Account.ClanID)
                {
                    return(Content("Cannot post in this clan"));
                }

                var lastPost = thread.ForumPosts.OrderByDescending(x => x.ForumPostID).FirstOrDefault();

                int?gotoPostId = null;
                //double post preventer
                if (lastPost == null || lastPost.AuthorAccountID != Global.AccountID || lastPost.Text != text ||
                    (!string.IsNullOrEmpty(title) && title != currentTitle))
                {
                    if (forumPostID != null)
                    {
                        var post = thread.ForumPosts.Single(x => x.ForumPostID == forumPostID);
                        if (!post.CanEdit(Global.Account))
                        {
                            throw new ApplicationException("Not authorized to edit the post");
                        }
                        post.ForumPostEdits.Add(
                            new ForumPostEdit
                        {
                            EditorAccountID = Global.AccountID,
                            EditTime        = DateTime.UtcNow,
                            OriginalText    = post.Text,
                            NewText         = text
                        });
                        post.Text = text;
                    }
                    else
                    {
                        var p = new ForumPost {
                            AuthorAccountID = Global.AccountID, Text = text, Created = DateTime.UtcNow
                        };
                        thread.ForumPosts.Add(p);
                        db.SaveChanges();
                        gotoPostId = p.ForumPostID;
                    }

                    thread.LastPost          = DateTime.UtcNow;
                    thread.LastPostAccountID = Global.AccountID;
                    thread.PostCount         = thread.ForumPosts.Count();
                    thread.UpdateLastRead(Global.AccountID, true, thread.LastPost);

                    db.SaveChanges();
                }

                scope.Complete();


                if (missionID.HasValue)
                {
                    return(RedirectToAction("Detail", "Missions", new { id = missionID }));
                }
                if (resourceID.HasValue)
                {
                    return(RedirectToAction("Detail", "Maps", new { id = resourceID }));
                }
                if (springBattleID.HasValue)
                {
                    return(RedirectToAction("Detail", "Battles", new { id = springBattleID }));
                }
                if (clanID.HasValue)
                {
                    return(RedirectToAction("Detail", "Clans", new { id = clanID }));
                }
                if (planetID.HasValue)
                {
                    return(RedirectToAction("Planet", "Planetwars", new { id = planetID }));
                }
                if (forumPostID.HasValue)
                {
                    return(RedirectToAction("Thread", "Forum", new { id = thread.ForumThreadID, postID = forumPostID }));
                }
                return(RedirectToAction("Thread", "Forum", new { id = thread.ForumThreadID, postID = gotoPostId }));
            }
        }
Exemplo n.º 21
0
        public void Can_save_and_load_forumpost()
        {
            var customer       = GetTestCustomer();
            var customerFromDb = SaveAndLoadEntity(customer);

            customerFromDb.ShouldNotBeNull();

            var forumGroup = new ForumGroup
            {
                Name         = "Forum Group 1",
                DisplayOrder = 1,
                CreatedOnUtc = DateTime.UtcNow,
                UpdatedOnUtc = DateTime.UtcNow
            };

            var forumGroupFromDb = SaveAndLoadEntity(forumGroup);

            forumGroupFromDb.ShouldNotBeNull();
            forumGroupFromDb.Name.ShouldEqual("Forum Group 1");
            forumGroupFromDb.DisplayOrder.ShouldEqual(1);

            var forum = new Forum
            {
                ForumGroup   = forumGroupFromDb,
                Name         = "Forum 1",
                Description  = "Forum 1 Description",
                ForumGroupId = forumGroupFromDb.Id,
                DisplayOrder = 10,
                CreatedOnUtc = DateTime.UtcNow,
                UpdatedOnUtc = DateTime.UtcNow,
                NumPosts     = 25,
                NumTopics    = 15
            };

            forumGroup.Forums.Add(forum);
            var forumFromDb = SaveAndLoadEntity(forum);

            forumFromDb.ShouldNotBeNull();
            forumFromDb.Name.ShouldEqual("Forum 1");
            forumFromDb.Description.ShouldEqual("Forum 1 Description");
            forumFromDb.DisplayOrder.ShouldEqual(10);
            forumFromDb.NumTopics.ShouldEqual(15);
            forumFromDb.NumPosts.ShouldEqual(25);
            forumFromDb.ForumGroupId.ShouldEqual(forumGroupFromDb.Id);

            var forumTopic = new ForumTopic
            {
                Subject      = "Forum Topic 1",
                ForumId      = forumFromDb.Id,
                TopicTypeId  = (int)ForumTopicType.Sticky,
                Views        = 123,
                CreatedOnUtc = DateTime.UtcNow,
                UpdatedOnUtc = DateTime.UtcNow,
                NumPosts     = 100,
                CustomerId   = customerFromDb.Id,
            };

            var forumTopicFromDb = SaveAndLoadEntity(forumTopic);

            forumTopicFromDb.ShouldNotBeNull();
            forumTopicFromDb.Subject.ShouldEqual("Forum Topic 1");
            forumTopicFromDb.Views.ShouldEqual(123);
            forumTopicFromDb.NumPosts.ShouldEqual(100);
            forumTopicFromDb.TopicTypeId.ShouldEqual((int)ForumTopicType.Sticky);
            forumTopicFromDb.ForumId.ShouldEqual(forumFromDb.Id);

            var forumPost = new ForumPost
            {
                Text         = "Forum Post 1 Text",
                ForumTopic   = forumTopicFromDb,
                TopicId      = forumTopicFromDb.Id,
                IPAddress    = "127.0.0.1",
                CreatedOnUtc = DateTime.UtcNow,
                UpdatedOnUtc = DateTime.UtcNow,
                CustomerId   = customerFromDb.Id,
            };

            var forumPostFromDb = SaveAndLoadEntity(forumPost);

            forumPostFromDb.ShouldNotBeNull();
            forumPostFromDb.Text.ShouldEqual("Forum Post 1 Text");
            forumPostFromDb.IPAddress.ShouldEqual("127.0.0.1");
            forumPostFromDb.TopicId.ShouldEqual(forumTopicFromDb.Id);
        }
Exemplo n.º 22
0
        private void addNotification( ForumPost post )
        {
            ForumTopic topic = ForumTopic.findById( post.TopicId );
            if (topic == null) return;

            // 给主题的作者发送通知
            addNotificationToTopicCreator( topic, post );

            // 给父帖的作者发送通知
            addNotificationToParentCreator( topic, post );
        }
Exemplo n.º 23
0
        public async Task AddForumTokens(LiquidObject liquidObject, Customer customer, Store store, Forum forum, ForumTopic forumTopic = null, ForumPost forumPost = null,
                                         int?friendlyForumTopicPageIndex = null, string appendedPostIdentifierAnchor = "")
        {
            var liquidForum = new LiquidForums(forum, forumTopic, forumPost, customer, store, friendlyForumTopicPageIndex, appendedPostIdentifierAnchor);

            liquidObject.Forums = liquidForum;

            await _mediator.EntityTokensAdded(forum, liquidForum, liquidObject);

            await _mediator.EntityTokensAdded(forumTopic, liquidForum, liquidObject);

            await _mediator.EntityTokensAdded(forumPost, liquidForum, liquidObject);
        }
Exemplo n.º 24
0
        public virtual IActionResult TopicEdit(EditForumTopicModel model, bool captchaValid)
        {
            if (!_forumSettings.ForumsEnabled)
            {
                return(RedirectToRoute("Homepage"));
            }

            var forumTopic = _forumService.GetTopicById(model.Id);

            if (forumTopic == null)
            {
                return(RedirectToRoute("Boards"));
            }

            var forum = _forumService.GetForumById(forumTopic.ForumId);

            if (forum == null)
            {
                return(RedirectToRoute("Boards"));
            }

            //validate CAPTCHA
            if (_captchaSettings.Enabled && _captchaSettings.ShowOnForum && !captchaValid)
            {
                ModelState.AddModelError("", _localizationService.GetResource("Common.WrongCaptchaMessage"));
            }

            if (ModelState.IsValid)
            {
                try
                {
                    if (!_forumService.IsCustomerAllowedToEditTopic(_workContext.CurrentCustomer, forumTopic))
                    {
                        return(Challenge());
                    }

                    var subject          = model.Subject;
                    var maxSubjectLength = _forumSettings.TopicSubjectMaxLength;
                    if (maxSubjectLength > 0 && subject.Length > maxSubjectLength)
                    {
                        subject = subject.Substring(0, maxSubjectLength);
                    }

                    var text          = model.Text;
                    var maxPostLength = _forumSettings.PostMaxLength;
                    if (maxPostLength > 0 && text.Length > maxPostLength)
                    {
                        text = text.Substring(0, maxPostLength);
                    }

                    var topicType = ForumTopicType.Normal;
                    var ipAddress = _webHelper.GetCurrentIpAddress();
                    var nowUtc    = DateTime.UtcNow;

                    if (_forumService.IsCustomerAllowedToSetTopicPriority(_workContext.CurrentCustomer))
                    {
                        topicType = (ForumTopicType)Enum.ToObject(typeof(ForumTopicType), model.TopicTypeId);
                    }

                    //forum topic
                    forumTopic.TopicTypeId  = (int)topicType;
                    forumTopic.Subject      = subject;
                    forumTopic.UpdatedOnUtc = nowUtc;
                    _forumService.UpdateTopic(forumTopic);

                    //forum post
                    var firstPost = _forumService.GetFirstPost(forumTopic);
                    if (firstPost != null)
                    {
                        firstPost.Text         = text;
                        firstPost.UpdatedOnUtc = nowUtc;
                        _forumService.UpdatePost(firstPost);
                    }
                    else
                    {
                        //error (not possible)
                        firstPost = new ForumPost
                        {
                            TopicId      = forumTopic.Id,
                            CustomerId   = forumTopic.CustomerId,
                            Text         = text,
                            IPAddress    = ipAddress,
                            UpdatedOnUtc = nowUtc
                        };

                        _forumService.InsertPost(firstPost, false);
                    }

                    //subscription
                    if (_forumService.IsCustomerAllowedToSubscribe(_workContext.CurrentCustomer))
                    {
                        var forumSubscription = _forumService.GetAllSubscriptions(_workContext.CurrentCustomer.Id,
                                                                                  0, forumTopic.Id, 0, 1).FirstOrDefault();
                        if (model.Subscribed)
                        {
                            if (forumSubscription == null)
                            {
                                forumSubscription = new ForumSubscription
                                {
                                    SubscriptionGuid = Guid.NewGuid(),
                                    CustomerId       = _workContext.CurrentCustomer.Id,
                                    TopicId          = forumTopic.Id,
                                    CreatedOnUtc     = nowUtc
                                };

                                _forumService.InsertSubscription(forumSubscription);
                            }
                        }
                        else
                        {
                            if (forumSubscription != null)
                            {
                                _forumService.DeleteSubscription(forumSubscription);
                            }
                        }
                    }

                    // redirect to the topic page with the topic slug
                    return(RedirectToRoute("TopicSlug", new { id = forumTopic.Id, slug = _forumService.GetTopicSeName(forumTopic) }));
                }
                catch (Exception ex)
                {
                    ModelState.AddModelError("", ex.Message);
                }
            }

            //redisplay form
            _forumModelFactory.PrepareTopicEditModel(forumTopic, model, true);

            return(View(model));
        }
Exemplo n.º 25
0
        public virtual IActionResult PostCreate(EditForumPostModel model, bool captchaValid)
        {
            if (!_forumSettings.ForumsEnabled)
            {
                return(RedirectToRoute("Homepage"));
            }

            var forumTopic = _forumService.GetTopicById(model.ForumTopicId);

            if (forumTopic == null)
            {
                return(RedirectToRoute("Boards"));
            }

            //validate CAPTCHA
            if (_captchaSettings.Enabled && _captchaSettings.ShowOnForum && !captchaValid)
            {
                ModelState.AddModelError("", _localizationService.GetResource("Common.WrongCaptchaMessage"));
            }

            if (ModelState.IsValid)
            {
                try
                {
                    if (!_forumService.IsCustomerAllowedToCreatePost(_workContext.CurrentCustomer, forumTopic))
                    {
                        return(Challenge());
                    }

                    var text          = model.Text;
                    var maxPostLength = _forumSettings.PostMaxLength;
                    if (maxPostLength > 0 && text.Length > maxPostLength)
                    {
                        text = text.Substring(0, maxPostLength);
                    }

                    var ipAddress = _webHelper.GetCurrentIpAddress();

                    var nowUtc = DateTime.UtcNow;

                    var forumPost = new ForumPost
                    {
                        TopicId      = forumTopic.Id,
                        CustomerId   = _workContext.CurrentCustomer.Id,
                        Text         = text,
                        IPAddress    = ipAddress,
                        CreatedOnUtc = nowUtc,
                        UpdatedOnUtc = nowUtc
                    };
                    _forumService.InsertPost(forumPost, true);

                    //subscription
                    if (_forumService.IsCustomerAllowedToSubscribe(_workContext.CurrentCustomer))
                    {
                        var forumSubscription = _forumService.GetAllSubscriptions(_workContext.CurrentCustomer.Id,
                                                                                  0, forumPost.TopicId, 0, 1).FirstOrDefault();
                        if (model.Subscribed)
                        {
                            if (forumSubscription == null)
                            {
                                forumSubscription = new ForumSubscription
                                {
                                    SubscriptionGuid = Guid.NewGuid(),
                                    CustomerId       = _workContext.CurrentCustomer.Id,
                                    TopicId          = forumPost.TopicId,
                                    CreatedOnUtc     = nowUtc
                                };

                                _forumService.InsertSubscription(forumSubscription);
                            }
                        }
                        else
                        {
                            if (forumSubscription != null)
                            {
                                _forumService.DeleteSubscription(forumSubscription);
                            }
                        }
                    }

                    var pageSize = _forumSettings.PostsPageSize > 0 ? _forumSettings.PostsPageSize : 10;

                    var pageIndex = _forumService.CalculateTopicPageIndex(forumPost.TopicId, pageSize, forumPost.Id) + 1;
                    var url       = string.Empty;
                    if (pageIndex > 1)
                    {
                        url = Url.RouteUrl("TopicSlugPaged", new { id = forumPost.TopicId, slug = _forumService.GetTopicSeName(forumTopic), pageNumber = pageIndex });
                    }
                    else
                    {
                        url = Url.RouteUrl("TopicSlug", new { id = forumPost.TopicId, slug = _forumService.GetTopicSeName(forumTopic) });
                    }
                    return(LocalRedirect($"{url}#{forumPost.Id}"));
                }
                catch (Exception ex)
                {
                    ModelState.AddModelError("", ex.Message);
                }
            }

            //redisplay form
            model = _forumModelFactory.PreparePostCreateModel(forumTopic, 0, true);

            return(View(model));
        }
Exemplo n.º 26
0
        public void PostLoop()
        {
            List <ForumPost>  posts   = ctx.GetItem("posts") as List <ForumPost>;
            List <Attachment> attachs = ctx.GetItem("attachs") as List <Attachment>;
            int pageSize = cvt.ToInt(ctx.GetItem("pageSize"));

            ForumBoard board = ctx.GetItem("forumBoard") as ForumBoard;
            ForumTopic topic = ctx.GetItem("forumTopic") as ForumTopic;

            IBlock block = getBlock("posts");

            for (int i = 0; i < posts.Count; i++)
            {
                ForumPost data = posts[i];
                if (data.Creator == null)
                {
                    continue;
                }

                populatePostTopic(data);

                block.Set("post.Id", data.Id);
                block.Set("post.TopicId", data.TopicId);
                block.Set("post.MemberName", data.Creator.Name);
                block.Set("post.MemberUrl", toUser(data.Creator));

                String face = "";
                if (strUtil.HasText(data.Creator.Pic))
                {
                    face = string.Format("<img src=\"{0}\"/>", data.Creator.PicMedium);
                }

                block.Set("post.MemberFace", face);


                block.Set("post.MemberRank", getRankStr(data));
                block.Set("post.StarList", data.Creator.Rank.StarHtml);
                block.Set("post.IncomeList", data.Creator.IncomeInfo);
                block.Set("post.MemberTitle", getUserTitle(data));
                block.Set("post.MemberGender", data.Creator.GenderString);
                block.Set("post.MemberPostCount", data.Creator.PostCount);
                block.Set("post.MemberCreateTime", data.Creator.Created.ToShortDateString());
                block.Set("post.UserLastLogin", data.Creator.LastLoginTime.ToShortDateString());

                String signature = strUtil.HasText(data.Creator.Signature) ? "<div class=\"posC\">" + data.Creator.Signature + "</div>" : "";
                block.Set("post.UserSignature", signature);

                block.Set("post.OnlyOneMember", to(new TopicController().Show, data.TopicId) + "?userId=" + data.Creator.Id);
                block.Set("post.FloorNo", getFloorNumber(pageSize, i));
                block.Set("post.Title", addRewardInfo(data, data.Title));

                block.Set("post.TitleText", data.Title);

                block.Set("post.Admin", getAdminString(data));
                block.Set("post.CreateTime", data.Created);

                List <Attachment> attachList = getAttachByPost(attachs, data.Id);

                if (data.ParentId == 0)
                {
                    bindTopicOne(block, data, board, attachList);
                }
                else
                {
                    bindPostOne(block, data, board, attachList);
                }

                block.Set("relativePosts", getRelativePosts(data));

                block.Set("adForumPosts", AdItem.GetAdById(AdCategory.ForumPosts));


                block.Next();
            }
        }
Exemplo n.º 27
0
 private void setCreditAction(ForumPost data, StringBuilder sb)
 {
     sb.AppendFormat("<li cmdurl=\"{0}\"><a href='#' class=\"postAdminItem frmBox\"><i class=\"icon-gift\"></i> {1}</a></li>", to(new Moderators.PostController().AddCredit, data.Id) + "?boardId=" + data.ForumBoardId, alang("cmdCredit"));
 }
Exemplo n.º 28
0
        //----------------------------------------------------------------------------------------------------------------------------------


        private String getAdminString(ForumPost post)
        {
            return(getAdminActions(post) + " " + getEditAction(post));
        }
Exemplo n.º 29
0
        private string getRelativePosts(ForumPost data)
        {
            if (data.ParentId > 0)
            {
                return("");
            }
            ForumTopic topic = data.Topic;

            if (topic == null)
            {
                return("");
            }

            String tagIds = topic.Tag.TagIds;

            if (strUtil.IsNullOrEmpty(tagIds))
            {
                return("");
            }

            List <DataTagShip> list = DataTagShip.find("TagId in (" + tagIds + ")").list(21);

            if (list.Count <= 1)
            {
                return("");
            }

            StringBuilder sb = new StringBuilder();

            sb.AppendLine("<div class=\"relative-post\">");
            sb.AppendLine("<div class=\"relative-title\">相关文章</div>");
            sb.AppendLine("<ul>");

            List <IAppData> addList = new List <IAppData>();

            foreach (DataTagShip dt in list)
            {
                if (dt.DataId == topic.Id && dt.TypeFullName == typeof(ForumTopic).FullName)
                {
                    continue;
                }

                EntityInfo ei = Entity.GetInfo(dt.TypeFullName);
                if (ei == null)
                {
                    continue;
                }

                IAppData obj = ndb.findById(ei.Type, dt.DataId) as IAppData;
                if (obj == null)
                {
                    continue;
                }

                if (hasAdded(addList, obj))
                {
                    continue;
                }

                sb.AppendFormat("<li><div><a href=\"{0}\">{1}</a></div></li>", alink.ToAppData(obj), obj.Title);
                sb.AppendLine();

                addList.Add(obj);
            }

            sb.AppendLine("</ul>");
            sb.AppendLine("<div style=\"clear:both;\"></div>");
            sb.AppendLine("</div>");

            return(sb.ToString());
        }
Exemplo n.º 30
0
 protected void btnCancel_Click(object sender, EventArgs e)
 {
     try
     {
         if (this.AddTopic)
         {
             Forum forum = ForumManager.GetForumByID(this.ForumID);
             if (forum != null)
             {
                 string forumUrl = SEOHelper.GetForumURL(forum);
                 Response.Redirect(forumUrl);
             }
             else
             {
                 Response.Redirect(SEOHelper.GetForumMainURL());
             }
         }
         else if (this.EditTopic)
         {
             ForumTopic forumTopic = ForumManager.GetTopicByID(this.ForumTopicID);
             if (forumTopic != null)
             {
                 string topicUrl = SEOHelper.GetForumTopicURL(forumTopic.ForumTopicID);
                 Response.Redirect(topicUrl);
             }
             else
             {
                 Response.Redirect(SEOHelper.GetForumMainURL());
             }
         }
         else if (this.AddPost)
         {
             ForumTopic forumTopic = ForumManager.GetTopicByID(this.ForumTopicID);
             if (forumTopic != null)
             {
                 string topicUrl = SEOHelper.GetForumTopicURL(forumTopic.ForumTopicID);
                 Response.Redirect(topicUrl);
             }
             else
             {
                 Response.Redirect(SEOHelper.GetForumMainURL());
             }
         }
         else if (this.EditPost)
         {
             ForumPost forumPost = ForumManager.GetPostByID(this.ForumPostID);
             if (forumPost != null)
             {
                 string topicUrl = SEOHelper.GetForumTopicURL(forumPost.TopicID);
                 Response.Redirect(topicUrl);
             }
             else
             {
                 Response.Redirect(SEOHelper.GetForumMainURL());
             }
         }
     }
     catch (Exception exc)
     {
         pnlError.Visible   = true;
         lErrorMessage.Text = Server.HtmlEncode(exc.Message);
     }
 }
Exemplo n.º 31
0
 public virtual void SubstractAuthorIncome( ForumPost post, int actionId, String actionName )
 {
     String msg = string.Format( "帖子被{0} <a href=\"{1}\">{2}</a>", actionName, alink.ToAppData( post ), post.Title );
     incomeService.AddIncomeReverse( post.Creator, actionId, msg );
 }
Exemplo n.º 32
0
        public virtual int GetPostPage(int postId, int topicId, int pageSize)
        {
            int count = ForumPost.count("Id<=" + postId + " and TopicId=" + topicId + " and " + TopicStatus.GetShowCondition());

            return(getPage(count, pageSize));
        }
Exemplo n.º 33
0
 public virtual Result Update( ForumPost post, User editor )
 {
     post.EditTime = DateTime.Now;
     post.EditCount++;
     post.EditMemberId = editor.Id;
     return db.update( post );
 }
Exemplo n.º 34
0
        //--------------------------------------------------------------------------------


        public virtual int CountReply(int topicId)
        {
            return(ForumPost.find("TopicId=" + topicId + " and Status<>" + TopicStatus.Delete).count() - 1);
        }
Exemplo n.º 35
0
        public virtual async Task <IActionResult> TopicCreate(EditForumTopicModel model, [FromServices] ICustomerService customerService)
        {
            if (!_forumSettings.ForumsEnabled)
            {
                return(RedirectToRoute("HomePage"));
            }

            var forum = await _forumService.GetForumById(model.ForumId);

            if (forum == null)
            {
                return(RedirectToRoute("Boards"));
            }

            if (ModelState.IsValid)
            {
                try
                {
                    if (!_forumService.IsCustomerAllowedToCreateTopic(_workContext.CurrentCustomer, forum))
                    {
                        return(new ChallengeResult());
                    }

                    string subject          = model.Subject;
                    var    maxSubjectLength = _forumSettings.TopicSubjectMaxLength;
                    if (maxSubjectLength > 0 && subject.Length > maxSubjectLength)
                    {
                        subject = subject.Substring(0, maxSubjectLength);
                    }

                    var text          = model.Text;
                    var maxPostLength = _forumSettings.PostMaxLength;
                    if (maxPostLength > 0 && text.Length > maxPostLength)
                    {
                        text = text.Substring(0, maxPostLength);
                    }

                    var topicType = ForumTopicType.Normal;

                    string ipAddress = _webHelper.GetCurrentIpAddress();

                    var nowUtc = DateTime.UtcNow;

                    if (_forumService.IsCustomerAllowedToSetTopicPriority(_workContext.CurrentCustomer))
                    {
                        topicType = (ForumTopicType)Enum.ToObject(typeof(ForumTopicType), model.TopicTypeId);
                    }

                    //forum topic
                    var forumTopic = new ForumTopic
                    {
                        ForumId      = forum.Id,
                        ForumGroupId = forum.ForumGroupId,
                        CustomerId   = _workContext.CurrentCustomer.Id,
                        TopicTypeId  = (int)topicType,
                        Subject      = subject,
                        CreatedOnUtc = nowUtc,
                        UpdatedOnUtc = nowUtc
                    };
                    await _forumService.InsertTopic(forumTopic, true);

                    if (!_workContext.CurrentCustomer.HasContributions)
                    {
                        await customerService.UpdateContributions(_workContext.CurrentCustomer);
                    }
                    //forum post
                    var forumPost = new ForumPost
                    {
                        TopicId      = forumTopic.Id,
                        ForumId      = forum.Id,
                        ForumGroupId = forum.ForumGroupId,
                        CustomerId   = _workContext.CurrentCustomer.Id,
                        Text         = text,
                        IPAddress    = ipAddress,
                        CreatedOnUtc = nowUtc,
                        UpdatedOnUtc = nowUtc
                    };
                    await _forumService.InsertPost(forumPost, false);

                    //update forum topic
                    forumTopic.NumPosts           = 1;
                    forumTopic.LastPostId         = forumPost.Id;
                    forumTopic.LastPostCustomerId = forumPost.CustomerId;
                    forumTopic.LastPostTime       = forumPost.CreatedOnUtc;
                    forumTopic.UpdatedOnUtc       = nowUtc;
                    await _forumService.UpdateTopic(forumTopic);

                    //subscription
                    if (_forumService.IsCustomerAllowedToSubscribe(_workContext.CurrentCustomer))
                    {
                        if (model.Subscribed)
                        {
                            var forumSubscription = new ForumSubscription
                            {
                                SubscriptionGuid = Guid.NewGuid(),
                                CustomerId       = _workContext.CurrentCustomer.Id,
                                TopicId          = forumTopic.Id,
                                CreatedOnUtc     = nowUtc
                            };

                            await _forumService.InsertSubscription(forumSubscription);
                        }
                    }

                    return(RedirectToRoute("TopicSlug", new { id = forumTopic.Id, slug = forumTopic.GetSeName() }));
                }
                catch (Exception ex)
                {
                    ModelState.AddModelError("", ex.Message);
                }
            }
            // redisplay form
            model.TopicPriorities = _boardsViewModelService.ForumTopicTypesList();
            model.IsEdit          = false;
            model.ForumId         = forum.Id;
            model.ForumName       = forum.Name;
            model.ForumSeName     = forum.GetSeName();
            model.Id = "";
            model.IsCustomerAllowedToSetTopicPriority = _forumService.IsCustomerAllowedToSetTopicPriority(_workContext.CurrentCustomer);
            model.IsCustomerAllowedToSubscribe        = _forumService.IsCustomerAllowedToSubscribe(_workContext.CurrentCustomer);
            model.ForumEditor = _forumSettings.ForumEditor;

            return(View(model));
        }
Exemplo n.º 36
0
        public virtual ActionResult PostCreate(EditForumPostModel model)
        {
            if (!_forumSettings.ForumsEnabled)
            {
                return(RedirectToRoute("HomePage"));
            }

            var forumTopic = _forumService.GetTopicById(model.ForumTopicId);

            if (forumTopic == null)
            {
                return(RedirectToRoute("Boards"));
            }

            if (ModelState.IsValid)
            {
                try
                {
                    if (!_forumService.IsCustomerAllowedToCreatePost(_workContext.CurrentCustomer, forumTopic))
                    {
                        return(new HttpUnauthorizedResult());
                    }

                    var text          = model.Text;
                    var maxPostLength = _forumSettings.PostMaxLength;
                    if (maxPostLength > 0 && text.Length > maxPostLength)
                    {
                        text = text.Substring(0, maxPostLength);
                    }

                    string ipAddress = _webHelper.GetCurrentIpAddress();

                    DateTime nowUtc = DateTime.UtcNow;

                    var forumPost = new ForumPost
                    {
                        TopicId      = forumTopic.Id,
                        CustomerId   = _workContext.CurrentCustomer.Id,
                        Text         = text,
                        IPAddress    = ipAddress,
                        CreatedOnUtc = nowUtc,
                        UpdatedOnUtc = nowUtc
                    };
                    _forumService.InsertPost(forumPost, true);

                    //subscription
                    if (_forumService.IsCustomerAllowedToSubscribe(_workContext.CurrentCustomer))
                    {
                        var forumSubscription = _forumService.GetAllSubscriptions(_workContext.CurrentCustomer.Id,
                                                                                  0, forumPost.TopicId, 0, 1).FirstOrDefault();
                        if (model.Subscribed)
                        {
                            if (forumSubscription == null)
                            {
                                forumSubscription = new ForumSubscription
                                {
                                    SubscriptionGuid = Guid.NewGuid(),
                                    CustomerId       = _workContext.CurrentCustomer.Id,
                                    TopicId          = forumPost.TopicId,
                                    CreatedOnUtc     = nowUtc
                                };

                                _forumService.InsertSubscription(forumSubscription);
                            }
                        }
                        else
                        {
                            if (forumSubscription != null)
                            {
                                _forumService.DeleteSubscription(forumSubscription);
                            }
                        }
                    }

                    int pageSize = _forumSettings.PostsPageSize > 0 ? _forumSettings.PostsPageSize : 10;

                    int pageIndex = (_forumService.CalculateTopicPageIndex(forumPost.TopicId, pageSize, forumPost.Id) + 1);
                    var url       = string.Empty;
                    if (pageIndex > 1)
                    {
                        url = Url.RouteUrl("TopicSlugPaged", new { id = forumPost.TopicId, slug = forumPost.ForumTopic.GetSeName(), page = pageIndex });
                    }
                    else
                    {
                        url = Url.RouteUrl("TopicSlug", new { id = forumPost.TopicId, slug = forumPost.ForumTopic.GetSeName() });
                    }
                    return(Redirect(string.Format("{0}#{1}", url, forumPost.Id)));
                }
                catch (Exception ex)
                {
                    ModelState.AddModelError("", ex.Message);
                }
            }

            //redisplay form
            _forumModelFactory.PreparePostCreateModel(forumTopic, 0, true);
            return(View(model));
        }
Exemplo n.º 37
0
        public ActionResult VotePost(int forumPostID, int delta)
        {
            var     db    = new ZkDataContext();
            Account myAcc = Global.Account;

            if (myAcc.Level < GlobalConst.MinLevelForForumVote)
            {
                return(Content(string.Format("You cannot vote until you are level {0} or higher", GlobalConst.MinLevelForForumVote)));
            }
            if ((Global.Account.ForumTotalUpvotes - Global.Account.ForumTotalDownvotes) < GlobalConst.MinNetKarmaToVote)
            {
                return(Content("Your net karma is too low to vote"));
            }

            if (delta > 1)
            {
                delta = 1;
            }
            else if (delta < -1)
            {
                delta = -1;
            }

            ForumPost post   = db.ForumPosts.First(x => x.ForumPostID == forumPostID);
            Account   author = post.Account;

            if (author.AccountID == Global.AccountID)
            {
                return(Content("Cannot vote for your own posts"));
            }
            if (myAcc.VotesAvailable <= 0)
            {
                return(Content("Out of votes"));
            }

            AccountForumVote existingVote = db.AccountForumVotes.SingleOrDefault(x => x.ForumPostID == forumPostID && x.AccountID == Global.AccountID);

            if (existingVote != null)   // clear existing vote
            {
                int oldDelta = existingVote.Vote;
                // reverse vote effects
                if (oldDelta > 0)
                {
                    author.ForumTotalUpvotes = author.ForumTotalUpvotes - oldDelta;
                    post.Upvotes             = post.Upvotes - oldDelta;
                }
                else if (oldDelta < 0)
                {
                    author.ForumTotalDownvotes = author.ForumTotalDownvotes + oldDelta;
                    post.Downvotes             = post.Downvotes + oldDelta;
                }
                db.AccountForumVotes.DeleteOnSubmit(existingVote);
            }
            if (delta > 0)
            {
                author.ForumTotalUpvotes = author.ForumTotalUpvotes + delta;
                post.Upvotes             = post.Upvotes + delta;
            }
            else if (delta < 0)
            {
                author.ForumTotalDownvotes = author.ForumTotalDownvotes - delta;
                post.Downvotes             = post.Downvotes - delta;
            }

            if (delta != 0)
            {
                AccountForumVote voteEntry = new AccountForumVote {
                    AccountID = Global.AccountID, ForumPostID = forumPostID, Vote = delta
                };
                db.AccountForumVotes.InsertOnSubmit(voteEntry);
                myAcc.VotesAvailable--;
            }

            db.SubmitChanges();

            return(RedirectToAction("Thread", new { id = post.ForumThreadID, postID = forumPostID }));
        }
Exemplo n.º 38
0
        public virtual ActionResult TopicCreate(EditForumTopicModel model)
        {
            if (!_forumSettings.ForumsEnabled)
            {
                return(RedirectToRoute("HomePage"));
            }

            var forum = _forumService.GetForumById(model.ForumId);

            if (forum == null)
            {
                return(RedirectToRoute("Boards"));
            }

            if (ModelState.IsValid)
            {
                try
                {
                    if (!_forumService.IsCustomerAllowedToCreateTopic(_workContext.CurrentCustomer, forum))
                    {
                        return(new HttpUnauthorizedResult());
                    }

                    string subject          = model.Subject;
                    var    maxSubjectLength = _forumSettings.TopicSubjectMaxLength;
                    if (maxSubjectLength > 0 && subject.Length > maxSubjectLength)
                    {
                        subject = subject.Substring(0, maxSubjectLength);
                    }

                    var text          = model.Text;
                    var maxPostLength = _forumSettings.PostMaxLength;
                    if (maxPostLength > 0 && text.Length > maxPostLength)
                    {
                        text = text.Substring(0, maxPostLength);
                    }

                    var topicType = ForumTopicType.Normal;

                    string ipAddress = _webHelper.GetCurrentIpAddress();

                    var nowUtc = DateTime.UtcNow;

                    if (_forumService.IsCustomerAllowedToSetTopicPriority(_workContext.CurrentCustomer))
                    {
                        topicType = (ForumTopicType)Enum.ToObject(typeof(ForumTopicType), model.TopicTypeId);
                    }

                    //forum topic
                    var forumTopic = new ForumTopic
                    {
                        ForumId      = forum.Id,
                        CustomerId   = _workContext.CurrentCustomer.Id,
                        TopicTypeId  = (int)topicType,
                        Subject      = subject,
                        CreatedOnUtc = nowUtc,
                        UpdatedOnUtc = nowUtc
                    };
                    _forumService.InsertTopic(forumTopic, true);

                    //forum post
                    var forumPost = new ForumPost
                    {
                        TopicId      = forumTopic.Id,
                        CustomerId   = _workContext.CurrentCustomer.Id,
                        Text         = text,
                        IPAddress    = ipAddress,
                        CreatedOnUtc = nowUtc,
                        UpdatedOnUtc = nowUtc
                    };
                    _forumService.InsertPost(forumPost, false);

                    //update forum topic
                    forumTopic.NumPosts           = 1;
                    forumTopic.LastPostId         = forumPost.Id;
                    forumTopic.LastPostCustomerId = forumPost.CustomerId;
                    forumTopic.LastPostTime       = forumPost.CreatedOnUtc;
                    forumTopic.UpdatedOnUtc       = nowUtc;
                    _forumService.UpdateTopic(forumTopic);

                    //subscription
                    if (_forumService.IsCustomerAllowedToSubscribe(_workContext.CurrentCustomer))
                    {
                        if (model.Subscribed)
                        {
                            var forumSubscription = new ForumSubscription
                            {
                                SubscriptionGuid = Guid.NewGuid(),
                                CustomerId       = _workContext.CurrentCustomer.Id,
                                TopicId          = forumTopic.Id,
                                CreatedOnUtc     = nowUtc
                            };

                            _forumService.InsertSubscription(forumSubscription);
                        }
                    }

                    return(RedirectToRoute("TopicSlug", new { id = forumTopic.Id, slug = forumTopic.GetSeName() }));
                }
                catch (Exception ex)
                {
                    ModelState.AddModelError("", ex.Message);
                }
            }

            //redisplay form
            _forumModelFactory.PrepareTopicCreateModel(forum, model);
            return(View(model));
        }
Exemplo n.º 39
0
        public virtual async Task <IActionResult> TopicEdit(EditForumTopicModel model)
        {
            if (!_forumSettings.ForumsEnabled)
            {
                return(RedirectToRoute("HomePage"));
            }

            var forumTopic = await _forumService.GetTopicById(model.Id);

            if (forumTopic == null)
            {
                return(RedirectToRoute("Boards"));
            }
            var forum = await _forumService.GetForumById(forumTopic.ForumId);

            if (forum == null)
            {
                return(RedirectToRoute("Boards"));
            }

            if (ModelState.IsValid)
            {
                try
                {
                    if (!_forumService.IsCustomerAllowedToEditTopic(_workContext.CurrentCustomer, forumTopic))
                    {
                        return(new ChallengeResult());
                    }

                    string subject          = model.Subject;
                    var    maxSubjectLength = _forumSettings.TopicSubjectMaxLength;
                    if (maxSubjectLength > 0 && subject.Length > maxSubjectLength)
                    {
                        subject = subject.Substring(0, maxSubjectLength);
                    }

                    var text          = model.Text;
                    var maxPostLength = _forumSettings.PostMaxLength;
                    if (maxPostLength > 0 && text.Length > maxPostLength)
                    {
                        text = text.Substring(0, maxPostLength);
                    }

                    var topicType = ForumTopicType.Normal;

                    string ipAddress = _webHelper.GetCurrentIpAddress();

                    DateTime nowUtc = DateTime.UtcNow;

                    if (_forumService.IsCustomerAllowedToSetTopicPriority(_workContext.CurrentCustomer))
                    {
                        topicType = (ForumTopicType)Enum.ToObject(typeof(ForumTopicType), model.TopicTypeId);
                    }

                    //forum topic
                    forumTopic.TopicTypeId  = (int)topicType;
                    forumTopic.Subject      = subject;
                    forumTopic.UpdatedOnUtc = nowUtc;
                    await _forumService.UpdateTopic(forumTopic);

                    //forum post
                    var firstPost = await forumTopic.GetFirstPost(_forumService);

                    if (firstPost != null)
                    {
                        firstPost.Text         = text;
                        firstPost.UpdatedOnUtc = nowUtc;
                        await _forumService.UpdatePost(firstPost);
                    }
                    else
                    {
                        //error (not possible)
                        firstPost = new ForumPost
                        {
                            TopicId      = forumTopic.Id,
                            ForumId      = forum.Id,
                            ForumGroupId = forum.ForumGroupId,
                            CustomerId   = forumTopic.CustomerId,
                            Text         = text,
                            IPAddress    = ipAddress,
                            UpdatedOnUtc = nowUtc
                        };

                        await _forumService.InsertPost(firstPost, false);
                    }

                    //subscription
                    if (_forumService.IsCustomerAllowedToSubscribe(_workContext.CurrentCustomer))
                    {
                        var forumSubscription = (await _forumService.GetAllSubscriptions(_workContext.CurrentCustomer.Id,
                                                                                         "", forumTopic.Id, 0, 1)).FirstOrDefault();
                        if (model.Subscribed)
                        {
                            if (forumSubscription == null)
                            {
                                forumSubscription = new ForumSubscription
                                {
                                    SubscriptionGuid = Guid.NewGuid(),
                                    CustomerId       = _workContext.CurrentCustomer.Id,
                                    TopicId          = forumTopic.Id,
                                    CreatedOnUtc     = nowUtc
                                };

                                await _forumService.InsertSubscription(forumSubscription);
                            }
                        }
                        else
                        {
                            if (forumSubscription != null)
                            {
                                await _forumService.DeleteSubscription(forumSubscription);
                            }
                        }
                    }

                    // redirect to the topic page with the topic slug
                    return(RedirectToRoute("TopicSlug", new { id = forumTopic.Id, slug = forumTopic.GetSeName() }));
                }
                catch (Exception ex)
                {
                    ModelState.AddModelError("", ex.Message);
                }
            }

            // redisplay form
            model.TopicPriorities = _boardsViewModelService.ForumTopicTypesList();
            model.IsEdit          = true;
            model.ForumName       = forum.Name;
            model.ForumSeName     = forum.GetSeName();
            model.ForumId         = forum.Id;
            model.ForumEditor     = _forumSettings.ForumEditor;

            model.IsCustomerAllowedToSetTopicPriority = _forumService.IsCustomerAllowedToSetTopicPriority(_workContext.CurrentCustomer);
            model.IsCustomerAllowedToSubscribe        = _forumService.IsCustomerAllowedToSubscribe(_workContext.CurrentCustomer);

            return(View(model));
        }
Exemplo n.º 40
0
        public virtual void AddReward( ForumPost post, int rewardValue )
        {
            ForumTopic topic = topicService.GetByPost( post.Id );

            post.Reward = rewardValue;
            db.update( post, "Reward" );

            String msg = string.Format( "回复悬赏贴 \"<a href=\"{0}\">{1}</a>\",作者答谢:{2}{3}", alink.ToAppData( topic ), topic.Title, rewardValue, KeyCurrency.Instance.Unit );

            incomeService.AddKeyIncome( post.Creator, rewardValue, msg );

            // 以下步骤不需要,因为发帖的时候已经被扣除了
            //incomeService.AddKeyIncome( topic.Creator, -rewardValue );

            topicService.SubstractTopicReward( topic, rewardValue );

            notificationService.send( post.Creator.Id, msg );
        }
Exemplo n.º 41
0
 public virtual List <ForumPost> GetRecentByApp(int appId, int count)
 {
     return(ForumPost.find("AppId=" + appId + " and " + TopicStatus.GetShowCondition()).list(count));
 }
Exemplo n.º 42
0
        public virtual async Task <IActionResult> PostCreate(EditForumPostModel model, [FromServices] ICustomerService customerService)
        {
            if (!_forumSettings.ForumsEnabled)
            {
                return(RedirectToRoute("HomePage"));
            }

            var forumTopic = await _forumService.GetTopicById(model.ForumTopicId);

            if (forumTopic == null)
            {
                return(RedirectToRoute("Boards"));
            }

            if (ModelState.IsValid)
            {
                try
                {
                    if (!_forumService.IsCustomerAllowedToCreatePost(_workContext.CurrentCustomer, forumTopic))
                    {
                        return(new ChallengeResult());
                    }

                    var text          = model.Text;
                    var maxPostLength = _forumSettings.PostMaxLength;
                    if (maxPostLength > 0 && text.Length > maxPostLength)
                    {
                        text = text.Substring(0, maxPostLength);
                    }

                    string ipAddress = _webHelper.GetCurrentIpAddress();

                    DateTime nowUtc = DateTime.UtcNow;

                    var forumPost = new ForumPost
                    {
                        TopicId      = forumTopic.Id,
                        ForumId      = forumTopic.ForumId,
                        ForumGroupId = forumTopic.ForumGroupId,
                        CustomerId   = _workContext.CurrentCustomer.Id,
                        Text         = text,
                        IPAddress    = ipAddress,
                        CreatedOnUtc = nowUtc,
                        UpdatedOnUtc = nowUtc
                    };
                    await _forumService.InsertPost(forumPost, true);

                    if (!_workContext.CurrentCustomer.HasContributions)
                    {
                        await customerService.UpdateContributions(_workContext.CurrentCustomer);
                    }

                    //subscription
                    if (_forumService.IsCustomerAllowedToSubscribe(_workContext.CurrentCustomer))
                    {
                        var forumSubscription = (await _forumService.GetAllSubscriptions(_workContext.CurrentCustomer.Id,
                                                                                         "", forumPost.TopicId, 0, 1)).FirstOrDefault();
                        if (model.Subscribed)
                        {
                            if (forumSubscription == null)
                            {
                                forumSubscription = new ForumSubscription
                                {
                                    SubscriptionGuid = Guid.NewGuid(),
                                    CustomerId       = _workContext.CurrentCustomer.Id,
                                    TopicId          = forumPost.TopicId,
                                    CreatedOnUtc     = nowUtc
                                };

                                await _forumService.InsertSubscription(forumSubscription);
                            }
                        }
                        else
                        {
                            if (forumSubscription != null)
                            {
                                await _forumService.DeleteSubscription(forumSubscription);
                            }
                        }
                    }

                    int pageSize = _forumSettings.PostsPageSize > 0 ? _forumSettings.PostsPageSize : 10;

                    int pageIndex   = (await _forumService.CalculateTopicPageIndex(forumPost.TopicId, pageSize, forumPost.Id) + 1);
                    var url         = string.Empty;
                    var _forumTopic = await _forumService.GetTopicById(forumPost.TopicId);

                    if (pageIndex > 1)
                    {
                        url = Url.RouteUrl("TopicSlugPaged", new { id = forumPost.TopicId, slug = _forumTopic.GetSeName(), pageNumber = pageIndex });
                    }
                    else
                    {
                        url = Url.RouteUrl("TopicSlug", new { id = forumPost.TopicId, slug = _forumTopic.GetSeName() });
                    }
                    return(Redirect($"{url}#{forumPost.Id}"));
                }
                catch (Exception ex)
                {
                    ModelState.AddModelError("", ex.Message);
                }
            }

            // redisplay form
            var forum = await _forumService.GetForumById(forumTopic.ForumId);

            if (forum == null)
            {
                return(RedirectToRoute("Boards"));
            }

            model.IsEdit            = false;
            model.ForumName         = forum.Name;
            model.ForumTopicId      = forumTopic.Id;
            model.ForumTopicSubject = forumTopic.Subject;
            model.ForumTopicSeName  = forumTopic.GetSeName();
            model.Id = "";
            model.IsCustomerAllowedToSubscribe = _forumService.IsCustomerAllowedToSubscribe(_workContext.CurrentCustomer);
            model.ForumEditor = _forumSettings.ForumEditor;

            return(View(model));
        }
Exemplo n.º 43
0
        //--------------------------------------- admin -----------------------------------------

        public virtual void AddHits(ForumPost post)
        {
            //post.Hits++;
            //db.update( post, "Hits" );
            HitsJob.Add(post);
        }
Exemplo n.º 44
0
        //--------------------------------------- income -----------------------------------------

        public virtual void AddAuthorIncome(ForumPost post, int actionId, String actionName)
        {
            String msg = string.Format("帖子被{0} <a href=\"{1}\">{2}</a>", actionName, alink.ToAppData(post), post.Title);

            incomeService.AddIncome(post.Creator, actionId, msg);
        }
        /// <inheritdoc/>
        public void AddPostTo(string postContent, Course course, Person author)
        {
            var post = new ForumPost(postContent, author, course);

            dbContext.Posts.Add(post);
        }
Exemplo n.º 46
0
        private void addNotificationToTopicCreator( ForumTopic topic, ForumPost post )
        {
            User creator = post.Creator;
            int topicReceiverId = topic.Creator.Id;

            if (topicReceiverId == creator.Id) return;

            String msg = "<a href=\"" + Link.ToMember( creator ) + "\">" + creator.Name + "</a> " + alang.get( typeof( ForumApp ), "replyYourPost" ) + " <a href=\"" + alink.ToAppData( post ) + "\">" + topic.Title + "</a>";
            notificationService.send( topicReceiverId, post.Creator.GetType().FullName, msg, NotificationType.Comment );
        }
Exemplo n.º 47
0
        public virtual void BanPost( ForumPost post, String reason, int isSendMsg, User user, int appId, String ip )
        {
            post.Status = 1;
            db.update( post, "Status" );
            if (isSendMsg == 1) {
                String msgTitle = string.Format( ForumConfig.Instance.BanMsgTitle, post.Title );
                String msgBody = string.Format( ForumConfig.Instance.BanMsgTitle, post.Title );

                msgService.SendMsg( user, post.Creator.Name, msgTitle, msgBody );
            }

            String msg = string.Format( "帖子被屏蔽 <a href=\"{0}\">{1}</a>", alink.ToAppData( post ), post.Title );
            incomeService.AddIncome( post.Creator, UserAction.Forum_PostBanned.Id, msg );

            forumLogService.AddPost( user, appId, post.Id, ForumLogAction.Ban, ip );
        }
Exemplo n.º 48
0
 public async Task <bool> UpdatePostAsync(ForumPost editedPost) =>
 await new Data.Repository.ForumPosts(_context).UpdatePostAsync(editedPost);
Exemplo n.º 49
0
        public virtual void DeleteTrue( ForumPost post, IMember owner, User user, String ip )
        {
            int id = post.Id;
            int creatorId = post.Creator.Id;
            int topicId = post.TopicId;
            int forumBoardId = post.ForumBoardId;

            db.delete( post );

            attachmentService.DeleteByPost( id );
            topicService.DeletePostCount( topicId, owner );
            boardService.DeletePostCount( forumBoardId, owner );
            if (creatorId > 0) { //规避已注销用户
                userService.DeletePostCount( creatorId );
            }
            forumLogService.AddPost( user, post.AppId, id, ForumLogAction.DeleteTrue, ip );
        }
Exemplo n.º 50
0
        private static void _GetLatestPosts(ForumSection _ForumSection, Action <ForumPost> _RetPosts, ForumType _ForumType)
        {
            if ((DateTime.Now - _ForumSection.m_LastPollDatTime).TotalMinutes < 5)
            {
                return;
            }

            if (_ForumType == ForumType.Twitter)
            {
                _ForumSection.UpdateThread(_ForumSection.m_ForumSectionURL, "", DateTime.UtcNow, _RetPosts, _ForumType);
                return;//There are no posts for individual tweets, replies are not interesting.
            }
            string website = _GetHTMLFile(_ForumSection.m_ForumSectionURL);

            if (_ForumType == ForumType.FeenixForum)
            {
                string[] websitePart = website.SplitVF("<td class='col_f_content '>");


                for (int i = 1; i < websitePart.Length; ++i)
                {
                    string currContent = websitePart[i].SplitVF("</td>", 2).First();
                    //<h4><a id="tid-link-66240" href="http://www.wow-one.com/forum/topic/66240-maintenance-notification-ed/" title='View topic, started  18 December 2013 - 08:27 AM' class='topic_title'>Maintenance Notification - ED</a></h4>
                    //<br />
                    //<span class='desc lighter blend_links'>
                    //Started by <a hovercard-ref="member" hovercard-id="36033" class="_hovertrigger url fn " href='http://www.wow-one.com/forum/user/36033-danut/'>Danut</a>, 18 Dec 2013
                    //</span>

                    string   topicName      = currContent.SplitVF("class='topic_title'>", 2).Last().SplitVF("</a>").First();
                    DateTime latestPostDate = DateTime.Now;
                    try
                    {
                        string dateStr = websitePart[i].SplitVF("page__view__getlastpost' title='Go to last post'>", 2).Last().SplitVF("</a>").First();
                        if (dateStr.StartsWith("Today") == true)
                        {
                            DateTime refDate = DateTime.Now;
                            latestPostDate = DateTime.Parse(dateStr.Replace("Today,", "" + refDate.Day + " " + refDate.ToString("MMM") + " " + refDate.Year));
                        }
                        else if (dateStr.StartsWith("Yesterday") == true)
                        {
                            DateTime refDate = DateTime.Now.AddDays(-1);
                            latestPostDate = DateTime.Parse(dateStr.Replace("Yesterday,", "" + refDate.Day + " " + refDate.ToString("MMM") + " " + refDate.Year));
                        }
                        else
                        {
                            latestPostDate = DateTime.Parse(dateStr);
                        }
                    }
                    catch (Exception)
                    {
                        latestPostDate = DateTime.Now;
                    }

                    string threadLink = currContent.SplitVF("href=\"", 2).Last().SplitVF("\"").First();
                    //http://www.wow-one.com/forum/topic/66240-maintenance-notification-ed/

                    if (threadLink.StartsWith("http://www.wow-one.com/forum/topic") == false)
                    {
                        continue;
                    }

                    if ((DateTime.Now - latestPostDate).TotalDays < 14)
                    {
                        _ForumSection.UpdateThread(threadLink, threadLink + "page__view__getlastpost", latestPostDate, _RetPosts, _ForumType);
                    }

                    //topics.Add(Tuple.Create(System.Net.WebUtility.HtmlDecode(topicName), topicLink));
                }
            }
            else if (_ForumType == ForumType.KronosForum)
            {
                //Kronos forum is through RSS feed example: http://forum.twinstar.cz/external.php?type=RSS2&forumids=969
                try
                {
                    System.Xml.XmlDocument xmlDocument = new System.Xml.XmlDocument();
                    xmlDocument.LoadXml(website);
                    var rssNode = xmlDocument.DocumentElement;
                    if (rssNode.Name == "rss")
                    {
                        var channelNode = rssNode.FirstChild;
                        if (channelNode.Name == "channel")
                        {
                            for (int i = 0; i < channelNode.ChildNodes.Count; ++i)
                            {
                                if (channelNode.ChildNodes[i].Name == "item")
                                {
                                    ForumPost fPost = new ForumPost();
                                    fPost.m_PosterImageURL = "";
                                    var postNode = channelNode.ChildNodes[i];
                                    foreach (System.Xml.XmlElement node in postNode.ChildNodes)
                                    {
                                        if (node.Name == "title")
                                        {
                                            fPost.m_ThreadName = node.InnerText;
                                        }
                                        else if (node.Name == "content:encoded")
                                        {
                                            fPost.m_PostContent = ParsePostHTMLContent(node.InnerText.Replace("<![CDATA[", "").Replace("]]>", ""));
                                        }
                                        else if (node.Name == "link")
                                        {
                                            fPost.m_PostURL   = node.InnerText.Replace("?goto=newpost", "");
                                            fPost.m_ThreadURL = fPost.m_PostURL;
                                        }
                                        else if (node.Name == "pubDate")
                                        {
                                            fPost.m_PostDate = ParseDateString(node.InnerText, DateTime.MinValue);
                                        }
                                        else if (node.Name == "dc:creator")
                                        {
                                            fPost.m_PosterName = node.InnerText;
                                        }
                                    }

                                    if (fPost.m_ThreadName != "" && fPost.m_PostContent != "" &&
                                        fPost.m_ThreadURL != "" && fPost.m_PosterName != "" && fPost.m_PostDate != DateTime.MinValue)
                                    {
                                        _ForumSection.UpdateThread(fPost, _RetPosts, _ForumType);
                                    }
                                }
                            }
                        }
                    }
                }
                catch (Exception)
                {}
            }
            else if (_ForumType == ForumType.RSS_RealmPlayersForum || _ForumType == ForumType.RSS_NostalriusForum)
            {
                //RSS example: http://realmplayers.com:5555/feed.php?f=14
                //https://www.phpbb.com/support/docs/en/3.1/kb/article/faq-phpbb-atom-feeds/
                try
                {
                    System.Xml.XmlDocument xmlDocument = new System.Xml.XmlDocument();
                    xmlDocument.LoadXml(website);
                    var rssNode = xmlDocument.DocumentElement;
                    if (rssNode.Name == "feed")
                    {
                        for (int i = 0; i < rssNode.ChildNodes.Count; ++i)
                        {
                            if (rssNode.ChildNodes[i].Name == "entry")
                            {
                                var entryNode = rssNode.ChildNodes[i];

                                ForumPost fPost = new ForumPost();
                                foreach (System.Xml.XmlElement node in entryNode.ChildNodes)
                                {
                                    if (node.Name == "author")
                                    {
                                        if (node.FirstChild.Name == "name")
                                        {
                                            fPost.m_PosterName = node.FirstChild.InnerText.Replace("<![CDATA[", "").Replace("]]>", "");
                                        }
                                    }
                                    else if (node.Name == "published")
                                    {
                                        fPost.m_PostDate = ParseDateString(node.InnerText, DateTime.MinValue);
                                    }
                                    else if (node.Name == "link")
                                    {
                                        fPost.m_PostURL   = node.Attributes["href"].Value;
                                        fPost.m_ThreadURL = fPost.m_PostURL;
                                    }
                                    else if (node.Name == "title")
                                    {
                                        fPost.m_ThreadName = node.InnerText.Replace("<![CDATA[", "").Replace("]]>", "");
                                        fPost.m_ThreadName = fPost.m_ThreadName.SplitVF(" • ").Last();
                                    }
                                    else if (node.Name == "content")
                                    {
                                        fPost.m_PostContent = ParsePostHTMLContent(node.InnerText.Replace("<![CDATA[", "").Replace("]]>", ""));
                                    }
                                }

                                if (fPost.m_ThreadName != "" && fPost.m_PostContent != "" &&
                                    fPost.m_ThreadURL != "" && fPost.m_PosterName != "" && fPost.m_PostDate != DateTime.MinValue)
                                {
                                    _ForumSection.UpdateThread(fPost, _RetPosts, _ForumType);
                                }
                            }
                        }
                    }
                }
                catch (Exception)
                { }
            }
            else
            {
                string forumBaseURL = "http://forum.realmplayers.com/";
                if (_ForumType == ForumType.NostalriusForum)
                {
                    forumBaseURL = "http://forum.nostalrius.org/";
                }

                string[] websitePart = website.SplitVF("<dt title=\"");

                for (int i = 1; i < websitePart.Length; ++i)
                {
                    //string topicName = websitePart[i].SplitVF("class=\"topictitle\">", 2).Last().SplitVF("</a>").First();
                    string   dateStr        = websitePart[i].SplitVF("\"View the latest post\" /></a> <br />", 2).Last().SplitVF("</span>").First();
                    DateTime latestPostDate = ParseDateString(dateStr, DateTime.MinValue);

                    string threadLink = websitePart[i].SplitVF("<a href=\"", 2).Last().SplitVF("\" class", 2).First().SplitVF("&amp;sid=").First();

                    if (threadLink.StartsWith("./viewtopic.php?") == false)
                    {
                        continue;
                    }

                    DateTime createdThreadDate = ParseDateString(websitePart[i].SplitVF("&raquo; ", 2).Last().SplitVF("\n", 2).First(), DateTime.MinValue);

                    string lastPostLink = threadLink + websitePart[i].SplitVF("<dd class=\"lastpost\"", 2).Last().SplitVF(threadLink).Last().SplitVF("\"><img src=", 2).First();
                    if ((DateTime.Now - createdThreadDate).TotalDays < 14)
                    {
                        _ForumSection.UpdateThread(System.Net.WebUtility.HtmlDecode(threadLink.Replace("./viewtopic.php", forumBaseURL + "viewtopic.php")), System.Net.WebUtility.HtmlDecode(threadLink.Replace("./viewtopic.php", forumBaseURL + "viewtopic.php")), createdThreadDate, _RetPosts, _ForumType);
                    }
                    if ((DateTime.Now - latestPostDate).TotalDays < 14)
                    {
                        _ForumSection.UpdateThread(System.Net.WebUtility.HtmlDecode(threadLink.Replace("./viewtopic.php", forumBaseURL + "viewtopic.php")), System.Net.WebUtility.HtmlDecode(lastPostLink.Replace("./viewtopic.php", forumBaseURL + "viewtopic.php")), latestPostDate, _RetPosts, _ForumType);
                    }
                }
            }
            _ForumSection.m_LastPollDatTime = DateTime.Now;
        }
Exemplo n.º 51
0
        public virtual void SetPostCredit( ForumPost post, int currencyId, int credit, String reason, User viewer )
        {
            post.Rate += credit;
            db.update( post, "Rate" );

            rateService.Insert( post.Id, viewer, currencyId, credit, reason );

            String msg = string.Format( "帖子被评分 <a href=\"{0}\">{1}</a>", alink.ToAppData( post ), post.Title );

            incomeService.AddIncome( post.Creator, currencyId, credit, msg );

            notificationService.send( post.Creator.Id, msg );
        }
Exemplo n.º 52
0
 public virtual void AddForumPostTokens(IList <Token> tokens, ForumPost forumPost)
 {
     tokens.Add(new Token("Forums.PostAuthor", forumPost.Customer.FormatUserName()));
     tokens.Add(new Token("Forums.PostBody", forumPost.FormatPostText(), true));
 }
Exemplo n.º 53
0
        public virtual void UnBanPost( ForumPost post, User user, int appId, String ip )
        {
            post.Status = 0;
            db.update( post, "Status" );

            String msg = string.Format( "帖子取消屏蔽 <a href=\"{0}\">{1}</a>", alink.ToAppData( post ), post.Title );
            incomeService.AddIncomeReverse( post.Creator, UserAction.Forum_PostBanned.Id, msg );
            forumLogService.AddPost( user, appId, post.Id, ForumLogAction.UnBan, ip );
        }
Exemplo n.º 54
0
        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            try
            {
                string text = string.Empty;

                switch (ForumManager.ForumEditor)
                {
                case EditorTypeEnum.SimpleTextBox:
                {
                    text = txtTopicBodySimple.Text.Trim();
                }
                break;

                case EditorTypeEnum.BBCodeEditor:
                {
                    text = txtTopicBodyBBCode.Text.Trim();
                }
                break;

                case EditorTypeEnum.HtmlEditor:
                {
                    text = txtTopicBodyHtml.Value;
                }
                break;

                default:
                    break;
                }

                string             subject   = txtTopicTitle.Text;
                ForumTopicTypeEnum topicType = ForumTopicTypeEnum.Normal;
                bool subscribe = cbSubscribe.Checked;

                string IPAddress = string.Empty;
                if (HttpContext.Current != null && HttpContext.Current.Request != null)
                {
                    IPAddress = HttpContext.Current.Request.UserHostAddress;
                }

                DateTime nowDT = DateTime.Now;

                if (ForumManager.IsUserAllowedToSetTopicPriority(NopContext.Current.User))
                {
                    topicType = (ForumTopicTypeEnum)Enum.ToObject(typeof(ForumTopicTypeEnum), int.Parse(ddlPriority.SelectedItem.Value));
                }

                text = text.Trim();
                if (String.IsNullOrEmpty(text))
                {
                    throw new NopException(GetLocaleResourceString("Forum.TextCannotBeEmpty"));
                }

                if (this.AddTopic)
                {
                    #region Adding topic
                    Forum forum = ForumManager.GetForumByID(this.ForumID);
                    if (forum == null)
                    {
                        Response.Redirect(SEOHelper.GetForumMainURL());
                    }

                    if (!ForumManager.IsUserAllowedToCreateTopic(NopContext.Current.User, forum))
                    {
                        string loginURL = CommonHelper.GetLoginPageURL(true);
                        Response.Redirect(loginURL);
                    }

                    subject = subject.Trim();
                    if (String.IsNullOrEmpty(subject))
                    {
                        throw new NopException(GetLocaleResourceString("Forum.TopicSubjectCannotBeEmpty"));
                    }

                    ForumTopic forumTopic = ForumManager.InsertTopic(forum.ForumID, NopContext.Current.User.CustomerID,
                                                                     topicType, subject, 0, 0, 0, 0, null, nowDT, nowDT, true);

                    ForumPost forumPost = ForumManager.InsertPost(forumTopic.ForumTopicID, NopContext.Current.User.CustomerID,
                                                                  text, IPAddress, nowDT, nowDT, false);

                    forumTopic = ForumManager.UpdateTopic(forumTopic.ForumTopicID, forumTopic.ForumID,
                                                          forumTopic.UserID, forumTopic.TopicType, forumTopic.Subject, 1,
                                                          0, forumPost.ForumPostID, forumTopic.UserID,
                                                          forumPost.CreatedOn, forumTopic.CreatedOn, nowDT);

                    //subscription
                    if (ForumManager.IsUserAllowedToSubscribe(NopContext.Current.User))
                    {
                        if (subscribe)
                        {
                            ForumSubscription forumSubscription = ForumManager.InsertSubscription(Guid.NewGuid(),
                                                                                                  NopContext.Current.User.CustomerID, 0, forumTopic.ForumTopicID, nowDT);
                        }
                    }

                    string topicURL = SEOHelper.GetForumTopicURL(forumTopic.ForumTopicID);
                    Response.Redirect(topicURL);
                    #endregion
                }
                else if (this.EditTopic)
                {
                    #region Editing topic
                    ForumTopic forumTopic = ForumManager.GetTopicByID(this.ForumTopicID);
                    if (forumTopic == null)
                    {
                        Response.Redirect(SEOHelper.GetForumMainURL());
                    }

                    if (!ForumManager.IsUserAllowedToEditTopic(NopContext.Current.User, forumTopic))
                    {
                        string loginURL = CommonHelper.GetLoginPageURL(true);
                        Response.Redirect(loginURL);
                    }

                    subject = subject.Trim();
                    if (String.IsNullOrEmpty(subject))
                    {
                        throw new NopException(GetLocaleResourceString("Forum.TopicSubjectCannotBeEmpty"));
                    }

                    forumTopic = ForumManager.UpdateTopic(forumTopic.ForumTopicID, forumTopic.ForumID,
                                                          forumTopic.UserID, topicType, subject, forumTopic.NumPosts,
                                                          forumTopic.Views, forumTopic.LastPostID, forumTopic.LastPostUserID,
                                                          forumTopic.LastPostTime, forumTopic.CreatedOn, nowDT);

                    ForumPost firstPost = forumTopic.FirstPost;
                    if (firstPost != null)
                    {
                        firstPost = ForumManager.UpdatePost(firstPost.ForumPostID, firstPost.TopicID,
                                                            firstPost.UserID, text, firstPost.IPAddress, firstPost.CreatedOn, nowDT);
                    }
                    else
                    {
                        //error
                        firstPost = ForumManager.InsertPost(forumTopic.ForumTopicID,
                                                            forumTopic.UserID, text, IPAddress, forumTopic.CreatedOn, nowDT, false);
                    }

                    //subscription
                    if (ForumManager.IsUserAllowedToSubscribe(NopContext.Current.User.CustomerID))
                    {
                        ForumSubscription forumSubscription = ForumManager.GetAllSubscriptions(NopContext.Current.User.CustomerID,
                                                                                               0, forumTopic.ForumTopicID, 1, 0).FirstOrDefault();
                        if (subscribe)
                        {
                            if (forumSubscription == null)
                            {
                                forumSubscription = ForumManager.InsertSubscription(Guid.NewGuid(),
                                                                                    NopContext.Current.User.CustomerID, 0, forumTopic.ForumTopicID, nowDT);
                            }
                        }
                        else
                        {
                            if (forumSubscription != null)
                            {
                                ForumManager.DeleteSubscription(forumSubscription.ForumSubscriptionID);
                            }
                        }
                    }

                    string topicURL = SEOHelper.GetForumTopicURL(forumTopic.ForumTopicID);
                    Response.Redirect(topicURL);
                    #endregion
                }
                else if (this.AddPost)
                {
                    #region Adding post
                    ForumTopic forumTopic = ForumManager.GetTopicByID(this.ForumTopicID);
                    if (forumTopic == null)
                    {
                        Response.Redirect(SEOHelper.GetForumMainURL());
                    }

                    if (!ForumManager.IsUserAllowedToCreatePost(NopContext.Current.User, forumTopic))
                    {
                        string loginURL = CommonHelper.GetLoginPageURL(true);
                        Response.Redirect(loginURL);
                    }

                    ForumPost forumPost = ForumManager.InsertPost(this.ForumTopicID, NopContext.Current.User.CustomerID,
                                                                  text, IPAddress, nowDT, nowDT, true);

                    //subscription
                    if (ForumManager.IsUserAllowedToSubscribe(NopContext.Current.User.CustomerID))
                    {
                        ForumSubscription forumSubscription = ForumManager.GetAllSubscriptions(NopContext.Current.User.CustomerID,
                                                                                               0, forumPost.TopicID, 1, 0).FirstOrDefault();
                        if (subscribe)
                        {
                            if (forumSubscription == null)
                            {
                                forumSubscription = ForumManager.InsertSubscription(Guid.NewGuid(),
                                                                                    NopContext.Current.User.CustomerID, 0, forumPost.TopicID, nowDT);
                            }
                        }
                        else
                        {
                            if (forumSubscription != null)
                            {
                                ForumManager.DeleteSubscription(forumSubscription.ForumSubscriptionID);
                            }
                        }
                    }


                    int pageSize = 10;
                    if (ForumManager.PostsPageSize > 0)
                    {
                        pageSize = ForumManager.PostsPageSize;
                    }
                    int    pageIndex = ForumManager.CalculateTopicPageIndex(forumPost.TopicID, pageSize, forumPost.ForumPostID);
                    string topicURL  = SEOHelper.GetForumTopicURL(forumPost.TopicID, "p", pageIndex + 1, forumPost.ForumPostID);
                    Response.Redirect(topicURL);
                    #endregion
                }
                else if (this.EditPost)
                {
                    #region Editing post
                    ForumPost forumPost = ForumManager.GetPostByID(this.ForumPostID);
                    if (forumPost == null)
                    {
                        Response.Redirect(SEOHelper.GetForumMainURL());
                    }

                    if (!ForumManager.IsUserAllowedToEditPost(NopContext.Current.User, forumPost))
                    {
                        string loginURL = CommonHelper.GetLoginPageURL(true);
                        Response.Redirect(loginURL);
                    }

                    forumPost = ForumManager.UpdatePost(forumPost.ForumPostID, forumPost.TopicID,
                                                        forumPost.UserID, text, forumPost.IPAddress, forumPost.CreatedOn, nowDT);

                    //subscription
                    if (ForumManager.IsUserAllowedToSubscribe(NopContext.Current.User.CustomerID))
                    {
                        ForumSubscription forumSubscription = ForumManager.GetAllSubscriptions(NopContext.Current.User.CustomerID,
                                                                                               0, forumPost.TopicID, 1, 0).FirstOrDefault();
                        if (subscribe)
                        {
                            if (forumSubscription == null)
                            {
                                forumSubscription = ForumManager.InsertSubscription(Guid.NewGuid(),
                                                                                    NopContext.Current.User.CustomerID, 0, forumPost.TopicID, nowDT);
                            }
                        }
                        else
                        {
                            if (forumSubscription != null)
                            {
                                ForumManager.DeleteSubscription(forumSubscription.ForumSubscriptionID);
                            }
                        }
                    }

                    int pageSize = 10;
                    if (ForumManager.PostsPageSize > 0)
                    {
                        pageSize = ForumManager.PostsPageSize;
                    }
                    int    pageIndex = ForumManager.CalculateTopicPageIndex(forumPost.TopicID, pageSize, forumPost.ForumPostID);
                    string topicURL  = SEOHelper.GetForumTopicURL(forumPost.TopicID, "p", pageIndex + 1, forumPost.ForumPostID);
                    Response.Redirect(topicURL);
                    #endregion
                }
            }
            catch (Exception exc)
            {
                pnlError.Visible   = true;
                lErrorMessage.Text = Server.HtmlEncode(exc.Message);
            }
        }
Exemplo n.º 55
0
        private void addFeedInfo( ForumPost data )
        {
            // 回复论坛帖子:不再加入feed中
            String lnkPost = alink.ToAppData( data );

            //String msg = string.Format( "<div class=\"feed-item-title\">回复了论坛帖子 <a href=\"{0}\">{1}</a></div>", lnkPost, data.Title );
            //msg += string.Format( "<div class=\"feed-item-body\"><div class=\"feed-item-quote\">{0}</div></div>", strUtil.ParseHtml( data.Content, MicroblogAppSetting.Instance.MicroblogContentMax ) );

            //microblogService.Add( data.Creator, msg, typeof( ForumPost ).FullName, data.Id, data.Ip );
        }
Exemplo n.º 56
0
 private static string GetKey(ForumPost p)
 {
     return("p" + p.ForumPostID);
 }
Exemplo n.º 57
0
        private void addNotificationToParentCreator( ForumTopic topic, ForumPost post )
        {
            User creator = post.Creator;
            if (post.ParentId <= 0) return;

            // 如果不清理缓存,则parent.Creator就是null(受制于ORM查询的关联深度只有2级)
            ForumPost parent = db.nocache.findById<ForumPost>( post.ParentId );
            if (parent == null) return;

            User parentUser = userService.GetById( parent.Creator.Id );
            if (parentUser == null) return;

            int parentReceiverId = parent.Creator.Id;
            parentReceiverId = parent.Creator.Id;
            int topicReceiverId = topic.Creator.Id;
            if (parentReceiverId == creator.Id || parentReceiverId == topicReceiverId) return;

            String msgToParent = "<a href=\"" + Link.ToMember( creator ) + "\">" + creator.Name + "</a> " + alang.get( typeof( ForumApp ), "replyYourPost" ) + " <a href=\"" + alink.ToAppData( post ) + "\">" + topic.Title + "</a>";
            notificationService.send( parentReceiverId, typeof( User ).FullName, msgToParent, NotificationType.Comment );
        }
Exemplo n.º 58
0
        private void BindData()
        {
            pnlError.Visible = false;

            txtTopicBodySimple.Visible = false;
            txtTopicBodyBBCode.Visible = false;
            txtTopicBodyHtml.Visible   = false;
            switch (ForumManager.ForumEditor)
            {
            case EditorTypeEnum.SimpleTextBox:
            {
                txtTopicBodySimple.Visible     = true;
                rfvTopicBody.ControlToValidate = "txtTopicBodySimple";
            }
            break;

            case EditorTypeEnum.BBCodeEditor:
            {
                txtTopicBodyBBCode.Visible     = true;
                rfvTopicBody.ControlToValidate = "txtTopicBodyBBCode";
            }
            break;

            case EditorTypeEnum.HtmlEditor:
            {
                txtTopicBodyHtml.Visible = true;
                rfvTopicBody.Enabled     = false;
            }
            break;

            default:
                break;
            }

            if (this.AddTopic)
            {
                #region Adding topic

                Forum forum = ForumManager.GetForumByID(this.ForumID);
                if (forum == null)
                {
                    Response.Redirect(SEOHelper.GetForumMainURL());
                }

                if (!ForumManager.IsUserAllowedToCreateTopic(NopContext.Current.User, forum))
                {
                    string loginURL = CommonHelper.GetLoginPageURL(true);
                    Response.Redirect(loginURL);
                }

                lblTitle.Text         = GetLocaleResourceString("Forum.NewTopic");
                phForumName.Visible   = true;
                lblForumName.Text     = Server.HtmlEncode(forum.Name);
                txtTopicTitle.Visible = true;
                txtTopicTitle.Text    = string.Empty;
                lblTopicTitle.Visible = false;
                lblTopicTitle.Text    = string.Empty;

                ctrlForumBreadcrumb.ForumID = forum.ForumID;
                ctrlForumBreadcrumb.BindData();

                phPriority.Visible  = ForumManager.IsUserAllowedToSetTopicPriority(NopContext.Current.User);
                phSubscribe.Visible = ForumManager.IsUserAllowedToSubscribe(NopContext.Current.User);

                #endregion
            }
            else if (this.EditTopic)
            {
                #region Editing topic
                ForumTopic forumTopic = ForumManager.GetTopicByID(this.ForumTopicID);

                if (forumTopic == null)
                {
                    Response.Redirect(SEOHelper.GetForumMainURL());
                }

                if (!ForumManager.IsUserAllowedToEditTopic(NopContext.Current.User, forumTopic))
                {
                    string loginURL = CommonHelper.GetLoginPageURL(true);
                    Response.Redirect(loginURL);
                }

                Forum forum = forumTopic.Forum;
                if (forum == null)
                {
                    Response.Redirect(SEOHelper.GetForumMainURL());
                }

                lblTitle.Text         = GetLocaleResourceString("Forum.EditTopic");
                phForumName.Visible   = true;
                lblForumName.Text     = Server.HtmlEncode(forum.Name);
                txtTopicTitle.Visible = true;
                txtTopicTitle.Text    = forumTopic.Subject;
                lblTopicTitle.Visible = false;
                lblTopicTitle.Text    = string.Empty;

                ctrlForumBreadcrumb.ForumTopicID = forumTopic.ForumTopicID;
                ctrlForumBreadcrumb.BindData();

                CommonHelper.SelectListItem(this.ddlPriority, forumTopic.TopicTypeID);

                ForumPost firstPost = forumTopic.FirstPost;
                if (firstPost != null)
                {
                    switch (ForumManager.ForumEditor)
                    {
                    case EditorTypeEnum.SimpleTextBox:
                    {
                        txtTopicBodySimple.Text = firstPost.Text;
                    }
                    break;

                    case EditorTypeEnum.BBCodeEditor:
                    {
                        txtTopicBodyBBCode.Text = firstPost.Text;
                    }
                    break;

                    case EditorTypeEnum.HtmlEditor:
                    {
                        txtTopicBodyHtml.Value = firstPost.Text;
                    }
                    break;

                    default:
                        break;
                    }
                }


                phPriority.Visible = ForumManager.IsUserAllowedToSetTopicPriority(NopContext.Current.User);
                //subscription
                if (ForumManager.IsUserAllowedToSubscribe(NopContext.Current.User.CustomerID))
                {
                    phSubscribe.Visible = true;
                    ForumSubscription forumSubscription = ForumManager.GetAllSubscriptions(NopContext.Current.User.CustomerID,
                                                                                           0, forumTopic.ForumTopicID, 1, 0).FirstOrDefault();
                    cbSubscribe.Checked = forumSubscription != null;
                }
                else
                {
                    phSubscribe.Visible = false;
                }
                #endregion
            }
            else if (this.AddPost)
            {
                #region Adding post

                ForumTopic forumTopic = ForumManager.GetTopicByID(this.ForumTopicID);
                if (forumTopic == null)
                {
                    Response.Redirect(SEOHelper.GetForumMainURL());
                }

                if (!ForumManager.IsUserAllowedToCreatePost(NopContext.Current.User, forumTopic))
                {
                    string loginURL = CommonHelper.GetLoginPageURL(true);
                    Response.Redirect(loginURL);
                }

                ctrlForumBreadcrumb.ForumTopicID = forumTopic.ForumTopicID;
                ctrlForumBreadcrumb.BindData();

                lblTitle.Text         = GetLocaleResourceString("Forum.NewPost");
                phForumName.Visible   = false;
                lblForumName.Text     = string.Empty;
                txtTopicTitle.Visible = false;
                txtTopicTitle.Text    = string.Empty;
                lblTopicTitle.Visible = true;
                lblTopicTitle.Text    = Server.HtmlEncode(forumTopic.Subject);

                phPriority.Visible = false;
                //subscription
                if (ForumManager.IsUserAllowedToSubscribe(NopContext.Current.User))
                {
                    phSubscribe.Visible = true;
                    ForumSubscription forumSubscription = ForumManager.GetAllSubscriptions(NopContext.Current.User.CustomerID,
                                                                                           0, forumTopic.ForumTopicID, 1, 0).FirstOrDefault();
                    cbSubscribe.Checked = forumSubscription != null;
                }
                else
                {
                    phSubscribe.Visible = false;
                }
                #endregion
            }
            else if (this.EditPost)
            {
                #region Editing post

                ForumPost forumPost = ForumManager.GetPostByID(this.ForumPostID);

                if (forumPost == null)
                {
                    Response.Redirect(SEOHelper.GetForumMainURL());
                }

                if (!ForumManager.IsUserAllowedToEditPost(NopContext.Current.User, forumPost))
                {
                    string loginURL = CommonHelper.GetLoginPageURL(true);
                    Response.Redirect(loginURL);
                }

                ForumTopic forumTopic = forumPost.Topic;
                if (forumTopic == null)
                {
                    Response.Redirect(SEOHelper.GetForumMainURL());
                }

                lblTitle.Text         = GetLocaleResourceString("Forum.EditPost");
                phForumName.Visible   = false;
                lblForumName.Text     = string.Empty;
                txtTopicTitle.Visible = false;
                txtTopicTitle.Text    = string.Empty;
                lblTopicTitle.Visible = true;
                lblTopicTitle.Text    = Server.HtmlEncode(forumTopic.Subject);

                ctrlForumBreadcrumb.ForumTopicID = forumTopic.ForumTopicID;
                ctrlForumBreadcrumb.BindData();


                switch (ForumManager.ForumEditor)
                {
                case EditorTypeEnum.SimpleTextBox:
                {
                    txtTopicBodySimple.Text = forumPost.Text;
                }
                break;

                case EditorTypeEnum.BBCodeEditor:
                {
                    txtTopicBodyBBCode.Text = forumPost.Text;
                }
                break;

                case EditorTypeEnum.HtmlEditor:
                {
                    txtTopicBodyHtml.Value = forumPost.Text;
                }
                break;

                default:
                    break;
                }

                phPriority.Visible = false;
                //subscription
                if (ForumManager.IsUserAllowedToSubscribe(NopContext.Current.User.CustomerID))
                {
                    phSubscribe.Visible = true;
                    ForumSubscription forumSubscription = ForumManager.GetAllSubscriptions(NopContext.Current.User.CustomerID,
                                                                                           0, forumTopic.ForumTopicID, 1, 0).FirstOrDefault();
                    cbSubscribe.Checked = forumSubscription != null;
                }
                else
                {
                    phSubscribe.Visible = false;
                }
                #endregion
            }
            else
            {
                Response.Redirect(SEOHelper.GetForumMainURL());
            }
        }
Exemplo n.º 59
0
        private void updateCount( ForumPost post, User user, IMember owner, IApp app )
        {
            ForumTopic topic = post.Topic;
            if (topic == null) {
                topic = topicService.GetById( post.TopicId, owner );
            }
            topic.Replies = topicService.CountReply( post.TopicId );
            topic.RepliedUserName = user.Name;
            topic.RepliedUserFriendUrl = user.Url;
            topic.Replied = DateTime.Now;
            topicService.UpdateReply( topic );

            ForumBoard fb = ForumBoard.findById( post.ForumBoardId );
            fb.TodayPosts++;
            fb.Posts = boardService.CountPost( fb.Id );

            LastUpdateInfo info = new LastUpdateInfo();
            info.PostId = post.Id;
            info.PostType = typeof( ForumPost ).Name;
            info.PostTitle = post.Title;
            info.CreatorName = user.Name;
            info.CreatorUrl = user.Url;
            info.UpdateTime = DateTime.Now;

            fb.LastUpdateInfo = info;
            fb.Updated = info.UpdateTime;

            boardService.Update( fb );

            ForumApp forum = app as ForumApp;
            forum.PostCount++;
            forum.TodayPostCount++;

            forum.LastUpdateMemberName = user.Name;
            forum.LastUpdateMemberUrl = user.Url;
            forum.LastUpdatePostTitle = post.Title;

            forum.LastUpdateTime = post.Created;
            forumService.Update( forum );

            userService.AddPostCount( user );
        }
Exemplo n.º 60
0
        private static List <ForumPost> GetThreadPosts(string _ThreadURL, string _LastPostURL, DateTime _EarliestPostDate, ForumType _ForumType)
        {
            if (_ForumType == ForumType.Twitter)
            {
                List <ForumPost> threadPosts = new List <ForumPost>();

                var tweets = GetTweets(_ThreadURL);
                foreach (var tweet in tweets)
                {
                    string tweetTitle     = tweet.m_Text;
                    int    prevFoundIndex = 0;
                    while (prevFoundIndex != -1 && prevFoundIndex < 10)
                    {
                        int newFoundIndex = tweetTitle.IndexOfAny(new char[] { '.', '!', '?' }, prevFoundIndex);
                        if (newFoundIndex == -1)
                        {
                            break;//unable to breakup the tweetTitle!
                        }
                        else//if (newFoundIndex != -1)
                        {
                            if (newFoundIndex > 10)
                            {
                                if (newFoundIndex > 50 && prevFoundIndex > 0)
                                {
                                    newFoundIndex = prevFoundIndex;
                                }
                                tweetTitle = tweetTitle.Substring(0, newFoundIndex + 1);
                                break;//Done with breaking up the tweetTitle!
                            }
                        }
                        prevFoundIndex = newFoundIndex;
                    }
                    var newForumPost = new ForumPost {
                        m_ThreadName = tweetTitle, m_ThreadURL = _ThreadURL, m_PostURL = tweet.m_TweetLink, m_PosterName = tweet.m_Creator + " twitter", m_PosterImageURL = "", m_PostContent = tweet.m_Text, m_PostDate = tweet.m_PostDate
                    };
                    threadPosts.Add(newForumPost);
                }
                return(threadPosts);
            }
            else if (_ForumType == ForumType.FeenixForum)
            {
                List <ForumPost> threadPosts = new List <ForumPost>();

                string website    = _GetHTMLFile(_LastPostURL);
                string threadName = website.SplitVF("<h1 class='ipsType_pagetitle'>", 2).Last().SplitVF("</h1>").First();
                threadName = System.Net.WebUtility.HtmlDecode(threadName.Replace("\t", "").Replace("\n", ""));

                string[] websitePart = website.SplitVF("<div class='post_wrap' >");

                for (int i = websitePart.Length - 1; i >= 1; --i)
                {
                    try
                    {
                        string postURL     = websitePart[i].SplitVF("<span class='post_id right ipsType_small desc blend_links'><a href='", 2).Last().SplitVF("'").First();
                        string posterName  = websitePart[i].SplitVF("title='View Profile'>", 2).Last().SplitVF("</a>").First();
                        string gravatarURL = "null";
                        try
                        {
                            gravatarURL = "http://www.gravatar.com" + websitePart[i].SplitVF("<img src='http://www.gravatar.com", 2).Last().SplitVF("'").First();
                        }
                        catch (Exception) { }

                        string   postBody   = websitePart[i].SplitVF("<div class='post_body'>", 2).Last();
                        string   dateString = postBody.SplitVF("<abbr class=\"published\" title=\"", 2).Last().SplitVF("\">").First();
                        DateTime postDate   = DateTime.Parse(dateString);
                        if (_EarliestPostDate > postDate)
                        {
                            break;
                        }
                        string postContent = websitePart[i].SplitVF("<div class='post entry-content '>").Last().SplitVF("</div>").First().SplitVF("-->", 2).Last();

                        string[] postContentParts = postContent.Replace("<br />", "\n").Split('<');

                        string realContent = "";
                        try
                        {
                            foreach (var postContentPart in postContentParts)
                            {
                                if (postContentPart.Contains('>'))
                                {
                                    if (postContentPart.StartsWith("li>") == true)
                                    {
                                        realContent += "\n*";
                                    }
                                    realContent += postContentPart.Substring(postContentPart.IndexOf('>') + 1);
                                }
                                else
                                {
                                    realContent += postContentPart;
                                }
                            }
                        }
                        catch (Exception)
                        {
                            realContent += "\n!!!COULD NOT READ REST OF THE POST!!!";
                        }
                        realContent = System.Net.WebUtility.HtmlDecode(realContent);
                        realContent = realContent.Replace("\t", "");

                        string[] cn = realContent.SplitVF("\n", StringSplitOptions.RemoveEmptyEntries);

                        realContent = "";
                        foreach (var c in cn)
                        {
                            realContent += c + "\n";
                        }
                        var newForumPost = new ForumPost {
                            m_ThreadName = threadName, m_ThreadURL = _ThreadURL, m_PostURL = postURL, m_PosterName = posterName, m_PosterImageURL = gravatarURL, m_PostContent = realContent, m_PostDate = postDate
                        };
                        threadPosts.Add(newForumPost);
                    }
                    catch (Exception)
                    { }
                }
                return(threadPosts);
            }
            else
            {
                string forumBaseURL = "http://forum.realmplayers.com/";
                if (_ForumType == ForumType.NostalriusForum)
                {
                    forumBaseURL = "http://forum.nostalrius.org/";
                }
                List <ForumPost> threadPosts = new List <ForumPost>();

                string website       = _GetHTMLFile(_LastPostURL);
                string threadContent = website.SplitVF("<div id=\"page-body\">", 2).Last();
                string threadName    = System.Net.WebUtility.HtmlDecode(threadContent.SplitVF("viewtopic.php", 2).Last().SplitVF(">", 2).Last().SplitVF("</a></h2>", 2).First());


                string[] websitePart;
                if (_ForumType == ForumType.NostalriusForum)
                {
                    websitePart = website.SplitVF("<div class=\"postbody\">");//"<p class=\"author\">by <strong><a href=\"");
                }
                else
                {
                    websitePart = website.SplitVF("<p class=\"author\"><a href=\"");
                }

                for (int i = websitePart.Length - 1; i >= 1; --i)
                {
                    try
                    {
                        string postURL;

                        if (_ForumType == ForumType.NostalriusForum)
                        {
                            string postNumber = websitePart[i].SplitVF("><a href=\"#p", 2).Last();
                            postNumber = postNumber.SplitVF("\">", 2).First();
                            //postURL = _ThreadURL + "#" + System.Net.WebUtility.HtmlDecode(postURL);
                            if (_LastPostURL.Contains("&sid") == true)
                            {
                                //postURL = _LastPostURL.SplitVF("&sid=", 2).First() + "#" + _LastPostURL.SplitVF("#", 2).Last();
                                postURL = _LastPostURL.SplitVF("&sid=", 2).First() + "#p" + postNumber;
                            }
                            else
                            {
                                postURL = _LastPostURL + "&p=" + postNumber + "#p" + postNumber;
                            }
                        }
                        else
                        {
                            postURL = websitePart[i].SplitVF("\">", 2).First();
                            postURL = postURL.Replace("./", forumBaseURL);
                            postURL = System.Net.WebUtility.HtmlDecode(postURL);
                        }
                        string posterInfo;
                        if (_ForumType == ForumType.NostalriusForum)
                        {
                            posterInfo = websitePart[i].SplitVF("<p class=\"author\">by <strong><a href=\"").Last().SplitVF("<dl class=\"postprofile\"", 2).Last().SplitVF("</dt>").First();
                        }
                        else
                        {
                            posterInfo = websitePart[i].SplitVF("<dl class=\"postprofile\"", 2).Last().SplitVF("</dt>").First();
                        }
                        string posterName;
                        if (_ForumType == ForumType.NostalriusForum)
                        {
                            posterName = posterInfo.SplitVF("</a>\n ").First().SplitVF(">").Last();
                        }
                        else
                        {
                            posterName = posterInfo.SplitVF("</a>\r\n").First().SplitVF(">").Last();
                        }
                        string posterImageURL = posterInfo.SplitVF("User avatar\" /></a><br />").First().SplitVF("<img src=\"", 2).Last().SplitVF("\"").First();
                        posterImageURL = posterImageURL.Replace("./", forumBaseURL);

                        string   dateString = websitePart[i].SplitVF("</strong> &raquo; ", 2).Last().SplitVF(" </p>", 2).First();
                        DateTime postDate   = ParseDateString(dateString, DateTime.MinValue);
                        if (_EarliestPostDate > postDate)
                        {
                            break;
                        }
                        string postContent = websitePart[i].SplitVF("<div class=\"content\">", 2).Last().SplitVF("<dl class", 2).First();

                        string realContent  = ParsePostHTMLContent(postContent);
                        var    newForumPost = new ForumPost {
                            m_ThreadName = threadName, m_ThreadURL = _ThreadURL, m_PostURL = postURL, m_PosterName = posterName, m_PosterImageURL = posterImageURL, m_PostContent = realContent, m_PostDate = postDate
                        };
                        threadPosts.Add(newForumPost);
                    }
                    catch (Exception)
                    { }
                }
                return(threadPosts);
            }
        }