Exemplo n.º 1
0
		public static string TopicLink(int tabId, int moduleId, TopicInfo ti)
		{	
			string sURL;
			var mainSettings = DataCache.MainSettings(moduleId);

			if (string.IsNullOrEmpty(ti.URL) || !mainSettings.URLRewriteEnabled)
			{
				sURL = Utilities.NavigateUrl(tabId, string.Empty, ParamKeys.TopicId + "=" + ti.TopicId);
			}
			else
			{
                var db = new Data.Common();
				sURL = "/" + db.GetUrl(moduleId, -1, -1, ti.TopicId, -1, -1);
			}

			var sHost = Utilities.GetHost();
			if (! (sURL.StartsWith(sHost)))
			{
				if (sHost.EndsWith("/"))
					sHost = sHost.Substring(0, sHost.Length - 1);

				sURL = sHost + sURL;
			}

			return sURL;
		}
        public string Create(TopicInfo info)
        {
            string templateName;
            Type templateType;
            ProgramInfo programInfo = info as ProgramInfo;
            if (programInfo != null)
            {
                templateName = "CobolProgramTemplate.razor";
                templateType = typeof(ProgramInfoTemplate);
            }
            else
            {
                templateName = "TemplateBase.razor";
                templateType = typeof(FolderTemplate);
            }
            TextReader razorTemplateReader = new StreamReader(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), templateName));
            RazorEngineHostWrapper razorEngineHostWrapper = new RazorEngineHostWrapper();
            var generatedAssembly = razorEngineHostWrapper.ParseAndCompileTemplate(templateType, "BlissInSoftware.Sandcastle.Cobol", "TopicTemplate", razorTemplateReader);

            Type type = generatedAssembly.GetType("BlissInSoftware.Sandcastle.Cobol.TopicTemplate");
            var instance = (TemplateBase)Activator.CreateInstance(type);
            if (programInfo != null)
            {

               // programInfo.ProgramDescription = programInfo.ProgramDescription.Replace(Environment.NewLine, "<markup><br /></markup>");
                ((ProgramInfoTemplate)instance).ProgramInfo = programInfo;
            }
            else
            {
                ((FolderTemplate)instance).TopicInfo = info;
            }
            instance.Execute();
            return instance.Buffer.ToString();
        }
 private TopicInfo BuildTopics()
 {
     using (md5 = HashAlgorithm.Create("MD5"))
     {
         RootTopic = TopicInfo.Create(Guid.NewGuid(), "API - Programas Cobol", ""); 
         BuildTopicsTree(sourcePath, RootTopic);
     }
     return RootTopic;
 }
        private void BuildTopicsTree(string parentPath, TopicInfo parentTopic)
        {
            /*
            foreach (string featureSet in Directory.EnumerateDirectories(parentPath))
            {
                builder.ReportProgress("Feature set: " + featureSet);
                Topic currentTopic = Topic.Create(TopicType.FeatureSet, CreateTopicId(featureSet), Path.GetFileName(featureSet), featureSet, gherkinFeaturesLanguage);
                parentTopic.Children.Add(currentTopic);
                BuildTopicsTree(featureSet, currentTopic);
            }
            */

            foreach (string topicFilePath in Directory.EnumerateFiles(parentPath, "*.txt"))
            {
                builder.ReportProgress("Topic file: " + topicFilePath);
                ProgramInfo currentTopic = (ProgramInfo)TopicInfo.Create(CreateTopicId(topicFilePath), Path.GetFileNameWithoutExtension(topicFilePath), topicFilePath);
                parentTopic.Children.Add(currentTopic);
            }
        }
Exemplo n.º 5
0
 /// <summary>
 /// 加载主题分类信息
 /// </summary>
 /// <param name="topicTypePrefix"></param>
 /// <param name="topicTypeList"></param>
 /// <param name="topicinfo"></param>
 private static void LoadTopicType(int topicTypePrefix, SortedList <int, string> topicTypeList, TopicInfo topicinfo)
 {
     //扩展属性
     if (topicTypePrefix > 0 && topicinfo.Typeid > 0)
     {
         string typeName = "";
         topicTypeList.TryGetValue(topicinfo.Typeid, out typeName);
         topicinfo.Topictypename = typeName.Trim();
     }
 }
Exemplo n.º 6
0
 /// <summary>
 /// 创建活动专题
 /// </summary>
 /// <param name="topicInfo">活动专题信息</param>
 public static void CreateTopic(TopicInfo topicInfo)
 {
     OWZX.Data.Topics.CreateTopic(topicInfo);
 }
Exemplo n.º 7
0
        /// <summary>
        /// 加载主题所在版块名称
        /// </summary>
        /// <param name="topicInfo"></param>
        private static void LoadTopicForumName(TopicInfo topicInfo)
        {
            ForumInfo forumInfo = Forums.GetForumInfo(topicInfo.Fid);

            topicInfo.Forumname = forumInfo == null ? "" : forumInfo.Name;
        }
Exemplo n.º 8
0
 /// <summary>
 /// 更新活动专题
 /// </summary>
 /// <param name="topicInfo">活动专题信息</param>
 public static void UpdateTopic(TopicInfo topicInfo)
 {
     NStore.Data.Topics.UpdateTopic(topicInfo);
     NStore.Core.BMACache.Remove(CacheKeys.MALL_TOPIC_INFO + topicInfo.TopicId);
     NStore.Core.BMACache.Remove(CacheKeys.MALL_TOPIC_INFO + topicInfo.SN);
 }
Exemplo n.º 9
0
        protected override void ShowPage()
        {
            if (postid == 0)
            {
                base.AddErrLine("指定的主题不存在或已被删除或正在被审核,请返回.");
                return;
            }

            PostInfo postInfo = Posts.GetPostInfo(topicid, postid);

            if (postInfo == null)
            {
                base.AddErrLine("指定的主题不存在或已被删除或正在被审核,请返回.");
                return;
            }

            ip         = postInfo.Ip;
            iplocation = IpSearch.GetAddressWithIP(ip);

            // 如果数据库文件不存在
            if (iplocation == null)
            {
                iplocation = "(IP数据库文件不存在,无法查询)";
            }
            else if (iplocation == "") // 如果没有查到
            {
                iplocation = "没有查询到该用户的地理所在地";
            }

            // 获取该主题的信息
            TopicInfo topic = Topics.GetTopicInfo(postInfo.Tid);

            // 如果该主题不存在
            if (topic == null)
            {
                AddErrLine("不存在的主题ID");
                return;
            }

            ForumInfo forum = Forums.GetForumInfo(postInfo.Fid);

            forumname = forum.Name;
            pagetitle = topic.Title;
            forumnav  = ForumUtils.UpdatePathListExtname(forum.Pathlist.Trim(), config.Extname);

            AdminGroupInfo admininfo = AdminGroups.GetAdminGroupInfo(usergroupid);

            if (admininfo == null || admininfo.Allowviewip != 1)
            {
                AddErrLine("你没有查看IP的权限");
                return;
            }
            if (DNTRequest.GetString("action") == "ipban")
            {
                if (admininfo.Allowbanip != 1)
                {
                    AddErrLine("你无权禁止用户IP,请返回");
                    return;
                }
                if (Utils.InIPArray(DNTRequest.GetString("ip"), Utils.SplitString(config.Ipdenyaccess, "\n")))
                {
                    Users.UpdateUserGroup(postInfo.Posterid, 6);
                    AddErrLine("IP已在列表中存在,无需重复添加");
                    return;
                }
                if (GeneralConfigs.SetIpDenyAccess(DNTRequest.GetString("ip")))
                {
                    //调整用户到禁止IP组
                    Users.UpdateUserGroup(postInfo.Posterid, 6);

                    SetUrl(base.ShowTopicAspxRewrite(topic.Tid, 0));
                    SetMetaRefresh();
                    SetShowBackLink(false);
                    MsgForward("getip_succeed");
                    base.AddMsgLine("IP已加入到用户禁止列表中");
                    base.ispost = true;
                }
                else
                {
                    base.AddErrLine("未知原因,IP无法加到禁止列表中");
                }
            }
        }
Exemplo n.º 10
0
        /// <summary>
        /// 获取帖子参数信息(PostPramsInfo)
        /// </summary>
        /// <param name="price"></param>
        /// <returns></returns>
        private List <ShowtopicPageAttachmentInfo> GetAttachList(int price, string onlyauthor, int ismoder, int posterid, UserInfo userinfo, UserGroupInfo usergroupinfo, TopicInfo topic, ForumInfo forum)
        {
            GeneralConfigInfo config = GeneralConfigs.GetConfig();
            //获取当前页主题列表
            PostpramsInfo postpramsInfo = new PostpramsInfo();

            postpramsInfo.Fid                    = forum.Fid;
            postpramsInfo.Tid                    = topic.Tid;
            postpramsInfo.Jammer                 = forum.Jammer;
            postpramsInfo.Pagesize               = 10000; // 得到Ppp设置
            postpramsInfo.Pageindex              = 1;
            postpramsInfo.Getattachperm          = forum.Getattachperm;
            postpramsInfo.Usergroupid            = usergroupinfo.Groupid;
            postpramsInfo.Attachimgpost          = config.Attachimgpost;
            postpramsInfo.Showattachmentpath     = config.Showattachmentpath;
            postpramsInfo.Price                  = price;
            postpramsInfo.Usergroupreadaccess    = (ismoder == 1) ? int.MaxValue : usergroupinfo.Readaccess;
            postpramsInfo.CurrentUserid          = userinfo.Uid;
            postpramsInfo.Showimages             = forum.Allowimgcode;
            postpramsInfo.Smiliesinfo            = Smilies.GetSmiliesListWithInfo();
            postpramsInfo.Customeditorbuttoninfo = Editors.GetCustomEditButtonListWithInfo();
            postpramsInfo.Smiliesmax             = config.Smiliesmax;
            postpramsInfo.Bbcodemode             = config.Bbcodemode;
            postpramsInfo.CurrentUserGroup       = usergroupinfo;
            postpramsInfo.Topicinfo              = topic;
            //判断是否为回复可见帖, hide=0为不解析[hide]标签, hide>0解析为回复可见字样, hide=-1解析为以下内容回复可见字样显示真实内容
            //将逻辑判断放入取列表的循环中处理,此处只做是否为回复人的判断,主题作者也该可见
            postpramsInfo.Hide        = (topic.Hide == 1 && (Posts.IsReplier(topic.Tid, userinfo.Uid) || ismoder == 1)) ? -1 : 1;
            postpramsInfo.Hide        = topic.Posterid == userinfo.Uid ? -2 : postpramsInfo.Hide;
            postpramsInfo.Condition   = Posts.GetPostPramsInfoCondition(onlyauthor, topic.Tid, posterid);
            postpramsInfo.Usercredits = userinfo == null ? 0 : userinfo.Credits;
            List <ShowtopicPageAttachmentInfo> attachmentlist = new List <ShowtopicPageAttachmentInfo>();
            List <ShowtopicPagePostInfo>       postlist       = GetPostList(postpramsInfo, out attachmentlist, ismoder == 1);
            int allowGetAttach = GetAllowGetAttachValue(postpramsInfo);

            foreach (ShowtopicPageAttachmentInfo showtopicpageattachinfo in attachmentlist)
            {
                if (Forums.AllowGetAttachByUserID(forum.Permuserlist, userinfo.Uid))
                {
                    showtopicpageattachinfo.Getattachperm = 1;
                    showtopicpageattachinfo.Allowread     = 1;
                }
            }
            List <ShowtopicPageAttachmentInfo> attachDeleteList = new List <ShowtopicPageAttachmentInfo>();

            foreach (ShowtopicPageAttachmentInfo attachInfo in attachmentlist)
            {
                if (allowGetAttach == 1 && attachInfo.Allowread == 1)
                {
                    if (attachInfo.Filetype.IndexOf("jpeg") >= 0 || attachInfo.Filetype.IndexOf("png") >= 0)
                    {
                        if (!attachInfo.Filename.ToLower().StartsWith("http"))
                        {
                            attachInfo.Filename = Utils.GetRootUrl(BaseConfigs.GetForumPath) + "upload/" + attachInfo.Filename.Trim();
                        }
                    }
                    else
                    {
                        attachDeleteList.Add(attachInfo);//记录不是JPG或PNG的图片,以便进行remove操作
                    }
                }
                else
                {
                    attachDeleteList.Add(attachInfo);//记录不是JPG或PNG的图片,以便进行remove操作
                }
            }
            foreach (ShowtopicPageAttachmentInfo attach in attachDeleteList)
            {
                attachmentlist.Remove(attach);
            }
            return(attachmentlist);
        }
