protected override void NewItem(string path, string itemTypeName, object newItemValue) { try { LogInfo("Executing NewItem(string path='{0}', string itemTypeName='{1}', string newItemValue='{2}')", path, itemTypeName, newItemValue); if (itemTypeName.IsNullOrEmpty()) { WriteError( new ErrorRecord(new InvalidOperationException("Template not provided, please specify -ItemType"), ErrorIds.TemplateNotFound.ToString(), ErrorCategory.InvalidType, path)); return; } var templateItem = TemplateUtils.GetFromPath(itemTypeName, PSDriveInfo.Name); var parentItem = GetItemForPath(PathUtilities.GetParentFromPath(path)); var dic = DynamicParameters as RuntimeDefinedParameterDictionary; if (dic != null && dic[ParentParam].IsSet) { parentItem = dic[ParentParam].Value as Item; } if (!ShouldProcess(PathUtilities.GetParentFromPath(path), "Create item '" + PathUtilities.GetLeafFromPath(path) + "' of type '" + itemTypeName + "'")) { return; } var name = PathUtilities.GetLeafFromPath(path); Item createdItem = null; switch (TemplateUtils.GetType(templateItem)) { case TemplateItemType.Template: createdItem = parentItem.Add(name, (TemplateItem)templateItem); break; case TemplateItemType.Branch: createdItem = parentItem.Add(name, (BranchItem)templateItem); break; default: WriteError( new ErrorRecord(new InvalidOperationException("Cannot create item as type provided is neither Template nor Branch"), ErrorIds.InvalidItemType.ToString(), ErrorCategory.InvalidType, path)); return; } if (dic != null && dic[LanguageParam].IsSet) { var forcedLanguage = dic[LanguageParam].Value.ToString(); var language = LanguageManager.GetLanguage(forcedLanguage); createdItem = ForceItemLanguage(createdItem, language); } // start default workflow on the created item if necessary if (dic != null && dic[StartWorkflowParam].IsSet && Context.Workflow.HasDefaultWorkflow(createdItem)) { var defaultWorkflow = createdItem.Database.WorkflowProvider.GetWorkflow(createdItem[FieldIDs.DefaultWorkflow]); if (null != defaultWorkflow) { defaultWorkflow.Start(createdItem); } } WriteItem(createdItem); } catch (Exception ex) { LogError(ex, "Error while executing NewItem(string path='{0}', string itemTypeName='{1}', string newItemValue='{2}')", path, itemTypeName, newItemValue); throw; } }
private void TopicDisplay_Init(object sender, System.EventArgs e) { SettingsInfo MainSettings = DataCache.MainSettings(ControlConfig.InstanceId); PageSize = MainSettings.PageSize; string sTemp = string.Empty; if ((ControlConfig != null)) { object obj = DataCache.CacheRetrieve(ControlConfig.InstanceId + CurrentView); if (obj == null) { sTemp = ParseTemplate(); } else { sTemp = Convert.ToString(obj); } if (sTemp.Contains("[NOPAGING]")) { RowIndex = 0; PageSize = int.MaxValue; sTemp = sTemp.Replace("[NOPAGING]", string.Empty); } sTemp = Utilities.ParseTokenConfig(sTemp, "topic", ControlConfig); string Subject = string.Empty; string Body = string.Empty; System.DateTime CreateDate = null; System.DateTime EditDate = null; string Tags = string.Empty; string AuthorRoles = string.Empty; string IPAddress = string.Empty; System.DateTime LastPostDate = null; string LastPostData = string.Empty; UserProfileInfo tAuthor = null; int ReplyCount = 0; Data.Topics tc = new Data.Topics(); int rowCount = 0; int nextTopic = 0; int prevTopic = 0; int statusId = -1; double topicRating = 0; IDataReader dr = tc.TopicForDisplay(ControlConfig.SiteId, ControlConfig.InstanceId, -1, TopicId, UserId, RowIndex, PageSize, "ASC"); while (dr.Read()) { ForumId = int.Parse(dr["ForumId"].ToString()); Subject = dr["Subject"].ToString(); Body = dr["Body"].ToString(); CreateDate = Convert.ToDateTime(dr["DateCreated"].ToString()); EditDate = Convert.ToDateTime(dr["DateUpdated"].ToString()); Tags = dr["Tags"].ToString(); IPAddress = dr["IPAddress"].ToString(); LastPostDate = System.DateTime.Parse(Utilities.GetDate(System.DateTime.Parse(dr["LastPostDate"].ToString()), ControlConfig.InstanceId)); LastPostData = dr["LastPostData"].ToString(); ReplyCount = int.Parse(dr["ReplyCount"].ToString()); nextTopic = int.Parse(dr["NextTopic"].ToString()); prevTopic = int.Parse(dr["PrevTopic"].ToString()); topicRating = double.Parse(dr["TopicRating"].ToString()); UserProfileInfo profile = new UserProfileInfo(); var _with1 = profile; _with1.UserID = int.Parse(dr["AuthorId"].ToString()); if (string.IsNullOrEmpty(dr["DisplayName"].ToString())) { _with1.DisplayName = dr["AuthorName"].ToString(); } else { _with1.DisplayName = dr["DisplayName"].ToString(); } _with1.FirstName = dr["FirstName"].ToString(); _with1.LastName = dr["LastName"].ToString(); _with1.Username = dr["Username"].ToString(); _with1.UserCaption = dr["UserCaption"].ToString(); _with1.AnswerCount = int.Parse(dr["AnswerCount"].ToString()); _with1.AOL = dr["AOL"].ToString(); _with1.Avatar = dr["Avatar"].ToString(); _with1.AvatarType = (AvatarTypes)int.Parse(dr["AvatarType"].ToString()); _with1.DateCreated = System.DateTime.Parse(Utilities.GetDate(System.DateTime.Parse(dr["UserDateCreated"].ToString()), ControlConfig.InstanceId)); _with1.DateLastActivity = System.DateTime.Parse(Utilities.GetDate(System.DateTime.Parse(dr["DateLastActivity"].ToString()), ControlConfig.InstanceId)); _with1.DateLastPost = System.DateTime.Parse(Utilities.GetDate(System.DateTime.Parse(dr["DateLastPost"].ToString()), ControlConfig.InstanceId)); if (!string.IsNullOrEmpty(dr["UserDateUpdated"].ToString())) { _with1.DateUpdated = System.DateTime.Parse(Utilities.GetDate(System.DateTime.Parse(dr["UserDateUpdated"].ToString()), ControlConfig.InstanceId)); } _with1.Interests = dr["Interests"].ToString(); _with1.IsUserOnline = bool.Parse(dr["IsUserOnline"].ToString()); _with1.Location = dr["Location"].ToString(); _with1.MSN = dr["MSN"].ToString(); _with1.Occupation = dr["Occupation"].ToString(); _with1.TopicCount = int.Parse(dr["UserTopicCount"].ToString()); _with1.ReplyCount = int.Parse(dr["UserReplyCount"].ToString()); _with1.RewardPoints = int.Parse(dr["RewardPoints"].ToString()); _with1.Roles = dr["UserRoles"].ToString(); _with1.Signature = dr["Signature"].ToString(); _with1.TrustLevel = int.Parse(dr["TrustLevel"].ToString()); _with1.WebSite = dr["WebSite"].ToString(); _with1.Yahoo = dr["Yahoo"].ToString(); tAuthor = profile; if (DataPageId == 1) { sTemp = ParseTopic(sTemp, Subject, CreateDate, Body, Tags, Convert.ToString(EditDate), IPAddress, ForumUser, rowCount); rowCount += 1; } else { sTemp = TemplateUtils.ReplaceSubSection(sTemp, string.Empty, "[TOPIC]", "[/TOPIC]"); } } if (ForumInfo == null) { ForumController fc = new ForumController(); Forum fi = null; fi = fc.Forums_Get(ForumId, UserId, true, true); ForumInfo = fi; } sTemp = sTemp.Replace("[FORUMID]", ForumId.ToString); sTemp = sTemp.Replace("[FORUMNAME]", ForumInfo.ForumName); sTemp = sTemp.Replace("[TOPICID]", TopicId.ToString); sTemp = sTemp.Replace("[CREATEROLES]", ForumInfo.Security.Create); sTemp = sTemp.Replace("[USERROLES]", ForumUser.UserRoles); sTemp = sTemp.Replace("[THEMEPATH]", ThemePath); sTemp = sTemp.Replace("[SUBJECT]", Subject); sTemp = sTemp.Replace("[PAGEID]", PageId.ToString); sTemp = sTemp.Replace("[REPLYROLES]", ForumInfo.Security.Reply); sTemp = sTemp.Replace("AF:SECURITY:MODROLES]", "AF:SECURITY:MODROLES:" + ForumInfo.Security.ModApprove + "]"); sTemp = sTemp.Replace("AF:SECURITY:MODAPPROVE]", "AF:SECURITY:MODAPPROVE:" + ForumInfo.Security.ModApprove + "]"); sTemp = sTemp.Replace("AF:SECURITY:DELETE]", "AF:SECURITY:DELETE:" + ForumInfo.Security.Delete + ForumInfo.Security.ModDelete + "]"); sTemp = sTemp.Replace("AF:SECURITY:EDIT]", "AF:SECURITY:EDIT:" + ForumInfo.Security.Edit + ForumInfo.Security.ModEdit + "]"); sTemp = sTemp.Replace("AF:SECURITY:LOCK]", "AF:SECURITY:LOCK:" + ForumInfo.Security.Lock + ForumInfo.Security.ModLock + "]"); sTemp = sTemp.Replace("AF:SECURITY:MOVE]", "AF:SECURITY:MOVE:" + ForumInfo.Security.ModMove + "]"); sTemp = sTemp.Replace("AF:SECURITY:PIN]", "AF:SECURITY:PIN:" + ForumInfo.Security.Pin + ForumInfo.Security.ModPin + "]"); sTemp = sTemp.Replace("AF:SECURITY:SPLIT]", "AF:SECURITY:SPLIT:" + ForumInfo.Security.ModSplit + "]"); sTemp = sTemp.Replace("AF:SECURITY:REPLY]", "AF:SECURITY:REPLY:" + ForumInfo.Security.Reply + "]"); if (LastPostDate == null) { LastPostDate = CreateDate; } string LastPostAuthor = string.Empty; if (((bRead & tAuthor.UserID == this.UserId)) & statusId >= 0) { sTemp = sTemp.Replace("[AF:CONTROL:STATUS]", "<asp:placeholder id=\"plhStatus\" runat=\"server\" />"); sTemp = sTemp.Replace("[AF:CONTROL:STATUSICON]", "<img alt=\"[RESX:PostStatus" + statusId.ToString() + "]\" src=\"" + ThemePath + "status" + statusId.ToString() + ".png\" />"); } else if (statusId >= 0) { sTemp = sTemp.Replace("[AF:CONTROL:STATUS]", string.Empty); sTemp = sTemp.Replace("[AF:CONTROL:STATUSICON]", "<img alt=\"[RESX:PostStatus" + statusId.ToString() + "]\" src=\"" + ThemePath + "status" + statusId.ToString() + ".png\" />"); } else { sTemp = sTemp.Replace("[AF:CONTROL:STATUS]", string.Empty); sTemp = sTemp.Replace("[AF:CONTROL:STATUSICON]", string.Empty); sTemp = sTemp.Replace("[ACTIONS:ANSWER]", string.Empty); } if (string.IsNullOrEmpty(LastPostData)) { LastPostAuthor = UserProfiles.GetDisplayName(ControlConfig.InstanceId, MainSettings.ProfileVisibility, false, tAuthor.UserID, MainSettings.UserNameDisplay, MainSettings.DisableUserProfiles, tAuthor.Username, tAuthor.FirstName, tAuthor.LastName, tAuthor.DisplayName); } else { Author la = new Author(); System.Xml.XmlDocument xDoc = new System.Xml.XmlDocument(); xDoc.LoadXml(LastPostData); System.Xml.XmlNode xNode = xDoc.SelectSingleNode("//root/lastpost"); if ((xNode != null)) { var _with2 = la; _with2.AuthorId = int.Parse(xNode["authorid"].InnerText.ToString()); _with2.DisplayName = xNode["displayname"].InnerText; _with2.FirstName = xNode["firstname"].InnerText; _with2.LastName = xNode["lastname"].InnerText; _with2.Username = xNode["username"].InnerText; } LastPostAuthor = UserProfiles.GetDisplayName(ControlConfig.InstanceId, MainSettings.ProfileVisibility, false, la.AuthorId, MainSettings.UserNameDisplay, MainSettings.DisableUserProfiles, la.Username, la.FirstName, la.LastName, la.DisplayName); } //TODO:Fix LastPostDate Format sTemp = sTemp.Replace("[AF:LABEL:LastPostDate]", LastPostDate.ToString()); sTemp = sTemp.Replace("[AF:LABEL:LastPostAuthor]", LastPostAuthor); sTemp = sTemp.Replace("[AF:LABEL:ReplyCount]", ReplyCount.ToString()); string sURL = "<a rel=\"nofollow\" href=\"" + Utilities.NavigateUrl(PageId, "", ParamKeys.ForumId + "=" + ForumId, ParamKeys.ViewType + "=" + Views.Topic, ParamKeys.TopicId + "=" + TopicId, "mid=" + ControlConfig.InstanceId.ToString, "dnnprintmode=true") + "?skinsrc=" + HttpUtility.UrlEncode("[G]" + DotNetNuke.UI.Skins.SkinInfo.RootSkin + "/" + DotNetNuke.Common.glbHostSkinFolder + "/" + "No Skin") + "&containersrc=" + HttpUtility.UrlEncode("[G]" + DotNetNuke.UI.Skins.SkinInfo.RootContainer + "/" + DotNetNuke.Common.glbHostSkinFolder + "/" + "No Container") + "\" target=\"_blank\">"; sURL += "<img src=\"" + ThemePath + "images/spacer.gif\" alt=\"[RESX:PrinterFriendly]\" class=\"aficon aficonprint\" /></a>"; sTemp = sTemp.Replace("[AF:CONTROL:PRINTER]", sURL); if (HttpContext.Current.Request.IsAuthenticated) { sURL = Utilities.NavigateUrl(PageId, "", new string[] { ParamKeys.ViewType + "=sendto", ParamKeys.ForumId + "=" + ForumId, ParamKeys.TopicId + "=" + TopicId }); sTemp = sTemp.Replace("[AF:CONTROL:EMAIL]", "<a href=\"" + sURL + "\" rel=\"nofollow\"><img src=\"" + ThemePath + "images/spacer.gif\" class=\"aficon aficonemail\" alt=\"[RESX:EmailThis]\" /></a>"); } else { sTemp = sTemp.Replace("[AF:CONTROL:EMAIL]", string.Empty); } if (ForumInfo.AllowRSS) { string Url = null; Url = DotNetNuke.Common.AddHTTP(DotNetNuke.Common.GetDomainName(HttpContext.Current.Request)) + "/DesktopModules/ActiveForums/feeds.aspx?portalid=" + ControlConfig.SiteId + "&forumid=" + ForumId + "&tabid=" + PageId + "&moduleid=" + ControlConfig.InstanceId; sTemp = sTemp.Replace("[RSSLINK]", "<a href=\"" + Url + "\"><img src=\"" + ThemePath + "images/rss.png\" runat=server border=\"0\" alt=\"[RESX:RSS]\" /></a>"); } else { sTemp = sTemp.Replace("[RSSLINK]", string.Empty); } if (nextTopic == 0) { sTemp = sTemp.Replace("[NEXTTOPICID]", string.Empty); sTemp = sTemp.Replace("[HASNEXTTOPIC]", "False"); } else { sTemp = sTemp.Replace("[NEXTTOPICID]", nextTopic.ToString()); sTemp = sTemp.Replace("[HASNEXTTOPIC]", "True"); } if (prevTopic == 0) { sTemp = sTemp.Replace("[PREVTOPICID]", string.Empty); sTemp = sTemp.Replace("[HASPREVTOPIC]", "False"); } else { sTemp = sTemp.Replace("[PREVTOPICID]", prevTopic.ToString()); sTemp = sTemp.Replace("[HASPREVTOPIC]", "True"); } dr.NextResult(); //Process Replies StringBuilder sb = new StringBuilder(); sb.Append(string.Empty); int replyId = 0; while (dr.Read()) { Subject = dr["Subject"].ToString(); Body = dr["Body"].ToString(); CreateDate = Convert.ToDateTime(dr["DateCreated"].ToString()); EditDate = Convert.ToDateTime(dr["DateUpdated"].ToString()); IPAddress = dr["IPAddress"].ToString(); replyId = int.Parse(dr["ReplyId"].ToString()); UserProfileInfo profile = new UserProfileInfo(); var _with3 = profile; _with3.UserID = int.Parse(dr["AuthorId"].ToString()); if (string.IsNullOrEmpty(dr["DisplayName"].ToString())) { _with3.DisplayName = dr["AuthorName"].ToString(); } else { _with3.DisplayName = dr["DisplayName"].ToString(); } _with3.FirstName = dr["FirstName"].ToString(); _with3.LastName = dr["LastName"].ToString(); _with3.Username = dr["Username"].ToString(); _with3.UserCaption = dr["UserCaption"].ToString(); _with3.AnswerCount = int.Parse(dr["AnswerCount"].ToString()); _with3.AOL = dr["AOL"].ToString(); _with3.Avatar = dr["Avatar"].ToString(); _with3.AvatarType = (AvatarTypes)int.Parse(dr["AvatarType"].ToString()); _with3.DateCreated = System.DateTime.Parse(Utilities.GetDate(System.DateTime.Parse(dr["UserDateCreated"].ToString()), ControlConfig.InstanceId)); _with3.DateLastActivity = System.DateTime.Parse(Utilities.GetDate(System.DateTime.Parse(dr["DateLastActivity"].ToString()), ControlConfig.InstanceId)); if (!string.IsNullOrEmpty(dr["DateLastPost"].ToString())) { _with3.DateLastPost = System.DateTime.Parse(Utilities.GetDate(System.DateTime.Parse(dr["DateLastPost"].ToString()), ControlConfig.InstanceId)); } if (!string.IsNullOrEmpty(dr["UserDateUpdated"].ToString())) { _with3.DateUpdated = System.DateTime.Parse(Utilities.GetDate(System.DateTime.Parse(dr["UserDateUpdated"].ToString()), ControlConfig.InstanceId)); } _with3.Interests = dr["Interests"].ToString(); _with3.IsUserOnline = bool.Parse(dr["IsUserOnline"].ToString()); _with3.Location = dr["Location"].ToString(); _with3.MSN = dr["MSN"].ToString(); _with3.Occupation = dr["Occupation"].ToString(); _with3.TopicCount = int.Parse(dr["UserTopicCount"].ToString()); _with3.ReplyCount = int.Parse(dr["UserReplyCount"].ToString()); _with3.RewardPoints = int.Parse(dr["RewardPoints"].ToString()); _with3.Roles = dr["UserRoles"].ToString(); _with3.Signature = dr["Signature"].ToString(); _with3.TrustLevel = int.Parse(dr["TrustLevel"].ToString()); _with3.WebSite = dr["WebSite"].ToString(); _with3.Yahoo = dr["Yahoo"].ToString(); sb.Append(ParseReply(sTemp, replyId, Subject, CreateDate, Body, Convert.ToString(EditDate), IPAddress, ForumUser, rowCount)); rowCount += 1; } dr.Close(); sTemp = TemplateUtils.ReplaceSubSection(sTemp, sb.ToString(), "[REPLIES]", "[/REPLIES]"); sTemp = Utilities.LocalizeControl(sTemp); sTemp = sTemp.Replace("[TOPICID]", TopicId.ToString); sTemp = sTemp.Replace("[GROUPNAME]", ForumInfo.GroupName); sTemp = sTemp.Replace("[FORUMNAME]", ForumInfo.ForumName); sTemp = sTemp.Replace("[TOPICRATING]", topicRating.ToString()); sTemp = sTemp.Replace("[CURRENTUSERID]", UserId.ToString); sTemp = Utilities.ParseSecurityTokens(sTemp, ForumUser.UserRoles); if (!sTemp.Contains(Globals.ControlRegisterAFTag)) { sTemp = Globals.ControlRegisterAFTag + sTemp; } Control ctl = Page.ParseControl(sTemp); LinkControls(ctl.Controls); this.Controls.Add(ctl); } }
public override void ToString(StringBuilder sb, ScopedDictionary <string, ValueProviderBase> variables) { sb.Append("@"); if (IsRaw) { sb.Append("raw"); } ValueProvider !.ToStringBrackets(sb, variables, Format.HasText() ? (":" + TemplateUtils.ScapeColon(Format)) : null); }
protected override void ProcessItem(Item item) { if (Template != null) { // Get template item, and implicitly cast to TemplateItem as this will perform a template-check on the // item returned, to ensure it is a template. TemplateItem = TemplateUtils.GetFromPath(Template, CurrentDrive); } // GetFromPath will WriteError if not found, and the cast will throw an error if item is not a template, so no need to handle separately here. if (!ShouldProcess(item.GetProviderPath(), $"Set item template '{TemplateItem.InnerItem.GetProviderPath()}'")) { return; } var newTemplate = TemplateManager.GetTemplate(TemplateItem.ID, TemplateItem.Database); var oldTemplate = TemplateManager.GetTemplate(item.TemplateID, item.Database); if (oldTemplate == null) { WriteVerbose(Translate.Text(Texts.TemplateMissing, item.TemplateID, item.Database)); oldTemplate = newTemplate; } if (FieldsToCopy == null) { TemplateManager.ChangeTemplate(item, new TemplateChangeList(oldTemplate, newTemplate)); return; } var values = new Dictionary <string, string>(); foreach (var fieldName in FieldsToCopy.Keys.OfType <string>()) { var field = item.Fields[fieldName]; if (field != null) { values.Add(fieldName, field.Value); } else { WriteError(typeof(MissingFieldException), $"Source template does not contain '{fieldName}' field.", ErrorIds.FieldNotFound, ErrorCategory.ObjectNotFound, item); } } TemplateManager.ChangeTemplate(item, new TemplateChangeList(oldTemplate, newTemplate)); item.Edit(args => { foreach (var fieldName in values.Keys) { var field = item.Fields[FieldsToCopy[fieldName].ToString()]; if (field != null) { field.Value = values[fieldName]; } else { WriteError(typeof(MissingFieldException), $"Target template does not contain '{fieldName}' field.", ErrorIds.FieldNotFound, ErrorCategory.ObjectNotFound, item); } } }); }
/// <summary> /// 压缩后的字符 /// </summary> /// <returns></returns> private string ToCompressedString() { return(TemplateUtils.CompressHtml(ToString())); }
private string BuildRSS() { const int indent = 2; var counter = 0; var sb = new StringBuilder(1024); // build header sb.Append(XmlHeader + System.Environment.NewLine); sb.Append(RSSHeader + System.Environment.NewLine); // build channel var pc = new PortalController(); var ps = PortalController.GetCurrentPortalSettings(); var offSet = Convert.ToInt32(PortalSettings.Current.TimeZone.BaseUtcOffset.TotalMinutes); sb.Append(WriteElement("channel", indent)); sb.Append(WriteElement("title", ps.PortalName, indent)); sb.Append(WriteElement("link", "http://" + HttpContext.Current.Request.Url.Host, indent)); sb.Append(WriteElement("description", ps.PortalName, indent)); sb.Append(WriteElement("generator", "ActiveForums 5.0", indent)); sb.Append(WriteElement("language", ps.DefaultLanguage, indent)); if (ps.LogoFile != string.Empty) { var sLogo = "<image><url>http://" + HttpContext.Current.Request.Url.Host + ps.HomeDirectory + ps.LogoFile + "</url>"; sLogo += "<title>" + ps.PortalName + "</title>"; sLogo += "<link>http://" + HttpContext.Current.Request.Url.Host + "</link></image>"; sb.Append(sLogo); } sb.Append(WriteElement("copyright", ps.FooterText.Replace("[year]", DateTime.Now.Year.ToString()), 2)); sb.Append(WriteElement("lastBuildDate", "[LASTBUILDDATE]", 2)); var lastBuildDate = DateTime.MinValue; // build items var forumids = Settings.RSSIgnoreSecurity ? Settings.Forums : AuthorizedForums; var useFriendly = Utilities.IsRewriteLoaded(); var dr = DataProvider.Instance().GetPosts(RequestPortalID, forumids, true, false, Settings.Rows, Settings.Tags); var sHost = Utilities.GetHost(); try { while (dr.Read()) { var groupName = Convert.ToString(dr["GroupName"]); var groupId = Convert.ToInt32(dr["ForumGroupId"]); var topicTabId = Convert.ToInt32(dr["TabId"]); var topicModuleId = Convert.ToInt32(dr["ModuleId"]); var forumName = Convert.ToString(dr["ForumName"]); var forumId = Convert.ToInt32(dr["ForumId"]); var subject = Convert.ToString(dr["Subject"]); var userName = Convert.ToString(dr["AuthorUserName"]); var postDate = Convert.ToString(dr["DateCreated"]); var body = Utilities.StripHTMLTag(Convert.ToString(dr["Body"])); var bodyHtml = Convert.ToString(dr["Body"]); var displayName = Convert.ToString(dr["AuthorDisplayName"]); var replyCount = Convert.ToString(dr["ReplyCount"]); var lastPostDate = string.Empty; var topicId = Convert.ToInt32(dr["TopicId"]); var replyId = Convert.ToInt32(dr["ReplyId"]); var firstName = Convert.ToString(dr["AuthorFirstName"]); var lastName = Convert.ToString(dr["AuthorLastName"]); var authorId = Convert.ToInt32(dr["AuthorId"]); var sForumUrl = Convert.ToString(dr["PrefixURL"]); var sTopicUrl = Convert.ToString(dr["TopicURL"]); var sGroupPrefixUrl = Convert.ToString(dr["GroupPrefixURL"]); var dateCreated = Convert.ToDateTime(dr["DateCreated"]).AddMinutes(offSet); if (lastBuildDate == DateTime.MinValue || dateCreated > lastBuildDate) { lastBuildDate = dateCreated; } var ts = DataCache.MainSettings(topicModuleId); string url; if (string.IsNullOrEmpty(sTopicUrl) || !useFriendly) { string[] Params = { ParamKeys.ViewType + "=" + Views.Topic, ParamKeys.ForumId + "=" + forumId, ParamKeys.TopicId + "=" + topicId }; url = Common.Globals.NavigateURL(topicTabId, "", Params); if (url.IndexOf(HttpContext.Current.Request.Url.Host, StringComparison.CurrentCulture) == -1) { url = Common.Globals.AddHTTP(HttpContext.Current.Request.Url.Host) + url; } } else { var ctlUtils = new ControlUtils(); sTopicUrl = ctlUtils.BuildUrl(topicTabId, topicModuleId, sGroupPrefixUrl, sForumUrl, groupId, forumId, topicId, sTopicUrl, -1, -1, string.Empty, 1, replyId, -1); if (sHost.EndsWith("/") && sTopicUrl.StartsWith("/")) { sHost = sHost.Substring(0, sHost.Length - 1); } url = sHost + sTopicUrl; } sb.Append(WriteElement("item", indent)); sb.Append(WriteElement("title", subject, indent + 1)); if (Settings.RSSIncludeBody) { if (bodyHtml.IndexOf("<body>", StringComparison.CurrentCulture) > 0) { bodyHtml = TemplateUtils.GetTemplateSection(bodyHtml, "<body>", "</body>"); } // Legacy Attachment functionality uses "attachid" if (bodyHtml.Contains("[IMAGE:")) { var strHost = Common.Globals.AddHTTP(Common.Globals.GetDomainName(HttpContext.Current.Request)) + "/"; const string pattern = "([IMAGE:(.+?)])"; var regExp = new Regex(pattern); var matches = regExp.Matches(bodyHtml); foreach (Match match in matches) { var sImage = "<img src=\"" + strHost + "DesktopModules/ActiveForums/viewer.aspx?portalid=" + RequestPortalID + "&moduleid=" + RequestModuleID + "&attachid=" + match.Groups[2].Value + "\" border=\"0\" />"; bodyHtml = bodyHtml.Replace(match.Value, sImage); } } // Legacy Attachment functionality uses "attachid" if (bodyHtml.Contains("[THUMBNAIL:")) { var strHost = Common.Globals.AddHTTP(Common.Globals.GetDomainName(HttpContext.Current.Request)) + "/"; const string pattern = "([THUMBNAIL:(.+?)])"; var regExp = new Regex(pattern); var matches = regExp.Matches(bodyHtml); foreach (Match match in matches) { var thumbId = match.Groups[2].Value.Split(':')[0]; var parentId = match.Groups[2].Value.Split(':')[1]; var sImage = "<a href=\"" + strHost + "DesktopModules/ActiveForums/viewer.aspx?portalid=" + RequestPortalID + "&moduleid=" + RequestModuleID + "&attachid=" + parentId + "\" target=\"_blank\"><img src=\"" + strHost + "DesktopModules/ActiveForums/viewer.aspx?portalid=" + RequestPortalID + "&moduleid=" + RequestModuleID + "&attachid=" + thumbId + "\" border=\"0\" /></a>"; bodyHtml = bodyHtml.Replace(match.Value, sImage); } } bodyHtml = bodyHtml.Replace("src=\"/Portals", "src=\"" + Common.Globals.AddHTTP(HttpContext.Current.Request.Url.Host) + "/Portals"); bodyHtml = Utilities.ManageImagePath(bodyHtml, Common.Globals.AddHTTP(HttpContext.Current.Request.Url.Host)); sb.Append(WriteElement("description", bodyHtml, indent + 1)); } else { sb.Append(WriteElement("description", string.Empty, indent + 1)); } sb.Append(WriteElement("link", url, indent + 1)); sb.Append(WriteElement("comments", url, indent + 1)); sb.Append(WriteElement("pubDate", Convert.ToDateTime(postDate).AddMinutes(offSet).ToString("r"), indent + 1)); sb.Append(WriteElement("dc:creator", displayName, indent + 1)); sb.Append(WriteElement("guid", url, indent + 1)); sb.Append(WriteElement("slash:comments", replyCount, indent + 1)); sb.Append(WriteElement("/item", indent)); } dr.Close(); sb.Append("<atom:link href=\"http://" + HttpContext.Current.Request.Url.Host + HttpUtility.HtmlEncode(HttpContext.Current.Request.RawUrl) + "\" rel=\"self\" type=\"application/rss+xml\" />"); sb.Append(WriteElement("/channel", 1)); sb.Append("</rss>"); sb.Replace("[LASTBUILDDATE]", lastBuildDate.ToString("r")); return(sb.ToString()); } catch (Exception ex) { return(ex.ToString()); } }
public string Render() { StringBuilder sb = new StringBuilder(); Data.CommonDB db = new Data.CommonDB(); string sHost = Utilities.GetHost(); if (sHost.EndsWith("/")) { sHost = sHost.Substring(0, sHost.Length - 1); } ControlUtils ctlUtils = new ControlUtils(); string forumPrefix = string.Empty; string groupPrefix = string.Empty; //Dim _forumGroupId As Integer = -1 if (ParentForumId == -1) { ParentForumId = ForumId; } string groupTemplate = TemplateUtils.GetTemplateSection(ItemTemplate, "[AF:DIR:FORUMGROUP]", "[/AF:DIR:FORUMGROUP]"); string forumTemplate = TemplateUtils.GetTemplateSection(ItemTemplate, "[AF:DIR:FORUM]", "[/AF:DIR:FORUM]"); string subForumTemplate = TemplateUtils.GetTemplateSection(ItemTemplate, "[AF:DIR:SUBFORUM]", "[/AF:DIR:SUBFORUM]"); bool useFriendlyUrl = Utilities.IsRewriteLoaded(); int currGroup = -1; string gtmp = string.Empty; string ftmp = string.Empty; string subtmp = string.Empty; using (IDataReader dr = db.ForumContent_List(PortalId, ModuleId, ForumGroupId, ForumId, ParentForumId)) { //ParentForum Section while (dr.Read()) { string sURL = ctlUtils.BuildUrl(TabId, ModuleId, dr["GroupPrefixURL"].ToString(), dr["PrefixURL"].ToString(), int.Parse(dr["ForumGroupId"].ToString()), int.Parse(dr["ForumId"].ToString()), -1, -1, string.Empty, 1, -1, -1); if (IncludeClasses) { sb.Append("<div class=\"fcv-header\"><a href=\"" + sURL + "\"><span>" + dr["ForumName"].ToString() + "</span></a></div>"); } else { sb.Append("<div><a href=\"" + sURL + "\"><span>" + dr["ForumName"].ToString() + "</span></a></div>"); } forumPrefix = dr["PrefixURL"].ToString(); groupPrefix = dr["GroupPrefixURL"].ToString(); // _forumGroupId = Integer.Parse(dr("ForumGroupId").ToString) } //SubForums dr.NextResult(); int subForumCount = 0; string sSubforums = string.Empty; while (dr.Read()) { if (Permissions.HasPerm(dr["CanRead"].ToString(), ForumUser.UserRoles)) { string sURL = ctlUtils.BuildUrl(TabId, ModuleId, dr["GroupPrefixURL"].ToString(), dr["PrefixURL"].ToString(), int.Parse(dr["ForumGroupId"].ToString()), int.Parse(dr["ForumId"].ToString()), -1, -1, string.Empty, 1, -1, -1); if (ForumId == int.Parse(dr["ForumId"].ToString())) { sSubforums += "<li class=\"fcv-selected\">"; } else { sSubforums += "<li>"; } sSubforums += "<a href=\"" + sURL + "\"><em></em><span>" + dr["ForumName"].ToString() + "</span></a></li>"; if (IncludeClasses) { sSubforums += "<li class=\"fcv-desc\">" + dr["ForumDesc"].ToString() + "</li>"; } else { sSubforums += "<li>" + dr["ForumDesc"].ToString() + "</li>"; } } } if (!(string.IsNullOrEmpty(sSubforums))) { if (IncludeClasses) { sb.Append("<ul class=\"fcv-subforums\">"); } else { sb.Append("<ul>"); } sb.Append(sSubforums); sb.Append("</ul>"); } //Topics in ParentForum dr.NextResult(); string catKey = string.Empty; int count = 0; int catCount = 0; while (dr.Read()) { if (catKey != dr["CategoryName"].ToString() + dr["CategoryId"].ToString()) { if (count > 0) { sb.Replace("[CATCOUNT]", catCount.ToString()); sb.Append("</ul></div>"); count = 0; catCount = 0; } if (IncludeClasses) { sb.Append("<div class=\"fcv-categorysection\"><div class=\"fcv-categoryname\"><span class=\"fcv-catcount\">[CATCOUNT]</span>" + dr["CategoryName"].ToString() + " </div>"); sb.Append("<ul class=\"fcv-topicslist\">"); } else { sb.Append("<div><div><span>[CATCOUNT]</span>" + dr["CategoryName"].ToString() + " </div>"); sb.Append("<ul>"); } catKey = dr["CategoryName"].ToString() + dr["CategoryId"].ToString(); } //Dim Params As String() = {"aff=" & ForumId, "fcc=" & dr("TopicId").ToString} if (TopicId == Convert.ToInt32(dr["TopicId"].ToString())) { sb.Append("<li class=\"fcv-selected\">"); } else { sb.Append("<li>"); } catCount += 1; //Dim Params As String() = {ParamKeys.ForumId & "=" & ForumId, ParamKeys.TopicId & "=" & TopicId, ParamKeys.ViewType & "=topic"} string[] Params = { ParamKeys.TopicId + "=" + dr["TopicId"].ToString() }; string sTopicURL = ctlUtils.BuildUrl(TabId, ModuleId, groupPrefix, forumPrefix, ForumGroupId, ForumId, int.Parse(dr["TopicId"].ToString()), dr["URL"].ToString(), -1, -1, string.Empty, 1, -1, -1); sb.Append("<a href=\"" + sTopicURL + "\"><span>" + dr["Subject"].ToString() + "</span></a></li>"); if (TopicId > 0) { if (Convert.ToInt32(dr["TopicId"].ToString()) == TopicId) { // RenderTopic(dr) } } count += 1; } sb.Replace("[CATCOUNT]", catCount.ToString()); if (count > 0) { sb.Append("</ul></div>"); } dr.Close(); } return(sb.ToString()); }
private string GetSubForums(string Template, int ForumId, int ModuleId, int TabId, string ThemePath) { int i = 0; string sFilter = "ParentForumId = " + ForumId; //If Not ForumIds = String.Empty Then // sFilter = String.Empty // For Each f As String In ForumIds.Split(CChar(";")) // If Not f = String.Empty Then // If Not sFilter = String.Empty Then // sFilter = sFilter & " OR " // End If // sFilter &= " (ParentForumId = " & ForumId & " AND ForumId = " & f & ") " // End If // Next //End If ForumTable.DefaultView.RowFilter = sFilter; int rows = ForumTable.DefaultView.Count; if (Template == string.Empty) { var sb = new StringBuilder(); string SubForum; foreach (DataRow dr in ForumTable.DefaultView.ToTable().Rows) { if (Convert.ToInt32(dr["ParentForumId"]) == ForumId) { bool canView = Permissions.HasPerm(dr["CanView"].ToString(), ForumUser.UserRoles); SubForum = GetForumName(ModuleId, canView, Convert.ToBoolean(dr["ForumHidden"]), TabId, Convert.ToInt32(dr["ForumGroupId"]), Convert.ToInt32(dr["ForumId"]), dr["ForumName"].ToString(), MainSettings.UseShortUrls); if (SubForum != string.Empty) { sb.Append(SubForum); if (i < rows - 1) { sb.Append(", "); } i += 1; } } } string subs = string.Empty; if (sb.Length > 0) { sb.Insert(0, "<br />[RESX:SubForums] "); subs = sb.ToString(); subs = subs.Trim(); if (subs.IndexOf(",", subs.Length - 1) > 0) { subs = subs.Substring(0, subs.LastIndexOf(",")); } } ForumTable.DefaultView.RowFilter = ""; return(subs); } else { string subs = string.Empty; foreach (DataRow dr in ForumTable.DefaultView.ToTable().Rows) { i += 1; string tmpSubs = TemplateUtils.GetTemplateSection(Template, "[SUBFORUMS]", "[/SUBFORUMS]"); Forum fi = FillForumRow(dr); bool canView = Permissions.HasPerm(dr["CanView"].ToString(), ForumUser.UserRoles); if (canView || (!fi.Hidden) | UserInfo.IsSuperUser) { string sIcon = TemplateUtils.ShowIcon(canView, fi.ForumID, CurrentUserId, fi.LastPostDateTime, fi.LastRead, fi.LastPostID); //string sIconImage = "<img alt=\"" + fi.ForumName + "\" src=\"" + ThemePath + "images/" + sIcon + "\" />"; //tmpSubs = tmpSubs.Replace("[FORUMICONSM]", sIconImage.Replace("folder", "folder16")); string sFolderCSS = "fa-folder fa-blue"; switch (sIcon.ToLower()) { case "folder.png": sFolderCSS = "fa-folder fa-blue"; break; case "folder_new.png": sFolderCSS = "fa-folder fa-red"; break; case "folder_forbidden.png": sFolderCSS = "fa-folder fa-grey"; break; case "folder_closed.png": sFolderCSS = "fa-folder-o fa-grey"; break; } tmpSubs = tmpSubs.Replace("[FORUMICONSM]", "<i class=\"fa " + sFolderCSS + " fa-fw\"></i> "); //tmpSubs = tmpSubs.Replace("[FORUMICONSM]", "<i class=\"fa fa-folder fa-fw fa-blue\"></i> "); tmpSubs = ParseForumRow(tmpSubs, fi, i, ThemePath, ForumTable.DefaultView.ToTable().Rows.Count); } else { tmpSubs = string.Empty; } subs += tmpSubs; } ForumTable.DefaultView.RowFilter = ""; Template = TemplateUtils.ReplaceSubSection(Template, subs, "[SUBFORUMS]", "[/SUBFORUMS]"); return(Template); } }
private string ParseTemplate() { SettingsInfo MainSettings = DataCache.MainSettings(ControlConfig.InstanceId); string sOut = DisplayTemplate; //sOut = ParseForumData(sOut) string sort = SortColumns.ReplyCreated; if (sOut.Contains("[AF:SORT:TOPICCREATED]")) { sort = SortColumns.TopicCreated; sOut = sOut.Replace("[AF:SORT:TOPICCREATED]", string.Empty); } int Replies = 0; int Views = 0; string Subject = string.Empty; string summary = string.Empty; string body = string.Empty; int replyCount = 0; int viewCount = 0; int topicid = 0; string topicIcon = string.Empty; int UserLastTopicRead = 0; int UserLastReplyRead = 0; int topicRating = 0; int LastReplyId = 0; bool isLocked = false; bool isPinned = false; int AuthorId = -1; string AuthorName = string.Empty; string AuthorFirstName = string.Empty; string AuthorLastName = string.Empty; string AuthorUserName = string.Empty; string AuthorDisplayName = string.Empty; string LastPostData = string.Empty; System.DateTime LastPostDate = default(System.DateTime); System.DateTime DateCreated = default(System.DateTime); string sTopicURL = string.Empty; string sBodyTitle = string.Empty; int statusId = -1; bool isAnnounce = false; System.DateTime AnnounceStart = default(System.DateTime); System.DateTime AnnounceEnd = default(System.DateTime); int topicType = 0; Author la = null; string ModApprove = string.Empty; string ModDelete = string.Empty; string ModEdit = string.Empty; string ModPin = string.Empty; string ModLock = string.Empty; string ModMove = string.Empty; string ModSplit = string.Empty; string Reply = string.Empty; string Lock = string.Empty; string Pin = string.Empty; string Delete = string.Empty; string Edit = string.Empty; string groupName = string.Empty; //Dim t As New Data.Topics string topics = TemplateUtils.GetTemplateSection(sOut, "[TOPICS]", "[/TOPICS]"); System.Text.StringBuilder sb = new System.Text.StringBuilder(); System.Xml.XmlNodeList xTopics = null; xTopics = topicsData.SelectNodes("//topics/topic"); int rowCount = 0; foreach (System.Xml.XmlNode xNode in xTopics) { string ForumName = string.Empty; ForumId = int.Parse(xNode.Attributes["forumid"].Value.ToString()); ForumName = xNode["forumname"].InnerText; groupName = xNode["groupname"].InnerText; topicid = int.Parse(xNode.Attributes["topicid"].Value.ToString()); LastReplyId = int.Parse(xNode.Attributes["lastreplyid"].Value.ToString()); viewCount = int.Parse(xNode.Attributes["viewcount"].Value.ToString()); replyCount = int.Parse(xNode.Attributes["replycount"].Value.ToString()); isLocked = bool.Parse(xNode.Attributes["islocked"].Value.ToString()); isPinned = bool.Parse(xNode.Attributes["ispinned"].Value.ToString()); topicIcon = xNode.Attributes["topicicon"].Value.ToString(); statusId = int.Parse(xNode.Attributes["statusid"].Value.ToString()); isAnnounce = bool.Parse(xNode.Attributes["isannounce"].Value.ToString()); AnnounceStart = Convert.ToDateTime(xNode.Attributes["announcestart"].Value.ToString()); AnnounceEnd = Convert.ToDateTime(xNode.Attributes["announceend"].Value.ToString()); topicType = int.Parse(xNode.Attributes["topictype"].Value.ToString()); AuthorId = int.Parse(xNode.Attributes["authorid"].Value.ToString()); DateCreated = Convert.ToDateTime(xNode.Attributes["datecreated"].Value.ToString()); if (!string.IsNullOrEmpty(xNode.Attributes["lastpostdate"].Value.ToString())) { LastPostDate = Convert.ToDateTime(xNode.Attributes["lastpostdate"].Value.ToString()); } else { LastPostDate = DateCreated; } UserLastReplyRead = int.Parse(xNode.Attributes["userlastreplyread"].Value.ToString()); UserLastTopicRead = int.Parse(xNode.Attributes["userlasttopicread"].Value.ToString()); topicRating = int.Parse(xNode.Attributes["topicrating"].Value.ToString()); Subject = xNode["subject"].InnerText; Subject = Utilities.StripHTMLTag(Subject); Subject = Subject.Replace("[", "["); Subject = Subject.Replace("]", "]"); summary = xNode["summary"].InnerText; body = xNode["body"].InnerText; AuthorName = xNode["authorname"].InnerText; AuthorUserName = xNode["username"].InnerText; AuthorFirstName = xNode["firstname"].InnerText; AuthorLastName = xNode["lastname"].InnerText; AuthorDisplayName = xNode["displayname"].InnerText; XmlNode secNode = xNode["security"]; ModApprove = secNode["modapprove"].InnerText; ModDelete = secNode["moddelete"].InnerText; ModEdit = secNode["modedit"].InnerText; ModPin = secNode["modpin"].InnerText; ModLock = secNode["modlock"].InnerText; ModMove = secNode["modmove"].InnerText; Reply = secNode["reply"].InnerText; Lock = secNode["lock"].InnerText; Pin = secNode["pin"].InnerText; Delete = secNode["delete"].InnerText; Edit = secNode["edit"].InnerText; if ((xNode["lastpost"] != null)) { LastPostData = xNode["lastpost"].OuterXml; } else { LastPostData = string.Empty; } if (!string.IsNullOrEmpty(LastPostData)) { la = new Author(); System.Xml.XmlDocument xDoc = new System.Xml.XmlDocument(); xDoc.LoadXml(LastPostData); System.Xml.XmlNode xLast = xDoc.SelectSingleNode("//lastpost"); if ((xLast != null)) { var _with1 = la; _with1.AuthorId = int.Parse(xLast["authorid"].InnerText.ToString()); _with1.DisplayName = xLast["displayname"].InnerText; _with1.FirstName = xLast["firstname"].InnerText; _with1.LastName = xLast["lastname"].InnerText; _with1.Username = xLast["username"].InnerText; } } int BodyLength = -1; string BodyTrim = ""; sTopicURL = URL.ForTopic(TabId, PortalId, ForumId, topicid, groupName, ForumName, Subject, 1); string tmp = topics; string sLastPost = TemplateUtils.GetTemplateSection(tmp, "[LASTPOST]", "[/LASTPOST]"); if ((la != null)) { sLastPost = sLastPost.Replace("[LASTPOSTDISPLAYNAME]", UserProfiles.GetDisplayName(ModuleId, ProfileVisibility, false, la.AuthorId, UserNameDisplay, DisableUserProfiles, la)); sLastPost = sLastPost.Replace("[AF:PROFILE:AVATAR]", UserProfiles.GetAvatar(la.AuthorId, PortalId, ThemePath, MainSettings.Theme, string.Empty, 0, MainSettings.AvatarWidth, MainSettings.ProfileType, MainSettings.AvatarDefault)); sLastPost = sLastPost.Replace("[LASTPOSTDATE]", Utilities.GetDate(LastPostDate, ModuleId)); if (bRead) { //TODO: Replace with link sLastPost = sLastPost.Replace("[AF:ICONLINK:LASTREPLY]", string.Empty); } else { sLastPost = sLastPost.Replace("[AF:ICONLINK:LASTREPLY]", string.Empty); } tmp = TemplateUtils.ReplaceSubSection(tmp, sLastPost, "[LASTPOST]", "[/LASTPOST]"); } else { tmp = TemplateUtils.ReplaceSubSection(tmp, string.Empty, "[LASTPOST]", "[/LASTPOST]"); } //Dim sLastReplyURL As String = NavigateUrl(TabId, "", New String() {ParamKeys.ForumId & "=" & ForumId, ParamKeys.TopicId & "=" & topicid, ParamKeys.ViewType & "=topic", ParamKeys.ContentJumpId & "=" & LastReplyId}) string sLastReadURL = string.Empty; string sUserJumpUrl = string.Empty; //If UserLastReplyRead > 0 Then //sLastReadURL = NavigateUrl(TabId, "", New String() {ParamKeys.ForumId & "=" & ForumId, ParamKeys.TopicId & "=" & topicid, ParamKeys.ViewType & "=topic", ParamKeys.FirstNewPost & "=" & UserLastReplyRead}) //End If //If UserPrefJumpLastPost And sLastReadURL <> String.Empty Then // ' sTopicURL = sLastReadURL // sUserJumpUrl = sLastReadURL //End If if (tmp.Contains("[BODY:")) { int inStart = Strings.InStr(tmp, "[BODY:") + 5; int inEnd = Strings.InStr(inStart, tmp, "]") - 1; string sLength = tmp.Substring(inStart, inEnd - inStart); BodyLength = Convert.ToInt32(sLength); BodyTrim = "[BODY:" + BodyLength.ToString() + "]"; } if (!(BodyTrim == string.Empty)) { string BodyPlain = body.Replace("<br>", Constants.vbCrLf); BodyPlain = BodyPlain.Replace("<br />", Constants.vbCrLf); BodyPlain = Utilities.StripHTMLTag(BodyPlain); if (BodyLength > 0 & BodyPlain.Length > BodyLength) { BodyPlain = BodyPlain.Substring(0, BodyLength); } BodyPlain = BodyPlain.Replace(Constants.vbCrLf, "<br />"); tmp = tmp.Replace(BodyTrim, BodyPlain); } if (isLocked) { tmp = tmp.Replace("[RESX:LockTopic]", "[RESX:UnLockTopic]"); tmp = tmp.Replace("[RESX:Confirm:Lock]", "[RESX:Confirm:UnLock]"); } if (isPinned) { tmp = tmp.Replace("[RESX:PinTopic]", "[RESX:UnPinTopic]"); tmp = tmp.Replace("[RESX:Confirm:Pin]", "[RESX:Confirm:UnPin]"); } tmp = tmp.Replace("[BODY]", GetBody(body, AuthorId)); tmp = tmp.Replace("[BODYTITLE]", GetTitle(body, AuthorId)); tmp = tmp.Replace("[AUTHORID]", AuthorId.ToString()); tmp = tmp.Replace("[USERID]", UserId.ToString); if (string.IsNullOrEmpty(Subject)) { Subject = "(no subject)"; } string LastSubject = Subject; if (LastReplyId > 0) { LastSubject = "[RESX:RE]" + LastSubject; } tmp = tmp.Replace("[SUBJECT]", Subject); string sSubjectLink = GetTopic(topicid, Subject, sBodyTitle, UserId, AuthorId, replyCount, -1, sUserJumpUrl, groupName, ForumName); string lastSubjectLink = GetTopic(topicid, Subject, string.Empty, UserId, AuthorId, replyCount, -1, sUserJumpUrl, groupName, ForumName); tmp = tmp.Replace("[SUBJECTLINK]", sSubjectLink); tmp = tmp.Replace("[THEMEPATH]", ThemePath); tmp = tmp.Replace("[TOPICID]", topicid.ToString()); tmp = tmp.Replace("[MODEDIT]", string.Empty); tmp = tmp.Replace("[MODDELETE]", string.Empty); tmp = tmp.Replace("[MODMOVE]", string.Empty); tmp = tmp.Replace("[MODLOCK]", string.Empty); tmp = tmp.Replace("[MODPIN]", string.Empty); tmp = tmp.Replace("[REPLIES]", replyCount.ToString()); tmp = tmp.Replace("[VIEWS]", viewCount.ToString()); tmp = tmp.Replace("[POSTICONIMAGE]", GetIcon(UserLastTopicRead, UserLastReplyRead, topicid, LastReplyId, topicIcon, isPinned, isLocked)); tmp = tmp.Replace("[POSTICONCSS]", GetIconCSS(UserLastTopicRead, UserLastReplyRead, topicid, LastReplyId, topicIcon, isPinned, isLocked)); if (tmp.Contains("[STATUSCSS]")) { string sImg = string.Empty; if (statusId == -1) { tmp = tmp.Replace("[STATUSCSS]", string.Empty); } else { sImg = "<span title=\"[RESX:PostStatus" + statusId.ToString() + "]\" class=\"afstatus afstatus" + statusId.ToString() + "\"></span>"; } tmp = tmp.Replace("[STATUSCSS]", sImg); } tmp = tmp.Replace("[STARTEDBY]", UserProfiles.GetDisplayName(ModuleId, ProfileVisibility, false, AuthorId, UserNameDisplay, DisableUserProfiles, AuthorUserName, AuthorFirstName, AuthorLastName, AuthorDisplayName)); tmp = tmp.Replace("[DATECREATED]", Utilities.GetDate(DateCreated, ModuleId)); tmp = tmp.Replace("[TOPICURL]", sTopicURL); //TODO: Still need to process tmp = tmp.Replace("[AF:ICONLINK:LASTREAD]", string.Empty); tmp = tmp.Replace("[AF:URL:LASTREAD]", string.Empty); if (tmp.Contains("[STATUS]")) { string sImg = string.Empty; if (statusId == -1) { tmp = tmp.Replace("[STATUS]", string.Empty); } else { sImg = "<img alt=\"[RESX:PostStatus" + statusId.ToString() + "]\" src=\"" + Utilities.AppPath + "themes/images/status" + statusId.ToString() + ".png\" />"; } tmp = tmp.Replace("[STATUS]", sImg); } //sTopicsTemplate = sTopicsTemplate.Replace("[AF:UI:MINIPAGER]", GetSubPages(TabId, ModuleId, ReplyCount, ForumId, TopicId)) tmp = tmp.Replace("[AF:UI:MINIPAGER]", string.Empty); tmp = tmp.Replace("[POSTRATINGDISPLAY]", string.Empty); tmp = tmp.Replace("[TOPICRATING]", topicRating.ToString()); tmp = tmp.Replace("[ROWCSS]", GetRowCSS(UserLastTopicRead, UserLastReplyRead, topicid, LastReplyId, rowCount)); tmp = tmp.Replace("[AF:TOPIC:FRIENDLYDATE]", Utilities.HumanFriendlyDate(DateCreated, ModuleId)); tmp = tmp.Replace("[AF:REPLY:FRIENDLYDATE]", Utilities.HumanFriendlyDate(LastPostDate, ModuleId)); tmp = tmp.Replace("[AF:TOPIC:FORUMNAME]", ForumName); tmp = tmp.Replace("[AF:TOPIC:LASTSUBJECT:LINK]", lastSubjectLink); tmp = tmp.Replace("[AF:TOPIC:LASTSUBJECT]", LastSubject); tmp = tmp.Replace("[AF:TOPIC:FORUMNAME:LINK]", "<a href=\"" + URL.ForForum(PageId, ForumId, groupName[ForumId], ForumName) + "\" title=\"" + ForumName + "\">" + ForumName + "</a>"); tmp = tmp.Replace("AF:SECURITY:MODROLES]", "AF:SECURITY:MODROLES:" + ModApprove + "]"); tmp = tmp.Replace("AF:SECURITY:MODAPPROVE]", "AF:SECURITY:MODAPPROVE:" + ModApprove + "]"); tmp = tmp.Replace("AF:SECURITY:DELETE]", "AF:SECURITY:DELETE:" + Delete + ModDelete + "]"); tmp = tmp.Replace("AF:SECURITY:EDIT]", "AF:SECURITY:EDIT:" + Edit + ModEdit + "]"); tmp = tmp.Replace("AF:SECURITY:LOCK]", "AF:SECURITY:LOCK:" + Lock + ModLock + "]"); tmp = tmp.Replace("AF:SECURITY:MOVE]", "AF:SECURITY:MOVE:" + ModMove + "]"); tmp = tmp.Replace("AF:SECURITY:PIN]", "AF:SECURITY:PIN:" + Pin + ModPin + "]"); tmp = tmp.Replace("AF:SECURITY:SPLIT]", "AF:SECURITY:SPLIT:" + ModSplit + "]"); tmp = tmp.Replace("AF:SECURITY:REPLY]", "AF:SECURITY:REPLY:" + Reply + "]"); sb.Append(tmp); rowCount += 1; } sOut = TemplateUtils.ReplaceSubSection(sOut, sb.ToString(), "[TOPICS]", "[/TOPICS]"); sOut = sOut.Replace("[TOPICS]", string.Empty); sOut = sOut.Replace("[/TOPICS]", string.Empty); DataCache.CacheStore(ModuleId + "topicsview", sOut); return(sOut); }
/// <summary> /// 执行解析模板内容 /// </summary> /// <param name="html"></param> /// <returns></returns> private void CompileTemplateTag(ref string html) { //返回结果 //const string paramPattern = "\\s*'([^']*)',*|\\s*(?!=')([^,]+),*"; if (!TagRegex.IsMatch(html)) { return; } Type type = this._classInstance.GetType(); MethodInfo method; string tagName; object[] parameters; Type[] parameterTypes; //参数类型数组 MatchCollection paramMcs; html = TagRegex.Replace(html, m => { tagName = m.Groups[1].Value; //获得参数 paramMcs = TagParamRegex.Matches(m.Groups[2].Value); // // foreach (Match m3 in paramMcs) // { // Console.WriteLine("-------"); // Console.WriteLine(m3.Value); // } //参数 parameters = new object[paramMcs.Count]; //查找是否存在方法(方法参数均为string类型) parameterTypes = new Type[parameters.Length]; for (int i = 0; i < parameterTypes.Length; i++) { parameterTypes[i] = typeof(String); } method = type.GetMethod( tagName, BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.IgnoreCase, null, parameterTypes, null); //如果方法存在且包含template特性,则执行返回结果,否则返回原始值 if (method == null || method.GetCustomAttributes(typeof(TemplateTagAttribute), true) == null) { return(m.Value); } //数字参数 //则给参数数组赋值 for (int i = 0; i < paramMcs.Count; i++) { var paramGroupValue = paramMcs[i].Groups[1].Value.Trim(); var value = TemplateUtils.GetFunctionParamValue(paramGroupValue); //Console.WriteLine("---value:"); //Console.WriteLine(value); parameters[i] = value; } _count?.Add($"Tag:{method.Name},{DateTime.Now:mmssfff}"); //执行方法并返回结果 return(method.Invoke(this._classInstance, parameters).ToString()); }); }
protected override string InsertBody(string snippet, int position, string body) { body = body.TrimStart('\t'); return(TemplateUtils.ReplaceTemplateVariable(snippet, "EntryPoint", body)); }
void ParseInternal() { try { this.mainBlock = new BlockNode(null); this.stack = new Stack <BlockNode>(); this.errors = new List <TemplateError>(); PushBlock(mainBlock); var matches = TemplateUtils.KeywordsRegex.Matches(text); if (matches.Count == 0) { stack.Peek().Nodes.Add(new LiteralNode { Text = text }); stack.Pop(); return; } int index = 0; foreach (Match match in matches) { if (index < match.Index) { stack.Peek().Nodes.Add(new LiteralNode { Text = text.Substring(index, match.Index - index) }); } var type = match.Groups["type"].Value; var token = match.Groups["token"].Value; var keyword = match.Groups["keyword"].Value; var dec = match.Groups["dec"].Value; switch (keyword) { case "": case "raw": var s = TemplateUtils.SplitToken(token); if (s == null) { AddError(true, "{0} has invalid format".FormatWith(token)); } else { var t = TryParseValueProvider(type, s.Value.Token, dec); stack.Peek().Nodes.Add(new ValueNode(t, s.Value.Format, isRaw: keyword.Contains("raw"))); DeclareVariable(t); } break; case "declare": { var t = TryParseValueProvider(type, token, dec); stack.Peek().Nodes.Add(new DeclareNode(t, this.AddError)); DeclareVariable(t); } break; case "any": { AnyNode any; ValueProviderBase vp; var filter = TemplateUtils.TokenOperationValueRegex.Match(token); if (!filter.Success) { vp = TryParseValueProvider(type, token, dec); any = new AnyNode(vp); } else { vp = TryParseValueProvider(type, filter.Groups["token"].Value, dec); var comparer = filter.Groups["comparer"].Value; var value = filter.Groups["value"].Value; any = new AnyNode(vp, comparer, value, this.AddError); } stack.Peek().Nodes.Add(any); PushBlock(any.AnyBlock); DeclareVariable(vp); break; } case "notany": { var an = (AnyNode)PopBlock(typeof(AnyNode)).owner; if (an != null) { PushBlock(an.CreateNotAny()); } break; } case "endany": { PopBlock(typeof(AnyNode)); break; } case "foreach": { ValueProviderBase vp = TryParseValueProvider(type, token, dec); var fn = new ForeachNode(vp); stack.Peek().Nodes.Add(fn); PushBlock(fn.Block); vp.IsForeach = true; DeclareVariable(vp); break; } case "endforeach": { PopBlock(typeof(ForeachNode)); } break; case "if": { IfNode ifn; ValueProviderBase vp; var filter = TemplateUtils.TokenOperationValueRegex.Match(token); if (!filter.Success) { vp = TryParseValueProvider(type, token, dec); ifn = new IfNode(vp, this); } else { vp = TryParseValueProvider(type, filter.Groups["token"].Value, dec); var comparer = filter.Groups["comparer"].Value; var value = filter.Groups["value"].Value; ifn = new IfNode(vp, comparer, value, this.AddError); } stack.Peek().Nodes.Add(ifn); PushBlock(ifn.IfBlock); DeclareVariable(vp); break; } case "else": { var ifn = (IfNode)PopBlock(typeof(IfNode)).owner; if (ifn != null) { PushBlock(ifn.CreateElse()); } break; } case "endif": { PopBlock(typeof(IfNode)); break; } default: AddError(true, "'{0}' is deprecated".FormatWith(keyword)); break; } index = match.Index + match.Length; } if (stack.Count != 1) { AddError(true, "Last block is not closed: {0}".FormatWith(stack.Peek())); } var lastM = matches.Cast <Match>().LastOrDefault(); if (lastM != null && lastM.Index + lastM.Length < text.Length) { stack.Peek().Nodes.Add(new LiteralNode { Text = text.Substring(lastM.Index + lastM.Length) }); } stack.Pop(); } catch (Exception e) { AddError(true, e.Message); } }
/// <summary> /// 赋值到变量 /// $v = form('key') /// </summary> private static string SetToVariable(IDataContainer dc, string content) { //正则模式,支持以下 // //$menu="123456\" f" sdf // $menu=12 fsdf // $menu=item:123456 // $menu=>getmenu(test,item,get) //const string expressionPattern = "(/*/*|#*)\\$([_a-zA-Z][a-zA-Z0-9_]*)\\s*=\\s*(\"(\"|[^\"\\n])*\"|[^<>\\s\\n\"\\$/]+)(\\s+\\B)*"; const string expressionPattern = "(/*/*|#*)\\$([_a-zA-Z][a-zA-Z0-9_]*)\\s*=\\s*([^()]+)\\(((\\{[^}]*\\})|([^)]*))\\)"; //设置表达式 //const string specialVarPattern = "(item|cache|query|form)\\([\"']*(.+?)[\"']*\\)"; //特殊数据 var outHtml = Regex.Replace(content, expressionPattern, m => { //注释 if (m.Groups[1].Value != "") { return(String.Empty); } //获取变量及表达式 var varName = m.Groups[2].Value; var expName = m.Groups[3].Value; var expValue = TemplateUtils.GetFunctionParamValue(m.Groups[4].Value); var value = String.Empty; switch (expName) { case "item": value = dc.GetAdapter().GetItem(expValue).ToString(); break; case "cache": value = dc.GetAdapter().GetCache(expValue).ToString(); break; case "query": value = dc.GetAdapter().GetQueryParam(expValue); break; case "form": value = dc.GetAdapter().GetFormParam(expValue); break; } dc.DefineVariable(varName, value ?? ""); /* * } * else * { * string varRealValue = Regex.Replace(expValue, "\\B\"|\"\\B", String.Empty); * * //如果为字符,否则读取指定值的变量 * if (Regex.IsMatch(expValue, "\\B\"|\"\\B")) * { * dc.DefineVariable(varName, varRealValue); * } * else * { * object obj = dc.GetVariable(varRealValue); * if (obj != null) * { * if (obj is Variable) * { * dc.DefineVariable(varName, (Variable) obj); * } * else * { * dc.DefineVariable(varName, obj.ToString()); * } * } * else * { * string message = ""; * int i = 0; * foreach (string key in dc.GetDefineVariable().Keys) * { * message += (++i == 1 ? "" : "," + key); * } * throw new NotSupportedException("数据引用键错误:" + m.Value + "\n" + + (message != "" + ? "受支持可引用的数据键包括" + message + "\n使用\"$" + varName + + "=>键\"进行调用!" + : "")); + } + } + } */ return(String.Empty); }, RegexOptions.Singleline); return(outHtml); }
public string BuildForumView(int ForumTemplateId, int CurrentUserId, string ThemePath) { try { SettingsInfo MainSettings = DataCache.MainSettings(ModuleId); string sOutput = string.Empty; string sTemplate; int TemplateCache = MainSettings.TemplateCache; if (UseTemplatePath && TemplatePath != string.Empty) { DisplayTemplate = Utilities.GetFileContent(TemplatePath + "ForumView.htm"); DisplayTemplate = Utilities.ParseSpacer(DisplayTemplate); } else if (DisplayTemplate == string.Empty) { DisplayTemplate = Utilities.GetFileContent(Server.MapPath(ThemePath) + "templates/ForumView.ascx"); DisplayTemplate = Utilities.ParseSpacer(DisplayTemplate); } sTemplate = DisplayTemplate == string.Empty ? DataCache.GetCachedTemplate(TemplateCache, ModuleId, "ForumView", ForumTemplateId) : DisplayTemplate; try { sTemplate = ParseControls(sTemplate); } catch (Exception ex) { Services.Exceptions.Exceptions.ProcessModuleLoadException(this, ex); sTemplate = ex.Message; //ParseControls(sTemplate) } if (sTemplate.Contains("[NOTOOLBAR]")) { if (HttpContext.Current.Items.Contains("ShowToolbar")) { HttpContext.Current.Items["ShowToolbar"] = false; } else { HttpContext.Current.Items.Add("ShowToolbar", false); } sTemplate = sTemplate.Replace("[NOTOOLBAR]", string.Empty); } if (sTemplate.Contains("[FORUMS]")) { string sGroupSection = string.Empty; string sGroupSectionTemp = TemplateUtils.GetTemplateSection(sTemplate, "[GROUPSECTION]", "[/GROUPSECTION]"); string sGroup = TemplateUtils.GetTemplateSection(sTemplate, "[GROUP]", "[/GROUP]"); string sForums = string.Empty; string sForumTemp = TemplateUtils.GetTemplateSection(sTemplate, "[FORUMS]", "[/FORUMS]"); string tmpGroup = string.Empty; //Dim reader As IDataReader = Nothing if (ForumTable == null) { var ds = new DataSet(); dtForums = new DataTable(); var fc = new ForumController(); ForumTable = fc.GetForumView(PortalId, ModuleId, CurrentUserId, UserInfo.IsSuperUser, ForumIds); // KR - added cache retreival //ds = DataProvider.Instance.UI_ForumView(PortalId, ModuleId, CurrentUserId, UserInfo.IsSuperUser, ForumIds) //ForumTable = ds.Tables(0) } string sCrumb = string.Empty; string sGroupName = string.Empty; //Dim ForumGroupId As Integer = 0 if (ForumGroupId != -1) { DataRow tmpDR = null; ForumTable.DefaultView.RowFilter = "ForumGroupId = " + ForumGroupId; if (ForumTable.DefaultView.ToTable().Rows.Count > 0) { tmpDR = ForumTable.DefaultView.ToTable().Rows[0]; } if (tmpDR != null) { sGroupName = tmpDR["GroupName"].ToString(); sCrumb = "<div class=\"afcrumb\"><i class=\"fa fa-comments-o fa-grey\"></i> <a href=\"" + Utilities.NavigateUrl(TabId) + "\">[RESX:ForumMain]</a> <i class=\"fa fa-long-arrow-right fa-grey\"></i> " + tmpDR["GroupName"] + "</div>"; } //dtForums.DefaultView.RowFilter = "" } if (ParentForumId != -1) { //SubsOnly = True DataRow tmpDR = null; string sFilter = "ForumId = " + ParentForumId + " "; ForumTable.DefaultView.RowFilter = sFilter; if (ForumTable.DefaultView.ToTable().Rows.Count > 0) { tmpDR = ForumTable.DefaultView.ToTable().Rows[0]; } ForumTable.DefaultView.RowFilter = ""; sGroupName = tmpDR["GroupName"].ToString(); } if (MainSettings.UseSkinBreadCrumb && ForumTable.Rows.Count > 0 && SubsOnly == false && ForumGroupId != -1) { Environment.UpdateBreadCrumb(Page.Controls, "<a href=\"" + NavigateUrl(TabId, "", ParamKeys.GroupId + "=" + ForumGroupId) + "\">" + sGroupName + "</a>"); sTemplate = sTemplate.Replace("<div class=\"afcrumb\">[FORUMMAINLINK] > [FORUMGROUPLINK]</div>", string.Empty); sTemplate = sTemplate.Replace("[BREADCRUMB]", string.Empty); } else { sTemplate = sTemplate.Replace("[BREADCRUMB]", sCrumb); } int iForum = 1; int ForumCount = 0; bool hasForums = false; DataTable rsForums = ForumTable.DefaultView.ToTable(); Forum fi; int tmpGroupCount = 0; int asForumGroupId; var social = new Social(); asForumGroupId = social.GetMasterForumGroup(PortalId, TabId); int groupForumsCount = 0; foreach (DataRow dr in rsForums.Rows) { //If CBool(dr("CanView")) Or (Not CBool(dr("GroupHidden"))) Then ' And Not CBool(dr("CanView"))) Or UserInfo.IsSuperUser Then if (!(asForumGroupId == Convert.ToInt32(dr["ForumGroupId"]) && Convert.ToBoolean(dr["GroupHidden"]))) { if (tmpGroup != dr["GroupName"].ToString()) { if (tmpGroupCount < Globals.GroupCount) { ForumTable.DefaultView.RowFilter = "ForumGroupId = " + Convert.ToInt32(dr["ForumGroupId"]) + " AND ParentForumId = 0"; ForumCount = ForumTable.DefaultView.Count; ForumTable.DefaultView.RowFilter = ""; if (sForums != string.Empty) { sGroupSection = TemplateUtils.ReplaceSubSection(sGroupSection, sForums, "[FORUMS]", "[/FORUMS]"); sForums = string.Empty; } int GroupId = Convert.ToInt32(dr["ForumGroupId"]); sGroupSectionTemp = TemplateUtils.GetTemplateSection(sTemplate, "[GROUPSECTION]", "[/GROUPSECTION]"); sGroupSectionTemp = sGroupSectionTemp.Replace("[GROUPNAME]", dr["GroupName"].ToString()); sGroupSectionTemp = sGroupSectionTemp.Replace("[FORUMGROUPID]", dr["ForumGroupId"].ToString()); sGroupSectionTemp = sGroupSectionTemp.Replace("[GROUPCOLLAPSE]", "<img class=\"afarrow\" id=\"imgGroup" + GroupId.ToString() + "\" onclick=\"toggleGroup(" + GroupId.ToString() + ");\" src=\"" + ThemePath + GetImage(GroupId) + "\" alt=\"[RESX:ToggleGroup]\" />"); //any replacements on the group string sNewGroup = "<div id=\"group" + GroupId + "\" " + GetDisplay(GroupId) + " class=\"afgroup\">" + sGroup + "</div>"; sGroupSectionTemp = TemplateUtils.ReplaceSubSection(sGroupSectionTemp, sNewGroup, "[GROUP]", "[/GROUP]"); sGroupSection += sGroupSectionTemp; tmpGroup = dr["GroupName"].ToString(); tmpGroupCount += 1; iForum = 1; } } if (iForum <= Globals.ForumCount) { fi = FillForumRow(dr); bool canView = Permissions.HasPerm(fi.Security.View, ForumUser.UserRoles); if (canView || (!fi.Hidden)) { sForumTemp = TemplateUtils.GetTemplateSection(sTemplate, "[FORUMS]", "[/FORUMS]"); hasForums = true; if (fi.ParentForumId == 0 || SubsOnly || (SubsOnly == false && fi.ParentForumId > 0 && rsForums.Rows.Count == 1)) { sForumTemp = ParseForumRow(sForumTemp, fi, iForum, ThemePath, ForumCount); iForum += 1; sForums += sForumTemp; } } } } //End If } if (hasForums == false && SubsOnly) { return(string.Empty); } if (sForums != string.Empty) { sGroupSection = TemplateUtils.ReplaceSubSection(sGroupSection, sForums, "[FORUMS]", "[/FORUMS]"); } sTemplate = sTemplate.Contains("[GROUPSECTION]") ? TemplateUtils.ReplaceSubSection(sTemplate, sGroupSection, "[GROUPSECTION]", "[/GROUPSECTION]") : sGroupSection; sTemplate = TemplateUtils.ReplaceSubSection(sTemplate, string.Empty, "[FORUMS]", "[/FORUMS]"); } return(sTemplate); } catch (Exception ex) { Services.Exceptions.Exceptions.LogException(ex); return(string.Empty); } }
/// <summary> /// 显示模板信息到页面 /// </summary> public static string GetTemplatePagesHTML() { string templateContent = ResourcesReader.Read(typeof(TemplateUtility).Assembly, "Template/Resources/SysTemplatePage.html"); StringBuilder sb = new StringBuilder(); sb.Append(@"<style type=""text/css""> table{width:100%;background:#eee;margin:0 auto;line-height:25px;color:#222;cursor:pointer} table td{background:white;padding:0 8px;} table th{background:#006699;color:white;} table tr.hover td{background:#222;color:white;} table tr.even td{} </style> <script type=""text/javascript""> function dynamicTable(table) { if (table && table.nodeName === 'TABLE') { var rows = table.getElementsByTagName('tr'); for (var i = 0; i < rows.length; i++) { if (i % 2 == 1) if (!rows[i].className) rows[i].className = 'even'; rows[i].onmouseover = function () { this.className = this.className.indexOf('even') != -1 ? 'hover even' : 'hover'; }; rows[i].onmouseout = function () { this.className = this.className.indexOf('even') == -1 ? '' : 'even'; }; } } }</script> <table cellspacing=""1"" id=""templates""> <tr> <th style=""width:50px;""></th><th style=""width:150px;"">模板编号</th><th style=""width:80px;"">模板类型</th><th>文件名</th><th>模板注释</th><th>文件路径</th></tr> <!-- <tr><td colspan=""6"" align=""center"" style=""background:#c20000;color:white"">扩展名为“.phtml”表示为一个部分视图;部分视图只能使用ID命名</td></tr> -->" ); string tplContent; //模板文件名,内容 int i = 0; foreach (string key in TemplateCache.TemplateDictionary.Keys) { var tpl = TemplateCache.TemplateDictionary[key]; var tplFileName = new Regex("templates(/|\\\\)+#*(.+?)$", RegexOptions.IgnoreCase).Match(tpl.FilePath).Groups[2].Value .Replace("\\", "/"); //模板文件名,内容 tplContent = tpl.GetContent(); sb.Append("<tr><td class=\"center\">").Append((++i).ToString()).Append("</td><td class=\"center\">") .Append(key.ToLower()).Append("</td><td class=\"center\">") .Append( //RegexUtility.partialRegex.IsMatch(tplContent) && tplContent.IndexOf("<title>") != -1 !tpl.FilePath.EndsWith(".phtml") ? "<span style=\"color:#333\">模板页面</span>" : "<span style=\"color:#006699\">部分视图</span>") .Append("</td><td>/").Append(tplFileName).Append("</td><td>").Append(tpl.Comment) .Append("</td><td>").Append(tpl.FilePath).Append("</td></tr>"); } sb.Append(@"<tr><td colspan=""6"" align=""center"" style=""background:#f0f0f0;color:#333""> 部分视图扩展名为“.phtml”,可允许格式如: A:${include:""inc/header.html""} B:${include:""/tmpdir/inc/header.html""} C:${include:""../../inc/header.html""} </td></tr>" ); sb.Append( "</table><script type=\"text/javascript\">dynamicTable(document.getElementsByTagName('table')[0]);</script>"); templateContent = TemplateRegexUtility.Replace(templateContent, match => { switch (match.Groups[1].Value) { case "title": return("模板信息"); case "content": return(sb.ToString()); case "year": return(DateTime.Now.Year.ToString()); } return(String.Empty); }); return(TemplateUtils.CompressHtml(templateContent)); }
private string ParseForumRow(string Template, Forum fi, int currForumIndex, string ThemePath, int totalForums) { if (Template.Contains("[SUBFORUMS]") && Template.Contains("[/SUBFORUMS]")) { Template = GetSubForums(Template, fi.ForumID, ModuleId, TabId, ThemePath); } else { Template = Template.Replace("[SUBFORUMS]", GetSubForums(fi.ForumID, ModuleId, TabId)); } string[] css = null; string cssmatch = string.Empty; if (Template.Contains("[CSS:")) { string pattern = "(\\[CSS:.+?\\])"; if (Regex.IsMatch(Template, pattern)) { cssmatch = Regex.Match(Template, pattern).Value; css = cssmatch.Split(':'); //0=CSS,1=TopRow, 2=mid rows, 3=lastRow } } if (cssmatch != string.Empty) { if (currForumIndex == 1) { Template = Template.Replace(cssmatch, css[1]); } else if (currForumIndex > 1 & currForumIndex < totalForums) { Template = Template.Replace(cssmatch, css[2]); } else { Template = Template.Replace(cssmatch, css[3].Replace("]", string.Empty)); } } bool canView = Permissions.HasPerm(fi.Security.View, ForumUser.UserRoles); bool canSubscribe = Permissions.HasPerm(fi.Security.Subscribe, ForumUser.UserRoles); bool canRead = Permissions.HasPerm(fi.Security.Read, ForumUser.UserRoles); string sIcon = TemplateUtils.ShowIcon(canView, fi.ForumID, CurrentUserId, fi.LastPostDateTime, fi.LastRead, fi.LastPostID); string sIconImage = "<img alt=\"" + fi.ForumName + "\" src=\"" + ThemePath + "images/" + sIcon + "\" />"; if (Template.Contains("[FORUMICON]")) { Template = Template.Replace("[FORUMICON]", sIconImage); } else if (Template.Contains("[FORUMICONCSS]")) { string sFolderCSS = "fa-folder fa-blue"; switch (sIcon.ToLower()) { case "folder.png": sFolderCSS = "fa-folder fa-blue"; break; case "folder_new.png": sFolderCSS = "fa-folder fa-red"; break; case "folder_forbidden.png": sFolderCSS = "fa-folder fa-grey"; break; case "folder_closed.png": sFolderCSS = "fa-folder-o fa-grey"; break; } Template = Template.Replace("[FORUMICONCSS]", "<div style=\"height:30px;margin-right:10px;\"><i class=\"fa " + sFolderCSS + " fa-2x\"></i></div>"); } var ctlUtils = new ControlUtils(); ForumURL = ctlUtils.BuildUrl(ForumTabId, ForumModuleId, fi.ForumGroup.PrefixURL, fi.PrefixURL, fi.ForumGroupId, fi.ForumID, -1, string.Empty, -1, -1, string.Empty, 1, -1, SocialGroupId); //ForumURL = GetForumLink(.ForumID, TabId, canView, MainSettings.UseShortUrls, .PrefixURL) Template = Template.Replace("[FORUMNAME]", GetForumLink(fi.ForumName, fi.ForumID, TabId, canView, ForumURL)); Template = Template.Replace("[FORUMNAMENOLINK]", fi.ForumName); Template = Template.Replace("[FORUMID]", fi.ForumID.ToString()); if (Template.Contains("[RSSLINK]")) { if (fi.AllowRSS && canRead) { string Url; Url = Common.Globals.AddHTTP(Common.Globals.GetDomainName(Request)) + "/DesktopModules/ActiveForums/feeds.aspx?portalid=" + PortalId + "&forumid=" + fi.ForumID + "&tabid=" + TabId + "&moduleid=" + ModuleId; Template = Template.Replace("[RSSLINK]", "<a href=\"" + Url + "\" target=\"_blank\"><img src=\"" + ThemePath + "images/rss.png\" border=\"0\" alt=\"[RESX:RSS]\" /></a>"); } else { Template = Template.Replace("[RSSLINK]", "<img src=\"" + ThemePath + "images/rss_disabled.png\" border=\"0\" alt=\"[RESX:RSSDisabled]\" />"); } } if (Template.Contains("[AF:CONTROL:TOGGLESUBSCRIBE]")) { if (canSubscribe) { bool IsSubscribed = Subscriptions.IsSubscribed(PortalId, ModuleId, fi.ForumID, 0, SubscriptionTypes.Instant, CurrentUserId); string sAlt = "[RESX:ForumSubscribe:" + IsSubscribed.ToString().ToUpper() + "]"; string sImg = ThemePath + "images/email_unchecked.png"; if (IsSubscribed) { sImg = ThemePath + "images/email_checked.png"; } var subControl = new ToggleSubscribe(0, fi.ForumID, -1); subControl.Checked = IsSubscribed; subControl.DisplayMode = 1; subControl.UserId = CurrentUserId; subControl.ImageURL = sImg; subControl.Text = "[RESX:ForumSubscribe:" + IsSubscribed.ToString().ToUpper() + "]"; string subOption = subControl.Render(); //Template = Template.Replace("[AF:CONTROL:TOGGLESUBSCRIBE]", "<a href=""javascript:af_toggleSubscribe(" & .ForumID & ",'" & PortalId & "|" & ModuleId & "|" & .ForumID & "|" & CurrentUserId & "');""><img id=""toggleSub" & .ForumID & """ src=""" & sImg & """ border=""0"" alt=""" & sAlt & """ /></a>") Template = Template.Replace("[AF:CONTROL:TOGGLESUBSCRIBE]", subOption); } else { Template = Template.Replace("[AF:CONTROL:TOGGLESUBSCRIBE]", "<img src=\"" + ThemePath + "email_disabled.png\" border=\"0\" alt=\"[RESX:ForumSubscribe:Disabled]\" />"); } } Template = canRead ? Template.Replace("[AF:CONTROL:ADDFAVORITE]", "<a href=\"javascript:afAddBookmark('" + fi.ForumName + "','" + ForumURL + "');\"><img src=\"" + ThemePath + "images/favorites16_add.png\" border=\"0\" alt=\"[RESX:AddToFavorites]\" /></a>") : Template.Replace("[AF:CONTROL:ADDFAVORITE]", string.Empty); if (Template.Contains("[AF:CONTROL:ADDTHIS")) { Template = TemplateUtils.ParseSpecial(Template, SpecialTokenTypes.AddThis, ForumURL, fi.ForumName, canRead, MainSettings.AddThisAccount); } if (fi.ForumDesc != "") { Template = Template.Replace("[FORUMDESCRIPTION]", "<i class=\"fa fa-file-o fa-grey\"></i> " + fi.ForumDesc); } else { Template = Template.Replace("[FORUMDESCRIPTION]", ""); } Template = Template.Replace("[TOTALTOPICS]", fi.TotalTopics.ToString()); Template = Template.Replace("[TOTALREPLIES]", fi.TotalReplies.ToString()); //Last Post Section int intLength = 0; if ((Template.IndexOf("[LASTPOSTSUBJECT:", 0) + 1) > 0) { int inStart = (Template.IndexOf("[LASTPOSTSUBJECT:", 0) + 1) + 17; int inEnd = (Template.IndexOf("]", inStart - 1) + 1); string sLength = Template.Substring(inStart - 1, inEnd - inStart); intLength = Convert.ToInt32(sLength); } string ReplaceTag = "[LASTPOSTSUBJECT:" + intLength.ToString() + "]"; if (fi.LastPostID == 0) { Template = Template.Replace("[RESX:BY]", string.Empty); Template = Template.Replace("[DISPLAYNAME]", string.Empty); Template = Template.Replace("[LASTPOSTDATE]", string.Empty); Template = Template.Replace(ReplaceTag, string.Empty); //Template = TemplateUtils.ParseUserDetails(PortalId, -1, Template, String.Empty) } else { if (canView) { if (fi.LastPostUserID <= 0) { //Template = Template.Replace("[RESX:BY]", String.Empty) Template = Template.Replace("[DISPLAYNAME]", "<i class=\"fa fa-user fa-fw fa-blue\"></i> " + fi.LastPostDisplayName); //Template = TemplateUtils.ParseUserDetails(PortalId, -1, Template, "FG") } else { bool isMod = CurrentUserType == CurrentUserTypes.Admin || CurrentUserType == CurrentUserTypes.ForumMod || CurrentUserType == CurrentUserTypes.SuperUser; bool isAdmin = CurrentUserType == CurrentUserTypes.Admin || CurrentUserType == CurrentUserTypes.SuperUser; Template = Template.Replace("[DISPLAYNAME]", "<i class=\"fa fa-user fa-fw fa-blue\"></i> " + UserProfiles.GetDisplayName(ModuleId, true, isMod, isAdmin, fi.LastPostUserID, fi.LastPostUserName, fi.LastPostFirstName, fi.LastPostLastName, fi.LastPostDisplayName)); //Template = TemplateUtils.ParseUserDetails(PortalId, .LastPostUserID, Template, "FG") } DateTime dtLastPostDate = fi.LastPostDateTime; Template = Template.Replace("[LASTPOSTDATE]", Utilities.GetDate(dtLastPostDate, ModuleId, TimeZoneOffset)); string Subject = fi.LastPostSubject; if (Subject == "") { Subject = GetSharedResource("[RESX:SubjectPrefix]") + " " + fi.TopicSubject; } if (Subject != string.Empty) { string sDots = ""; if (Subject.Length > intLength) { sDots = "..."; } Template = Template.Replace(ReplaceTag, GetLastPostSubject(fi.LastPostID, fi.TopicId, fi.ForumID, TabId, Subject, intLength, MainSettings.PageSize, fi)); } else { Template = Template.Replace("[RESX:BY]", string.Empty); Template = Template.Replace(ReplaceTag, string.Empty); } } else { Template = Template.Replace("[DISPLAYNAME]", string.Empty); Template = Template.Replace("[LASTPOSTDATE]", string.Empty); Template = Template.Replace("[RESX:BY]", string.Empty); Template = Template.Replace(ReplaceTag, string.Empty); } } return(Template); }
private string ParseTemplate() { var sb = new StringBuilder(); string groupTemplate = DisplayTemplate; if (groupTemplate.Contains("[GROUPSECTION]")) { groupTemplate = TemplateUtils.GetTemplateSection(DisplayTemplate, "[GROUPSECTION]", "[/GROUPSECTION]"); } var db = new Data.ForumsDB(); ForumData = db.ForumListXML(ControlConfig.SiteId, ControlConfig.InstanceId); if (ForumData != null) { XmlNodeList xGroups; xGroups = ForumGroupId == -1 ? ForumData.SelectNodes("//groups/group[@active='true']") : ForumData.SelectNodes("//groups/group[@groupid='" + ForumGroupId + "' and @active='true']"); foreach (XmlNode xNode in xGroups) { string sGroup = groupTemplate; int groupId = int.Parse(xNode.Attributes["groupid"].Value); string groupName = xNode.Attributes["name"].Value; sGroup = sGroup.Replace("[GROUPNAME]", groupName); bool isVisible = ToggleBehavior != 1; sGroup = sGroup.Replace("[GROUPCOLLAPSE]", "<af:toggle IsVisible=\"" + isVisible + "\" id=\"tgGroup" + groupId + "\" key=\"" + groupId + "\" cssclass=\"afarrow\" CssClassOn=\"aficon afarrowdown\" CssClassOff=\"aficon afarrowleft\" runat=\"server\" ImagePath=\"" + ThemePath + "\" />"); var xNodeList = ForumData.SelectNodes("//forums/forum[@active='true' and @groupid='" + groupId + "' and @parentforumid='0']"); var forums = new StringBuilder(); int i = 0; foreach (XmlNode fNode in xNodeList) { i += 1; string sCSSClass = "afforumrowmid"; if (i == 1) { sCSSClass = "afforumrowtop"; } else if (i == xNodeList.Count) { sCSSClass = "afforumrowbottom"; } int fid = int.Parse(fNode.Attributes["forumid"].Value); //Dim viewRoles As String = fNode.Attributes["canview"].Value.ToString //Dim readRoles As String = fNode.Attributes["canread"].Value.ToString string sForum = TemplateUtils.GetTemplateSection(sGroup, "[FORUMS]", "[/FORUMS]"); sForum = sForum.Replace("[CSS:ROWCLASS]", sCSSClass); sForum = ParseForumRow(fNode, sForum, groupName); forums.Append(sForum); } sGroup = TemplateUtils.ReplaceSubSection(sGroup, forums.ToString(), "[FORUMS]", "[/FORUMS]"); sGroup = sGroup.Replace("[GROUP]", "<af:toggledisplay IsVisible=\"" + isVisible + "\" id=\"tgdGroup" + groupId + "\" key=\"" + groupId + "\" runat=\"server\"><content>"); sGroup = sGroup.Replace("[/GROUP]", "</content></af:toggledisplay>"); sb.Append(sGroup); } } string sOut = sb.ToString(); if (sOut.Contains("[GROUPSECTION]")) { sOut = TemplateUtils.ReplaceSubSection(DisplayTemplate, sb.ToString(), "[GROUPSECTION]", "[/GROUPSECTION]"); } //sOut = sOut.Replace("[BREADCRUMB]", String.Empty) //sOut = sOut.Replace("[WHOSONLINE]", "<af:usersonline id=""ctlUsersOnline"" templatefile=""usersonline.htm"" runat=""server"" />") //sOut = sOut.Replace("[JUMPTO]", String.Empty) //sOut = sOut.Replace("[TEMPLATE:TOOLBAR]", "<af:toolbar id=""ctlToolbar"" templatefile=""toolbar.htm"" runat=""server"" />") //DataCache.CacheStore(ModuleId & "fvt", sOut) return(sOut); }
public string Render() { StringBuilder sb = new StringBuilder(); Data.CommonDB db = new Data.CommonDB(); string sHost = Utilities.GetHost(); if (sHost.EndsWith("/")) { sHost = sHost.Substring(0, sHost.Length - 1); } ControlUtils ctlUtils = new ControlUtils(); string forumPrefix = string.Empty; string groupPrefix = string.Empty; //Dim _forumGroupId As Integer = -1 if (ParentForumId == -1) { ParentForumId = ForumId; } string groupTemplate = TemplateUtils.GetTemplateSection(ItemTemplate, "[AF:DIR:FORUMGROUP]", "[/AF:DIR:FORUMGROUP]"); string forumTemplate = TemplateUtils.GetTemplateSection(ItemTemplate, "[AF:DIR:FORUM]", "[/AF:DIR:FORUM]"); string subForumTemplate = TemplateUtils.GetTemplateSection(ItemTemplate, "[AF:DIR:SUBFORUM]", "[/AF:DIR:SUBFORUM]"); bool useFriendlyUrl = Utilities.IsRewriteLoaded(); int currGroup = -1; string gtmp = string.Empty; string ftmp = string.Empty; string subtmp = string.Empty; using (IDataReader dr = db.ForumContent_List(PortalId, ModuleId, ForumGroupId, ForumId, ParentForumId)) { //ParentForum Section dr.Read(); //SubForums dr.NextResult(); dr.Read(); //Topics in ParentForum dr.NextResult(); string catKey = string.Empty; int count = 0; int catCount = 0; sb.Append("<ul>"); while (dr.Read()) { if (catKey != dr["CategoryName"].ToString() + dr["CategoryId"].ToString()) { if (count > 0) { sb.Replace("[CATCOUNT]", catCount.ToString()); sb.Append("</ul></li>"); count = 0; catCount = 0; } sb.Append("<li class=\"category\" id=\"afcat-" + dr["CategoryId"].ToString() + "\">"); sb.Append("<em>[CATCOUNT]</em>"); sb.Append("<span>" + dr["CategoryName"].ToString() + "</span>"); sb.Append("<ul>"); catKey = dr["CategoryName"].ToString() + dr["CategoryId"].ToString(); } //Dim Params As String() = {"aff=" & ForumId, "fcc=" & dr("TopicId").ToString} if (TopicId == Convert.ToInt32(dr["TopicId"].ToString())) { sb.Append("<li class=\"fcv-selected\">"); sb.Replace("<li class=\"category\" id=\"afcat-" + dr["CategoryId"].ToString() + "\">", "<li class=\"category cat-selected\" id=\"afcat-" + dr["CategoryId"].ToString() + "\">"); } else { sb.Append("<li>"); } catCount += 1; //Dim Params As String() = {ParamKeys.ForumId & "=" & ForumId, ParamKeys.TopicId & "=" & TopicId, ParamKeys.ViewType & "=topic"} string[] Params = { ParamKeys.TopicId + "=" + dr["TopicId"].ToString() }; //Dim sTopicURL As String = ctlUtils.BuildUrl(TabId, ModuleId, groupPrefix, forumPrefix, ForumGroupId, ForumId, Integer.Parse(dr("TopicId").ToString), dr("URL").ToString, -1, -1, String.Empty, 1) string sTopicURL = ctlUtils.TopicURL(dr, TabId, ModuleId); sb.Append("<a href=\"" + sTopicURL + "\"><span>" + dr["Subject"].ToString() + "</span></a></li>"); if (TopicId > 0) { if (Convert.ToInt32(dr["TopicId"].ToString()) == TopicId) { // RenderTopic(dr) } } count += 1; } sb.Replace("[CATCOUNT]", catCount.ToString()); if (count > 0) { sb.Append("</ul></li>"); } sb.Append("</ul>"); dr.Close(); } return(sb.ToString()); }
private string ParseForumRow(XmlNode fNode, string Template, string GroupName) { string sForum = Template; int lasttopicid; int lastreplyid; int fid; string lastpostdate = fNode.Attributes["lastpostdate"].Value; DateTime lastReadDate = DateTime.Parse(fNode.Attributes["lastread"].Value); string viewRoles = fNode.Attributes["viewroles"].Value; string readRoles = fNode.Attributes["readroles"].Value; string forumname = fNode.Attributes["name"].Value; string hidden = fNode.Attributes["hidden"].Value; lasttopicid = int.Parse(fNode.Attributes["lasttopicid"].Value); lastreplyid = int.Parse(fNode.Attributes["lastreplyid"].Value); fid = int.Parse(fNode.Attributes["forumid"].Value); //TODO: Validate can view //sForum = sForum.Replace("[FORUMNAME]", "<af:link id=""hypForumName" & fid & """ navigateurl=""" & Utilities.NavigateUrl(PageId, "", New String() {ParamKeys.ViewType & "=" & Views.Topics, ParamKeys.ForumId & "=" & fid}) & """ text=""" & forumname & """ runat=""server"" />") 'GetForumLink(forumname, PageId, True)) sForum = sForum.Replace("[FORUMNAME]", "<af:link id=\"hypForumName" + fid + "\" navigateurl=\"" + URL.ForForum(PageId, fid, string.Empty, forumname) + "\" text=\"" + forumname + "\" runat=\"server\" />"); //GetForumLink(forumname, PageId, True)) sForum = sForum.Replace("[FORUMNAMENOLINK]", forumname); sForum = sForum.Replace("[FORUMDESCRIPTION]", fNode.Attributes["desc"].Value); sForum = sForum.Replace("[TOTALTOPICS]", fNode.Attributes["totaltopics"].Value); sForum = sForum.Replace("[TOTALREPLIES]", fNode.Attributes["totalreplies"].Value); sForum = sForum.Replace("[DISPLAYNAME]", "<i class=\"fa fa-user fa-fw fa-blue\"></i> " + fNode.Attributes["lastpostauthorname"].Value); sForum = sForum.Replace("[LASTPOST]", "<asp:placeholder id=\"plhLastPost" + fid + "\" runat=\"server\">"); sForum = sForum.Replace("[/LASTPOST]", "</asp:placeholder>"); int intLength = 0; if ((sForum.IndexOf("[LASTPOSTSUBJECT:", 0) + 1) > 0) { int inStart = (sForum.IndexOf("[LASTPOSTSUBJECT:", 0) + 1) + 17; int inEnd = (sForum.IndexOf("]", inStart - 1) + 1); string sLength = sForum.Substring(inStart - 1, inEnd - inStart); intLength = Convert.ToInt32(sLength); } string ReplaceTag = "[LASTPOSTSUBJECT:" + intLength.ToString() + "]"; string sSubject = fNode.Attributes["lastpostsubject"].Value; if (lastreplyid == 0) { lastreplyid = lasttopicid; } sSubject = GetLastPostSubject(lastreplyid, lasttopicid, fid, sSubject, intLength); sForum = sForum.Replace(ReplaceTag, sSubject); if (sSubject == string.Empty) { sForum = sForum.Replace("[RESX:BY]", string.Empty); sForum = sForum.Replace("[LASTPOSTDATE]", string.Empty); } else { sForum = sForum.Replace("[LASTPOSTDATE]", lastpostdate); } //TODO: Properly check "canview" string sIcon = TemplateUtils.ShowIcon(true, fid, UserId, DateTime.Parse(lastpostdate), lastReadDate, lastreplyid); string sIconImage = "<img alt=\"" + forumname + "\" src=\"" + ThemePath + "images/" + sIcon + "\" />"; //sForum = sForum.Replace("[FORUMICON]", sIconImage); sForum = sForum.Replace("[FORUMICON]", "<div style=\"height:30px;margin=right:10px;\"><i class=\"fa fa-folder fa-2x fa-blue\"></i></div>"); sForum = sForum.Replace("[CSS:FORUMICON]", "affoldernorm"); sForum = sForum.Replace("[CSS:FORUMICONSM]", "affoldersmnorm"); //sForum = sForum.Replace("[FORUMICONSM]", sIconImage.Replace("folder", "folder16")); sForum = sForum.Replace("[FORUMICONSM]", ""); var xNodeList = ForumData.SelectNodes("//forums/forum[@active='true' and @parentforumid='" + fid + "']"); string sSubs = string.Empty; if (xNodeList.Count > 0) { string sTemplate = TemplateUtils.GetTemplateSection(Template, "[SUBFORUMS]", "[/SUBFORUMS]"); foreach (XmlNode n in xNodeList) { sSubs += ParseForumRow(n, sTemplate, GroupName); } } sForum = TemplateUtils.ReplaceSubSection(sForum, sSubs, "[SUBFORUMS]", "[/SUBFORUMS]"); string fc = "<af:forumrow id=\"ctlFR" + fid + "\" Hidden=\"" + hidden + "\" ForumId=\"" + fid + "\" ReadRoles=\"" + readRoles + "\" ViewRoles=\"" + viewRoles + "\" runat=\"server\">"; fc += "<content>" + sForum + "</content>"; fc += "</af:forumrow>"; return(fc); }
void ParseInternal() { try { this.mainBlock = new BlockNode(null); this.stack = new Stack <BlockNode>(); this.errors = new List <TemplateError>(); PushBlock(mainBlock); var matches = TemplateUtils.KeywordsRegex.Matches(text); if (matches.Count == 0) { stack.Peek().Nodes.Add(new LiteralNode(text)); stack.Pop(); return; } int index = 0; foreach (Match match in matches.Cast <Match>()) { if (index < match.Index) { stack.Peek().Nodes.Add(new LiteralNode(text.Substring(index, match.Index - index))); } var expr = match.Groups["expr"].Value; var keyword = match.Groups["keyword"].Value; var variable = match.Groups["dec"].Value; switch (keyword) { case "": case "raw": var s = TemplateUtils.SplitToken(expr); if (s == null) { AddError(true, "{0} has invalid format".FormatWith(expr)); } else { var t = ValueProviderBase.TryParse(s.Value.Token, variable, this); stack.Peek().Nodes.Add(new ValueNode(t, s.Value.Format, isRaw: keyword.Contains("raw"))); DeclareVariable(t); } break; case "declare": { var t = ValueProviderBase.TryParse(expr, variable, this); stack.Peek().Nodes.Add(new DeclareNode(t, this.AddError)); DeclareVariable(t); } break; case "any": { ConditionBase cond = TemplateUtils.ParseCondition(expr, variable, this); AnyNode any = new AnyNode(cond); stack.Peek().Nodes.Add(any); PushBlock(any.AnyBlock); if (cond is ConditionCompare cc) { DeclareVariable(cc.ValueProvider); } break; } case "notany": { var an = (AnyNode?)PopBlock(typeof(AnyNode))?.owner; if (an != null) { PushBlock(an.CreateNotAny()); } break; } case "endany": { PopBlock(typeof(AnyNode)); break; } case "foreach": { ValueProviderBase?vp = ValueProviderBase.TryParse(expr, variable, this); if (vp is TokenValueProvider tvp && tvp.ParsedToken.QueryToken != null && QueryToken.IsCollection(tvp.ParsedToken.QueryToken.Type)) { AddError(false, $"@foreach[{expr}] is a collection, missing 'Element' token at the end"); } var fn = new ForeachNode(vp); stack.Peek().Nodes.Add(fn); PushBlock(fn.Block); if (vp != null) { vp.IsForeach = true; } DeclareVariable(vp); break; } case "endforeach": { PopBlock(typeof(ForeachNode)); } break; case "if": { ConditionBase cond = TemplateUtils.ParseCondition(expr, variable, this); IfNode ifn = new IfNode(cond, this); stack.Peek().Nodes.Add(ifn); PushBlock(ifn.IfBlock); if (cond is ConditionCompare cc) { DeclareVariable(cc.ValueProvider); } break; } case "else": { var ifn = (IfNode?)PopBlock(typeof(IfNode))?.owner; if (ifn != null) { PushBlock(ifn.CreateElse()); } break; } case "endif": { PopBlock(typeof(IfNode)); break; } default: AddError(true, "'{0}' is deprecated".FormatWith(keyword)); break; } index = match.Index + match.Length; } if (stack.Count != 1) { AddError(true, "Last block is not closed: {0}".FormatWith(stack.Peek())); } var lastM = matches.Cast <Match>().LastOrDefault(); if (lastM != null && lastM.Index + lastM.Length < text.Length) { stack.Peek().Nodes.Add(new LiteralNode(text.Substring(lastM.Index + lastM.Length))); } stack.Pop(); } catch (Exception e) { AddError(true, e.Message); } }
protected override void OnLoad(EventArgs e) { base.OnLoad(e); string sTemplate = string.Empty; if (System.IO.File.Exists(Server.MapPath(ImagePath + "/_userprofile.txt"))) { sTemplate = Utilities.GetFileContent(Server.MapPath(ImagePath + "/_userprofile.txt")); } else { sTemplate = Utilities.GetFileContent(Server.MapPath("~/DesktopModules/ActiveForums/config/templates/_userprofile.txt")); } sTemplate = Utilities.ParseSpacer(sTemplate); if (ProfileMode == ProfileModes.Edit) { sTemplate = "<%@ Register TagPrefix=\"dnn\" Assembly=\"DotNetNuke\" Namespace=\"DotNetNuke.UI.WebControls\"%>" + sTemplate; } Literal lit = new Literal(); UserController upc = new UserController(); User up = upc.GetUser(PortalId, ModuleId, UID); ForumController fc = new ForumController(); up.UserForums = fc.GetForumsForUser(up.UserRoles, PortalId, ForumModuleId, "CanRead"); sTemplate = TemplateUtils.ParseProfileTemplate(sTemplate, up, PortalId, ModuleId, ImagePath, CurrentUserType, UserInfo.UserID, TimeZoneOffset); sTemplate = RenderModals(sTemplate); sTemplate = sTemplate.Replace("[AM:CONTROLS:AdminProfileSettings]", "<asp:placeholder id=\"plhProfileAdminSettings\" runat=\"server\" />"); sTemplate = sTemplate.Replace("[AM:CONTROLS:ProfileMyPreferences]", "<asp:placeholder id=\"plhProfilePrefs\" runat=\"server\" />"); sTemplate = sTemplate.Replace("[AM:CONTROLS:ProfileUserAccount]", "<asp:placeholder id=\"plhProfileUserAccount\" runat=\"server\" />"); sTemplate = sTemplate.Replace("[AM:CONTROLS:ProfileForumTracker]", "<asp:placeholder id=\"plhTracker\" runat=\"server\" />"); sTemplate = sTemplate.Replace("[AF:PROFILE:VIEWUSERPOSTS]", "<a href=\"" + NavigateUrl(TabId, "", ParamKeys.ViewType + "=search&uid=" + UID.ToString()) + "\">[RESX:ViewPostsByUser]</a>"); sTemplate = GetTabsSection(sTemplate); Control ctl = this.ParseControl(sTemplate); this.Controls.Add(ctl); while (!(ctl.Controls.Count == 0)) { this.Controls.Add(ctl.Controls[0]); } //Begin Load Tab Control plhTabs = (PlaceHolder)(this.FindControl("plhTabs")); if (plhTabs != null & amTabs != null) { plhTabs.Controls.Add(amTabs); } LinkControls(Controls); if (plhProfileEditButton != null) { btnProfileEdit = new ImageButton(); btnProfileEdit.ID = "btnProfileEdit"; btnProfileEdit.CssClass = "amimagebutton"; btnProfileEdit.PostBack = true; btnProfileEdit.Height = 50; btnProfileEdit.Width = 50; btnProfileEdit.ImageLocation = "TOP"; btnProfileEdit.Text = "[RESX:Button:Edit]"; btnProfileEdit.ImageUrl = "~/DesktopModules/ActiveForums/images/edit32.png"; btnProfileEdit.Visible = false; plhProfileEditButton.Controls.Add(btnProfileEdit); } if (plhProfileCancelButton != null) { btnProfileCancel = new ImageButton(); btnProfileCancel.ID = "btnProfileCancel"; btnProfileCancel.CssClass = "amimagebutton"; btnProfileCancel.PostBack = true; btnProfileCancel.Height = 50; btnProfileCancel.Width = 50; btnProfileCancel.ImageLocation = "TOP"; btnProfileCancel.Text = "[RESX:Button:Cancel]"; btnProfileCancel.ImageUrl = "~/DesktopModules/ActiveForums/images/cancel32.png"; btnProfileCancel.Visible = false; plhProfileCancelButton.Controls.Add(btnProfileCancel); } if (plhProfileSaveButton != null) { btnProfileSave = new ImageButton(); btnProfileSave.ID = "btnProfileSave"; btnProfileSave.CssClass = "amimagebutton"; btnProfileSave.PostBack = true; btnProfileSave.Height = 50; btnProfileSave.Width = 50; btnProfileSave.ImageLocation = "TOP"; btnProfileSave.Text = "[RESX:Button:Save]"; btnProfileSave.ImageUrl = "~/DesktopModules/ActiveForums/images/save32.png"; btnProfileSave.Visible = false; plhProfileSaveButton.Controls.Add(btnProfileSave); } if (plhProfileAdminSettings != null) { ProfileBase tmpCtl = (ProfileBase)(this.LoadControl("~/DesktopModules/ActiveForums/controls/profile_adminsettings.ascx")); tmpCtl.ModuleConfiguration = this.ModuleConfiguration; tmpCtl.UserProfile = up.Profile; plhProfileAdminSettings.Controls.Add(tmpCtl); } if (plhProfilePrefs != null) { ProfileBase tmpCtl = (ProfileBase)(this.LoadControl("~/DesktopModules/ActiveForums/controls/profile_mypreferences.ascx")); tmpCtl.ModuleConfiguration = this.ModuleConfiguration; tmpCtl.UserProfile = up.Profile; plhProfilePrefs.Controls.Add(tmpCtl); } if (plhProfileUserAccount != null) { ProfileBase tmpCtl = (ProfileBase)(this.LoadControl("~/DesktopModules/ActiveForums/controls/profile_useraccount.ascx")); tmpCtl.ModuleConfiguration = this.ModuleConfiguration; tmpCtl.UserProfile = up.Profile; plhProfileUserAccount.Controls.Add(tmpCtl); } if (plhTracker != null) { ForumView ctlForums = new ForumView(); ctlForums.ModuleConfiguration = this.ModuleConfiguration; ctlForums.DisplayTemplate = DataCache.GetTemplate("ForumTracking.txt"); ctlForums.CurrentUserId = UID; ctlForums.ForumIds = up.UserForums; plhTracker.Controls.Add(ctlForums); } if (btnProfileEdit != null) { if (!(CurrentUserType == CurrentUserTypes.Anon) && (UID == this.UserId || (CurrentUserType == CurrentUserTypes.Admin || CurrentUserType == CurrentUserTypes.Admin || CurrentUserType == CurrentUserTypes.SuperUser))) { if (ProfileMode == ProfileModes.View) { btnProfileEdit.Visible = true; btnProfileCancel.Visible = false; btnProfileSave.Visible = false; } else { btnProfileEdit.Visible = false; btnProfileCancel.Visible = true; btnProfileSave.Visible = true; } } } }
public string Render() { if (string.IsNullOrEmpty(Template)) { return("Please specify a template"); } StringBuilder sb = new StringBuilder(); Data.ForumsDB fdb = new Data.ForumsDB(); ForumCollection allForums = fdb.Forums_List(PortalId, ModuleId); ForumCollection filteredForums = new ForumCollection(); foreach (Forum f in allForums) { if (f.ForumGroup.Active && f.Active && f.ParentForumId == 0) { if (Permissions.HasPerm(f.Security.View, ForumUser.UserRoles)) { f.TabId = TabId; f.SubForums = GetSubForums(allForums, f.ForumID); filteredForums.Add(f); } } } string groupTemplate = TemplateUtils.GetTemplateSection(Template, "[AF:DIR:FORUMGROUP]", "[/AF:DIR:FORUMGROUP]"); string forumTemplate = TemplateUtils.GetTemplateSection(Template, "[AF:DIR:FORUM]", "[/AF:DIR:FORUM]"); string subForumTemplate = TemplateUtils.GetTemplateSection(Template, "[AF:DIR:SUBFORUM]", "[/AF:DIR:SUBFORUM]"); int currGroup = -1; string gtmp = string.Empty; string ftmp = string.Empty; string subtmp = string.Empty; StringBuilder list = new StringBuilder(); bool inprogress = false; foreach (Forum f in filteredForums) { if (currGroup != f.ForumGroupId) { if (!(string.IsNullOrEmpty(gtmp))) { gtmp = gtmp.Replace("[FORUMHOLDER]", string.Empty); list.Append(gtmp); } gtmp = groupTemplate; gtmp = TemplateUtils.ReplaceSubSection(gtmp, "[FORUMHOLDER]", "[AF:DIR:FORUM]", "[/AF:DIR:FORUM]"); gtmp = ParseForumGroup(f.ForumGroup, gtmp); ftmp = forumTemplate; ftmp = TemplateUtils.ReplaceSubSection(ftmp, "[SUBFORUMHOLDER]", "[AF:DIR:SUBFORUM]", "[/AF:DIR:SUBFORUM]"); subtmp = subForumTemplate; currGroup = f.ForumGroupId; } string forums = ParseForum(f, ftmp); if (f.SubForums != null) { foreach (Forum s in f.SubForums) { forums = forums.Replace("[SUBFORUMHOLDER]", ParseForum(s, subtmp) + "[SUBFORUMHOLDER]"); } } forums = forums.Replace("[SUBFORUMHOLDER]", string.Empty); gtmp = gtmp.Replace("[FORUMHOLDER]", forums + "[FORUMHOLDER]"); } gtmp = gtmp.Replace("[FORUMHOLDER]", string.Empty); list.Append(gtmp); Template = TemplateUtils.ReplaceSubSection(Template, list.ToString(), "[AF:DIR:FORUMGROUP]", "[/AF:DIR:FORUMGROUP]"); return(Template); }
private string RenderModals(string Template) { string sOut = Template; //[AM:CONTROLS:MODAL:MyPreferences:Private] string pattern = "(\\[AM:CONTROLS:MODAL:(.+?)\\])"; Regex regExp = new Regex(pattern); MatchCollection matches = null; matches = regExp.Matches(sOut); bool bAddModal = false; foreach (Match match in matches) { string matchValue = match.Groups[2].Value; if (matchValue.Contains(":")) { string sec = matchValue.Split(':')[1].ToLowerInvariant(); switch (sec.ToLowerInvariant()) { case "anon": bAddModal = true; break; case "private": if (!(CurrentUserType == CurrentUserTypes.Anon)) { if (UserId == UID || (CurrentUserType == CurrentUserTypes.Admin || CurrentUserType == CurrentUserTypes.SuperUser)) { bAddModal = true; } } break; case "auth": if (!(CurrentUserType == CurrentUserTypes.Anon)) { bAddModal = true; } break; case "forummod": if (!(CurrentUserType == CurrentUserTypes.Anon) && !(CurrentUserType == CurrentUserTypes.Auth)) { bAddModal = true; } break; case "admin": if (CurrentUserType == CurrentUserTypes.Admin || CurrentUserType == CurrentUserTypes.SuperUser) { bAddModal = true; } break; case "superuser": if (CurrentUserType == CurrentUserTypes.SuperUser) { bAddModal = true; } break; default: bAddModal = UserInfo.IsInRole(sec); break; } matchValue = matchValue.Split(':')[0]; } else { bAddModal = true; } if (bAddModal == true) { string sModalDivId = "afmodal" + matchValue; string sModalText = "[RESX:Label:" + matchValue + "]"; string sModalContent = string.Empty; Template = Template.Replace(match.Value, "<a href=\"javascript:void(0);\" onclick=\"amOpenModal('" + sModalDivId + "','" + sModalText + "',350, 300);\">" + sModalText + "</a>" + match.Value); if (sOut.Contains(match.Value.Replace("[AM", "[/AM"))) { string tmp = TemplateUtils.GetTemplateSection(sOut, match.Value, match.Value.Replace("[AM", "[/AM")); sModalContent = "<div id=\"" + sModalDivId + "\" style=\"display:none;\">" + tmp + "</div>"; } Template = TemplateUtils.ReplaceSubSection(Template, string.Empty, match.Value, match.Value.Replace("[AM", "[/AM")); Template = Template + sModalContent; } } return(Template); }
protected internal override void RenderTemplate(ScopedDictionary <string, ValueProviderBase> variables) { var str = "@" + this.ValueProvider.ToString(variables, Format.HasText() ? (":" + TemplateUtils.ScapeColon(Format)) : null); this.ReplaceBy(this.NodeProvider.NewRun((OpenXmlCompositeElement?)this.RunProperties?.CloneNode(true), str)); }
private string GetTabsSection(string Template) { string sOut = string.Empty; sOut = TemplateUtils.GetTemplateSection(Template, "[AM:CONTROLS:TABS]", "[/AM:CONTROLS:TABS]"); string pattern = "(\\[AM:CONTROLS:TAB:(.+?)\\])"; Regex regExp = new Regex(pattern); MatchCollection matches = null; matches = regExp.Matches(sOut); amTabs = new DotNetNuke.Modules.ActiveForums.Controls.ActiveTabs(); foreach (Match match in matches) { bool bAddTab = false; string matchValue = match.Groups[2].Value; CurrentUserTypes access = CurrentUserTypes.Anon; if (matchValue.Contains(":")) { string sec = matchValue.Split(':')[1].ToLowerInvariant(); if (sec == "private") { if (!(CurrentUserType == CurrentUserTypes.Anon)) { if (UserId == UID || (CurrentUserType == CurrentUserTypes.Admin || CurrentUserType == CurrentUserTypes.SuperUser)) { bAddTab = true; access = CurrentUserTypes.Admin; } } } else { switch (sec) { case "auth": access = CurrentUserTypes.Auth; break; case "forummod": access = CurrentUserTypes.ForumMod; break; case "admin": access = CurrentUserTypes.Admin; break; case "superuser": access = CurrentUserTypes.SuperUser; break; } switch (access) { case CurrentUserTypes.Anon: bAddTab = true; break; case CurrentUserTypes.Auth: if (!(CurrentUserType == CurrentUserTypes.Anon)) { bAddTab = true; } break; case CurrentUserTypes.ForumMod: if (!(CurrentUserType == CurrentUserTypes.Anon) && !(CurrentUserType == CurrentUserTypes.Auth)) { bAddTab = true; } break; case CurrentUserTypes.Admin: if (CurrentUserType == CurrentUserTypes.Admin || CurrentUserType == CurrentUserTypes.SuperUser) { bAddTab = true; } break; case CurrentUserTypes.SuperUser: if (CurrentUserType == CurrentUserTypes.SuperUser) { bAddTab = true; } break; } } matchValue = matchValue.Split(':')[0]; } else { bAddTab = true; } if (bAddTab) { DotNetNuke.Modules.ActiveForums.Controls.Tab tb = new DotNetNuke.Modules.ActiveForums.Controls.Tab(); tb.ControlKey = matchValue; tb.Text = "[RESX:Label:" + matchValue + "]"; if (sOut.Contains(match.Value.Replace("[AM", "[/AM"))) { DotNetNuke.Modules.ActiveForums.Controls.TabContent tbc = new DotNetNuke.Modules.ActiveForums.Controls.TabContent(); string tmp = TemplateUtils.GetTemplateSection(sOut, match.Value, match.Value.Replace("[AM", "[/AM")); if (tmp.Contains("<dnn:")) { tmp = "<%@ Register TagPrefix=\"dnn\" Assembly=\"DotNetNuke\" Namespace=\"DotNetNuke.UI.WebControls\"%>" + tmp; } if (tmp.Contains("<social:")) { tmp = Globals.SocialRegisterTag + tmp; } Control ctl = this.ParseControl(tmp); tbc.Controls.Add(ctl); tb.Content = tbc; } amTabs.Tabs.Add(tb); } } Template = TemplateUtils.ReplaceSubSection(Template, "<asp:placeholder id=\"plhTabs\" runat=\"server\" />", "[AM:CONTROLS:TABS]", "[/AM:CONTROLS:TABS]"); return(Template); }
private string ProcessFileTemplate(string args) { Int32 eolMode = (Int32)MainForm.Settings.EOLMode; String lineBreak = LineEndDetector.GetNewLineMarker(eolMode); List <String> imports = new List <string>(); string extends = ""; string implements = ""; string access = ""; string inheritedMethods = ""; string paramString = ""; string superConstructor = ""; string classMetadata = ""; int index; // resolve imports if (lastFileOptions.interfaces != null && lastFileOptions.interfaces.Count > 0) { string implementContinuation; implements = " implements "; index = 0; if (lastFileOptions.Language == "haxe") { bool isHaxe2 = PluginBase.CurrentSDK != null && PluginBase.CurrentSDK.Name.ToLower().Contains("haxe 2"); implementContinuation = isHaxe2 ? ", implements " : " implements "; } else { implementContinuation = ", "; } foreach (string item in lastFileOptions.interfaces) { if (item.Contains('.')) { imports.Add(item); } implements += (index > 0 ? implementContinuation : "") + item.Split('.').Last(); if (lastFileOptions.createInheritedMethods) { processOnSwitch = lastFileFromTemplate; // let ASCompletion generate the implementations when file is opened } index++; } } if (lastFileOptions.superClass != "") { var superClassFullName = lastFileOptions.superClass; if (superClassFullName.Contains(".")) { imports.Add(superClassFullName); } var superClassShortName = superClassFullName.Split('.').Last(); var fileName = Path.GetFileNameWithoutExtension(lastFileFromTemplate); extends = fileName == superClassShortName ? $" extends {superClassFullName}" : $" extends {superClassShortName}"; processContext = ASContext.GetLanguageContext(lastFileOptions.Language); if (lastFileOptions.createConstructor && processContext != null && constructorArgs == null) { var lastDotIndex = superClassFullName.LastIndexOf('.'); var cmodel = processContext.GetModel(lastDotIndex < 0 ? "" : superClassFullName.Substring(0, lastDotIndex), superClassShortName, ""); if (!cmodel.IsVoid()) { if ((cmodel.Flags & FlagType.TypeDef) != 0) { var tmp = cmodel; while (!tmp.IsVoid()) { if (!string.IsNullOrEmpty(tmp.Constructor)) { cmodel = tmp; break; } tmp.ResolveExtends(); tmp = tmp.Extends; } } foreach (MemberModel member in cmodel.Members) { if (member.Name == cmodel.Constructor) { paramString = member.ParametersString(); AddImports(imports, member, cmodel); superConstructor = "super("; index = 0; if (member.Parameters != null) { foreach (MemberModel param in member.Parameters) { if (param.Name.StartsWith('.')) { break; } var pname = TemplateUtils.GetParamName(param); superConstructor += (index > 0 ? ", " : "") + pname; index++; } } superConstructor += ");\n" + (lastFileOptions.Language == "as3" ? "\t\t\t" : "\t\t"); break; } } } } processContext = null; } if (constructorArgs != null) { paramString = constructorArgs; foreach (String type in constructorArgTypes) { if (!imports.Contains(type)) { imports.Add(type); } } } if (lastFileOptions.Language == "as3") { access = lastFileOptions.isPublic ? "public " : "internal "; access += lastFileOptions.isDynamic ? "dynamic " : ""; access += lastFileOptions.isFinal ? "final " : ""; } else if (lastFileOptions.Language == "haxe") { access = lastFileOptions.isPublic ? "public " : "private "; access += lastFileOptions.isDynamic ? "dynamic " : ""; if (lastFileOptions.isFinal) { classMetadata += "@:final\n"; } } else { access = lastFileOptions.isDynamic ? "dynamic " : ""; } string importsSrc = ""; string prevImport = null; imports.Sort(); foreach (string import in imports) { if (prevImport != import) { prevImport = import; if (import.LastIndexOf('.') == -1) { continue; } if (import.Substring(0, import.LastIndexOf('.')) == lastFileOptions.Package) { continue; } importsSrc += (lastFileOptions.Language == "as3" ? "\t" : "") + "import " + import + ";" + lineBreak; } } if (importsSrc.Length > 0) { importsSrc += (lastFileOptions.Language == "as3" ? "\t" : "") + lineBreak; } args = args.Replace("$(Import)", importsSrc); args = args.Replace("$(Extends)", extends); args = args.Replace("$(Implements)", implements); args = args.Replace("$(Access)", access); args = args.Replace("$(InheritedMethods)", inheritedMethods); args = args.Replace("$(ConstructorArguments)", paramString); args = args.Replace("$(Super)", superConstructor); args = args.Replace("$(ClassMetadata)", classMetadata); return(args); }
public void CreateNodes() { foreach (var root in document.AllRootElements()) { var lists = root.Descendants <MatchNode>().ToList(); foreach (var matchNode in lists) { var m = matchNode.Match; var type = m.Groups["type"].Value; var token = m.Groups["token"].Value; var keyword = m.Groups["keyword"].Value; var dec = m.Groups["dec"].Value; switch (keyword) { case "": var s = TemplateUtils.SplitToken(token); if (s == null) { AddError(true, "{0} has invalid format".FormatWith(token)); } else { var vp = TryParseValueProvider(type, s.Value.Token, dec); matchNode.Parent.ReplaceChild(new TokenNode(matchNode.NodeProvider, vp, s.Value.Format) { RunProperties = (OpenXmlCompositeElement)matchNode.RunProperties?.CloneNode(true) }, matchNode); DeclareVariable(vp); } break; case "declare": { var vp = TryParseValueProvider(type, token, dec); matchNode.Parent.ReplaceChild(new DeclareNode(matchNode.NodeProvider, vp, this.AddError) { RunProperties = (OpenXmlCompositeElement)matchNode.RunProperties?.CloneNode(true) }, matchNode); DeclareVariable(vp); } break; case "any": { AnyNode any; ValueProviderBase vp; var filter = TemplateUtils.TokenOperationValueRegex.Match(token); if (!filter.Success) { vp = TryParseValueProvider(type, token, dec); any = new AnyNode(matchNode.NodeProvider, vp) { AnyToken = new MatchNodePair(matchNode) }; } else { vp = TryParseValueProvider(type, filter.Groups["token"].Value, dec); var comparer = filter.Groups["comparer"].Value; var value = filter.Groups["value"].Value; any = new AnyNode(matchNode.NodeProvider, vp, comparer, value, this.AddError) { AnyToken = new MatchNodePair(matchNode) }; } PushBlock(any); DeclareVariable(vp); break; } case "notany": { var an = PeekBlock <AnyNode>(); if (an != null) { an.NotAnyToken = new MatchNodePair(matchNode); } break; } case "endany": { var an = PopBlock <AnyNode>(); if (an != null) { an.EndAnyToken = new MatchNodePair(matchNode); an.ReplaceBlock(); } break; } case "if": { IfNode ifn; ValueProviderBase vpb; var filter = TemplateUtils.TokenOperationValueRegex.Match(token); if (!filter.Success) { vpb = TryParseValueProvider(type, token, dec); ifn = new IfNode(matchNode.NodeProvider, vpb) { IfToken = new MatchNodePair(matchNode) }; } else { vpb = TryParseValueProvider(type, filter.Groups["token"].Value, dec); var comparer = filter.Groups["comparer"].Value; var value = filter.Groups["value"].Value; ifn = new IfNode(matchNode.NodeProvider, vpb, comparer, value, this.AddError) { IfToken = new MatchNodePair(matchNode) }; } PushBlock(ifn); DeclareVariable(vpb); break; } case "else": { var an = PeekBlock <IfNode>(); if (an != null) { an.ElseToken = new MatchNodePair(matchNode); } break; } case "endif": { var ifn = PopBlock <IfNode>(); if (ifn != null) { ifn.EndIfToken = new MatchNodePair(matchNode); ifn.ReplaceBlock(); } break; } case "foreach": { var vp = TryParseValueProvider(type, token, dec); var fn = new ForeachNode(matchNode.NodeProvider, vp) { ForeachToken = new MatchNodePair(matchNode) }; PushBlock(fn); DeclareVariable(vp); break; } case "endforeach": { var fn = PopBlock <ForeachNode>(); if (fn != null) { fn.EndForeachToken = new MatchNodePair(matchNode); fn.ReplaceBlock(); } break; } default: AddError(true, "'{0}' is deprecated".FormatWith(keyword)); break; } } } }