private void LoadSettings() { pageId = WebUtils.ParseInt32FromQueryString("pageid", pageId); moduleId = WebUtils.ParseInt32FromQueryString("mid", moduleId); itemId = WebUtils.ParseInt32FromQueryString("ItemID", itemId); commentGuid = WebUtils.ParseGuidFromQueryString("c", commentGuid); if (commentGuid == Guid.Empty) { return; } blog = new Blog(itemId); module = GetModule(moduleId, Blog.FeatureGuid); commentRepository = new CommentRepository(); if (blog.ModuleId != module.ModuleId) { blog = null; module = null; return; } comment = commentRepository.Fetch(commentGuid); if ((comment.ContentGuid != blog.BlogGuid)||(comment.ModuleGuid != module.ModuleGuid)) { blog = null; module = null; return; } moduleSettings = ModuleSettings.GetModuleSettings(moduleId); config = new BlogConfiguration(moduleSettings); currentUser = SiteUtils.GetCurrentSiteUser(); userCanEdit = UserCanEditComment(); commentEditor.SiteGuid = CurrentSite.SiteGuid; commentEditor.SiteId = CurrentSite.SiteId; commentEditor.SiteRoot = SiteRoot; commentEditor.CommentsClosed = false; //commentEditor.CommentUrl = Request.RawUrl; commentEditor.ContentGuid = blog.BlogGuid; //commentEditor.DefaultCommentTitle = defaultCommentTitle; commentEditor.FeatureGuid = Blog.FeatureGuid; commentEditor.ModuleGuid = module.ModuleGuid; //commentEditor.NotificationAddresses = notificationAddresses; //commentEditor.NotificationTemplateName = notificationTemplateName; commentEditor.RequireCaptcha = false; commentEditor.UserCanModerate = userCanEdit; //commentEditor.Visible = !commentsClosed; commentEditor.CurrentUser = currentUser; commentEditor.UserComment = comment; commentEditor.ShowRememberMe = false; //commentEditor.IncludeIpAddressInNotification = includeIpAddressInNotification; //commentEditor.ContainerControl = this; }
private void PopulateControls() { if (moduleId == -1) { return; } if (itemId == -1) { return; } //if (module == null) { return; } if (historyGuid == Guid.Empty) { return; } Blog blog = new Blog(itemId); if (blog.ModuleId != moduleId) { SiteUtils.RedirectToAccessDeniedPage(this); return; } ContentHistory history = new ContentHistory(historyGuid); if (history.ContentGuid != blog.BlogGuid) { return; } litCurrentHeading.Text = string.Format(BlogResources.CurrentVersionHeadingFormat, DateTimeHelper.Format(blog.LastModUtc, timeZone, "g", timeOffset)); if (BlogConfiguration.UseHtmlDiff) { HtmlDiff diffHelper = new HtmlDiff(history.ContentText, blog.Description); litCurrentVersion.Text = diffHelper.Build(); } else { litCurrentVersion.Text = blog.Description; } litHistoryHead.Text = string.Format(BlogResources.VersionAsOfHeadingFormat, DateTimeHelper.Format(history.CreatedUtc, timeZone, "g", timeOffset)); litHistoryVersion.Text = history.ContentText; string onClick = "top.window.LoadHistoryInEditor('" + historyGuid.ToString() + "'); return false;"; btnRestore.Attributes.Add("onclick", onClick); }
private void Save() { if (blog == null) { blog = new Blog(itemId); if ((blog.ItemId > -1) && (blog.ModuleId != moduleId)) { SiteUtils.RedirectToAccessDeniedPage(this); return; } } Module module = GetModule(moduleId, Blog.FeatureGuid); if (module == null) { return; } if (currentUser == null) { return; } blog.UserGuid = currentUser.UserGuid; blog.LastModUserGuid = currentUser.UserGuid; blog.ContentChanged += new ContentChangedEventHandler(blog_ContentChanged); blog.ModuleId = moduleId; blog.ModuleGuid = module.ModuleGuid; DateTime localTime = DateTime.Parse(dpBeginDate.Text); if (timeZone != null) { blog.StartDate = localTime.ToUtc(timeZone); } else { blog.StartDate = localTime.AddHours(-timeOffset); } if (dpEndDate.Text.Length == 0) { blog.EndDate = DateTime.MaxValue; } else { DateTime localEndTime = DateTime.Parse(dpEndDate.Text); if (timeZone != null) { blog.EndDate = localEndTime.ToUtc(timeZone); } else { blog.EndDate = localEndTime.AddHours(-timeOffset); } } blog.Title = txtTitle.Text; blog.SubTitle = txtSubTitle.Text; blog.Location = txtLocation.Text; blog.Description = edContent.Text; blog.Excerpt = edExcerpt.Text; blog.UserName = Context.User.Identity.Name; blog.IncludeInFeed = this.chkIncludeInFeed.Checked; blog.IsPublished = chkIsPublished.Checked; int allowComentsForDays = -1; int.TryParse(ddCommentAllowedForDays.SelectedValue, out allowComentsForDays); blog.AllowCommentsForDays = allowComentsForDays; blog.MetaDescription = txtMetaDescription.Text; blog.MetaKeywords = txtMetaKeywords.Text; blog.ShowDownloadLink = chkShowDownloadLink.Checked; blog.UseBingMap = chkUseBing.Checked; blog.MapType = ((GMapTypeSetting)MapTypeControl).GetValue(); int mapZoom = 13; int.TryParse(((GMapZoomLevelSetting)ZoomLevelControl).GetValue(), out mapZoom); blog.MapZoom = mapZoom; blog.MapHeight = txtMapHeight.Text; blog.MapWidth = txtMapWidth.Text; blog.ShowMapOptions = chkShowMapOptions.Checked; blog.ShowZoomTool = chkShowMapZoom.Checked; blog.ShowLocationInfo = chkShowMapBalloon.Checked; blog.UseDrivingDirections = chkShowMapDirections.Checked; blog.IncludeInSearch = chkIncludeInSearchIndex.Checked; blog.ExcludeFromRecentContent = chkExcludeFromRecentContent.Checked; blog.IncludeInSiteMap = chkIncludeInSiteMap.Checked; blog.ShowAuthorName = chkShowAuthorName.Checked; blog.ShowAuthorAvatar = chkShowAuthorAvatar.Checked; blog.ShowAuthorBio = chkShowAuthorBio.Checked; blog.IncludeInNews = chkIncludeInNews.Checked; blog.PubName = txtPublicationName.Text; blog.PubLanguage = txtPubLanguage.Text; blog.PubAccess = config.PublicationAccess; blog.PubGenres = txtPubGenres.Text; blog.PubGeoLocations = txtPubGeoLocations.Text; blog.PubKeyWords = txtPubKeyWords.Text; blog.PubStockTickers = txtPubStockTickers.Text; blog.HeadlineImageUrl = txtHeadlineImage.Text; if (blog.HeadlineImageUrl.Length > 0) { imgPreview.ImageUrl = blog.HeadlineImageUrl; } blog.IncludeImageInExcerpt = chkIncludeImageInExcerpt.Checked; if (txtItemUrl.Text.Length == 0) { txtItemUrl.Text = SuggestUrl(); } String friendlyUrlString = SiteUtils.RemoveInvalidUrlChars(txtItemUrl.Text.Replace("~/", String.Empty)); FriendlyUrl friendlyUrl = new FriendlyUrl(siteSettings.SiteId, friendlyUrlString); if ( ((friendlyUrl.FoundFriendlyUrl) && (friendlyUrl.PageGuid != blog.BlogGuid)) && (blog.ItemUrl != txtItemUrl.Text) ) { lblError.Text = BlogResources.PageUrlInUseBlogErrorMessage; cancelRedirect = true; return; } if (!friendlyUrl.FoundFriendlyUrl) { if (WebPageInfo.IsPhysicalWebPage("~/" + friendlyUrlString)) { lblError.Text = BlogResources.PageUrlInUseBlogErrorMessage; cancelRedirect = true; return; } } string oldUrl = blog.ItemUrl.Replace("~/", string.Empty); string newUrl = SiteUtils.RemoveInvalidUrlChars(txtItemUrl.Text.Replace("~/", string.Empty)); blog.ItemUrl = "~/" + newUrl; if (enableContentVersioning) { blog.CreateHistory(siteSettings.SiteGuid); } blog.Save(); //added by suresh UploadCoverImage(blog.ItemId.ToInvariantString()); //added above by suresh if (!friendlyUrl.FoundFriendlyUrl) { if ((friendlyUrlString.Length > 0)&&(!WebPageInfo.IsPhysicalWebPage("~/" + friendlyUrlString))) { FriendlyUrl newFriendlyUrl = new FriendlyUrl(); newFriendlyUrl.SiteId = siteSettings.SiteId; newFriendlyUrl.SiteGuid = siteSettings.SiteGuid; newFriendlyUrl.PageGuid = blog.BlogGuid; newFriendlyUrl.Url = friendlyUrlString; newFriendlyUrl.RealUrl = "~/Blog/ViewPost.aspx?pageid=" + pageId.ToInvariantString() + "&mid=" + blog.ModuleId.ToInvariantString() + "&ItemID=" + blog.ItemId.ToInvariantString(); newFriendlyUrl.Save(); } //if post was renamed url will change, if url changes we need to redirect from the old url to the new with 301 if ((oldUrl.Length > 0) && (newUrl.Length > 0) && (!SiteUtils.UrlsMatch(oldUrl, newUrl)) && BlogConfiguration.Create301OnPostRename) { //worry about the risk of a redirect loop if the page is restored to the old url again // don't create it if a redirect for the new url exists if ( (!RedirectInfo.Exists(siteSettings.SiteId, oldUrl)) && (!RedirectInfo.Exists(siteSettings.SiteId, newUrl)) ) { RedirectInfo redirect = new RedirectInfo(); redirect.SiteGuid = siteSettings.SiteGuid; redirect.SiteId = siteSettings.SiteId; redirect.OldUrl = oldUrl; redirect.NewUrl = newUrl; redirect.Save(); } // since we have created a redirect we don't need the old friendly url FriendlyUrl oldFriendlyUrl = new FriendlyUrl(siteSettings.SiteId, oldUrl); if ((oldFriendlyUrl.FoundFriendlyUrl) && (oldFriendlyUrl.PageGuid == blog.BlogGuid)) { FriendlyUrl.DeleteUrl(oldFriendlyUrl.UrlId); } } } // new item posted so ping services if ((itemId == -1) && (blog.IsPublished) && (blog.StartDate <= DateTime.UtcNow)) { QueuePings(); } CurrentPage.UpdateLastModifiedTime(); // friendly feed urls are no longer needed since all params have been combined into 1 param // //String blogFriendlyUrl = "blog" + blog.ModuleId.ToInvariantString() + "rss.aspx"; //if (!FriendlyUrl.Exists(siteSettings.SiteId, blogFriendlyUrl)) //{ // FriendlyUrl rssUrl = new FriendlyUrl(); // rssUrl.SiteId = siteSettings.SiteId; // rssUrl.SiteGuid = siteSettings.SiteGuid; // rssUrl.PageGuid = blog.ModuleGuid; // rssUrl.Url = blogFriendlyUrl; // rssUrl.RealUrl = "~/Blog/RSS.aspx?pageid=" + pageId.ToInvariantString() // + "&mid=" + blog.ModuleId.ToInvariantString(); // rssUrl.Save(); //} Blog.DeleteItemCategories(blog.ItemId); // Mono doesn't see this in update panel // so help find it if (chkCategories == null) { log.Error("chkCategories was null"); chkCategories = (CheckBoxList)UpdatePanel1.FindControl("chkCategories"); } foreach (ListItem listItem in this.chkCategories.Items) { if (listItem.Selected) { Int32 categoryId; if (Int32.TryParse(listItem.Value, out categoryId)) { Blog.AddItemCategory(blog.ItemId, categoryId); } } } //CacheHelper.TouchCacheDependencyFile(cacheDependencyKey); CacheHelper.ClearModuleCache(moduleId); SiteUtils.QueueIndexing(); }
private void LoadSettings() { if ((WebUser.IsAdminOrContentAdmin) || (SiteUtils.UserIsSiteEditor())) { isAdmin = true; } txtTitle.MaxLength = BlogConfiguration.PostTitleMaxLength; currentUser = SiteUtils.GetCurrentSiteUser(); ScriptConfig.IncludeColorBox = true; Hashtable moduleSettings = ModuleSettings.GetModuleSettings(moduleId); config = new BlogConfiguration(moduleSettings); useFriendlyUrls = BlogConfiguration.UseFriendlyUrls(moduleId); if (!useFriendlyUrls) { divUrl.Attributes.Add("style", "display:none;"); } lnkCancel.NavigateUrl = SiteUtils.GetCurrentPageUrl(); lnkCancel2.NavigateUrl = lnkCancel.NavigateUrl; lnkCancel3.NavigateUrl = lnkCancel.NavigateUrl; lnkCancel5.NavigateUrl = lnkCancel.NavigateUrl; enableContentVersioning = config.EnableContentVersioning; if ((siteSettings.ForceContentVersioning) || (WebConfigSettings.EnforceContentVersioningGlobally)) { enableContentVersioning = true; } SiteUtils.EnsureFileAttachmentFolder(siteSettings); upLoadPath = SiteUtils.GetFileAttachmentUploadPath(); if (itemId > -1) { blog = new Blog(itemId); if (blog.ModuleId != moduleId) { SiteUtils.RedirectToAccessDeniedPage(this); return; } uploader.MaxFilesAllowed = BlogConfiguration.MaxAttachmentsToUploadAtOnce; //uploader.AcceptFileTypes = SecurityHelper.GetRegexValidationForAllowedExtensionsJqueryFileUploader(WebConfigSettings.AllowedMediaFileExtensions); uploader.UploadButtonClientId = btnUpload.ClientID; uploader.ServiceUrl = SiteRoot + "/Blog/upload.ashx?pageid=" + pageId.ToInvariantString() + "&mid=" + moduleId.ToInvariantString() + "&ItemID=" + itemId.ToInvariantString(); uploader.FormFieldClientId = hdnState.ClientID; // not really used but prevents submitting all the form string refreshFunction = "function refresh" + moduleId.ToInvariantString() + " () { window.location.reload(true); } "; uploader.UploadCompleteCallback = "refresh" + moduleId.ToInvariantString(); ScriptManager.RegisterClientScriptBlock( this, this.GetType(), "refresh" + moduleId.ToInvariantString(), refreshFunction, true); } btnUpload.Enabled = (blog != null); litAttachmentWarning.Visible = (blog == null); pnlMetaData.Visible = (blog != null); divHistoryDelete.Visible = (enableContentVersioning && isAdmin); pnlHistory.Visible = enableContentVersioning; if (enableContentVersioning) { SetupHistoryRestoreScript(); } try { // this keeps the action from changing during ajax postback in folder based sites SiteUtils.SetFormAction(Page, Request.RawUrl); } catch (MissingMethodException) { //this method was introduced in .NET 3.5 SP1 } FileSystemProvider p = FileSystemManager.Providers[WebConfigSettings.FileSystemProvider]; if (p == null) { return; } fileSystem = p.GetFileSystem(); }
/// <summary> /// metaWeblog.editPost method /// </summary> /// <param name="postId"> /// post guid in string format /// </param> /// <param name="userName"> /// login username /// </param> /// <param name="password"> /// login password /// </param> /// <param name="sentPost"> /// struct with post details /// </param> /// <param name="publish"> /// mark as published? /// </param> /// <returns> /// 1 if successful /// </returns> internal bool EditPost(string postId, string userName, string password, MWAPost sentPost, bool publish) { int blogid = Convert.ToInt32(postId); if (!UserCanEditPost(userName, blogid)) { throw new MetaWeblogException("11", MetaweblogResources.AccessDenied); } string author = String.IsNullOrEmpty(sentPost.author) ? userName : sentPost.author; Blog post = new Blog(blogid); if (post.ItemId == -1) { //not found throw new MetaWeblogException("11", MetaweblogResources.PostNotFound); } try { Hashtable moduleSettings = ModuleSettings.GetModuleSettings(post.ModuleId); BlogConfiguration config = new BlogConfiguration(moduleSettings); post.LastModUserGuid = siteUser.UserGuid; post.Title = sentPost.title; post.Description = SiteUtils.ChangeFullyQualifiedLocalUrlsToRelative(navigationSiteRoot, imageSiteRoot, sentPost.description); post.IsPublished = publish; //post.Slug = sentPost.slug; if (!string.IsNullOrEmpty(sentPost.excerpt)) { if (BlogConfiguration.UseExcerptFromMetawblogAsMetaDescription) { post.MetaDescription = UIHelper.CreateExcerpt(sentPost.excerpt, BlogConfiguration.MetaDescriptionMaxLengthToGenerate); } post.Excerpt = SiteUtils.ChangeFullyQualifiedLocalUrlsToRelative(navigationSiteRoot, imageSiteRoot, sentPost.excerpt); } switch (sentPost.commentPolicy) { //closed case "2": post.AllowCommentsForDays = -1; // closed break; // open case "1": // if the post was previously closed to comments // re-open it using the default allowed days if (post.AllowCommentsForDays < 0) { post.AllowCommentsForDays = config.DefaultCommentDaysAllowed; } break; //else unspecified, no change } post.ContentChanged += new ContentChangedEventHandler(blog_ContentChanged); bool enableContentVersioning = config.EnableContentVersioning; if ((siteSettings.ForceContentVersioning) || (WebConfigSettings.EnforceContentVersioningGlobally)) { enableContentVersioning = true; } if (enableContentVersioning) { post.CreateHistory(siteSettings.SiteGuid); } post.Save(); SetCategories(post, sentPost); SiteUtils.QueueIndexing(); return true; } catch (Exception ex) { log.Error(ex); throw new MetaWeblogException("12", string.Format("EditPost failed. Error: {0}", ex.Message)); } }
/// <summary> /// blogger.deletePost method /// </summary> /// <param name="appKey"> /// Key from application. Outdated methodology that has no use here. /// </param> /// <param name="postId"> /// post guid in string format /// </param> /// <param name="userName"> /// login username /// </param> /// <param name="password"> /// login password /// </param> /// <param name="publish"> /// mark as published? /// </param> /// <returns> /// Whether deletion was successful or not. /// </returns> internal bool DeletePost(string appKey, string postId, string userName, string password, bool publish) { int blogid = Convert.ToInt32(postId); if (!UserCanEditPost(userName, blogid)) { throw new MetaWeblogException("11", MetaweblogResources.AccessDenied); } Blog post = new Blog(blogid); if (post.ItemId == -1) { //not found throw new MetaWeblogException("11", MetaweblogResources.PostNotFound); } try { if (WebConfigSettings.LogIpAddressForContentDeletions) { log.Info("user " + siteUser.Name + " deleted blog post via metaweblogapi " + post.Title + " from ip address " + SiteUtils.GetIP4Address()); } post.ContentChanged += new ContentChangedEventHandler(blog_ContentChanged); post.Delete(); FriendlyUrl.DeleteByPageGuid(post.BlogGuid); SiteUtils.QueueIndexing(); } catch (Exception ex) { log.Error(ex); throw new MetaWeblogException("12", string.Format("DeletePost failed. Error: {0}", ex.Message)); } return true; }
private bool UserCanEditPost(string loginName, int postId) { Blog blog = new Blog(postId); if (blog.ItemId == -1) { return false; } //not found Module module = new Module(blog.ModuleId); if (module.ModuleId == -1) { return false; } if (module.FeatureGuid != Blog.FeatureGuid) { return false; } if (isAdmin) { return true; } if (module.EditUserId.Equals(siteUser.UserId)) { return true; } int pageId = GetPageIdForModule(blog.ModuleId); if (pageId > -1) { PageSettings blogPage = new PageSettings(siteSettings.SiteId, pageId); if (blogPage.EditRoles == "Admins") { return false; } if (isContentAdmin || isSiteEditor) { return true; } if (module.AuthorizedEditRoles == "Admins") { return false; } if (siteUser.IsInRoles(blogPage.EditRoles)) { return true; } if (siteUser.IsInRoles(module.AuthorizedEditRoles)) { return true; } } return false; }
private static void IndexItem(Blog blog) { if (WebConfigSettings.DisableSearchIndex) { return; } if (blog == null) { if (log.IsErrorEnabled) { log.Error("blog object passed to BlogIndexBuilderProvider.IndexItem was null"); } return; } if (!blog.IncludeInSearch) { return; } Module module = new Module(blog.ModuleId); Guid blogFeatureGuid = new Guid("026cbead-2b80-4491-906d-b83e37179ccf"); ModuleDefinition blogFeature = new ModuleDefinition(blogFeatureGuid); // get comments so they can be indexed too StringBuilder stringBuilder = new StringBuilder(); using (IDataReader comments = Blog.GetBlogComments(blog.ModuleId, blog.ItemId)) { while (comments.Read()) { stringBuilder.Append(" " + comments["Comment"].ToString()); stringBuilder.Append(" " + comments["Name"].ToString()); if (debugLog) log.Debug("BlogIndexBuilderProvider.IndexItem add comment "); } } // get list of pages where this module is published List<PageModule> pageModules = PageModule.GetPageModulesByModule(blog.ModuleId); foreach (PageModule pageModule in pageModules) { PageSettings pageSettings = new PageSettings( blog.SiteId, pageModule.PageId); //don't index pending/unpublished pages if (pageSettings.IsPending) { continue; } mojoPortal.SearchIndex.IndexItem indexItem = new mojoPortal.SearchIndex.IndexItem(); if (blog.SearchIndexPath.Length > 0) { indexItem.IndexPath = blog.SearchIndexPath; } indexItem.SiteId = blog.SiteId; indexItem.ExcludeFromRecentContent = blog.ExcludeFromRecentContent; indexItem.PageId = pageSettings.PageId; indexItem.PageName = pageSettings.PageName; indexItem.ViewRoles = pageSettings.AuthorizedRoles; indexItem.ModuleViewRoles = module.ViewRoles; indexItem.PageMetaDescription = blog.MetaDescription; indexItem.PageMetaKeywords = blog.MetaKeywords; indexItem.ItemId = blog.ItemId; indexItem.ModuleId = blog.ModuleId; indexItem.ModuleTitle = module.ModuleTitle; indexItem.Title = blog.Title; indexItem.Content = blog.Description + " " + blog.MetaDescription + " " + blog.MetaKeywords; indexItem.ContentAbstract = blog.Excerpt; indexItem.FeatureId = blogFeatureGuid.ToString(); indexItem.FeatureName = blogFeature.FeatureName; indexItem.FeatureResourceFile = blogFeature.ResourceFile; indexItem.OtherContent = stringBuilder.ToString(); indexItem.PublishBeginDate = pageModule.PublishBeginDate; if (blog.StartDate > pageModule.PublishBeginDate) { indexItem.PublishBeginDate = blog.StartDate; } indexItem.PublishEndDate = pageModule.PublishEndDate; if (blog.EndDate < pageModule.PublishEndDate) { indexItem.PublishEndDate = blog.EndDate; } if ((blog.UserFirstName.Length > 0) && (blog.UserLastName.Length > 0)) { indexItem.Author = string.Format(CultureInfo.InvariantCulture, BlogResources.FirstLastFormat, blog.UserFirstName, blog.UserLastName); } else { indexItem.Author = blog.UserName; } indexItem.CreatedUtc = blog.StartDate; indexItem.LastModUtc = blog.LastModUtc; if ((!WebConfigSettings.UseUrlReWriting) || (!BlogConfiguration.UseFriendlyUrls(indexItem.ModuleId))) { indexItem.ViewPage = "Blog/ViewPost.aspx?pageid=" + indexItem.PageId.ToInvariantString() + "&mid=" + indexItem.ModuleId.ToInvariantString() + "&ItemID=" + indexItem.ItemId.ToInvariantString() ; } else { indexItem.ViewPage = blog.ItemUrl.Replace("~/", string.Empty); } indexItem.UseQueryStringParams = false; mojoPortal.SearchIndex.IndexHelper.RebuildIndex(indexItem); } if (debugLog) log.Debug("Indexed " + blog.Title); }
/// <summary> /// metaWeblog.newPost method /// </summary> /// <param name="blogId"> /// always 1000 in BlogEngine since it is a singlar blog instance /// </param> /// <param name="userName"> /// login username /// </param> /// <param name="password"> /// login password /// </param> /// <param name="sentPost"> /// struct with post details /// </param> /// <param name="publish"> /// mark as published? /// </param> /// <returns> /// postID as string /// </returns> internal string NewPost(string blogId, string userName, string password, MWAPost sentPost, bool publish) { int moduleId = Convert.ToInt32(blogId); if (!UserCanPostToBlog(userName, moduleId)) { throw new MetaWeblogException("11", MetaweblogResources.AccessDenied); } try { Module module = new Module(moduleId); Blog post = new Blog(); post.ModuleId = module.ModuleId; post.ModuleGuid = module.ModuleGuid; post.UserGuid = siteUser.UserGuid; post.LastModUserGuid = siteUser.UserGuid; if ((sentPost.postDate != null) && (sentPost.postDate > DateTime.MinValue) && (sentPost.postDate < DateTime.MaxValue)) { if (!WebConfigSettings.DisableUseOfPassedInDateForMetaWeblogApi) { post.StartDate = sentPost.postDate; } } post.Title = sentPost.title; post.Description = SiteUtils.ChangeFullyQualifiedLocalUrlsToRelative(navigationSiteRoot, imageSiteRoot, sentPost.description); if (!string.IsNullOrEmpty(sentPost.excerpt)) { if (BlogConfiguration.UseExcerptFromMetawblogAsMetaDescription) { post.MetaDescription = UIHelper.CreateExcerpt(sentPost.excerpt, BlogConfiguration.MetaDescriptionMaxLengthToGenerate); } post.Excerpt = SiteUtils.ChangeFullyQualifiedLocalUrlsToRelative(navigationSiteRoot, imageSiteRoot, sentPost.excerpt); } post.IncludeInFeed = true; post.IsPublished = publish; //post.Slug = sentPost.slug; //string author = String.IsNullOrEmpty(sentPost.author) ? userName : sentPost.author; switch (sentPost.commentPolicy) { //closed case "2": post.AllowCommentsForDays = -1; // closed break; // open case "1": default: Hashtable moduleSettings = ModuleSettings.GetModuleSettings(post.ModuleId); BlogConfiguration config = new BlogConfiguration(moduleSettings); post.AllowCommentsForDays = config.DefaultCommentDaysAllowed; break; } string newUrl = SiteUtils.SuggestFriendlyUrl(post.Title, siteSettings); post.ItemUrl = "~/" + newUrl; if (!post.Title.Contains("Theme Detection")) // don't index a temp post from livewriter that will be deleted { post.ContentChanged += new ContentChangedEventHandler(blog_ContentChanged); } post.Save(); int pageId = GetPageIdForModule(moduleId); FriendlyUrl newFriendlyUrl = new FriendlyUrl(); newFriendlyUrl.SiteId = siteSettings.SiteId; newFriendlyUrl.SiteGuid = siteSettings.SiteGuid; newFriendlyUrl.PageGuid = post.BlogGuid; newFriendlyUrl.Url = newUrl; newFriendlyUrl.RealUrl = "~/Blog/ViewPost.aspx?pageid=" + pageId.ToInvariantString() + "&mid=" + post.ModuleId.ToInvariantString() + "&ItemID=" + post.ItemId.ToInvariantString(); if (pageId > -1) { newFriendlyUrl.Save(); } SetCategories(post, sentPost); //post.Tags.Clear(); //foreach (var item in sentPost.tags.Where(item => item != null && item.Trim() != string.Empty)) //{ // post.Tags.Add(item); //} if (!post.Title.Contains("Theme Detection")) // don't index a temp post from livewriter that will be deleted { SiteUtils.QueueIndexing(); } return post.ItemId.ToString(); } catch (Exception ex) { log.Error(ex); throw new MetaWeblogException("12", string.Format("Create new post failed. Error: {0}", ex.Message)); } }
/// <summary> /// metaWeblog.getPost method /// </summary> /// <param name="postId"> /// post guid in string format /// </param> /// <param name="userName"> /// login username /// </param> /// <param name="password"> /// login password /// </param> /// <returns> /// struct with post details /// </returns> internal MWAPost GetPost(string postId, string userName, string password) { var sendPost = new MWAPost(); int blogId = Convert.ToInt32(postId); if (blogId == -1) { throw new MetaWeblogException("11", MetaweblogResources.NoBlogConfigured); } if (!UserCanEditPost(userName, blogId)) { throw new MetaWeblogException("11", MetaweblogResources.AccessDenied); } Blog post = new Blog(blogId); if (post.ItemId == -1) { //not found throw new MetaWeblogException("11", MetaweblogResources.PostNotFound); } try { //Hashtable moduleSettings = ModuleSettings.GetModuleSettings(post.ModuleId); //BlogConfiguration config = new BlogConfiguration(moduleSettings); sendPost.link = FormatUrl(post.ItemUrl, post.ItemId, post.ModuleId); sendPost.postID = post.ItemId.ToString(); sendPost.postDate = post.StartDate.ToLocalTime(timeZone); sendPost.title = post.Title; sendPost.description = SiteUtils.ChangeRelativeUrlsToFullyQualifiedUrls(navigationSiteRoot, imageSiteRoot, post.Description); //sendPost.link = post.AbsoluteLink.AbsoluteUri; //sendPost.slug = post.Slug; sendPost.excerpt = SiteUtils.ChangeRelativeUrlsToFullyQualifiedUrls(navigationSiteRoot, imageSiteRoot, post.Excerpt); sendPost.publish = post.IsPublished; sendPost.categories = GetCategoriesForPost(post.ItemId); if(siteSettings.UseEmailForLogin) { sendPost.author = post.UserEmail; } else { sendPost.author = post.UserLoginName; } if (post.AllowCommentsForDays == -1) //closed { sendPost.commentPolicy = "2"; //closed } else { DateTime endDate = post.StartDate.AddDays((double)post.AllowCommentsForDays); if (endDate > DateTime.UtcNow) { sendPost.commentPolicy = "1"; //allowed } else { sendPost.commentPolicy = "2"; } } //var tags = post.Tags.ToList(); //sendPost.tags = tags; return sendPost; } catch (Exception ex) { log.Error(ex); throw new MetaWeblogException("12", string.Format("GetPost new post failed. Error: {0}", ex.Message)); } }
private void LoadSettings() { blog = new Blog(ItemId); module = basePage.GetModule(ModuleId); useFriendlyUrls = BlogConfiguration.UseFriendlyUrls(ModuleId); if (!WebConfigSettings.UseUrlReWriting) { useFriendlyUrls = false; } attachmentBaseUrl = SiteUtils.GetFileAttachmentUploadPath(); currentUser = SiteUtils.GetCurrentSiteUser(); comments = InternalCommentSystem as CommentsWidget; if ( (module.ModuleId == -1) || (blog.ModuleId == -1) || (blog.ModuleId != module.ModuleId) || (basePage.SiteInfo == null) ) { // query string params have been manipulated pnlInnerWrap.Visible = false; AllowComments = false; parametersAreInvalid = true; return; } else { if (Request.IsAuthenticated) { if (basePage.UserCanEditModule(ModuleId, Blog.FeatureGuid)) { IsEditable = true; } } } RegexRelativeImageUrlPatern = SecurityHelper.RegexRelativeImageUrlPatern; moduleSettings = ModuleSettings.GetModuleSettings(ModuleId); config = new BlogConfiguration(moduleSettings); blogAuthor = config.BlogAuthor; divTopPager.Visible = config.ShowNextPreviousLinks; divBottomPager.Visible = config.ShowNextPreviousLinks; GmapApiKey = SiteUtils.GetGmapApiKey(); if (config.InstanceCssClass.Length > 0) { pnlInnerWrap.SetOrAppendCss(config.InstanceCssClass); } searchBoxTop.Visible = config.ShowBlogSearchBox && !displaySettings.HideSearchBoxInPostDetail && !displaySettings.ShowSearchInNav; //if (config.AddThisCustomBrand.Length > 0) //{ // addThisCustomBrand = config.AddThisCustomBrand; //} //else //{ // addThisCustomBrand = basePage.SiteInfo.SiteName; //} lblCopyright.Text = config.Copyright; //litAuthor.Visible = config.ShowPostAuthor; navTop.ModuleId = ModuleId; navTop.ModuleGuid = module.ModuleGuid; navTop.PageId = PageId; navTop.IsEditable = IsEditable; navTop.Config = config; navTop.SiteRoot = SiteRoot; navTop.ImageSiteRoot = ImageSiteRoot; navTop.OverrideDate = blog.StartDate; navTop.ShowCalendar = config.ShowCalendarOnPostDetail; navBottom.ModuleId = ModuleId; navBottom.ModuleGuid = module.ModuleGuid; navBottom.PageId = PageId; navBottom.IsEditable = IsEditable; navBottom.Config = config; navBottom.SiteRoot = SiteRoot; navBottom.ImageSiteRoot = ImageSiteRoot; navBottom.OverrideDate = blog.StartDate; navBottom.ShowCalendar = config.ShowCalendarOnPostDetail; //pnlStatistics.Visible = config.ShowStatistics; if (!config.NavigationOnRight) { //this.divNav.CssClass = "blognavleft"; this.divblog.CssClass = "blogcenter-leftnav"; } //divNav.Visible = false; navTop.Visible = false; if (config.ShowArchives || config.ShowAddFeedLinks || displaySettings.ShowArchivesInPostDetail || config.ShowCategories || displaySettings.ShowCategoriesInPostDetail || config.ShowFeedLinks || displaySettings.ShowFeedLinksInPostDetail || config.ShowStatistics || displaySettings.ShowStatisticsInPostDetail || (config.UpperSidebar.Length > 0) || (config.LowerSidebar.Length > 0) ) { //divNav.Visible = true; navTop.Visible = true; } if (!navTop.Visible) { divblog.CssClass = "blogcenter-nonav"; } navBottom.Visible = false; if ((navTop.Visible) && (displaySettings.UseBottomNavigation)) { navTop.Visible = false; navBottom.Visible = true; } if (!Request.IsAuthenticated) { //if ((config.HideDetailsFromUnauthencticated) && (blog.Description.Length > config.ExcerptLength)) if (config.HideDetailsFromUnauthencticated) { pnlDetails.Visible = false; pnlExcerpt.Visible = true; AllowComments = false; divAddThis.Visible = false; tweetThis1.Visible = false; fblike.Visible = false; btnPlusOne.Visible = false; bsocial.Visible = false; } } if (!pnlExcerpt.Visible) { if (config.AddThisAccountId.Length > 0) { addThisAccountId = config.AddThisAccountId; } else { addThisAccountId = basePage.SiteInfo.AddThisDotComUsername; } if (config.EnableContentRating && !displaySettings.DetailViewDisableContentRating) { if (displaySettings.UseBottomContentRating) { ((mojoRating)RatingBottom).Enabled = true; ((mojoRating)RatingBottom).AllowFeedback = config.EnableRatingComments; ((mojoRating)RatingBottom).ContentGuid = blog.BlogGuid; } else { ((mojoRating)Rating).Enabled = true; ((mojoRating)Rating).AllowFeedback = config.EnableRatingComments; ((mojoRating)Rating).ContentGuid = blog.BlogGuid; } } } if (displaySettings.BlogViewUseBottomDate) { pnlDateTop.Visible = false; pnlBottomDate.Visible = true; } if (displaySettings.BlogViewHideTopPager) { divTopPager.Visible = false; } if (displaySettings.BlogViewHideBottomPager) { divBottomPager.Visible = false; } if (displaySettings.BlogViewInnerWrapElement.Length > 0) { pnlInnerWrap.Element = displaySettings.BlogViewInnerWrapElement; } if (displaySettings.BlogViewInnerBodyExtraCss.Length > 0) { pnlInnerBody.ExtraCssClasses = displaySettings.BlogViewInnerBodyExtraCss; pnlInnerBody.RenderContentsOnly = false; } if (displaySettings.BlogViewDivBlogExtraCss.Length > 0) { divblog.CssClass += " " + displaySettings.BlogViewDivBlogExtraCss; } if (displaySettings.BlogViewHeaderLiteralTopContent.Length > 0) { heading.LiteralExtraTopContent = displaySettings.BlogViewHeaderLiteralTopContent; } if (displaySettings.BlogViewHeaderLiteralBottomContent.Length > 0) { heading.LiteralExtraBottomContent = displaySettings.BlogViewHeaderLiteralBottomContent; } if (displaySettings.OverridePostDetailHeadingElement.Length > 0) { heading.HeadingTag = displaySettings.OverridePostDetailHeadingElement; } if ((config.RelatedItemsToShow > 0) && (displaySettings.RelatedPostsPosition == "Bottom") && (Page is BlogView)) { relatedPosts.PageId = PageId; relatedPosts.ModuleId = ModuleId; relatedPosts.ItemId = ItemId; relatedPosts.SiteRoot = SiteRoot; relatedPosts.MaxItems = config.RelatedItemsToShow; relatedPosts.UseFriendlyUrls = BlogConfiguration.UseFriendlyUrls(ModuleId); relatedPosts.HeadingElement = displaySettings.RelatedPostsHeadingElement; relatedPosts.OverrideHeadingText = displaySettings.RelatedPostsOverrideHeadingText; } switch (basePage.SiteInfo.AvatarSystem) { case "gravatar": allowGravatars = true; disableAvatars = false; break; case "internal": allowGravatars = false; disableAvatars = false; break; case "none": default: allowGravatars = false; disableAvatars = true; break; } if (!blog.ShowAuthorAvatar) { disableAvatars = true; } if (displaySettings.HideAvatarInPostDetail) { disableAvatars = true; } pnlAuthorInfo.Visible = (!disableAvatars) ||( blog.ShowAuthorBio && displaySettings.ShowAuthorBioInPostDetail &&(!pnlExcerpt.Visible)); userAvatar.Email = blog.UserEmail; userAvatar.UserName = blog.UserName; userAvatar.UserId = blog.UserId; userAvatar.AvatarFile = blog.UserAvatar; userAvatar.MaxAllowedRating = MaxAllowedGravatarRating; userAvatar.Disable = disableAvatars; userAvatar.UseGravatar = allowGravatars; userAvatar.SiteId = basePage.SiteInfo.SiteId; userAvatar.UserNameTooltipFormat = displaySettings.AvatarUserNameTooltipFormat; userAvatar.UseLink = UseProfileLinkForAvatar(); userAvatar.SiteRoot = SiteRoot; // if (pnlExcerpt.Visible) { userAvatar.Visible = false; } SetupCommentSystem(); }
private string GetExcerpt(Blog blog) { if ((blog.Excerpt.Length > 0) && (blog.Excerpt != "<p> </p>")) { return blog.Excerpt; } string result = string.Empty; if ((blog.Description.Length > config.ExcerptLength)) { return UIHelper.CreateExcerpt(blog.Description, config.ExcerptLength, config.ExcerptSuffix); } return blog.Description; }
private bool CanEditPost(Blog blog) { if (BlogConfiguration.SecurePostsByUser) { if (WebUser.IsInRoles(config.ApproverRoles)) { return true; } if (currentUser == null) { return false; } return (blog.UserId == currentUser.UserId); } return IsEditable; }
public void CreateHistory(Guid siteGuid) { if (this.blogGuid == Guid.Empty) { return; } Blog currentVersion = new Blog(this.itemID); if (currentVersion.Description == this.Description) { return; } ContentHistory history = new ContentHistory(); history.ContentGuid = currentVersion.BlogGuid; history.Title = currentVersion.Title; history.ContentText = currentVersion.Description; history.SiteGuid = siteGuid; history.UserGuid = currentVersion.LastModUserGuid; history.CreatedUtc = currentVersion.LastModUtc; history.Save(); }
private void SetCategories(Blog post, MWAPost sentPost) { List<MWACategory> allBlogCategories = GetCategoriesForBlog(post.ModuleId); List<string> postCategories = GetCategoriesForPost(post.ItemId); foreach (string category in sentPost.categories) { if (category.Trim().Length == 0) { continue; } MWACategory categoryInfo = allBlogCategories.Find(delegate(MWACategory ci) { return ci.title.Equals(category, StringComparison.OrdinalIgnoreCase); }); if ((categoryInfo.id != null) && (categoryInfo.id.Length > 0)) { if (!postCategories.Contains(category)) { Blog.AddItemCategory(post.ItemId, Convert.ToInt32(categoryInfo.id)); } } else { int newCategoryId = Blog.AddBlogCategory(post.ModuleId, category); Blog.AddItemCategory(post.ItemId, newCategoryId); } } }
public void ProcessRequest(HttpContext context) { base.Initialize(context); if (!UserCanEditModule(ModuleId, Blog.FeatureGuid)) { log.Info("User has no edit permission so returning 404"); Response.StatusCode = 404; return; } if (CurrentSite == null) { log.Info("CurrentSite is null so returning 404"); Response.StatusCode = 404; return; } if (CurrentUser == null) { log.Info("CurrentUser is null so returning 404"); Response.StatusCode = 404; return; } if (FileSystem == null) { log.Info("FileSystem is null so returning 404"); Response.StatusCode = 404; return; } if (Request.Files.Count == 0) { log.Info("Posted File Count is zero so returning 404"); Response.StatusCode = 404; return; } if (Request.Files.Count > BlogConfiguration.MaxAttachmentsToUploadAtOnce) { log.Info("Posted File Count is higher than allowed so returning 404"); Response.StatusCode = 404; return; } itemId = WebUtils.ParseInt32FromQueryString("ItemID", itemId); if (itemId == -1) { log.Info("No ItemID provided so returning 404"); Response.StatusCode = 404; return; } module = GetModule(ModuleId, Blog.FeatureGuid); if (module == null) { log.Info("Module is null so returning 404"); Response.StatusCode = 404; return; } blog = new Blog(itemId); if (blog.ModuleId != ModuleId) { log.Info("Invalid ItemID for module so returning 404"); Response.StatusCode = 404; return; } Hashtable moduleSettings = ModuleSettings.GetModuleSettings(ModuleId); config = new BlogConfiguration(moduleSettings); context.Response.ContentType = "text/plain";//"application/json"; var r = new System.Collections.Generic.List<UploadFilesResult>(); JavaScriptSerializer js = new JavaScriptSerializer(); SiteUtils.EnsureFileAttachmentFolder(CurrentSite); string upLoadPath = SiteUtils.GetFileAttachmentUploadPath(); for (int f = 0; f < Request.Files.Count; f++) { HttpPostedFile file = Request.Files[f]; string ext = System.IO.Path.GetExtension(file.FileName); if (!SiteUtils.IsAllowedUploadBrowseFile(ext, WebConfigSettings.AllowedMediaFileExtensions)) { log.Info("file extension was " + ext + " so discarding file " + file.FileName); r.Add(new UploadFilesResult() { Name = file.FileName, Length = file.ContentLength, Type = file.ContentType, ErrorMessage = string.Format( CultureInfo.InvariantCulture, GalleryResources.InvalidUploadExtensionFormat, file.FileName, WebConfigSettings.AllowedMediaFileExtensions.Replace("|", " ")) }); continue; } string mimeType = IOHelper.GetMimeType(ext).ToLower(); FileAttachment a = new FileAttachment(); a.CreatedBy = CurrentUser.UserGuid; a.FileName = System.IO.Path.GetFileName(file.FileName); a.ServerFileName = blog.ItemId.ToInvariantString() + a.FileName.ToCleanFileName(WebConfigSettings.ForceLowerCaseForUploadedFiles); a.ModuleGuid = blog.ModuleGuid; a.SiteGuid = CurrentSite.SiteGuid; a.ItemGuid = blog.BlogGuid; a.ContentLength = file.ContentLength; a.ContentType = mimeType; a.Save(); string destPath = upLoadPath + a.ServerFileName; using (Stream s = file.InputStream) { FileSystem.SaveFile(destPath, s, mimeType, true); } r.Add(new UploadFilesResult() { //Thumbnail_url = Name = a.FileName, Length = file.ContentLength, Type = mimeType }); if (WebConfigSettings.LogAllFileServiceRequests) { string userName = "******"; if (CurrentUser != null) { userName = CurrentUser.Name; } log.Info("File " + file.FileName + " uploaded by " + userName + " as a media attachment in the Blog"); } } var uploadedFiles = new { files = r.ToArray() }; var jsonObj = js.Serialize(uploadedFiles); context.Response.Write(jsonObj.ToString()); }
public void InstallContent(Module module, string configInfo) { if (string.IsNullOrEmpty(configInfo)) { return; } SiteSettings siteSettings = new SiteSettings(module.SiteId); SiteUser admin = SiteUser.GetNewestUser(siteSettings); XmlDocument xml = new XmlDocument(); using (StreamReader stream = File.OpenText(HostingEnvironment.MapPath(configInfo))) { xml.LoadXml(stream.ReadToEnd()); } XmlNode postsNode = null; foreach (XmlNode n in xml.DocumentElement.ChildNodes) { if (n.Name == "posts") { postsNode = n; break; } } if (postsNode != null) { foreach (XmlNode node in postsNode.ChildNodes) { if (node.Name == "post") { XmlAttributeCollection postAttrributes = node.Attributes; Blog b = new Blog(); b.ModuleGuid = module.ModuleGuid; b.ModuleId = module.ModuleId; if ((postAttrributes["title"] != null) && (postAttrributes["title"].Value.Length > 0)) { b.Title = postAttrributes["title"].Value; } b.ItemUrl = "~/" + SiteUtils.SuggestFriendlyUrl(b.Title, siteSettings); foreach (XmlNode descriptionNode in node.ChildNodes) { if (descriptionNode.Name == "excerpt") { b.Excerpt = descriptionNode.InnerText; break; } } foreach (XmlNode descriptionNode in node.ChildNodes) { if (descriptionNode.Name == "description") { b.Description = descriptionNode.InnerText; break; } } b.UserGuid = admin.UserGuid; if (b.Save()) { FriendlyUrl newFriendlyUrl = new FriendlyUrl(); newFriendlyUrl.SiteId = siteSettings.SiteId; newFriendlyUrl.SiteGuid = siteSettings.SiteGuid; newFriendlyUrl.PageGuid = b.BlogGuid; newFriendlyUrl.Url = b.ItemUrl.Replace("~/", string.Empty); ; newFriendlyUrl.RealUrl = "~/Blog/ViewPost.aspx?pageid=" + module.PageId.ToInvariantString() + "&mid=" + b.ModuleId.ToInvariantString() + "&ItemID=" + b.ItemId.ToInvariantString(); newFriendlyUrl.Save(); } } } } foreach (XmlNode node in xml.DocumentElement.ChildNodes) { if (node.Name == "moduleSetting") { XmlAttributeCollection settingAttributes = node.Attributes; if ((settingAttributes["settingKey"] != null) && (settingAttributes["settingKey"].Value.Length > 0)) { string key = settingAttributes["settingKey"].Value; string val = string.Empty; if (settingAttributes["settingValue"] != null) { val = settingAttributes["settingValue"].Value; } ModuleSettings.UpdateModuleSetting(module.ModuleGuid, module.ModuleId, key, val); } } } }