Exemplo n.º 11
0
 public void TopicPushFeed(TopicInfo topic, PostInfo post, AttachmentInfo[] attachments, int feedStatus)
 {
     pushFeed_asyncCallback = new PushFeedToCloud(PushFeedToDiscuzCloud);
     pushFeed_asyncCallback.BeginInvoke(topic, post, attachments, feedStatus, null, null);
 }
Exemplo n.º 12
0
 public static TopicInfo setToppic(TopicInfo topic)
 {
     return(CBO.FillObject <TopicInfo>(DataProvider.Instance().SetTopic(topic)));;
 }
Exemplo n.º 13
0
        /// <summary>
        /// 获取主题帖信息
        /// </summary>
        /// <param name="admininfo"></param>
        /// <returns></returns>
        public PostInfo GetPostAndTopic(AdminGroupInfo admininfo)
        {
            PostInfo postinfo = new PostInfo();

            //如果帖子id和主题id都没有指定
            if (postid == -1 && topicid == -1)
            {
                AddErrLine("无效的主题ID");
                return(postinfo);
            }

            //如果帖子id被指定
            if (postid != -1)
            {
                postinfo = Posts.GetPostInfo(topicid, postid);
                if (postinfo == null)
                {
                    AddErrLine("无效的帖子ID");
                    return(postinfo);
                }
                if (topicid != postinfo.Tid)
                {
                    AddErrLine("主题ID无效");
                    return(postinfo);
                }

                //如果帖子作者是禁止发言,禁止访问,禁止IP用户组或者帖子invisible属性小于0,则不允许引用及回复


                if (!string.IsNullOrEmpty(DNTRequest.GetString("quote")))
                {
                    if (postinfo.Invisible != 0)
                    {
                        postinfo.Message = "**** 作者被禁止或删除 内容自动屏蔽 ****";
                    }
                    else
                    {
                        string info = postinfo.Posterid > 0 ? Users.GetShortUserInfo(postinfo.Posterid).Groupid.ToString() : null;
                        if (Utils.InArray(info, "4.5.6"))
                        {
                            postinfo.Message = "**** 作者被禁止或删除 内容自动屏蔽 ****";
                        }
                    }
                    //if (Utils.InArray(Users.GetShortUserInfo(postinfo.Posterid).Groupid.ToString(), "4,5,6") || postinfo.Invisible != 0)
                    //    postinfo.Message = "**** 作者被禁止或删除 内容自动屏蔽 ****";

                    if ((postinfo.Message.IndexOf("[hide]") > -1) && (postinfo.Message.IndexOf("[/hide]") > -1))
                    {
                        message = string.Format("[quote] 原帖由 [b]{0}[/b] 于 {1} 发表\r\n ***隐藏帖*** [/quote]", postinfo.Poster, postinfo.Postdatetime);
                    }
                    //message = "[quote] 原帖由 [b]" + postinfo.Poster + "[/b] 于 " + postinfo.Postdatetime + " 发表\r\n ***隐藏帖*** [/quote]";
                    else
                    {
                        message = string.Format("[quote]{0}\r\n [color=#999999]{1} 发表于 {2} [/color][url={5}showtopic.aspx?topicid={3}&postid={4}#{4}][img]{5}images/common/back.gif[/img][/url][/size][/quote]"
                                                , UBB.ClearAttachUBB(Utils.GetSubString(postinfo.Message, 200, "......")), postinfo.Poster, postinfo.Postdatetime, topicid, postid, Utils.GetRootUrl(forumpath));
                    }
                }
            }

            // 获取该主题的信息
            topic = Topics.GetTopicInfo(topicid);
            // 如果该主题不存在
            if (topic == null)
            {
                AddErrLine("不存在的主题ID");
                return(postinfo);
            }

            topictitle = topic.Title.Trim();
            pagetitle  = topictitle;
            forumid    = topic.Fid;

            // 如果当前用户非管理员并且该主题已关闭,不允许用户发帖
            if ((admininfo == null || !Moderators.IsModer(admininfo.Admingid, userid, forumid)) && topic.Closed == 1)
            {
                AddErrLine("主题已关闭无法回复");
                return(postinfo);
            }

            if (topic.Readperm > usergroupinfo.Readaccess && topic.Posterid != userid && useradminid != 1)
            {
                if (forum.Moderators != null && !Utils.InArray(username, forum.Moderators.Split(',')))
                {
                    AddErrLine("本主题阅读权限为: " + topic.Readperm + ", 您当前的身份 \"" + usergroupinfo.Grouptitle + "\" 阅读权限不够");
                }
            }

            return(postinfo);
        }
Exemplo n.º 14
0
        /// <summary>
        /// 创建主题信息
        /// </summary>
        /// <param name="admininfo"></param>
        /// <param name="postmessage"></param>
        /// <param name="isbonus"></param>
        /// <param name="topicprice"></param>
        /// <returns></returns>
        public TopicInfo CreateTopic(AdminGroupInfo admininfo, string postmessage, bool isbonus, int topicprice)
        {
            TopicInfo topicinfo = new TopicInfo();

            topicinfo.Fid    = forumid;
            topicinfo.Iconid = (DNTRequest.GetInt("iconid", 0) < 0 || DNTRequest.GetInt("iconid", 0) > 15) ? 0 :
                               DNTRequest.GetInt("iconid", 0);
            message = Posts.GetPostMessage(usergroupinfo, admininfo, postmessage,
                                           (TypeConverter.StrToInt(DNTRequest.GetString("htmlon")) == 1));

            topicinfo.Title = (useradminid == 1) ? Utils.HtmlEncode(posttitle) :
                              Utils.HtmlEncode(ForumUtils.BanWordFilter(posttitle));

            if (useradminid != 1 && (ForumUtils.HasBannedWord(posttitle) || ForumUtils.HasBannedWord(postmessage)))
            {
                string bannedWord = ForumUtils.GetBannedWord(posttitle) == string.Empty ? ForumUtils.GetBannedWord(postmessage) : ForumUtils.GetBannedWord(posttitle);
                AddErrLine(string.Format("对不起, 您提交的内容包含不良信息  <font color=\"red\">{0}</font>, 请返回修改!", bannedWord));
                return(topicinfo);
            }

            if (Utils.GetCookie("lasttopictitle") == Utils.MD5(topicinfo.Title) || Utils.GetCookie("lasttopicmessage") == Utils.MD5(message))
            {
                AddErrLine("请勿重复发帖");
                return(topicinfo);
            }

            topicinfo.Typeid = DNTRequest.GetInt("typeid", 0);
            if (usergroupinfo.Allowsetreadperm == 1)
            {
                topicinfo.Readperm = DNTRequest.GetInt("topicreadperm", 0) > 255 ? 255 : DNTRequest.GetInt("topicreadperm", 0);
            }

            topicinfo.Price        = topicprice;
            topicinfo.Poster       = username;
            topicinfo.Posterid     = userid;
            topicinfo.Postdatetime = curdatetime;
            topicinfo.Lastpost     = curdatetime;
            topicinfo.Lastposter   = username;
            topicinfo.Displayorder = Topics.GetTitleDisplayOrder(usergroupinfo, useradminid, forum, topicinfo, message, disablepost);


            string htmltitle = DNTRequest.GetString("htmltitle").Trim();

            if (!Utils.StrIsNullOrEmpty(htmltitle) && Utils.HtmlDecode(htmltitle).Trim() != topicinfo.Title)
            {
                //按照  附加位/htmltitle(1位)/magic(3位)/以后扩展(未知位数) 的方式来存储  例: 11001
                topicinfo.Magic = 11000;
            }

            //标签(Tag)操作
            string tags = DNTRequest.GetString("tags").Trim();

            string[] tagArray = null;
            if (enabletag && !Utils.StrIsNullOrEmpty(tags))
            {
                if (ForumUtils.InBanWordArray(tags))
                {
                    AddErrLine("标签中含有系统禁止词语,请修改");
                    return(topicinfo);
                }

                tagArray = Utils.SplitString(tags, " ", true, 2, 10);
                if (tagArray.Length > 0 && tagArray.Length <= 5)
                {
                    if (topicinfo.Magic == 0)
                    {
                        topicinfo.Magic = 10000;
                    }

                    topicinfo.Magic = Utils.StrToInt(topicinfo.Magic.ToString() + "1", 0);
                }
                else
                {
                    AddErrLine("超过标签数的最大限制或单个标签长度没有介于2-10之间,最多可填写 5 个标签");
                    return(topicinfo);
                }
            }

            if (isbonus)
            {
                topicinfo.Special = 2;

                //检查积分是否足够
                if (mybonustranscredits < topicprice && usergroupinfo.Radminid != 1)
                {
                    AddErrLine(string.Format("无法进行悬赏<br /><br />您当前的{0}为 {1} {3}<br/>悬赏需要{0} {2} {3}", bonusextcreditsinfo.Name, mybonustranscredits, topicprice, bonusextcreditsinfo.Unit));
                    return(topicinfo);
                }
                else
                {
                    Users.UpdateUserExtCredits(topicinfo.Posterid, Scoresets.GetBonusCreditsTrans(),
                                               -topicprice * (Scoresets.GetCreditsTax() + 1)); //计算税后的实际支付
                }
            }

            if (type == "poll")
            {
                topicinfo.Special = 1;
            }

            if (type == "debate") //辩论帖
            {
                topicinfo.Special = 4;
            }

            if (!Moderators.IsModer(useradminid, userid, forumid))
            {
                topicinfo.Attention = 1;
            }

            if (ForumUtils.IsHidePost(postmessage) && usergroupinfo.Allowhidecode == 1)
            {
                topicinfo.Hide = 1;
            }

            topicinfo.Tid = Topics.CreateTopic(topicinfo);

            //canhtmltitle = config.Htmltitle == 1 && Utils.InArray(usergroupid.ToString(), config.Htmltitleusergroup);
            //canhtmltitle = config.Htmltitle == 1 && usergroupinfo.Allowhtml == 1;
            //保存htmltitle

            if (canhtmltitle && !Utils.StrIsNullOrEmpty(htmltitle) && htmltitle != topicinfo.Title)
            {
                Topics.WriteHtmlTitleFile(Utils.RemoveUnsafeHtml(htmltitle), topicinfo.Tid);
            }

            if (enabletag && tagArray != null && tagArray.Length > 0)
            {
                if (useradminid != 1 && ForumUtils.HasBannedWord(tags))
                {
                    string bannedWord = ForumUtils.GetBannedWord(tags);
                    AddErrLine(string.Format("标签中含有系统禁止词语 <font color=\"red\">{0}</font>,请修改", bannedWord));
                    return(topicinfo);
                }
                ForumTags.CreateTopicTags(tagArray, topicinfo.Tid, userid, curdatetime);
            }

            if (type == "debate")
            {
                DebateInfo debatetopic = new DebateInfo();
                debatetopic.Tid             = topicinfo.Tid;
                debatetopic.Positiveopinion = DNTRequest.GetString("positiveopinion");
                debatetopic.Negativeopinion = DNTRequest.GetString("negativeopinion");
                debatetopic.Terminaltime    = Convert.ToDateTime(DNTRequest.GetString("terminaltime"));
                Topics.CreateDebateTopic(debatetopic);
            }

            Topics.AddParentForumTopics(forum.Parentidlist.Trim(), 1);
            return(topicinfo);
        }
Exemplo n.º 15
0
 public static TopicInfo addTopic(TopicInfo topic)
 {
     return(CBO.FillObject <TopicInfo>(DataProvider.Instance().AddTopic(topic)));
 }
Exemplo n.º 16
0
        protected override void ShowPage()
        {
            if (oluserinfo.Groupid == 4)
            {
                AddErrLine("你所在的用户组,为禁止发言"); return;
            }

            #region 临时帐号发帖
            //int realuserid = -1;
            //bool tempaccountspost = false;
            //string tempusername = DNTRequest.GetString("tempusername");
            //if (!Utils.StrIsNullOrEmpty(tempusername) && tempusername != username)
            //{
            //    realuserid = Users.CheckTempUserInfo(tempusername, DNTRequest.GetString("temppassword"), DNTRequest.GetInt("question", 0), DNTRequest.GetString("answer"));
            //    if (realuserid == -1)
            //    {
            //        AddErrLine("临时帐号登录失败,无法继续发帖。"); return;
            //    }
            //    else
            //    {
            //        userid = realuserid;
            //        username = tempusername;
            //        tempaccountspost = true;
            //    }
            //}


            #endregion

            if (userid > 0)
            {
                userinfo = Users.GetShortUserInfo(userid);
                //    if (userinfo != null)
                //    {
                //        usergroupinfo = UserGroups.GetUserGroupInfo(userinfo.Groupid);
                //        usergroupid = usergroupinfo.Groupid;
                //        useradminid = userinfo.Adminid;
                //    }
            }

            #region 获取并检查版块信息
            forum = Forums.GetForumInfo(forumid);
            if (forum == null || forum.Layer == 0)
            {
                forum          = new ForumInfo();//如果不初始化对象,则会报错
                allowposttopic = false;
                AddErrLine("错误的论坛ID"); return;
            }

            pagetitle = Utils.RemoveHtml(forum.Name);
            enabletag = (config.Enabletag & forum.Allowtag) == 1;

            if (forum.Applytopictype == 1)  //启用主题分类
            {
                topictypeselectoptions = Forums.GetCurrentTopicTypesOption(forum.Fid, forum.Topictypes);
            }

            if (forum.Password != "" && Utils.MD5(forum.Password) != ForumUtils.GetCookie("forum" + forumid + "password"))
            {
                AddErrLine("本版块被管理员设置了密码");
                SetBackLink(base.ShowForumAspxRewrite(forumid, 0)); return;
            }
            needaudit         = UserAuthority.NeedAudit(forum, useradminid, userid, usergroupinfo);
            smileyoff         = 1 - forum.Allowsmilies;
            bbcodeoff         = (forum.Allowbbcode == 1 && usergroupinfo.Allowcusbbcode == 1) ? 0 : 1;
            allowimg          = forum.Allowimgcode;
            customeditbuttons = Caches.GetCustomEditButtonList();
            #endregion

            #region 访问和发帖权限校验
            if (!UserAuthority.VisitAuthority(forum, usergroupinfo, userid, ref msg))
            {
                AddErrLine(msg);
                needlogin = true; return;
            }

            if (!UserAuthority.PostAuthority(forum, usergroupinfo, userid, ref msg))
            {
                AddErrLine(msg);
                needlogin = true; return;
            }
            #endregion

            #region  附件信息绑定
            //得到用户可以上传的文件类型
            string attachmentTypeSelect = Attachments.GetAllowAttachmentType(usergroupinfo, forum);
            attachextensions       = Attachments.GetAttachmentTypeArray(attachmentTypeSelect);
            attachextensionsnosize = Attachments.GetAttachmentTypeString(attachmentTypeSelect);
            //得到今天允许用户上传的附件总大小(字节)
            int MaxTodaySize = (userid > 0 ? MaxTodaySize = Attachments.GetUploadFileSizeByuserid(userid) : 0);
            attachsize = usergroupinfo.Maxsizeperday - MaxTodaySize;//今天可上传得大小
            //是否有上传附件的权限
            canpostattach = UserAuthority.PostAttachAuthority(forum, usergroupinfo, userid, ref msg);

            if (canpostattach && (userinfo != null && userinfo.Uid > 0) && apb != null && config.Enablealbum == 1 &&
                (UserGroups.GetUserGroupInfo(userinfo.Groupid).Maxspacephotosize - apb.GetPhotoSizeByUserid(userid) > 0))
            {
                caninsertalbum = true;
                albumlist      = apb.GetSpaceAlbumByUserId(userid);
            }
            #endregion

            canhtmltitle = usergroupinfo.Allowhtmltitle == 1;

            #region 积分信息
            creditstrans        = Scoresets.GetTopicAttachCreditsTrans();
            userextcreditsinfo  = Scoresets.GetScoreSet(creditstrans);
            bonusextcreditsinfo = Scoresets.GetScoreSet(Scoresets.GetBonusCreditsTrans());
            #endregion

            #region 特殊主题权限判断
            if (forum.Allowspecialonly > 0 && !Utils.InArray(type, "poll,bonus,debate"))
            {
                AddErrLine(string.Format("当前版块 \"{0}\" 不允许发表普通主题", forum.Name)); return;
            }
            if (!UserAuthority.PostSpecialAuthority(forum, type, ref msg))
            {
                AddErrLine(msg); return;
            }
            if (!UserAuthority.PostSpecialAuthority(usergroupinfo, type, ref msg))
            {
                AddErrLine(msg);
                needlogin = true; return;
            }
            if (type == "bonus")
            {
                int creditTrans = Scoresets.GetBonusCreditsTrans();
                //当“交易积分设置”有效时(1-8的整数):
                if (creditTrans <= 0)
                {
                    //AddErrLine(string.Format("系统未设置\"交易积分设置\", 无法判断当前要使用的(扩展)积分字段, 暂时无法发布悬赏", usergroupinfo.Grouptitle)); return;
                    AddErrLine("系统未设置\"交易积分设置\", 无法判断当前要使用的(扩展)积分字段, 暂时无法发布悬赏"); return;
                }
                mybonustranscredits = Users.GetUserExtCredits(userid, creditTrans);
            }
            userGroupInfoList.Sort(delegate(UserGroupInfo x, UserGroupInfo y) { return((x.Readaccess - y.Readaccess) + (y.Groupid - x.Groupid)); });
            #endregion

            //发帖不受审核、过滤、灌水等限制权限
            AdminGroupInfo admininfo = AdminGroups.GetAdminGroupInfo(usergroupid);
            disablepost = admininfo != null ? admininfo.Disablepostctrl : usergroupinfo.Disableperiodctrl;
            //如果是提交...
            if (ispost)
            {
                #region 判断是否是灌水
                if (!UserAuthority.CheckPostTimeSpan(usergroupinfo, admininfo, oluserinfo, userinfo, ref msg))
                {
                    AddErrLine(msg); return;
                }
                #endregion

                SetBackLink(string.Format("posttopic.aspx?forumid={0}&restore=1&type={1}", forumid, type));

                ForumUtils.WriteCookie("postmessage", postmessage);

                #region 验证提交信息
                //常规项验证
                NormalValidate(admininfo, postmessage, userinfo);
                if (IsErr())
                {
                    return;
                }

                // 如果用户上传了附件,则检测用户是否有上传附件的权限
                if (ForumUtils.IsPostFile())
                {
                    if (Utils.StrIsNullOrEmpty(Attachments.GetAttachmentTypeArray(attachmentTypeSelect)))
                    {
                        AddErrLine("系统不允许上传附件");
                    }

                    if (!UserAuthority.PostAttachAuthority(forum, usergroupinfo, userid, ref msg))
                    {
                        AddErrLine(msg);
                    }
                }

                //发悬赏校验
                int  topicprice = 0;
                bool isbonus    = type == "bonus";
                ValidateBonus(ref topicprice, ref isbonus);

                //发特殊主题校验
                ValidatePollAndDebate();

                if (IsErr())
                {
                    return;
                }
                #endregion

                int hide = (ForumUtils.IsHidePost(postmessage) && usergroupinfo.Allowhidecode == 1) ? 1 : 0;

                TopicInfo topicinfo = CreateTopic(admininfo, postmessage, isbonus, topicprice);
                if (IsErr())
                {
                    return;
                }

                PostInfo postinfo = CreatePost(topicinfo);

                if (IsErr())
                {
                    return;
                }

                #region 处理附件
                //处理附件
                StringBuilder    sb             = new StringBuilder();
                AttachmentInfo[] attachmentinfo = null;
                string           attachId       = DNTRequest.GetFormString("attachid");
                if (!string.IsNullOrEmpty(attachId))
                {
                    attachmentinfo = Attachments.GetNoUsedAttachmentArray(userid, attachId);
                    Attachments.UpdateAttachment(attachmentinfo, topicinfo.Tid, postinfo.Pid, postinfo, ref sb, userid, config, usergroupinfo);
                }
                //加入相册
                if (config.Enablealbum == 1 && apb != null)
                {
                    sb.Append(apb.CreateAttachment(attachmentinfo, usergroupid, userid, username));
                }
                #endregion

                #region 添加日志的操作
                SpacePluginBase spb = SpacePluginProvider.GetInstance();
                if (DNTRequest.GetFormString("addtoblog") == "on" && spb != null)
                {
                    if (userid != -1 && userinfo.Spaceid > 0)
                    {
                        spb.CreateTopic(topicinfo, postinfo, attachmentinfo);
                    }
                    else
                    {
                        AddMsgLine("您的个人空间尚未开通, 无法同时添加为日志");
                    }
                }
                #endregion

                OnlineUsers.UpdateAction(olid, UserAction.PostTopic.ActionID, forumid, forum.Name, -1, "");

                #region 设置提示信息和跳转链接
                if (sb.Length > 0)
                {
                    SetUrl(base.ShowTopicAspxRewrite(topicinfo.Tid, 0));
                    SetMetaRefresh(5);
                    SetShowBackLink(true);
                    if (infloat == 1)
                    {
                        AddErrLine(sb.ToString());
                        return;
                    }
                    else
                    {
                        sb.Insert(0, "<table cellspacing=\"0\" cellpadding=\"4\" border=\"0\"><tr><td colspan=2 align=\"left\"><span class=\"bold\"><nobr>发表主题成功,但图片/附件上传出现问题:</nobr></span><br /></td></tr>");
                        AddMsgLine(sb.Append("</table>").ToString());
                    }
                }
                else
                {
                    SetShowBackLink(false);
                    if (useradminid != 1)
                    {
                        //是否需要审核
                        if (UserAuthority.NeedAudit(forum, useradminid, userid, usergroupinfo) || topicinfo.Displayorder == -2)
                        {
                            ForumUtils.WriteCookie("postmessage", "");
                            SetLastPostedForumCookie();
                            SetUrl(base.ShowForumAspxRewrite(forumid, forumpageid));
                            SetMetaRefresh();
                            AddMsgLine("发表主题成功, 但需要经过审核才可以显示. 返回该版块");
                        }
                        else
                        {
                            PostTopicSucceed(Forums.GetValues(forum.Postcredits), topicinfo, topicinfo.Tid);
                        }
                    }
                    else
                    {
                        PostTopicSucceed(Forums.GetValues(forum.Postcredits), topicinfo, topicinfo.Tid);
                    }
                }
                #endregion

                //ForumUtils.WriteCookie("postmessage", "");
                //SetLastPostedForumCookie();

                //如果已登录就不需要再登录
                if (needlogin && userid > 0)
                {
                    needlogin = false;
                }
            }
            else //非提交操作
            {
                AddLinkCss(BaseConfigs.GetForumPath + "templates/" + templatepath + "/editor.css", "css");
            }
        }
Exemplo n.º 17
0
        //=====================================================================

        /// <summary>
        /// This is used to set the current solution name and the projects
        /// </summary>
        /// <param name="solutionName">The current solution filename</param>
        /// <param name="projects">The current list of projects</param>
        public void SetCurrentSolutionAndProjects(string solutionName, IEnumerable <MSBuildProject> projects)
        {
            // If the solution changes, clear all existing topic information
            if (this.CurrentSolutionName != solutionName)
            {
                this.CurrentSolutionName = solutionName;
                topicInfo.Clear();
            }

            // Index the content layout files in each project.  This should happen quickly as there usually
            // aren't that many content layout files.
            foreach (var project in projects)
            {
                string projectPath = Path.GetDirectoryName(project.FullPath), filePath;

                foreach (var contentLayoutFile in project.GetItems("ContentLayout"))
                {
                    var link = contentLayoutFile.Metadata.FirstOrDefault(m => m.Name == "Link");

                    if (link == null)
                    {
                        filePath = Path.Combine(projectPath, contentLayoutFile.EvaluatedInclude);
                    }
                    else
                    {
                        filePath = Path.Combine(projectPath, link.EvaluatedValue);
                    }

                    if (File.Exists(filePath))
                    {
                        // TODO: Can it find an open content layout editor for the file if there is one and
                        // search its content instead?
                        var doc = XDocument.Load(filePath);

                        // Add or refresh the title information
                        foreach (var topic in doc.Descendants("Topic"))
                        {
                            TopicInfo info;

                            if (!topicInfo.TryGetValue(topic.Attribute("id").Value, out info))
                            {
                                info = new TopicInfo
                                {
                                    TopicId = topic.Attribute("id").Value,
                                }
                            }
                            ;

                            info.Title = (string)topic.Attribute("title") ?? info.Title ?? "(No title)";

                            topicInfo.AddOrUpdate(info.TopicId, info, (key, value) => value);
                        }
                    }
                }
            }

            // If any new topics are found, match the ID to actual files.  This is done in the background as
            // large projects may have hundreds of topics.  This may not be necessary but it saves blocking the
            // IDE while it does it just in case.
            if (topicInfo.Any(t => t.Value.Filename == null))
            {
                this.MatchFilesToTopics(projects.Select(p => Path.GetDirectoryName(p.FullPath)).Distinct());
            }
        }
Exemplo n.º 18
0
        protected override void ShowPage()
        {
            // 获取帖子ID
            topicid = DNTRequest.GetInt("topicid", -1);
            postid  = DNTRequest.GetInt("postid", -1);
            // 如果主题ID非数字
            if (postid == -1)
            {
                AddErrLine("无效的帖子ID");
                return;
            }

            // 获取该帖子的信息
            post = Posts.GetPostInfo(topicid, postid);
            // 如果该帖子不存在
            if (post == null)
            {
                AddErrLine("不存在的主题ID");
                return;
            }

            // 获取该主题的信息
            topic = Topics.GetTopicInfo(topicid);

            // 如果该主题不存在
            if (topic == null)
            {
                AddErrLine("不存在的主题ID");
                return;
            }

            if (topicid != post.Tid)
            {
                AddErrLine("主题ID无效");
                return;
            }

            topictitle = topic.Title;
            forumid    = topic.Fid;
            forum      = Forums.GetForumInfo(forumid);
            forumname  = forum.Name;
            pagetitle  = "删除" + post.Title;
            forumnav   = ForumUtils.UpdatePathListExtname(forum.Pathlist.Trim(), config.Extname);
            int opinion = DNTRequest.GetInt("opinion", -1);

            if (!CheckPermission(post, opinion))
            {
                return;
            }

            if (!allowdelpost)
            {
                AddErrLine("当前不允许删帖");
                return;
            }

            int Losslessdel = Utils.StrDateDiffHours(post.Postdatetime, config.Losslessdel * 24);

            // 通过验证的用户可以删除帖子,如果是主题贴则另处理
            if (post.Layer == 0)
            {
                TopicAdmins.DeleteTopics(topicid.ToString(), byte.Parse(forum.Recyclebin.ToString()), false);
                //重新统计论坛帖数
                Forums.SetRealCurrentTopics(forum.Fid);

                ForumTags.DeleteTopicTags(topicid);
            }
            else
            {
                int reval;
                if (topic.Special == 4)
                {
                    string opiniontext = "";

                    if (opinion != 1 && opinion != 2)
                    {
                        AddErrLine("参数错误");
                        return;
                    }
                    reval = Posts.DeletePost(Posts.GetPostTableID(topicid), postid, false, true);
                    switch (opinion)
                    {
                    case 1:
                        opiniontext = "positivediggs";
                        break;

                    case 2:
                        opiniontext = "negativediggs";
                        break;
                    }
                    Discuz.Data.DatabaseProvider.GetInstance().DeleteDebatePost(topicid, opiniontext, postid);
                }
                else
                {
                    reval = Posts.DeletePost(Posts.GetPostTableID(topicid), postid, false, true);
                }

                // 删除主题游客缓存
                ForumUtils.DeleteTopicCacheFile(topicid);

                //再次确保回复数精确
                Topics.UpdateTopicReplies(topic.Tid);

                //更新指定版块的最新发帖数信息
                Forums.UpdateLastPost(forum);

                if (reval > 0 && Losslessdel < 0)
                {
                    UserCredits.UpdateUserCreditsByPosts(post.Posterid, -1);
                }
            }


            SetUrl(Urls.ShowTopicAspxRewrite(post.Tid, 1));
            if (post.Layer == 0)
            {
                SetUrl(base.ShowForumAspxRewrite(post.Fid, 0));
            }
            SetMetaRefresh();
            SetShowBackLink(false);
            AddMsgLine("删除帖子成功, 返回主题");
        }
Exemplo n.º 19
0
		public static string ReplyLink(int tabId, TopicInfo ti, int userId, int replyId)
		{
			var sURL = Utilities.NavigateUrl(tabId, string.Empty, new [] { ParamKeys.TopicId + "=" + ti.TopicId, ParamKeys.ContentJumpId + "=" + replyId });

			if (string.IsNullOrEmpty(ti.URL) || ! Utilities.IsRewriteLoaded())
				return sURL;

            var db = new Data.Common();
			sURL = db.GetUrl(-1, -1, -1, ti.TopicId, userId, replyId);
			if (! (string.IsNullOrEmpty(sURL)))
			{
				var sHost = Utilities.GetHost();
				if (sURL.StartsWith("/"))
					sURL = sURL.Substring(1);

				if (!(sHost.EndsWith("/")))
					sHost += "/";

				sURL = sHost + sURL;
				if (! (sURL.EndsWith("/")))
					sURL += "/";

				if (replyId > 0)
					sURL += "#" + replyId.ToString();
			}

			return sURL;
		}
Exemplo n.º 20
0
 public IEnumerable <string> GetFiles(TopicInfo topic)
 {
     yield break;
 }
Exemplo n.º 21
0
 /// <summary>Find or create TopicInfo by Topic</summary>
 /// <param name="tp">Topic as key</param>
 /// <param name="sendRegister">Send MsRegister for new TopicInfo</param>
 /// <returns>found TopicInfo or null</returns>
 private TopicInfo GetTopicInfo(Topic tp, bool sendRegister=true) {
   if(tp==null) {
     return null;
   }
   TopicInfo rez=null;
   for(int i=_topics.Count-1; i>=0; i--) {
     if(_topics[i].path==tp.path) {
       rez=_topics[i];
       break;
     }
   }
   string tpc=(tp.path.StartsWith(Owner.path))?tp.path.Remove(0, Owner.path.Length+1):tp.path;
   if(rez==null) {
     rez=new TopicInfo();
     rez.topic=tp;
     rez.path=tp.path;
     ushort rtId;
     if(PredefinedTopics.TryGetValue(tpc, out rtId)) {
       rez.TopicId=rtId;
       rez.it=TopicIdType.PreDefined;
       rez.registred=true;
     } else {
       rez.TopicId=CalculateTopicId(rez.path);
       rez.it=TopicIdType.Normal;
     }
     _topics.Add(rez);
   }
   if(!rez.registred) {
     if(sendRegister) {
       Send(new MsRegister(rez.TopicId, tpc));
     } else {
       rez.registred=true;
     }
   }
   return rez;
 }
Exemplo n.º 22
0
        protected override void ShowPage()
        {
            if (postid == -1)
            {
                AddErrLine("无效的帖子ID");
                return;
            }

            // 获取该帖子的信息
            post = Posts.GetPostInfo(topicid, postid);
            if (post == null)
            {
                AddErrLine("不存在的帖子ID");
                return;
            }
            // 获取该主题的信息
            topic = Topics.GetTopicInfo(topicid);
            if (topic == null)
            {
                AddErrLine("不存在的主题ID");
                return;
            }
            if (topicid != post.Tid)
            {
                AddErrLine("主题ID无效");
                return;
            }

            topictitle = topic.Title;
            forumid    = topic.Fid;
            forum      = Forums.GetForumInfo(forumid);
            forumname  = forum.Name;
            pagetitle  = string.Format("删除{0}", post.Title);
            forumnav   = ShowForumAspxRewrite(forum.Pathlist.Trim(), forumid, forumpageid);

            if (!CheckPermission(post, DNTRequest.GetInt("opinion", -1)))
            {
                return;
            }

            if (!allowDelPost)
            {
                AddErrLine("当前不允许删帖");
                return;
            }

            // 通过验证的用户可以删除帖子,如果是主题帖则另处理
            if (post.Layer == 0)
            {
                TopicAdmins.DeleteTopics(topicid.ToString(), byte.Parse(forum.Recyclebin.ToString()), false);
                //重新统计论坛帖数
                Forums.SetRealCurrentTopics(forum.Fid);
                ForumTags.DeleteTopicTags(topicid);
            }
            else
            {
                int reval;
                if (topic.Special == 4)
                {
                    if (DNTRequest.GetInt("opinion", -1) != 1 && DNTRequest.GetInt("opinion", -1) != 2)
                    {
                        AddErrLine("参数错误");
                        return;
                    }
                    reval = Posts.DeletePost(Posts.GetPostTableId(topicid), postid, false, true);
                    Debates.DeleteDebatePost(topicid, DNTRequest.GetInt("opinion", -1), postid);
                }
                else
                {
                    reval = Posts.DeletePost(Posts.GetPostTableId(topicid), postid, false, true);
                }

                // 删除主题游客缓存
                ForumUtils.DeleteTopicCacheFile(topicid);
                //再次确保回复数精确
                Topics.UpdateTopicReplyCount(topic.Tid);
                //更新指定版块的最新发帖数信息
                Forums.UpdateLastPost(forum);

                if (reval > 0 && Utils.StrDateDiffHours(post.Postdatetime, config.Losslessdel * 24) < 0)
                {
                    UserCredits.UpdateUserCreditsByDeletePosts(post.Posterid);
                }
            }

            SetUrl(post.Layer == 0 ? base.ShowForumAspxRewrite(post.Fid, 0) : Urls.ShowTopicAspxRewrite(post.Tid, 1));
            SetMetaRefresh();
            SetShowBackLink(false);
            AddMsgLine("删除帖子成功, 返回主题");
        }
Exemplo n.º 23
0
        /// <summary>
        /// 发送feed请求到云平台
        /// </summary>
        /// <param name="topic"></param>
        /// <param name="post"></param>
        /// <param name="attachments"></param>
        /// <param name="connectInfo"></param>
        /// <returns></returns>
        public static bool PushFeedToDiscuzCloud(TopicInfo topic, PostInfo post, AttachmentInfo[] attachments, UserConnectInfo connectInfo, string ip, string rootUrl)
        {
            DiscuzCloudConfigInfo       config   = DiscuzCloudConfigs.GetConfig();
            List <DiscuzOAuthParameter> parmlist = new List <DiscuzOAuthParameter>();

            parmlist.Add(new DiscuzOAuthParameter("client_ip", ip));
            parmlist.Add(new DiscuzOAuthParameter("thread_id", topic.Tid.ToString()));
            parmlist.Add(new DiscuzOAuthParameter("author_id", topic.Posterid.ToString()));
            parmlist.Add(new DiscuzOAuthParameter("author", topic.Poster));
            parmlist.Add(new DiscuzOAuthParameter("forum_id", topic.Fid.ToString()));
            parmlist.Add(new DiscuzOAuthParameter("p_id", post.Pid.ToString()));
            parmlist.Add(new DiscuzOAuthParameter("subject", topic.Title));

            #region 构造postparmsinfo

            GeneralConfigInfo generalConfig = GeneralConfigs.GetConfig();
            PostpramsInfo     postpramsInfo = new PostpramsInfo();
            postpramsInfo.Sdetail     = post.Message;
            postpramsInfo.Smiliesinfo = Smilies.GetSmiliesListWithInfo();
            postpramsInfo.Bbcodemode  = generalConfig.Bbcodemode;
            postpramsInfo.Parseurloff = post.Parseurloff;
            postpramsInfo.Bbcodeoff   = post.Bbcodeoff;
            postpramsInfo.Signature   = 0;
            postpramsInfo.Allowhtml   = post.Htmlon;
            postpramsInfo.Pid         = post.Pid;
            postpramsInfo.Showimages  = 1 - post.Smileyoff;
            postpramsInfo.Smileyoff   = post.Smileyoff;
            postpramsInfo.Smiliesmax  = generalConfig.Smiliesmax;
            //判断是否为回复可见帖, hide=0为不解析[hide]标签, hide>0解析为回复可见字样, hide=-1解析为以下内容回复可见字样显示真实内容
            //将逻辑判断放入取列表的循环中处理,此处只做是否为回复人的判断,主题作者也该可见
            postpramsInfo.Hide = 0;

            #endregion
            parmlist.Add(new DiscuzOAuthParameter("html_content", UBB.UBBToHTML(postpramsInfo)));
            parmlist.Add(new DiscuzOAuthParameter("bbcode_content", post.Message));
            parmlist.Add(new DiscuzOAuthParameter("read_permission", "0"));
            parmlist.Add(new DiscuzOAuthParameter("u_id", topic.Posterid.ToString()));
            parmlist.Add(new DiscuzOAuthParameter("f_type", connectInfo.AllowPushFeed.ToString()));

            StringBuilder attachUrlList = new StringBuilder();
            int           attachCount   = 0;
            if (attachments != null)
            {
                foreach (AttachmentInfo info in attachments)
                {
                    if (attachCount < 3 && info.Filetype.IndexOf("image") > -1 && info.Attachprice <= 0)
                    {
                        attachUrlList.AppendFormat("|{0}upload/{1}", rootUrl, info.Filename.Replace("\\", "/"));
                        attachCount++;
                    }
                }
            }

            parmlist.Add(new DiscuzOAuthParameter("attach_images", attachUrlList.ToString().TrimStart('|')));

            DiscuzOAuth oAuth    = new DiscuzOAuth();
            string      queryStr = "";
            string      feedUrl  = oAuth.GetOAuthUrl(API_CONNECT_URL + "connect/feed/new", "POST",
                                                     config.Connectappid, config.Connectappkey, connectInfo.Token, connectInfo.Secret, "", "", parmlist, out queryStr);

            Utils.GetHttpWebResponse(feedUrl, queryStr);
            return(true);
        }
Exemplo n.º 24
0
 /// <summary>
 /// 按照displayorder排序
 /// </summary>
 /// <param name="x"></param>
 /// <param name="y"></param>
 /// <returns></returns>
 private static int CompareDisplayOrder(TopicInfo x, TopicInfo y)
 {
     return(new System.Collections.CaseInsensitiveComparer().Compare(x.Displayorder, y.Displayorder));
 }
Exemplo n.º 25
0
 /// <summary>
 /// 创建活动专题
 /// </summary>
 /// <param name="topicInfo">活动专题信息</param>
 public static void CreateTopic(TopicInfo topicInfo)
 {
     NStore.Data.Topics.CreateTopic(topicInfo);
 }
Exemplo n.º 26
0
 /// <summary>
 /// 获取指定用户组和版信息下主题的DisplayOrder
 /// </summary>
 /// <param name="usergroupinfo">用户组信息</param>
 /// <param name="useradminid">管理组ID</param>
 /// <param name="forum">当前版块</param>
 /// <param name="topicInfo">当前主题信息</param>
 /// <param name="message">帖子内容</param>
 /// <param name="disablepost">是否受灌水限制 1,不受限制;0,受限制</param>
 /// <returns>0:正常显示;-2:待审核</returns>
 public static int GetTitleDisplayOrder(UserGroupInfo usergroupinfo, int useradminid, ForumInfo forum, TopicInfo topicInfo, string message, int disablepost)
 {
     if (useradminid == 1 || Moderators.IsModer(useradminid, topicInfo.Posterid, forum.Fid))
     {
         return(topicInfo.Displayorder);
     }
     if (forum.Modnewtopics == 1 || usergroupinfo.ModNewTopics == 1 || Scoresets.BetweenTime(GeneralConfigs.GetConfig().Postmodperiods) && disablepost != 1 || ForumUtils.HasAuditWord(topicInfo.Title) || ForumUtils.HasAuditWord(message))
     {
         return(-2);
     }
     return(topicInfo.Displayorder);
 }
Exemplo n.º 27
0
 public IEnumerable <ReplyInfo> GetReplies(TopicInfo topic, int startrec, int maxrecs)
 {
     throw new System.NotImplementedException();
 }
        void ConfigurationEventTestBis(
            TopicInfo topicInfo,
            Action <XmlElement, TopicInfo> validateTopic,
            ValidateConfigurationMessageFunction validateMessageFunction,
            string sourceTokenSimpleItem,
            Action <string> validateConfigurationFunction)
        {
            int actualTerminationTime = 60;

            if (_eventSubscriptionTimeout != 0)
            {
                actualTerminationTime = _eventSubscriptionTimeout;
            }
            int timeout = _operationDelay / 1000;

            RunTest(
                () =>
            {
                // Get topic description from the DUT.
                XmlElement topicElement = GetTopicElement(topicInfo);

                Assert(null != topicElement,
                       string.Format("Topic {0} not supported", topicInfo.GetDescription()),
                       "Check if the event topic is supported");

                XmlElement messageDescription = topicElement.GetMessageDescription();
                validateTopic(messageDescription, topicInfo);

                // filter for current test
                TestTool.Proxies.Event.FilterType filter = CreateSubscriptionFilter(topicInfo);

                string message = string.Format("{0}  event is expected!", topicInfo.GetDescription());
                bool UseNotify = UseNotifyToGetEvents;

                Dictionary <NotificationMessageHolderType, XmlElement> notifications = null;
                SubscriptionHandler Handler = null;
                try
                {
                    Handler = new SubscriptionHandler(this, UseNotify, GetEventServiceAddress());
                    Handler.Subscribe(filter, actualTerminationTime);

                    Operator.ShowMessage(message);

                    var pullingCondition = new SubscriptionHandler.WaitFirstNotificationPollingCondition(timeout);
                    Handler.WaitMessages(1, pullingCondition, out notifications);
                }
                finally
                {
                    Operator.HideMessage();
                    SubscriptionHandler.Unsubscribe(Handler);
                }
                Assert(null != notifications && notifications.Any(),
                       string.Format("No notification messages are received.{0}WARNING: may be Operation delay is too low", Environment.NewLine),
                       "Check that DUT sent any notification messages");
                Assert(notifications.Count == 1,
                       string.Format("{0} messages received - unable to check actual configuration", notifications.Count),
                       "Check that exactly one notification is received");

                BeginStep("Validate message");

                XmlNamespaceManager manager = CreateNamespaceManager(notifications.First().Value.OwnerDocument);
                StringBuilder logger        = new StringBuilder();
                bool ok = true;

                MessageCheckSettings settings = new MessageCheckSettings();
                settings.ExpectedTopic        = topicInfo;
                settings.RawMessageElements   = notifications;
                settings.NamespaceManager     = manager;

                NotificationMessageHolderType m = notifications.Keys.First();
                ok = validateMessageFunction(m, notifications[m], manager, logger);

                if (!ok)
                {
                    throw new AssertException(logger.ToStringTrimNewLine());
                }

                StepPassed();

                // validateMessageFunction should return false, if this simple item is missing
                string token = m.Message.GetMessageSourceSimpleItems()[sourceTokenSimpleItem];
                validateConfigurationFunction(token);
            },
                () =>
            {
            });
        }
Exemplo n.º 29
0
        public MajorTopicPage(int courseId)
        {
            InitializeComponent();

            SetBusyIndicator(true);

            string MajorTopicUrl = "http://13.126.189.26:10008/api/GetMajorAndTopic/" + courseId; //387

            JObject data = c.GetDetail(MajorTopicUrl);

            mresults = data["list"]["listMajorTopic"].Children().ToList();

            tresults = data["list"]["listTopic"].Children().ToList();

            if (mresults.Count != 0)
            {
                listMajorTopics.IsVisible = true;

                listTopics.IsVisible = false;
                foreach (JToken result in mresults)
                {
                    System.Diagnostics.Debug.WriteLine(result);                                                      //just to check my json data.
                    MajorTopicInfo searchResult = JsonConvert.DeserializeObject <MajorTopicInfo>(result.ToString()); //get exception on this line.
                    majorTopicList.Add(searchResult);
                }
                if (majorTopicList.Count == 0)
                {
                    lbltxt.IsVisible    = true;
                    stackList.IsVisible = false;
                }
                else
                {
                    lbltxt.IsVisible            = false;
                    stackList.IsVisible         = true;
                    listMajorTopics.ItemsSource = majorTopicList;
                }

                SetBusyIndicator(false);
            }

            else
            {
                listTopics.IsVisible      = true;
                listMajorTopics.IsVisible = false;
                foreach (JToken result in tresults)
                {
                    System.Diagnostics.Debug.WriteLine(result);                                            //just to check my json data.
                    TopicInfo searchResult = JsonConvert.DeserializeObject <TopicInfo>(result.ToString()); //get exception on this line.
                    TopicList.Add(searchResult);
                }

                if (TopicList.Count == 0)
                {
                    lbltxt.IsVisible    = true;
                    stackList.IsVisible = false;
                }
                else
                {
                    lbltxt.IsVisible       = false;
                    stackList.IsVisible    = true;
                    listTopics.ItemsSource = TopicList;
                }

                SetBusyIndicator(false);
            }
        }
        void ConfigurationEventTest(
            TopicInfo topicInfo,
            Action <XmlElement, TopicInfo> validateTopic,
            ValidateConfigurationMessageFunction validateMessageFunction,
            string sourceTokenSimpleItem,
            Action <string> validateConfigurationFunction)
        {
            EndpointReferenceType subscriptionReference = null;

            System.DateTime subscribeStarted = System.DateTime.MaxValue;

            int timeout = 60;

            RunTest(
                () =>
            {
                // Get topic description from the DUT.
                XmlElement topicElement = GetTopicElement(topicInfo);

                BeginStep("Check if the event topic is supported");
                if (topicElement == null)
                {
                    LogStepEvent(string.Format("Topic {0} not supported", topicInfo.GetDescription()));
                }
                StepPassed();

                if (topicElement == null)
                {
                    return;
                }

                XmlElement messageDescription = topicElement.GetMessageDescription();
                validateTopic(messageDescription, topicInfo);

                // filter for current test
                TestTool.Proxies.Event.FilterType filter = CreateSubscriptionFilter(topicInfo);

                string message = string.Format("{0}  event is expected!", topicInfo.GetDescription());

                Notify notify   = null;
                XmlDocument doc = new XmlDocument();
                try
                {
                    subscriptionReference =
                        ReceiveMessages(filter,
                                        timeout,
                                        () => Operator.ShowMessage(message),
                                        doc,
                                        out notify,
                                        out subscribeStarted);
                }
                finally
                {
                    Operator.HideMessage();
                }

                Assert(notify.NotificationMessage.Length == 1,
                       string.Format("{0} messages received - unable to check actual configuration", notify.NotificationMessage.Length),
                       "Check that exactly one notification is received");

                BeginStep("Validate message");

                XmlNamespaceManager manager = CreateNamespaceManager(doc);
                Dictionary <NotificationMessageHolderType, XmlElement> notifications = GetRawElements(notify.NotificationMessage, doc, manager, true);

                StringBuilder logger = new StringBuilder();
                bool ok = true;

                MessageCheckSettings settings = new MessageCheckSettings();
                settings.ExpectedTopic        = topicInfo;
                settings.RawMessageElements   = notifications;
                settings.NamespaceManager     = manager;

                NotificationMessageHolderType m = notify.NotificationMessage[0];
                ok = validateMessageFunction(m, notifications[m], manager, logger);

                if (!ok)
                {
                    throw new AssertException(logger.ToStringTrimNewLine());
                }

                StepPassed();

                // validateMessageFunction should return false, if this simple item is missing
                string token = m.Message.GetMessageSourceSimpleItems()[sourceTokenSimpleItem];
                validateConfigurationFunction(token);
            },
                () =>
            {
                Operator.HideMessage();
                ReleaseSubscription(subscribeStarted, subscriptionReference, timeout);
            });
        }
Exemplo n.º 31
0
 /// <summary>
 /// 更新活动专题
 /// </summary>
 /// <param name="topicInfo">活动专题信息</param>
 public static void UpdateTopic(TopicInfo topicInfo)
 {
     OWZX.Data.Topics.UpdateTopic(topicInfo);
     OWZX.Core.BSPCache.Remove(CacheKeys.SHOP_TOPIC_INFO + topicInfo.TopicId);
     OWZX.Core.BSPCache.Remove(CacheKeys.SHOP_TOPIC_INFO + topicInfo.SN);
 }
Exemplo n.º 32
0
        public static void CreateReports()
        {
            ClientLocalDb.Current.ClearReports();

            var categories    = ClientLocalDb.Current.GetCategoriesEnable();
            var currReports   = ClientLocalDb.Current.GetReports(new int?());
            var reports       = new Dictionary <int, Dictionary <int, string> >();
            var allStatistics = ClientLocalDb.Current
                                .GetStatisticsByAllUsers()
                                .Where(x => !string.IsNullOrWhiteSpace(x.Item2))
                                .ToArray();

            var statistics = allStatistics
                             .Where(x => x.Item2 == Settings.Current.KeeperName)
                             .ToArray();
            var catIds = categories.Select(x => x.CategoryID).ToArray();

            var summaryTopicsAmount = statistics
                                      .Where(x => catIds.Contains(x.Item1))
                                      .Sum(x => x.Item3);
            var summaryTopicsSize = statistics
                                    .Where(x => catIds.Contains(x.Item1))
                                    .Sum(x => x.Item4);

            var summaryReportTemplate = Settings.Current.ReportSummaryTemplate;
            var categoriesList        = new List <object>();
            var summaryReportData     = new Dictionary <string, object>
            {
                { "today", DateTime.Now.ToString("dd.MM.yyyy") },
                { "summary_topics_count", summaryTopicsAmount },
                { "summary_topics_size", summaryTopicsSize.ToString("N") },
                { "categories", categoriesList }
            };

            foreach (var category in categories.OrderBy(x => x.FullName))
            {
                var st =
                    statistics.FirstOrDefault(x => x.Item1 == category.CategoryID) ??
                    new Tuple <int, string, int, decimal>(category.CategoryID, "<->", 0, decimal.Zero);

                if (!currReports.ContainsKey(new Tuple <int, int>(st.Item1, 1)))
                {
                    continue;
                }

                var url = currReports[new Tuple <int, int>(st.Item1, 1)].Item1;
                if (!string.IsNullOrWhiteSpace(url) && url.Split('=').Length > 2)
                {
                    url = url.Split('=')[2];
                }
                else
                {
                    url = null;
                }

                categoriesList.Add(
                    new Dictionary <string, object>
                {
                    {
                        "url",
                        url != null ? string.Format("https://rutracker.org/forum/viewtopic.php?p={0}#{0}", url) : ""
                    },
                    { "category_name", category.FullName },
                    { "topics_count", st.Item3 },
                    { "topics_size", st.Item4.ToString("N") }
                }
                    );
            }

            var summaryReportRendered = Stubble.Render(summaryReportTemplate, summaryReportData);

            reports.Add(0, new Dictionary <int, string>());
            reports[0].Add(0, summaryReportRendered);

            ClientLocalDb.Current.SaveReports(reports);

            reports.Clear();

            var headerOfReportTemplate = Settings.Current.ReportCategoryHeaderTemplate;

            foreach (var category in categories)
            {
                var st  = allStatistics.Where(x => x.Item1 == category.CategoryID && x.Item3 > 0 && x.Item2 != "All");
                var all = allStatistics.FirstOrDefault(x => x.Item1 == category.CategoryID && x.Item2 == "All");
                if (st.Count() != 0 && all != null)
                {
                    var keepersList  = new List <object>();
                    var reportHeader = new Dictionary <string, object>
                    {
                        { "category_uri", "viewforum.php?f=" + category.CategoryID },
                        { "category_name", category.Name },
                        { "category_check_seeds_uri", "tracker.php?f=" + category.CategoryID + "&tm=-1&o=10&s=1" },
                        { "today", DateTime.Now.ToString("dd.MM.yyyy") },
                        { "topics_count", all.Item3 },
                        { "topics_size", all.Item4.ToString("N") },
                        { "keepers_count", st.Count().ToString() },
                        { "keep_topics_count", st.Sum(x => x.Item3).ToString() },
                        { "keep_topics_size", st.Sum(x => x.Item4).ToString("N") },
                        { "keepers", keepersList }
                    };

                    var num = 0;
                    foreach (var tuple2 in st.OrderBy(x => x.Item2))
                    {
                        ++num;
                        keepersList.Add(
                            new Dictionary <string, string>
                        {
                            { "keeper_number", num.ToString() },
                            {
                                "keeper_profile_uri",
                                "profile.php?mode=viewprofile&u=" +
                                HttpUtility.UrlEncode(tuple2.Item2.Replace("<wbr>", "").Trim())
                            },
                            { "keeper_username", tuple2.Item2.Replace("<wbr>", "") },
                            { "keep_topics_count", tuple2.Item3.ToString() },
                            { "keep_topics_size", tuple2.Item4.ToString("N") }
                        }
                            );
                    }

                    var reportHeaderRendered = Stubble.Render(headerOfReportTemplate, reportHeader);

                    reports.Add(category.CategoryID, new Dictionary <int, string>());
                    reports[category.CategoryID].Add(0, reportHeaderRendered);
                }
            }

            ClientLocalDb.Current.SaveReports(reports);
            reports.Clear();
            var format1 = Settings.Current.ReportTop1.Replace("%%CreateDate%%", "{0}")
                          .Replace("%%CountTopics%%", "{1}").Replace("%%SizeTopics%%", "{2}") + "\r\n";
            var format2 = Settings.Current.ReportTop2.Replace("%%CreateDate%%", "{0}")
                          .Replace("%%CountTopics%%", "{1}").Replace("%%SizeTopics%%", "{2}")
                          .Replace("%%NumberTopicsFirst%%", "{3}").Replace("%%NumberTopicsLast%%", "{4}")
                          .Replace("%%ReportLines%%", "{5}").Replace("%%Top1%%", "{6}") + "\r\n";
            var format3 = Settings.Current.ReportLine.Replace("%%ID%%", "{0}").Replace("%%Name%%", "{1}")
                          .Replace("%%Size%%", "{2}").Replace("%%Status%%", "{3}").Replace("%%CountSeeders%%", "{4}")
                          .Replace("%%Date%%", "{5}");
            var num1           = 115000;
            var stringBuilder2 = new StringBuilder();
            var stringBuilder3 = new StringBuilder();

            foreach (var category in categories)
            {
                var num2 = 0;
                var num3 = 0;
                var num4 = 1;
                var key  = 0;
                stringBuilder2.Clear();
                stringBuilder3.Clear();
                var array3 = ClientLocalDb.Current.GetTopicsByCategory(category.CategoryID).Where(
                    x =>
                {
                    if (x.IsKeep && (x.Seeders <= Settings.Current.CountSeedersReport ||
                                     Settings.Current.CountSeedersReport == -1))
                    {
                        return(!x.IsBlackList);
                    }
                    return(false);
                }).OrderBy(x => x.Name2).ToArray();
                if (array3.Length != 0)
                {
                    reports.Add(category.CategoryID, new Dictionary <int, string>());
                    var dictionary = reports[category.CategoryID];
                    var str        = string.Format(format1, DateTime.Now.ToString("dd.MM.yyyy"),
                                                   array3.Length,
                                                   TopicInfo.sizeToString(
                                                       array3.Sum(x => x.Size)));
                    foreach (var topicInfo in array3)
                    {
                        stringBuilder3.AppendLine(string.Format(format3, (object)topicInfo.TopicID,
                                                                (object)topicInfo.Name2, (object)topicInfo.SizeToString,
                                                                (object)topicInfo.StatusToHtml, (object)topicInfo.Seeders,
                                                                (object)topicInfo.RegTimeToString));
                        ++num2;
                        ++num3;
                        if (num2 % 10 == 0 || array3.Length <= num2)
                        {
                            if (array3.Length == num2)
                            {
                                if (num3 == 0)
                                {
                                    stringBuilder2.AppendFormat("[*={0}{1}", num4,
                                                                stringBuilder3.ToString().Substring(2));
                                }
                                else
                                {
                                    stringBuilder2.AppendLine(stringBuilder3.ToString());
                                }
                            }

                            if (num1 <= stringBuilder2.Length + stringBuilder3.Length + str.Length ||
                                array3.Length <= num2)
                            {
                                ++key;
                                var num5 = num2 < array3.Length ? num2 - 10 : num2;
                                dictionary.Add(key,
                                               string.Format(format2, DateTime.Now.ToString("dd.MM.yyyy"),
                                                             (object)array3.Length,
                                                             (object)TopicInfo.sizeToString(
                                                                 array3.Sum(
                                                                     x => x.Size)), (object)num4, (object)num5,
                                                             (object)stringBuilder2.ToString(), (object)str) +
                                               Settings.Current.ReportBottom);
                                stringBuilder2.Clear();
                                num3 = 0;
                                num4 = num5 + 1;
                                str  = string.Empty;
                            }

                            if (num3 == 0)
                            {
                                stringBuilder2.AppendFormat("[*={0}{1}\r\n", num4,
                                                            stringBuilder3.ToString().Substring(2));
                            }
                            else
                            {
                                stringBuilder2.AppendLine(stringBuilder3.ToString());
                            }
                            stringBuilder3.Clear();
                        }
                    }
                }
            }

            ClientLocalDb.Current.SaveReports(reports);
        }
Exemplo n.º 33
0
        /// <summary>
        /// 加载主题图标信息
        /// </summary>
        /// <param name="autocloseTime">自动关闭时间(单位:小时)</param>
        /// <param name="newMinutes">新主题失效</param>
        /// <param name="hotReplyNumber">热帖基数</param>
        /// <param name="topicInfo">主题</param>
        private static void LoadTopicFolder(int autocloseTime, int newMinutes, int hotReplyNumber, TopicInfo topicInfo)
        {
            //处理关闭标记
            if (topicInfo.Closed == 0)
            {
                string oldtopic = ForumUtils.GetCookie("oldtopic") + "D";
                if (newMinutes > 0 && oldtopic.IndexOf("D" + topicInfo.Tid.ToString() + "D") == -1 && DateTime.Now.AddMinutes(-1 * newMinutes) < DateTime.Parse(topicInfo.Lastpost))
                {
                    topicInfo.Folder = "new";
                }
                else
                {
                    topicInfo.Folder = "old";
                }

                if (hotReplyNumber > 0 && topicInfo.Replies >= hotReplyNumber)
                {
                    topicInfo.Folder += "hot";
                }

                if (autocloseTime > 0 && Utils.StrDateDiffHours(topicInfo.Postdatetime, autocloseTime * 24) > 0)
                {
                    topicInfo.Closed = 1;
                    topicInfo.Folder = "closed";
                }
            }
            else
            {
                topicInfo.Folder = "closed";
                if (topicInfo.Closed > 1)
                {
                    topicInfo.Tid    = topicInfo.Closed;
                    topicInfo.Folder = "move";
                }
            }
        }
Exemplo n.º 34
0
		void NewsletterFeed(string newsletterName, XmlTextWriter newsletter)
		{
			NewsletterManager nm = new NewsletterManager(TheFederation, TheLinkMaker);
			TopicInfo info = TheFederation.GetTopicInfo(newsletterName);
			if (!info.Exists) 
			{
				throw new Exception("Newsletter " +  newsletterName + "  does not exist.");
			}
			if (!info.HasProperty("Topics")) 
			{
				throw new Exception("Topic " +  newsletterName + " is not a newsletter; no Topics property defined.");
			}
			string desc = info.GetProperty("Description");
			if (desc == null) 
			{
				desc = "";
			}

			newsletter.WriteStartDocument();
			newsletter.WriteStartElement("rss");
			newsletter.WriteAttributeString("version", "2.0");
			newsletter.WriteStartElement("channel");
			newsletter.WriteElementString("title", newsletterName);
			newsletter.WriteElementString("description", desc);

			Uri link = new Uri(TheLinkMaker.LinkToTopic(info.Fullname, true), false);
			newsletter.WriteElementString("link", link.AbsoluteUri);

			DateTime last = DateTime.MinValue;
			foreach (AbsoluteTopicName topic in nm.AllTopicsForNewsletter(info.Fullname))
			{
				FormatRSSItem(topic, newsletter);
				TopicInfo each = new TopicInfo(TheFederation, topic);
				DateTime lm = each.LastModified;
				if (lm > last) 
				{
					last = lm;
				}
			}

			newsletter.WriteElementString("lastBuildDate", last.ToUniversalTime().ToString("r"));

			newsletter.WriteEndElement();
			newsletter.WriteEndElement();
		}
Exemplo n.º 35
0
		//public List<TopicInfo> GetAllModuleTopics(int moduleId, int pageIndex, int pageSize)
		//{
		//    return CBO.FillCollection<TopicInfo>(_dataProvider.GetAllModuleTopics(moduleId, pageIndex, pageSize));
		//}

		public void UpdateTopic(TopicInfo objTopic, int moduleId, int portalId)
		{
			dataProvider.UpdateTopic(objTopic.TopicId, objTopic.ForumId, objTopic.ViewCount, objTopic.ReplyCount, objTopic.TopicTypeId, objTopic.LastPostId, objTopic.Slug, objTopic.ContentItemId);
			//Caching.ClearTopicCache(topicId, forumId, moduleId, portalId); 
		}
        private void GenerateContentFile(TopicInfo rootProgram)
        {
            builder.ReportProgress("Writing content file to: " + ContentFile + "..."); 
            
            var doc = new XmlDocument();
            var rootNode = doc.CreateElement("Topics");
            doc.AppendChild(rootNode);

            var definitionElement = doc.CreateElement("Topic");
            definitionElement.SetAttribute("id", rootProgram.TopicId.ToString());
            definitionElement.SetAttribute("visible", XmlConvert.ToString(true));
            definitionElement.SetAttribute("title", rootProgram.Title);
            rootNode.AppendChild(definitionElement);

            GenerateContentFileElements(definitionElement, rootProgram.Children);
            
            var directory = Path.GetDirectoryName(ContentFile);
            if (!Directory.Exists(directory))
                Directory.CreateDirectory(directory);
            doc.Save(ContentFile);
        }
Exemplo n.º 37
0
 //TODO: Unsubscribe
 private void SetValue(TopicInfo ti, byte[] msgData) {
   if(ti!=null) {
     if(!ti.path.StartsWith(Owner.path)) {
       return;     // not allow publish
     }
     object val;
     switch(Type.GetTypeCode(ti.topic.valueType)) {
     case TypeCode.Boolean:
       val=(msgData[0]!=0);
       break;
     case TypeCode.Int64: {
         long rv=(msgData[msgData.Length-1]&0x80)==0?0:-1;
         for(int i=msgData.Length-1; i>=0; i--) {
           rv<<=8;
           rv|=msgData[i];
         }
         val=rv;
         //Log.Debug("{0}={1}, {2}", ti.path, rv, BitConverter.ToString(msgData));
       }
       break;
     case TypeCode.String:
       val=Encoding.Default.GetString(msgData);
       break;
     case TypeCode.Object:
       if(ti.topic.valueType==typeof(PLC.ByteArray)) {
         val=new PLC.ByteArray(msgData);
         break;
       } else if(ti.topic.valueType==typeof(SmartTwi)) {
         var sa=(ti.topic.GetValue() as SmartTwi);
         if(sa==null) {
           sa=new SmartTwi(ti.topic);
           sa.Recv(msgData);
           val=sa;
         } else {
           sa.Recv(msgData);
           return;
         }
         break;
       } else {
         return;
       }
     default:
       return;
     }
     ti.topic.SetValue(val, new TopicChanged(TopicChanged.ChangeArt.Value, Owner));
   }
 }
Exemplo n.º 38
0
		public int AddTopic(TopicInfo objTopic, int moduleId, int portalId)
		{
			return dataProvider.AddTopic(objTopic.ForumId, objTopic.ViewCount, objTopic.ReplyCount, objTopic.TopicTypeId, objTopic.LastPostId, objTopic.Slug);
			//Caching.ClearTopicCache(topicId, forumId, moduleId, portalId); 
		}
Exemplo n.º 39
0
 /// <summary>Find or create TopicInfo by Topic</summary>
 /// <param name="tp">Topic as key</param>
 /// <param name="sendRegister">Send MsRegister for new TopicInfo</param>
 /// <returns>found TopicInfo or null</returns>
 private TopicInfo GetTopicInfo(Topic tp, bool sendRegister=true) {
   if(tp==null) {
     return null;
   }
   TopicInfo rez=null;
   for(int i=_topics.Count-1; i>=0; i--) {
     if(_topics[i].path==tp.path) {
       rez=_topics[i];
       break;
     }
   }
   string tpc=(tp.path.StartsWith(Owner.path))?tp.path.Remove(0, Owner.path.Length+1):tp.path;
   if(rez==null) {
     rez=new TopicInfo();
     rez.topic=tp;
     rez.path=tp.path;
     ushort rtId;
     if(PredefinedTopics.TryGetValue(tpc, out rtId)) {
       rez.TopicId=rtId;
       rez.it=TopicIdType.PreDefined;
       rez.registred=true;
     } else {
       Topic tmp=tp.parent;
       bool ignory=false;
       while(tmp!=null && tmp.valueType!=typeof(MsDevice)) {
         if(tmp.valueType==typeof(SmartTwi) || tmp.valueType==typeof(TWIDriver)) {
           ignory=true;
           break;
         }
         tmp=tmp.parent;
       }
       if(ignory) {
         rez.TopicId=0xFFFF;
         rez.it=TopicIdType.PreDefined;
         rez.registred=true;
       } else {
         rez.TopicId=CalculateTopicId(rez.path);
         rez.it=TopicIdType.Normal;
       }
     }
     _topics.Add(rez);
   }
   if(!rez.registred) {
     if(sendRegister) {
       Send(new MsRegister(rez.TopicId, tpc));
     } else {
       rez.registred=true;
     }
   }
   return rez;
 }
Exemplo n.º 40
0
        private int PostNewTopic()
        {
            string ipaddress = Common.GetIP4Address();

            #region Poll check code
            string topicPoll = String.Empty;

            var poll = new Regex(@"(?<poll>\[poll=\x22(?<question>.+?)\x22](?<answers>.+?)\[\/poll])", RegexOptions.Singleline);

            if (poll.IsMatch(Message.Text))
            {
                //there are poll tags, so store them and remove from the message text
                topicPoll    = poll.Match(Message.Text).Value;
                Message.Text = poll.Replace(Message.Text, "");
            }
            #endregion
            var topic = new TopicInfo
            {
                Subject            = tbxSubject.Text,
                Message            = Message.Text,
                Date               = DateTime.UtcNow,
                UseSignatures      = cbxSig.Checked,
                IsSticky           = cbxSticky.Checked,
                PosterIp           = ipaddress,
                Status             = (int)Enumerators.PostStatus.Open,
                UnModeratedReplies = 0,
                AuthorId           = Member.Id,
                ReplyCount         = 0,
                Views              = 0
            };
            if (ForumId.HasValue)
            {
                topic.Forum   = Forums.GetForum(ForumId.Value);
                topic.ForumId = ForumId.Value;
            }
            if (cbxLock.Checked)
            {
                topic.Status = (int)Enumerators.PostStatus.Closed;
            }
            else if (!_inModeratedList)
            {
                if (topic.Forum.ModerationLevel == (int)Enumerators.Moderation.AllPosts ||
                    topic.Forum.ModerationLevel == (int)Enumerators.Moderation.Topics)
                {
                    topic.Status = (int)Enumerators.PostStatus.UnModerated;
                }
            }
            if (CatId != null)
            {
                topic.CatId = CatId.Value;
            }
            topic.Id = Topics.Add(topic);
            if (pingSiteMap)
            {
                Ping("");
            }

            if (topicPoll != String.Empty && topic.Forum.AllowPolls)
            {
                CreatePoll(topicPoll, topic.Id);
            }
            InvalidateForumCache();
            return(topic.Id);
        }
Exemplo n.º 41
0
 protected virtual void OnTopicCreated(TopicInfo topic, PostInfo post, AttachmentInfo[] attachs)
 {
 }
Exemplo n.º 42
0
 public void CreateTopic(TopicInfo topic, PostInfo post, AttachmentInfo[] attachs)
 {
     this.OnTopicCreated(topic, post, attachs);
 }
Exemplo n.º 43
0
        //=====================================================================

        /// <summary>
        /// This is used to set the current solution name and the projects
        /// </summary>
        /// <param name="solutionName">The current solution filename</param>
        /// <param name="projects">The current list of projects</param>
        /// <returns>True if re-indexing was initiated, false if not</returns>
        public bool SetCurrentSolutionAndProjects(string solutionName, IEnumerable<MSBuildProject> projects)
        {
            // If the solution changes, clear all existing topic information
            if(this.CurrentSolutionName != solutionName)
            {
                this.CurrentSolutionName = solutionName;
                topicInfo.Clear();
            }

            // Index the content layout files in each project.  This should happen quickly as there usually
            // aren't that many content layout files.
            foreach(var project in projects)
            {
                string projectPath = Path.GetDirectoryName(project.FullPath), filePath;

                foreach(var contentLayoutFile in project.GetItems("ContentLayout"))
                {
                    var link = contentLayoutFile.Metadata.FirstOrDefault(m => m.Name == "Link");

                    if(link == null)
                        filePath = Path.Combine(projectPath, contentLayoutFile.EvaluatedInclude);
                    else
                        filePath = Path.Combine(projectPath, link.EvaluatedValue);

                    if(File.Exists(filePath))
                    {
                        // TODO: Can it find an open content layout editor for the file if there is one and
                        // search its content instead?
                        var doc = XDocument.Load(filePath);

                        // Add or refresh the title information
                        foreach(var topic in doc.Descendants("Topic"))
                        {
                            TopicInfo info;

                            if(!topicInfo.TryGetValue(topic.Attribute("id").Value, out info))
                                info = new TopicInfo
                                {
                                    TopicId = topic.Attribute("id").Value,
                                };

                            info.Title = (string)topic.Attribute("title") ?? info.Title ?? "(No title)";

                            topicInfo.AddOrUpdate(info.TopicId, info, (key, value) => value);
                        }
                    }
                }
            }

            // If any new topics are found, match the ID to actual files.  This is done in the background as
            // large projects may have hundreds of topics.  This may not be necessary but it saves blocking the
            // IDE while it does it just in case.
            if(topicInfo.Any(t => t.Value.Filename == null))
            {
                this.MatchFilesToTopics(projects.Select(p => Path.GetDirectoryName(p.FullPath)).Distinct());
                return true;
            }

            return false;
        }
Exemplo n.º 44
0
        void OnClientMessage(WebSocketConnection sender, DataReceivedEventArgs e)
        {
            OnlineUser user = Users.Single(a => a.Connection == sender);
            int index = e.Data.IndexOf(">>");
            string[] action = e.Data.Substring(0, index).Split(':');
            string[] args = action[1].Split(',');
            string data = e.Data.Remove(0, index + 2);
            Dictionary<string, string[]> actions = GetAllArgs(args);
            Func<string> combine = delegate()
            {
                List<string> newargs = new List<string>();
                foreach(KeyValuePair<string, string[]> a in actions)
                    newargs.Add(string.Format("{0}({1})", a.Key, String.Join("|", a.Value)));
                return string.Format("{0}:{1}>>{2}", action[0], string.Join(",", newargs.ToArray()), data);
            };
            switch(action[0])
            {
                case "REGISTER":
                    //auth here
                    int newuserid = int.Parse(args[0]);
                    if (Users.Exists(c => c.UserID == newuserid))
                        Users.Single(c => c.UserID == newuserid).Connection.Dispose();

                    user.UserID = newuserid;
                    user.Contacts = new List<int>();
                    ContactInfo.GetContacts(user.UserID).ForEach(delegate(ContactInfo i) { user.Contacts.Add(i.ContactID); });
                    user.Contacts.ForEach(delegate(int cid){
                        if (Users.Exists(c => c.UserID == cid))
                        {
                            SendToContact(cid, String.Format("ONLINE:{0}>>", user.UserID));
                            SendToContact(user.UserID, String.Format("ONLINE:{0}>>", cid));
                        }
                    });
                    foreach (MessageInfo undmessage in MessageInfo.GetAllUndelivered(user.UserID))
                    {
                        SendToContact(user.UserID, undmessage.MessageText);
                        UndeliveredMessageInfo.Create(undmessage.MessageID, user.UserID).Remove();
                    }
                    break;
                case "MESSAGE":
                    MessageInfo message = new MessageInfo();
                    message.UserID = user.UserID;
                    message.MessageText = e.Data;
                    message.CreatedDate = DateTime.Now;
                    if (actions["TYPE"][0] == "chat") message.MessageType = MessageTypes.Chat;
                    else if (actions["TYPE"][0] == "topic") message.MessageType = MessageTypes.Comment;
                    message.Update();
                    if (message.MessageID > 0 && actions["TYPE"][0] == "topic")
                    {
                        int tid = int.Parse(actions["ID"][0]);
                        MessageInTopicInfo.Create(message.MessageID, tid).Add();
                    }

                    int iid;
                    foreach (string id in actions["TO"])
                    {
                        if (int.TryParse(id, out iid) && user.Contacts.Contains(iid))
                        {
                            bool isOnline = Users.Exists(c => c.UserID == iid);
                            //save as undelivered
                            if (message.MessageID > 0 && !isOnline)
                                UndeliveredMessageInfo.Create(message.MessageID, iid).Add();
                            //dispatch message
                            if (isOnline)
                            {
                                OnlineUser contact = Users.Single(c => c.UserID == iid);
                                contact.Connection.Send(e.Data);
                            }
                        }
                    }
                    break;
                case "TOPICGET":
                    TopicInfo topicinfo = TopicInfo.Get(int.Parse(actions["ID"][0]));
                    List<UserInTopicInfo> usersintopic = UserInTopicInfo.GetByTopic(topicinfo.TopicID);
                    List<string> ids = new List<string>(),
                        mentors = new List<string>();
                    usersintopic.ForEach(delegate(UserInTopicInfo uit) { ids.Add(uit.UserID.ToString()); if (uit.UserTopicRole == UserTopicRoles.Mentor) mentors.Add(uit.UserID.ToString()); });
                    user.Connection.Send(string.Format("TOPIC:TO({0}),MENTORS({1}),TOPICID({2})>>{3}", string.Join("|", ids.ToArray()), string.Join("|", mentors.ToArray()), topicinfo.TopicID, topicinfo.TopicText));
                    foreach(MessageInfo topicmessageinfo in MessageInfo.GetByTopic(topicinfo.TopicID))
                    {
                        user.Connection.Send(topicmessageinfo.MessageText);
                    }
                    break;
                case "TOPIC":
                    TopicInfo info = new TopicInfo();
                    info.TopicText = data;
                    info.Update();
                    for (int i = 0; i < actions["TO"].Length; i++)
                    {
                        UserInTopicInfo usertopic = new UserInTopicInfo();
                        usertopic.UserID = int.Parse(actions["TO"][i]);
                        usertopic.TopicID = info.TopicID;
                        usertopic.UserTopicRole = (actions["MENTORS"].Contains(actions["TO"][i]) ? UserTopicRoles.Mentor : UserTopicRoles.User);
                        usertopic.Add();
                    }
                    actions.Add("TOPICID", new string[] { info.TopicID.ToString() });
                    string newdata = combine();
                    foreach (string id in actions["TO"])
                    {
                        if (int.TryParse(id, out iid) && iid != user.UserID && Users.Exists(c => c.UserID == iid))
                        {
                            OnlineUser contact = Users.Single(c => c.UserID == iid);
                            contact.Connection.Send(newdata);
                        }
                    }
                    user.Connection.Send(string.Format("TOPICREF:ID({0}),REF({1})>>{2}", info.TopicID, actions["REF"][0], info.GetTitle()));
                    break;
                case "TOPICEDIT":
                    topicinfo = TopicInfo.Get(int.Parse(actions["ID"][0]));
                    topicinfo.TopicText = data;
                    topicinfo.Update();
                    UserInfo.GetByTopic(topicinfo.TopicID).ForEach(delegate(UserInfo u) { SendToContact(u.UserID, e.Data); });
                    break;
                case "SETUSERS":
                    int setusersid = int.Parse(actions["ID"][0]);
                    string setusersdata = "";
                    if (actions["TYPE"][0] == "topic")
                    {
                        setusersdata = TopicInfo.Get(setusersid).GetTitle();
                    }
                    foreach (string setusersrej in actions["OLDUSERS"])
                    {
                        if (string.IsNullOrEmpty(setusersrej)) continue;
                        if (actions["TYPE"][0] == "topic")
                        {
                            UserInTopicInfo uintop = new UserInTopicInfo();
                            uintop.TopicID = setusersid;
                            uintop.UserID = int.Parse(setusersrej);
                            uintop.Remove();
                        }
                        SendToContact(int.Parse(setusersrej), string.Format("LEAVE:ID({0}),TYPE({1})>>", setusersid, actions["TYPE"][0]));
                    }
                    foreach (string setusersnew in actions["NEWUSERS"])
                    {
                        if (string.IsNullOrEmpty(setusersnew)) continue;
                        if (actions["TYPE"][0] == "topic")
                        {
                            UserInTopicInfo uintop = new UserInTopicInfo();
                            uintop.TopicID = setusersid;
                            uintop.UserID = int.Parse(setusersnew);
                            uintop.UserTopicRole = (actions["MENTORS"].Contains(setusersnew) ? UserTopicRoles.Mentor : UserTopicRoles.User);
                            uintop.Add();
                        }
                        SendToContact(int.Parse(setusersnew), string.Format("INVITED:ID({0}),TYPE({1})>>{2}", setusersid, actions["TYPE"][0], setusersdata));
                    }
                    TopicInfo.CheckForEmptyTopicByID(setusersid);
                    break;
                case "ATTACHMENT":
                    int attachmenttotopicid = int.Parse(actions["ID"][0]);
                    AttachmentInfo attach = new AttachmentInfo();
                    attach.AttachmentData = data;;
                    attach.AttachmentType = AttachmentTypes.Link;
                    attach.Update();
                    AttachmentInTopicInfo.Create(attachmenttotopicid, attach.AttachmentID).Add();
                    actions.Add("AID", new string[] { attach.AttachmentID.ToString() });
                    var newattachdata = combine();
                    UserInfo.GetByTopic(attachmenttotopicid).ForEach(delegate(UserInfo u) { SendToContact(u.UserID, newattachdata); });
                    break;
                case "ATTACHMENTGET":
                    AttachmentInfo.GetByTopic(int.Parse(actions["ID"][0])).ForEach(delegate(AttachmentInfo a) { user.Connection.Send("ATTACHMENT:ID(" + actions["ID"][0] + "),AID("+a.AttachmentID.ToString()+"),TYPE(link)>>" + a.AttachmentData); });
                    break;
                case "ATTACHMENTREMOVE":
                    attachmenttotopicid = int.Parse(actions["ID"][0]);
                    iid = int.Parse(actions["AID"][0]);
                    AttachmentInfo attmoveinfo = new AttachmentInfo();
                    attmoveinfo.AttachmentID = iid;
                    attmoveinfo.Remove();
                    UserInfo.GetByTopic(attachmenttotopicid).ForEach(delegate(UserInfo u) { SendToContact(u.UserID, e.Data); });
                    break;
            }
        }