public IEnumerable<string> GetAll()
 {
     using (var db = new CmsContext())
     {
         return db.Posts.SelectMany(post => post.Tags).Distinct();
     }
 }
예제 #2
0
 protected override XElement CreateElement(CmsContext context, CmsPart part)
 {
     return Parse(HttpUtility.HtmlEncode(
         part.Value
             .Replace("\r\n", "<br/>")
             .Replace("\n", "<br/>")));
 }
        public void Edit(string existingTag, string newTag)
        {
            using (var db = new CmsContext())
            {
                var posts = db.Posts.Where(post => post.CombinedTags.Contains(existingTag))
                    .ToList();

                posts = posts.Where(post => 
                    post.Tags.Contains(existingTag, StringComparer.CurrentCultureIgnoreCase))
                    .ToList();

                if (!posts.Any())
                {
                    throw new KeyNotFoundException("The tag " + existingTag + " does not exist.");
                }

                foreach (var post in posts)
                {
                    post.Tags.Remove(existingTag);
                    post.Tags.Add(newTag);
                }

                db.SaveChanges();
            }
        }
예제 #4
0
 /// <summary>
 /// 入口请求,返回false则应立即截断请求
 /// </summary>
 /// <param name="tag"></param>
 /// <param name="page"></param>
 public void PortalRequest(CmsContext context, ref bool result)
 {
     if (this.OnPortalRequest != null)
     {
         this.OnPortalRequest(context, ref result);
     }
 }
예제 #5
0
 /// <summary>
 /// 入口请求,返回false则应立即截断请求
 /// </summary>
 /// <param name="tag"></param>
 /// <param name="page"></param>
 public void SearchRequest(CmsContext context,string cate,string word, ref bool result)
 {
     if (this.OnSearchPageRequest != null)
     {
         this.OnSearchPageRequest(context,cate,word, ref result);
     }
 }
예제 #6
0
 /// <summary>
 /// 入口请求,返回false则应立即截断请求
 /// </summary>
 /// <param name="tag"></param>
 /// <param name="page"></param>
 public void TagRequest(CmsContext context, string tag, ref bool result)
 {
     if (this.OnTagPageRequest != null)
     {
         this.OnTagPageRequest(context,tag, ref result);
     }
 }
예제 #7
0
 /// <summary>
 /// 栏目请求,返回false则应立即截断请求
 /// </summary>
 /// <param name="tag"></param>
 /// <param name="page"></param>
 public void Request(CmsContext controller, string tag,int page,ref bool result)
 {
     if (this.OnCategoryPageRequest != null)
     {
         this.OnCategoryPageRequest(controller, tag,page, ref result);
     }
 }
예제 #8
0
 /// <summary>
 /// 栏目请求,返回false则应立即截断请求
 /// </summary>
 /// <param name="tag"></param>
 /// <param name="page"></param>
 public void PostRequest(CmsContext controller, string allhtml, ref bool result)
 {
     if (this.OnArchivePagePost != null)
     {
         this.OnArchivePagePost(controller, allhtml, ref result);
     }
 }
예제 #9
0
 	internal static void RenderNotFound(CmsContext context)
 	{
 		context.RenderNotfound("File not found!",tpl=>{
                                 tpl.AddVariable("site", context.CurrentSite);
 		                       	tpl.AddVariable("page",new PageVariable());
 		     					PageUtility.RegistEventHandlers(tpl);
 		 });
 	}
 public async Task<IEnumerable<Post>> GetAllAsync()
 {
     using (var db = new CmsContext())
     {
         return await db.Posts.Include("Author")
             .OrderByDescending(post => post.Created).ToArrayAsync();
     }
 }
 public IEnumerable<Post> GetAll()
 {
     using (var db = new CmsContext())
     {
         return db.Posts.Include("Author")
             .OrderByDescending(post => post.Created).ToArray();
     }
 }
 public Post Get(string id)
 {
     using (var db = new CmsContext())
     {
         return db.Posts.Include("Author")
             .SingleOrDefault(post => post.Id == id);
     }
 }
 public async Task<IEnumerable<Post>> GetPostsByAuthorAsync(string authorId)
 {
     using (var db = new CmsContext())
     {
         return await db.Posts.Include("Author")
             .Where(p => p.AuthorId == authorId)
             .OrderByDescending(post => post.Created).ToArrayAsync();
     }
 }
 public IEnumerable<string> GetAll()
 {
     using (var db = new CmsContext())
     {
         var tagsCollection = db.Posts.Select(p => p.CombinedTags).ToList();
         return string.Join(",", tagsCollection).Split(',').Distinct();
         
         //return db.Posts.ToList().SelectMany(post => post.Tags).Distinct();
     }
 }
예제 #15
0
 protected override XElement CreateElement(CmsContext context, CmsPart part)
 {
     var md = new MarkdownDeep.Markdown
     {
         ExtraMode = true,
         SafeMode = false,
         NewWindowForExternalLinks = true,
         FormatCodeBlock = (markdown, s) => FormatCodeBlock(context, markdown, s)
     };
     return Parse(md.Transform(part.Value));
 }
        public void Create(Post model)
        {
            using (var db = new CmsContext())
            {
                var post = db.Posts.SingleOrDefault(p => p.Id == model.Id);

                if (post != null)
                {
                    throw new ArgumentException("A post with the id of " + model.Id + " already exists.");
                }

                db.Posts.Add(model);
                db.SaveChanges();
            }
        }
        public void Delete(string id)
        {
            using (var db = new CmsContext())
            {
                var post = db.Posts.SingleOrDefault(p => p.Id == id);

                if (post == null)
                {
                    throw new KeyNotFoundException("The post with the id of " + id + " does not exist");
                }

                db.Posts.Remove(post);
                db.SaveChanges();
            }
        }
        public string Get(string tag)
        {
            using (var db = new CmsContext())
            {
                var posts = db.Posts.Where(post =>
                    post.Tags.Contains(tag, StringComparer.CurrentCultureIgnoreCase))
                    .ToList();

                if (!posts.Any())
                {
                    throw new KeyNotFoundException("The tag " + tag + " does not exist.");
                }

                return tag.ToLower();
            }
        }
예제 #19
0
        /// <summary>
        /// 呈现首页
        /// </summary>
        /// <param name="context"></param>
        public static void RenderIndex(CmsContext context)
        {
            //检测网站状态
            if (!context.CheckSiteState()) return;

            //检查缓存
            if (!context.CheckAndSetClientCache()) return;

        	int siteID=context.CurrentSite.SiteId;
        	string cacheID=String.Concat("cms_s",siteID.ToString(),"_index_page");
        	
        	ICmsPageGenerator cmsPage=new PageGeneratorObject(context);
        	
            if (context.Request["cache"] == "0")
            {
                Cms.Cache.Rebuilt();
            }


            string html = String.Empty;
            if (Settings.Opti_IndexCacheSeconds > 0)
            {
                ICmsCache cache = Cms.Cache;
                object obj = cache.Get(cacheID);
                if (obj == null)
                {
                    html = cmsPage.GetIndex(null);
                    cache.Insert(cacheID, html, DateTime.Now.AddSeconds(Settings.Opti_IndexCacheSeconds));
                }
                else
                {
                    html = obj as string;
                }
            }
            else
            {
                //DateTime dt = DateTime.Now;
                html = cmsPage.GetIndex(null);
                //context.Render("<br />"+(DateTime.Now - dt).TotalMilliseconds.ToString() + "<br />");
            }

            //response.AddHeader("Cache-Control", "max-age=" + maxAge.ToString());
            context.Render(html);
        }
예제 #20
0
 private string FormatCodeBlock(CmsContext context, MarkdownDeep.Markdown markdown, string source)
 {
     try
     {
         var match = _LanguageExpression.Match(source.Split('\n')[0].Trim());
         if (match.Success)
         {
             var language = match.Result("${language}");
             var contentType = "code/" + language;
             var codeRenderer = context.GetRenderService(contentType);
             if (codeRenderer != null)
             {
                 return codeRenderer.Render(context, new CmsPart(contentType, String.Join("\n", source.Split('\n').Skip(1)))).ToHtml().ToHtmlString();
             }
         }
     }
     catch
     {
     }
     return markdown.Transform(source);
 }
        public static void RegisterAdmin()
        {
            using (var context = new CmsContext())
            using (var userStore = new UserStore<CmsUser>(context))
            using (var userManager = new UserManager<CmsUser>(userStore))
            {
                var user = userStore.FindByNameAsync("admin").Result;

                if (user == null)
                {
                    var adminUser = new CmsUser
                    {
                        UserName = "******",
                        Email = "*****@*****.**",
                        DisplayName = "Administrator"
                    };

                    userManager.Create(adminUser, "Passw0rd1234");
                }
            }
        }
        public void Edit(string id, Models.Post updatedItem)
        {
            using (var db = new CmsContext())
            {
                var post = db.Posts.SingleOrDefault(p => p.Id == id);

                if (post == null)
                {
                    throw new KeyNotFoundException("A post with the id of " 
                        + id + " does not exist in the data store.");
                }

                post.Id = updatedItem.Id;
                post.Title = updatedItem.Title;
                post.Content = updatedItem.Content;
                post.Published = updatedItem.Published;
                post.Tags = updatedItem.Tags;

                db.SaveChanges();
            }
        }
예제 #23
0
        public void Edit(string id, Post updateModel)
        {
            using (var db = new CmsContext())
            {
                var editablePost = db.Posts.SingleOrDefault(post => post.Id == id);

                // TODO oma metodi IsNull
                if (editablePost.IsNull())
                {
                    throw new KeyNotFoundException("A post with the id of "
                        + id + "doe not exists in the data store");
                }

                editablePost.Id = updateModel.Id;
                editablePost.Title = updateModel.Title;
                editablePost.Content = updateModel.Content;
                editablePost.Published = updateModel.Published;
                editablePost.Tags = updateModel.Tags;

                db.SaveChanges();
            }
        }
예제 #24
0
        /// <summary>
        /// 访问文档
        /// </summary>
        /// <param name="context"></param>
        /// <param name="allhtml"></param>
        public static void RenderArchive(CmsContext context, string allhtml)
        {
            string     html;
            ArchiveDto archive = default(ArchiveDto);

            //检测网站状态
            if (!context.CheckSiteState())
            {
                return;
            }

            //检查缓存
            if (!context.CheckAndSetClientCache())
            {
                return;
            }


            var    siteId      = context.CurrentSite.SiteId;
            String archivePath = allhtml.Substring(0, allhtml.Length - ".html".Length);

            archive = ServiceCall.Instance.ArchiveService.GetArchiveByIdOrAlias(siteId, archivePath);
            if (archive.Id <= 0)
            {
                RenderNotFound(context);
                return;
            }

            // 如果设置了302跳转
            if (!String.IsNullOrEmpty(archive.Location))
            {
                string url;
                if (Regex.IsMatch(archive.Location, "^http://", RegexOptions.IgnoreCase))
                {
                    url = archive.Location;
                }
                else
                {
                    if (archive.Location.StartsWith("/"))
                    {
                        throw new Exception("URL不能以\"/\"开头!");
                    }
                    url = String.Concat(context.SiteDomain, "/", archive.Location);
                }
                context.Response.Redirect(url, true); //302
                return;
            }

            ICmsPageGenerator cmsPage = new PageGeneratorObject(context);

            if (!FlagAnd(archive.Flag, BuiltInArchiveFlags.Visible))
            {
                RenderNotFound(context);
                return;
            }

            CategoryDto category = archive.Category;

            if (!(category.ID > 0))
            {
                RenderNotFound(context);
                return;
            }
            else
            {
                string appPath = Cms.Context.SiteAppPath;
                if (appPath != "/")
                {
                    appPath += "/";
                }

                if (FlagAnd(archive.Flag, BuiltInArchiveFlags.AsPage))
                {
                    string pattern     = "^" + appPath + "[0-9a-zA-Z]+/[\\.0-9A-Za-z_-]+\\.html$";
                    string pagePattern = "^" + appPath + "[\\.0-9A-Za-z_-]+\\.html$";

                    if (!Regex.IsMatch(context.Request.Path, pagePattern))
                    {
                        context.Response.StatusCode       = 301;
                        context.Response.RedirectLocation = String.Format("{0}{1}.html",
                                                                          appPath,
                                                                          String.IsNullOrEmpty(archive.Alias) ? archive.StrId : archive.Alias
                                                                          );
                        context.Response.End();
                        return;
                    }
                }
                else
                {
                    //校验栏目是否正确
                    string categoryPath = category.Path;
                    string path         = appPath != "/" ? allhtml.Substring(appPath.Length - 1) : allhtml;

                    if (!path.StartsWith(categoryPath + "/"))
                    {
                        RenderNotFound(context);
                        return;
                    }

                    /*
                     * //设置了别名,则跳转
                     * if (!String.IsNullOrEmpty(archive.Alias) && String.Compare(id, archive.Alias,
                     *  StringComparison.OrdinalIgnoreCase) != 0)
                     * {
                     *  context.Response.StatusCode = 301;
                     *  context.Response.RedirectLocation = String.Format("{0}{1}/{2}.html",
                     *      appPath,
                     *      categoryPath,
                     *      String.IsNullOrEmpty(archive.Alias) ? archive.StrId : archive.Alias
                     *      );
                     *  context.Response.End();
                     *  return;
                     * }
                     */
                }

                //增加浏览次数
                ++archive.ViewCount;
                ServiceCall.Instance.ArchiveService.AddCountForArchive(siteId, archive.Id, 1);
                //显示页面
                html = cmsPage.GetArchive(archive);

                //再次处理模板
                //html = PageUtility.Render(html, new { }, false);
            }

            // return html;
            context.Render(html);
        }
예제 #25
0
 public BaseRepository(CmsContext cmsContext)
 {
     _cmsContext = cmsContext;
 }
예제 #26
0
 public AccountRepository(CmsContext CmsContext) : base(CmsContext)
 {
 }
예제 #27
0
        /// <summary>
        /// 访问文档
        /// </summary>
        /// <param name="context"></param>
        /// <param name="archivePath">文档路径</param>
        public static void RenderArchive(CmsContext context, string archivePath)
        {
            if (archivePath.StartsWith("/"))
            {
                archivePath = archivePath.Substring(1);
            }
            var siteId  = context.CurrentSite.SiteId;
            var archive = ServiceCall.Instance.ArchiveService.GetArchiveByIdOrAlias(siteId, archivePath);

            if (archive.Id <= 0)
            {
                RenderNotFound(context);
                return;
            }

            // 如果设置了302跳转
            if (!string.IsNullOrEmpty(archive.Location))
            {
                string url;
                if (Regex.IsMatch(archive.Location, "^http://", RegexOptions.IgnoreCase))
                {
                    url = archive.Location;
                }
                else
                {
                    if (archive.Location.StartsWith("/"))
                    {
                        throw new Exception("URL不能以\"/\"开头!");
                    }
                    url = string.Concat(context.SiteDomain, "/", archive.Location);
                }

                context.HttpContext.Response.Redirect(url, false); //302
                return;
            }

            ICmsPageGenerator cmsPage = new PageGeneratorObject(context);

            if (!FlagAnd(archive.Flag, BuiltInArchiveFlags.Visible))
            {
                RenderNotFound(context);
                return;
            }

            var category = archive.Category;

            if (!(category.ID > 0))
            {
                RenderNotFound(context);
                return;
            }

            if (FlagAnd(archive.Flag, BuiltInArchiveFlags.AsPage))
            {
                var pagePattern = "^[\\.0-9A-Za-z_-]+\\.html$";

                if (!Regex.IsMatch(context.HttpContext.Request.GetPath(), pagePattern))
                {
                    context.HttpContext.Response.StatusCode(301);
                    context.HttpContext.Response.AppendHeader("Location",
                                                              $"{(string.IsNullOrEmpty(archive.Alias) ? archive.StrId : archive.Alias)}.html");
                    return;
                }
            }
            else
            {
                //校验栏目是否正确
                var categoryPath = category.Path;
                if (!archivePath.StartsWith(categoryPath + "/"))
                {
                    RenderNotFound(context);
                    return;
                }
            }

            //增加浏览次数
            ++archive.ViewCount;
            ServiceCall.Instance.ArchiveService.AddCountForArchive(siteId, archive.Id, 1);
            try
            {
                //显示页面
                var html = cmsPage.GetArchive(archive);
                context.HttpContext.Response.WriteAsync(html);
            }
            catch (TemplateException ex)
            {
                RenderError(context, ex, false);
            }
        }
예제 #28
0
        /// <summary>
        /// 呈现分类页
        /// </summary>
        /// <param name="context"></param>
        public static void RenderCategory(CmsContext context, string tag, int page)
        {
            //检查缓存
            if (!context.CheckAndSetClientCache())
            {
                return;
            }

            int         siteId = context.CurrentSite.SiteId;
            string      html   = String.Empty;
            CategoryDto category;
            string      allcate = context.Request.Path.Substring(1);



            ICmsPageGenerator cmsPage = new PageGeneratorObject(context);

            category = ServiceCall.Instance.SiteService.GetCategory(siteId, tag);


            if (!(category.Id > 0))
            {
                RenderNotFound(context); return;
            }

            //获取路径
            string categoryPath = category.UriPath;
            string appPath      = AtNet.Cms.Cms.Context.SiteAppPath;
            string _path        = appPath != "/" ? allcate.Substring(appPath.Length) : allcate;

            if (!_path.StartsWith(categoryPath))
            {
                RenderNotFound(context);
                return;
            }

            /*********************************
            *  @ 单页,跳到第一个特殊文档,
            *  @ 如果未设置则最新创建的文档,
            *  @ 如未添加文档则返回404
            *********************************/
            if (String.IsNullOrEmpty(category.Location))
            {
                html = cmsPage.GetCategory(category, page);
                context.Render(html);
            }
            else
            {
                string url;

                if (Regex.IsMatch(category.Location, "^http://", RegexOptions.IgnoreCase))
                {
                    url = category.Location;
                }
                else
                {
                    if (category.Location.StartsWith("/"))
                    {
                        throw new Exception("URL不能以\"/\"开头!");
                    }
                    url = String.Concat(context.SiteDomain, "/", category.Location);
                }


                context.Response.Redirect(url, true);  //302

                //context.Response.StatusCode = 301;
                //context.Render(@"<html><head><meta name=""robots"" content=""noindex""><script>location.href='" +
                //                  url + "';</script></head><body></body></html>");
            }
        }
예제 #29
0
        protected void b_CreatePages_Click(object sender, EventArgs e)
        {
            try
            {
                // home page
                int HomePageId = InsertPage("", "Home Page", "Home Page", "", "HomePage", -1, 0, true);
                // create the home page security zones
                InsertHomePageZone(HomePageId);

                //# /_Login Page (not visible in menu)
                InsertPage("_Login", "Login", "Login", "", "_login", HomePageId, 0, false);

                // _Admin Page (hidden)
                int AdminPageId = InsertPage("_admin", "HatCMS Administration", "Admin", "", RedirectTemplateName, HomePageId, 0, false);
                // create the admin area security zones
                InsertAdminAreaZone(AdminPageId);

                // -- redirect the admin page to the home page.
                InsertRedirectPlaceholder(CmsContext.getPageById(AdminPageId), 1, "~/");


                //# Admin Actions Page

                int AdminActionsPageId = InsertPage("actions", "Admin Actions", "Admin Actions", "", RedirectTemplateName, AdminPageId, -1, false);

                // -- redirect the admin actions page to the home page.
                InsertRedirectPlaceholder(CmsContext.getPageById(AdminActionsPageId), 1, "~/");


                //# Toggle Edit Admin Action Page
                InsertPage("gotoEdit", "Goto Edit Mode", "Goto Edit Mode", "", "_gotoEditMode", AdminActionsPageId, -1, false);

                InsertPage("gotoView", "Goto View Mode", "Goto View Mode", "", "_gotoViewMode", AdminActionsPageId, -1, false);


                //# /_admin/actions/createPage
                InsertPage("createPage", "Create Page", "Create Page", "", "_CreateNewPagePopup", AdminActionsPageId, -1, false);


                // # Delete Page Admin Action Page
                InsertPage("deletePage", "Delete Page", "Delete Page", "", "_DeletePagePopup", AdminActionsPageId, -1, false);


                //# Sort Sub Pages Admin Action Page
                InsertPage("sortSubPages", "Sort Sub Pages", "Sort Sub Pages", "", "_SortSubPagesPopup", AdminActionsPageId, -1, false);

                //# Change Menu Visibiity (Show In Menu indicator) Admin Action Page
                InsertPage("MenuVisibilityPopup", "Change Menu Visibility", "Change Menu Visibility", "", "_MenuVisibilityPopup", AdminActionsPageId, -1, false);

                // /_admin/actions/movePage
                InsertPage("movePage", "Move Page", "Move Page", "", "_MovePagePopup", AdminActionsPageId, -1, false);


                // /_admin/actions/renamePage
                InsertPage("renamePage", "Rename Page", "Rename Page", "", "_RenamePagePopup", AdminActionsPageId, -1, false);

                // /_admin/actions/killLock
                InsertPage("killLock", "Kill Edit Page Lock", "Kill Edit Page Lock", "", "_KillLockPopup", AdminActionsPageId, -1, false);


                // /_admin/actions/changeTemplate
                InsertPage("changeTemplate", "Change Page's Template", "Change Page's Template", "", "_ChangePageTemplatePopup", AdminActionsPageId, -1, false);


                // /_admin/actions/deleteFileLibrary
                InsertPage("deleteFileLibrary", "Delete a file library", "Delete a file library", "", "_DeleteFileLibraryPopup", AdminActionsPageId, -1, false);


                //# Admin Tools page (/_admin/Audit)
                InsertPage("Audit", "Administration Tools", "Admin Tools", "", "_AdminMenuPopup", AdminPageId, -1, false);

                //# view revisions page (/_admin/ViewRevisions)
                InsertPage("ViewRevisions", "View Page Revisions", "View Page Revisions", "", "_PageRevisionsPopup", AdminPageId, -1, false);

                //# EditUsers page (/_admin/EditUsers)
                InsertPage("EditUsers", "Edit Users", "Edit Users", "", "_EditUsersPopup", AdminPageId, -1, false);

                // edit job location page
                InsertPage("JobLocation", "Job Location", "Job Location", "", "_JobLocationPopup", AdminPageId, -1, false);

                // edit event calendar category page
                InsertPage("EventCalendarCategory", "Event Calendar Category", "Event Calendar Category", "", "_EventCalendarCategoryPopup", AdminPageId, -1, false);

                // edit File Library category page
                InsertPage("FileLibraryCategory", "File Library Category", "File Library Category", "", "_FileLibraryCategoryPopup", AdminPageId, -1, false);

                // delete File Library page
                InsertPage("deleteFileLibrary", "Delete File Library", "Delete File Library", "", "_DeleteFileLibraryPopup", AdminPageId, -1, false);

                // --------------------------------
                // /_Internal Page
                int InternalPageId = InsertPage("_internal", "Internal CMS Functions", "Internal CMS Functions", "", RedirectTemplateName, HomePageId, -1, false);

                // -- redirect the /_internal page to the home page.
                InsertRedirectPlaceholder(CmsContext.getPageById(InternalPageId), 1, "~/");

                //# Show Single Image page (/_internal/showImage)
                InsertPage("showImage", "Show Image", "Show Image", "", "_SingleImageDisplay", InternalPageId, -1, false);

                l_msg.Text = "All standard pages have been added successfully.";
            }
            catch (Exception ex)
            {
                l_msg.Text = "Error: Standard Pages could not all be added. The state of the database is currently unknown. Please manually delete the database and start again.";
            }
        } // b_db_Click
 public ProductCategoryRepository(CmsContext CmsDBContext) : base(CmsDBContext)
 {
 }
예제 #31
0
 public async Task<IEnumerable<Post>> GetPublishedPostsAsync()
 {
     using (var db = new CmsContext())
     {
         return await db.Posts
             .Include("Author")
             .Where(p => p.Published < DateTime.Now)
             .OrderByDescending(p => p.Published)
             .ToArrayAsync();
     }
 }
 public UserManagerController(IPageManagerService pageManagerService, UserManager <IdentityUser> userManager, CmsContext context, SignInManager <IdentityUser> signInManager)
 {
     _pageManagerService = pageManagerService;
     _userManager        = userManager;
     _signInManager      = signInManager;
     _context            = context;
 }
예제 #33
0
 public PageGeneratorObject(CmsContext context)
 {
     //this.context=context;
     this._site = new PageSite(context.CurrentSite);
 }
예제 #34
0
 public LocationsController()
 {
     _cms = new CmsContext();
 }
 public Noticia Get([FromServices] CmsContext _db, int id)
 {
     return(_db.Noticias.Find(id));
 }
 public IEnumerable <Noticia> Get([FromServices] CmsContext _db)
 {
     return(_db.Noticias);
 }
예제 #37
0
        /// <summary>
        /// 文档页提交
        /// </summary>
        /// <param name="context"></param>
        /// <param name="allhtml"></param>
        public static void PostArchive(CmsContext context, string allhtml)
        {
            var form = context.Request.Form;
            var rsp  = context.Response;

            //检测网站状态
            if (!context.CheckSiteState())
            {
                return;
            }


            string id = form["id"];     //文档编号
            Member member;              //会员

            //提交留言
            if (form["action"] == "comment")
            {
                id = form["ce_id"];

                string view_name = form["ce_nickname"];
                string content   = form["ce_content"];
                int    memberID;
                member = UserState.Member.Current;

                //校验验证码
                if (!CheckVerifyCode(form["ce_verifycode"]))
                {
                    rsp.Write(ScriptUtility.ParentClientScriptCall("cetip(false,'验证码不正确!');jr.$('ce_verifycode').nextSibling.onclick();"));
                    return;
                }
                else if (String.Compare(content, "请在这里输入评论内容", true) == 0 || content.Length == 0)
                {
                    rsp.Write(ScriptUtility.ParentClientScriptCall("cetip(false,'请输入内容!'); "));
                    return;
                }
                else if (content.Length > 200)
                {
                    rsp.Write(ScriptUtility.ParentClientScriptCall("cetip(false,'评论内容长度不能大于200字!'); "));
                    return;
                }

                if (member == null)
                {
                    if (String.IsNullOrEmpty(view_name))
                    {
                        //会员未登录时,需指定名称
                        rsp.Write(ScriptUtility.ParentClientScriptCall("cetip(false,'不允许匿名评论!'); "));
                        return;
                    }
                    else
                    {
                        //补充用户
                        content  = String.Format("(u:'{0}'){1}", view_name, content);
                        memberID = 0;
                    }
                }
                else
                {
                    memberID = UserState.Member.Current.ID;
                }
                CmsLogic.Comment.InsertComment(id, memberID, context.Request.UserHostAddress, content);
                rsp.Write(ScriptUtility.ParentClientScriptCall("cetip(false,'提交成功!'); setTimeout(function(){location.reload();},500);"));
                return;
            }
        }
예제 #38
0
 protected abstract XElement CreateElement(CmsContext context, CmsPart part);
예제 #39
0
        }         // RenderEdit

        public override void RenderInViewMode(HtmlTextWriter writer, CmsPage page, int identifier, CmsLanguage langToRenderFor, string[] paramList)
        {
            ImageGalleryData data = new ImageGalleryData();

            data.subDir          = "images" + DirSeperator + "ImageGallery" + DirSeperator;
            data.thumbSize       = 200;
            data.largeSize       = 500;
            data.numThumbsPerRow = 3;

            ImageGalleryDb db = new ImageGalleryDb();

            data = db.getImageGallery(page, identifier, true);

            if (!data.subDir.EndsWith(DirSeperator))
            {
                data.subDir += DirSeperator;
            }



            if (currentViewRenderMode == RenderMode.FullSize)
            {             // -- render full size
                writer.Write("<div class=\"ImageGallery FullSize\">");
                string jpg = PageUtils.getFromForm("galleryImg", "");
                if (jpg == "")
                {
                    writer.Write("Invalid galleryImg parameter");
                    return;
                }

                string imgCaption            = "";
                int    currentImageDataIndex = -1;
                for (int i = 0; i < data.ImageData.Length; i++)
                {
                    ImageGalleryImageData d = data.ImageData[i];
                    if (Path.GetFileName(d.Filename) == Path.GetFileName(jpg) || d.Filename == jpg)
                    {
                        imgCaption            = "<p align=\"center\" class=\"caption full\">" + d.Caption + "</p>";
                        currentImageDataIndex = i;
                        break;
                    }
                }

                string imgFilenameUnderAppPath = data.subDir + Path.GetFileName(jpg);
                string largeUrl = CmsContext.UserInterface.ShowThumbnailPage.getThumbDisplayUrl(imgFilenameUnderAppPath, data.largeSize, -1);

                string backUrl = CmsContext.getUrlByPagePath(page.Path);
                writer.Write("<p class=\"ImageGalleryBackLink\"><a class=\"ImageGalleryBackLink\" href=\"" + backUrl + "\">&#171; back to thumbnails</a><p>");

                List <string> nextPrevLinks = new List <string>();
                if (currentImageDataIndex > 0)
                {
                    NameValueCollection prevImgParams = new NameValueCollection();
                    prevImgParams.Add("galleryMode", Convert.ToInt32(RenderMode.FullSize).ToString());
                    prevImgParams.Add("galleryImg", Path.GetFileName(data.ImageData[currentImageDataIndex - 1].Filename));
                    string prevUrl  = CmsContext.getUrlByPagePath(page.Path, prevImgParams);
                    string prevHtml = "<a class=\"ImageGalleryBackLink prev\" href=\"" + prevUrl + "\">&#171; prev</a>";
                    nextPrevLinks.Add(prevHtml);
                }

                if (data.ImageData.Length > 1 && currentImageDataIndex < (data.ImageData.Length - 1))
                {
                    NameValueCollection nextImgParams = new NameValueCollection();
                    nextImgParams.Add("galleryMode", Convert.ToInt32(RenderMode.FullSize).ToString());
                    nextImgParams.Add("galleryImg", Path.GetFileName(data.ImageData[currentImageDataIndex + 1].Filename));
                    string nextUrl  = CmsContext.getUrlByPagePath(page.Path, nextImgParams);
                    string nextHtml = "<a class=\"ImageGalleryBackLink next\" href=\"" + nextUrl + "\">next &#187;</a>";
                    nextPrevLinks.Add(nextHtml);
                }

                if (nextPrevLinks.Count > 0)
                {
                    writer.Write("<p class=\"ImageGalleryBackLink\">" + string.Join(" | ", nextPrevLinks.ToArray()) + "</p>");
                }


                writer.Write("<img class=\"ImageGalleryFullSizedImage\" src=\"" + largeUrl + "\">");
                writer.WriteLine(imgCaption);
            }
            else
            {             // -- render the directory
                writer.Write("<div class=\"ImageGallery thumbnails\">");

                string ImageGalleryId = "ImageGallery_" + page.Id.ToString() + "_" + identifier.ToString();
                string thumbViewHtml  = getHtmlForThumbView(page, data, ImageGalleryId, false);
                writer.WriteLine(thumbViewHtml);
            }     // render directory
            writer.Write("</div>");
        }         // RenderView
        public async Task<IEnumerable<Post>> GetPageAsync(int pageNumber, int pageSize)
        {
            using (var db = new CmsContext())
            {
                var skip = (pageNumber - 1) * pageSize;

                return await db.Posts.Where(p => p.Published < DateTime.Now)
                               .Include("Author")
                               .OrderByDescending(p => p.Published)
                               .Skip(skip)
                               .Take(pageSize)
                               .ToArrayAsync();
            }
        }
예제 #41
0
 public CartController(CmsContext context)
 {
     this.context = context;
 }
 protected override XElement CreateElement(CmsContext context, CmsPart part)
 {
     return Parse(new CodeColorizer().Colorize(part.Value, GetLanguage(part.ContentSubType)));
 }
예제 #43
0
        /// <summary>
        /// 访问文档
        /// </summary>
        /// <param name="context"></param>
        /// <param name="allhtml"></param>
        public static void RenderArchive(CmsContext context, string allhtml)
        {
            string     id = null;
            string     html;
            ArchiveDto archive = default(ArchiveDto);

            //检测网站状态
            if (!context.CheckSiteState())
            {
                return;
            }

            //检查缓存
            if (!context.CheckAndSetClientCache())
            {
                return;
            }


            var siteId = context.CurrentSite.SiteId;

            ICmsPageGenerator cmsPage = new PageGeneratorObject(context);


            Regex paramRegex = new Regex("/*([^/]+).html$", RegexOptions.IgnoreCase);

            if (paramRegex.IsMatch(allhtml))
            {
                id      = paramRegex.Match(allhtml).Groups[1].Value;
                archive = ServiceCall.Instance.ArchiveService.GetArchiveByIdOrAlias(siteId, id);
            }

            if (archive.Id <= 0)
            {
                RenderNotFound(context);
                return;
            }
            else
            {
                //跳转
                if (!String.IsNullOrEmpty(archive.Location))
                {
                    string url;
                    if (Regex.IsMatch(archive.Location, "^http://", RegexOptions.IgnoreCase))
                    {
                        url = archive.Location;
                    }
                    else
                    {
                        if (archive.Location.StartsWith("/"))
                        {
                            throw new Exception("URL不能以\"/\"开头!");
                        }
                        url = String.Concat(context.SiteDomain, "/", archive.Location);
                    }

                    context.Response.Redirect(url, true);  //302

                    //context.Response.StatusCode = 301;
                    //context.Render(@"<html><head><meta name=""robots"" content=""noindex""><script>location.href='" +
                    //                   url + "';</script></head><body></body></html>");

                    return;
                }

                BuiltInArchiveFlags flag = ArchiveFlag.GetBuiltInFlags(archive.Flags);

                if ((flag & BuiltInArchiveFlags.Visible) != BuiltInArchiveFlags.Visible)
                //|| (flag & BuiltInArchiveFlags.IsSystem)== BuiltInArchiveFlags.IsSystem)   //系统文档可以单独显示
                {
                    RenderNotFound(context);
                    return;
                }

                CategoryDto category = archive.Category;

                if (!(category.Id > 0))
                {
                    RenderNotFound(context);
                    return;
                }
                else
                {
                    string appPath = AtNet.Cms.Cms.Context.SiteAppPath;
                    if (appPath != "/")
                    {
                        appPath += "/";
                    }

                    if ((flag & BuiltInArchiveFlags.AsPage) == BuiltInArchiveFlags.AsPage)
                    {
                        string pattern     = "^" + appPath + "[0-9a-zA-Z]+/[\\.0-9A-Za-z_-]+\\.html$";
                        string pagePattern = "^" + appPath + "[\\.0-9A-Za-z_-]+\\.html$";

                        if (!Regex.IsMatch(context.Request.Path, pagePattern))
                        {
                            context.Response.StatusCode       = 301;
                            context.Response.RedirectLocation = String.Format("{0}{1}.html",
                                                                              appPath,
                                                                              String.IsNullOrEmpty(archive.Alias) ? archive.StrId : archive.Alias
                                                                              );
                            context.Response.End();
                            return;
                        }
                    }
                    else
                    {
                        //校验栏目是否正确
                        string categoryPath = category.UriPath;
                        string _path        = appPath != "/" ? allhtml.Substring(appPath.Length - 1) : allhtml;

                        if (!_path.StartsWith(categoryPath + "/"))
                        {
                            RenderNotFound(context);
                            return;
                        }

                        //设置了别名,则跳转
                        if (!String.IsNullOrEmpty(archive.Alias) && String.Compare(id, archive.Alias, true) != 0)
                        {
                            context.Response.StatusCode       = 301;
                            context.Response.RedirectLocation = String.Format("{0}{1}/{2}.html",
                                                                              appPath,
                                                                              categoryPath,
                                                                              String.IsNullOrEmpty(archive.Alias) ? archive.StrId : archive.Alias
                                                                              );
                            context.Response.End();
                            return;
                        }
                    }


                    //增加浏览次数
                    ++archive.ViewCount;
                    new System.Threading.Thread(() =>
                    {
                        try
                        {
                            ServiceCall.Instance.ArchiveService.AddCountForArchive(siteId, archive.Id, 1);
                        }
                        catch
                        {
                        }
                    }).Start();

                    //显示页面
                    html = cmsPage.GetArchive(archive);

                    //再次处理模板
                    //html = PageUtility.Render(html, new { }, false);
                }
            }

            // return html;
            context.Render(html);
        }
예제 #44
0
 protected override XElement CreateElement(CmsContext context, CmsPart part)
 {
     return Parse(part.Value);
 }
예제 #45
0
        /// <summary>
        /// 呈现首页
        /// </summary>
        /// <param name="context"></param>
        public static void RenderIndex(CmsContext context)
        {
            //检测网站状态
            if (!context.CheckSiteState())
            {
                return;
            }

            //检查缓存
            if (!context.CheckAndSetClientCache())
            {
                return;
            }

            SiteDto site = context.CurrentSite;

            //跳转
            if (!String.IsNullOrEmpty(site.Location))
            {
                //string url;
                //if (Regex.IsMatch(archive.Location, "^http://", RegexOptions.IgnoreCase))
                //{
                //    url = archive.Location;
                //}
                //else
                //{
                //    if (archive.Location.StartsWith("/")) throw new Exception("URL不能以\"/\"开头!");
                //    url = String.Concat(context.SiteDomain, site.Location);
                //}

                context.Response.Redirect(site.Location, true);  //302

                return;
            }


            int    siteID  = site.SiteId;
            string cacheID = String.Concat("cms_s", siteID.ToString(), "_index_page");

            ICmsPageGenerator cmsPage = new PageGeneratorObject(context);

            if (context.Request["cache"] == "0")
            {
                Cms.Cache.Rebuilt();
            }


            string html = String.Empty;

            if (Settings.Opti_IndexCacheSeconds > 0)
            {
                ICmsCache cache = Cms.Cache;
                object    obj   = cache.Get(cacheID);
                if (obj == null)
                {
                    html = cmsPage.GetIndex(null);
                    cache.Insert(cacheID, html, DateTime.Now.AddSeconds(Settings.Opti_IndexCacheSeconds));
                }
                else
                {
                    html = obj as string;
                }
            }
            else
            {
                //DateTime dt = DateTime.Now;
                html = cmsPage.GetIndex(null);
                //context.Render("<br />"+(DateTime.Now - dt).TotalMilliseconds.ToString() + "<br />");
            }

            //response.AddHeader("Cache-Control", "max-age=" + maxAge.ToString());
            context.Render(html);
        }
        /// <summary>
        /// Get the dependencies for FileLibrary
        /// </summary>
        /// <returns></returns>
        public override CmsDependency[] getDependencies()
        {
            List <CmsDependency> ret = new List <CmsDependency>();

            ret.Add(CmsFileDependency.UnderAppPath("images/_system/calendar/arrowLeft.jpg", new DateTime(2011, 3, 1)));
            ret.Add(CmsFileDependency.UnderAppPath("images/_system/arrowDown.jpg", new DateTime(2011, 3, 1)));

            ret.Add(CmsFileDependency.UnderAppPath("js/_system/FileLibrary/FileLibrary.js"));
            ret.Add(CmsFileDependency.UnderAppPath("js/_system/FileLibrary/FileLibraryCategory.js"));
            ret.Add(new CmsPageDependency(CmsConfig.getConfigValue("DeleteFileLibraryPath", "/_admin/actions/deleteFileLibrary"), CmsConfig.Languages));

            // -- database tables
            ret.Add(new CmsDatabaseTableDependency(@"
                CREATE TABLE `FileLibraryAggregator` (
                  `PageId` int(10) unsigned NOT NULL,
                  `Identifier` int(10) unsigned NOT NULL,
                  `LangCode` varchar(5) NOT NULL,
                  `NumFilesOverview` int(11) NOT NULL,
                  `NumFilesPerPage` int(11) NOT NULL,
                  `Deleted` datetime DEFAULT NULL,
                  PRIMARY KEY (`PageId`,`Identifier`,`LangCode`)
                ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
            "));
            ret.Add(new CmsDatabaseTableDependency(@"
                CREATE TABLE  `filelibrarydetails` (
                  `PageId` int(10) unsigned NOT NULL,
                  `Identifier` int(10) unsigned NOT NULL,
                  `LangCode` varchar(5) NOT NULL,
                  `Filename` varchar(255) NOT NULL,
                  `CategoryId` int(11) NOT NULL,
                  `Author` varchar(255) NOT NULL DEFAULT '',
                  `Description` text NOT NULL,
                  `LastModified` datetime NOT NULL,
                  `CreatedBy` varchar(255) NOT NULL,
                  `EventPageId` int(11) NOT NULL DEFAULT '-1',
                  `Deleted` datetime DEFAULT NULL,
                  PRIMARY KEY (`PageId`,`Identifier`,`LangCode`)
                ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
            "));
            ret.Add(new CmsDatabaseTableDependency(@"
                CREATE TABLE  `filelibrarycategory` (
                  `CategoryId` int(11) NOT NULL,
                  `LangCode` varchar(5) NOT NULL,
                  `EventRequired` int(1) NOT NULL DEFAULT '0',
                  `CategoryName` varchar(255) NOT NULL,
                  `SortOrdinal` int(11) NOT NULL DEFAULT '0',
                  PRIMARY KEY (`CategoryId`,`LangCode`)
                ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
            "));

            // -- REQUIRED config entries
            ret.Add(new CmsConfigItemDependency("FileLibrary.DetailsTemplateName"));
            ret.Add(new CmsConfigItemDependency("FileLibrary.NumEventsInList"));
            ret.Add(new CmsConfigItemDependency("FileLibrary.OverviewText"));
            ret.Add(new CmsConfigItemDependency("FileLibrary.NewUploadText"));
            ret.Add(new CmsConfigItemDependency("FileLibrary.CategoryText"));
            ret.Add(new CmsConfigItemDependency("FileLibrary.FileNameText"));
            ret.Add(new CmsConfigItemDependency("FileLibrary.AttachedEventText"));
            ret.Add(new CmsConfigItemDependency("FileLibrary.AttachToEventText"));
            ret.Add(new CmsConfigItemDependency("FileLibrary.FileText"));
            ret.Add(new CmsConfigItemDependency("FileLibrary.SeeFileDetailsText"));
            ret.Add(new CmsConfigItemDependency("FileLibrary.BackToText"));
            ret.Add(new CmsConfigItemDependency("FileLibrary.TabText"));
            ret.Add(new CmsConfigItemDependency("FileLibrary.DownloadText"));
            ret.Add(new CmsConfigItemDependency("FileLibrary.LinkOpensNewWindowText"));
            ret.Add(new CmsConfigItemDependency("FileLibrary.AuthorText"));
            ret.Add(new CmsConfigItemDependency("FileLibrary.DocumentAbstractText"));
            ret.Add(new CmsConfigItemDependency("FileLibrary.UploadedByText"));
            ret.Add(new CmsConfigItemDependency("FileLibrary.LastUpdatedText"));
            ret.Add(new CmsConfigItemDependency("FileLibrary.ImagePreviewText"));
            ret.Add(new CmsConfigItemDependency("FileLibrary.EditText"));
            ret.Add(new CmsConfigItemDependency("FileLibrary.DateTimeText"));
            ret.Add(new CmsConfigItemDependency("FileLibrary.EventCategoryText"));
            ret.Add(new CmsConfigItemDependency("FileLibrary.DescriptionText"));
            ret.Add(new CmsConfigItemDependency("FileLibrary.AddFileText"));
            ret.Add(new CmsConfigItemDependency("FileLibrary.MaxFileSizeText"));
            ret.Add(new CmsConfigItemDependency("FileLibrary.UploadButtonText"));
            ret.Add(new CmsConfigItemDependency("FileLibrary.EventNotAttachedText"));
            ret.Add(new CmsConfigItemDependency("FileLibrary.PageText"));

            // make sure that all files associated with FileLibraryDetails placeholder are live.
            Dictionary <CmsPage, CmsPlaceholderDefinition[]> phDefsDict = CmsContext.getAllPlaceholderDefinitions("FileLibraryDetails", CmsContext.HomePage, CmsContext.PageGatheringMode.FullRecursion);

            foreach (CmsPage page in phDefsDict.Keys)
            {
                foreach (CmsPlaceholderDefinition phDef in phDefsDict[page])
                {
                    foreach (CmsLanguage lang in CmsConfig.Languages)
                    {
                        FileLibraryDetailsData fileData = db.fetchDetailsData(page, phDef.Identifier, lang, true);
                        if (fileData.FileName != "")
                        {
                            string filenameOnDisk = FileLibraryDetailsData.getTargetNameOnDisk(page, phDef.Identifier, lang, fileData.FileName);
                            ret.Add(new CmsFileDependency(filenameOnDisk));
                            if (fileData.EventPageId >= 0) // make sure that the linked event page exists.
                            {
                                ret.Add(new CmsPageDependency(fileData.EventPageId, new CmsLanguage[] { lang }));
                            }
                        }
                    } // foreach lang
                }     // foreach placeholder definition
            }         // foreach page

            return(ret.ToArray());
        }
예제 #47
0
        /// <summary>
        /// 呈现分类页
        /// </summary>
        /// <param name="context"></param>
        /// <param name="catPath"></param>
        /// <param name="page"></param>
        public static void RenderCategory(CmsContext context, string catPath, int page)
        {
            if (catPath.StartsWith("/"))
            {
                catPath = catPath.Substring(1);
            }
            // 去掉末尾的"/"
            if (catPath.EndsWith("/"))
            {
                catPath = catPath.Substring(0, catPath.Length - 1);
            }
            var siteId   = context.CurrentSite.SiteId;
            var category = ServiceCall.Instance.SiteService.GetCategory(siteId, catPath);

            if (!(category.ID > 0))
            {
                RenderNotFound(context);
                return;
            }

            if (!catPath.StartsWith(category.Path))
            {
                RenderNotFound(context);
                return;
            }

            ICmsPageGenerator cmsPage = new PageGeneratorObject(context);

            /*********************************
            *  @ 单页,跳到第一个特殊文档,
            *  @ 如果未设置则最新创建的文档,
            *  @ 如未添加文档则返回404
            *********************************/
            if (string.IsNullOrEmpty(category.Location))
            {
                try
                {
                    var html = cmsPage.GetCategory(category, page);
                    context.HttpContext.Response.WriteAsync(html);
                }
                catch (TemplateException ex)
                {
                    RenderError(context, ex, false);
                }
            }
            else
            {
                var url = category.Location;
                if (category.Location.IndexOf("://") != -1)
                {
                    url = category.Location;
                }
                else
                {
                    if (!category.Location.StartsWith("/"))
                    {
                        url = string.Concat(context.SiteAppPath, context.SiteAppPath == "/" ? "" : "/",
                                            category.Location);
                    }
                }

                context.HttpContext.Response.Redirect(url, false); //302
            }
        }
예제 #48
0
 public DevicesController()
 {
     _cms = new CmsContext();
 }
예제 #49
0
 public AdvertisingRepository(CmsContext CmsContext) : base(CmsContext)
 {
 }
예제 #50
0
        /*
         * public static string getStandardHtmlView_Old(SingleImageData image, FullSizeImageLinkMode fullSizeLinkMode, string fullSizeDisplayUrl)
         * {
         *  StringBuilder html = new StringBuilder();
         *  if (image.ImagePath != "")
         *  {
         *      bool linkToLarger = false;
         *      if (image.FullSizeDisplayBoxHeight > 0 || image.FullSizeDisplayBoxWidth > 0)
         *          linkToLarger = true;
         *
         *      string thumbUrl = showThumbPage.getThumbDisplayUrl(image.ImagePath, image.ThumbnailDisplayBoxWidth, image.ThumbnailDisplayBoxHeight);
         *      System.Drawing.Size ThumbSize = showThumbPage.getDisplayWidthAndHeight(image.ImagePath, image.ThumbnailDisplayBoxWidth, image.ThumbnailDisplayBoxHeight);
         *
         *      html.Append("<div class=\"SingleImagePlaceholder View\">");
         *      if (linkToLarger)
         *      {
         *          bool useSubmodal = CmsConfig.getConfigValue("SingleImagePlaceHolderUseSubModal", false);
         *          bool useMultibox = CmsConfig.getConfigValue("SingleImagePlaceHolderUseMultibox", false);
         *
         *
         *          int popupPaddingWidth = CmsConfig.getConfigValue("SingleImagePlaceHolderPopupPaddingWidth", 50);
         *          int popupPaddingHeight = CmsConfig.getConfigValue("SingleImagePlaceHolderPopupPaddingHeight", 60);
         *
         *          int maxPopWidth = CmsConfig.getConfigValue("SingleImagePlaceHolderPopupMaxWidth", 700 - popupPaddingWidth);
         *          int maxPopHeight = CmsConfig.getConfigValue("SingleImagePlaceHolderPopupMaxHeight", 500 - popupPaddingHeight);
         *
         *
         *          int minPopWidth = CmsConfig.getConfigValue("SingleImagePlaceHolderPopupMinWidth", 200);
         *          int minPopHeight = CmsConfig.getConfigValue("SingleImagePlaceHolderPopupMinHeight", 200);
         *
         *
         *          string showLargerPagePath = CmsConfig.getConfigValue("SingleImage.DisplayPath", "/_internal/showImage");
         *
         *          NameValueCollection largerParams = new NameValueCollection();
         *          largerParams.Add("i", image.SingleImageId.ToString());
         *          string showLargerPageUrl = CmsContext.getUrlByPagePath(showLargerPagePath, largerParams);
         *
         *          System.Drawing.Size imgLargeSize = showThumbPage.getDisplayWidthAndHeight(image.ImagePath, image.FullSizeDisplayBoxWidth, image.FullSizeDisplayBoxHeight);
         *
         *          if (ThumbSize.Width > imgLargeSize.Width || ThumbSize.Height > imgLargeSize.Height)
         *          {
         *              linkToLarger = false;
         *          }
         *          else
         *          {
         *
         *              int popWidth = imgLargeSize.Width + popupPaddingWidth;
         *              int popHeight = imgLargeSize.Height + popupPaddingHeight;
         *
         *              if (popWidth < minPopWidth)
         *                  popWidth = minPopWidth;
         *              if (popHeight < minPopHeight)
         *                  popHeight = minPopHeight;
         *
         *              if (popWidth > maxPopWidth)
         *                  popWidth = maxPopWidth;
         *              if (popHeight > maxPopHeight)
         *                  popHeight = maxPopHeight;
         *
         *              if (useSubmodal &&
         *                  (fullSizeLinkMode == FullSizeImageLinkMode.SubModalOrPopupFromConfig || fullSizeLinkMode == FullSizeImageLinkMode.SubModalWindow))
         *              {
         *                  string submodalCssClass = "class=\"submodal-" + popWidth.ToString() + "-" + popHeight.ToString() + "\"";
         *                  html.Append("<a " + submodalCssClass + " href=\"" + showLargerPageUrl + "\" >");
         *              }
         *              else if (useMultibox && (fullSizeLinkMode == FullSizeImageLinkMode.SubModalOrPopupFromConfig || fullSizeLinkMode == FullSizeImageLinkMode.SubModalWindow))
         *              {
         *                  string submodalCssClass = "class=\"mb\"";
         *                  html.Append("<a " + submodalCssClass + " href=\"" + showLargerPageUrl + "\" rel=\"width:" + popWidth + ",height:" + popHeight + "\" >");
         *              }
         *              else if (fullSizeLinkMode == FullSizeImageLinkMode.SingleImagePopup || fullSizeLinkMode == FullSizeImageLinkMode.SubModalOrPopupFromConfig)
         *              {
         *                  string onclick = "var w = window.open(this.href, 'popupLargeImage', 'toolbar=no,menubar=no,resizable=yes,scrollbars=yes,status=yes,height=" + popWidth.ToString() + ",width=" + popWidth.ToString() + "'); ";
         *                  onclick += " return false;";
         *                  html.Append("<a href=\"" + showLargerPageUrl + "\" onclick=\"" + onclick + "\">");
         *              }
         *              else if (fullSizeLinkMode == FullSizeImageLinkMode.ProvidedUrl)
         *                  html.Append("<a href=\"" + fullSizeDisplayUrl + "\">");
         *              else
         *                  linkToLarger = false;
         *          } // else
         *      } // if link to larger
         *
         *      string width = "";
         *      string height = "";
         *      if (!ThumbSize.IsEmpty)
         *      {
         *          width = " width=\"" + ThumbSize.Width + "\"";
         *          height = " height=\"" + ThumbSize.Height.ToString() + "\"";
         *      }
         *
         *      html.Append("<img src=\"" + thumbUrl + "\"" + width + "" + height + ">");
         *      if (linkToLarger)
         *      {
         *          html.Append("</a>");
         *      }
         *
         *      if (image.Caption.Trim() != "")
         *      {
         *          html.Append("<div class=\"caption\">");
         *          html.Append(image.Caption);
         *          html.Append("</div>"); // caption
         *      }
         *
         *      if (image.Credits.Trim() != "")
         *      {
         *          html.Append("<div class=\"credits\">");
         *          string creditsPrefix = CmsConfig.getConfigValue("SingleImage.CreditsPrefix", "");
         *          html.Append(creditsPrefix + image.Credits);
         *          html.Append("</div>"); // credits
         *      }
         *
         *      if (linkToLarger)
         *      {
         *          string clickToEnlargeText = CmsConfig.getConfigValue("SingleImage.ClickToEnlargeText", "");
         *          if (clickToEnlargeText != "")
         *          {
         *              html.Append("<div class=\"clickToEnlarge\">");
         *              html.Append(clickToEnlargeText);
         *              html.Append("</div>"); // clickToEnlarge
         *          }
         *      }
         *
         *      html.Append("</div>");
         *  }
         *
         *  return html.ToString();
         * }
         */

        public override void RenderInViewMode(HtmlTextWriter writer, CmsPage page, int identifier, CmsLanguage langToRenderFor, string[] paramList)
        {
            // -- all rendering in View mode is handled by getStandardHtmlView()
            SingleImageDb   db    = (new SingleImageDb());
            SingleImageData image = db.getSingleImage(page, identifier, langToRenderFor, true);

            int fullWidth  = CmsConfig.getConfigValue("SingleImage.FullSizeDisplayWidth", -1);
            int fullHeight = CmsConfig.getConfigValue("SingleImage.FullSizeDisplayHeight", -1);

            int thumbWidth  = getThumbDisplayWidth(page, paramList);
            int thumbHeight = getThumbDisplayHeight(page, paramList);

            int popupPaddingWidth  = CmsConfig.getConfigValue("SingleImage.PopupPaddingWidth", 50);
            int popupPaddingHeight = CmsConfig.getConfigValue("SingleImage.PopupPaddingHeight", 60);

            int maxPopWidth  = CmsConfig.getConfigValue("SingleImage.PopupMaxWidth", 700 - popupPaddingWidth);
            int maxPopHeight = CmsConfig.getConfigValue("SingleImage.PopupMaxHeight", 500 - popupPaddingHeight);


            int minPopWidth  = CmsConfig.getConfigValue("SingleImage.PopupMinWidth", 200);
            int minPopHeight = CmsConfig.getConfigValue("SingleImage.PopupMinHeight", 200);

            string withLinkTemplate    = CmsConfig.getConfigValue("SingleImage.WithLinkTemplate", "<a href=\"{5}\"><img src=\"{2}\" width=\"{0}\" height=\"{1}\" /></a>");
            string withoutLinkTemplate = CmsConfig.getConfigValue("SingleImage.WithoutLinkTemplate", "<img src=\"{2}\" width=\"{0}\" height=\"{1}\" />");

            string showLargerPagePath = CmsConfig.getConfigValue("SingleImage.DisplayPath", "/_internal/showImage");

            NameValueCollection largerParams = new NameValueCollection();

            largerParams.Add("i", image.SingleImageId.ToString());
            string showLargerPageUrl = CmsContext.getUrlByPagePath(showLargerPagePath, largerParams);

            System.Drawing.Size imgLargeSize = showThumbPage.getDisplayWidthAndHeight(image.ImagePath, fullWidth, fullHeight);

            int popWidth  = imgLargeSize.Width + popupPaddingWidth;
            int popHeight = imgLargeSize.Height + popupPaddingHeight;

            if (popWidth < minPopWidth)
            {
                popWidth = minPopWidth;
            }
            if (popHeight < minPopHeight)
            {
                popHeight = minPopHeight;
            }

            if (popWidth > maxPopWidth)
            {
                popWidth = maxPopWidth;
            }
            if (popHeight > maxPopHeight)
            {
                popHeight = maxPopHeight;
            }


            // -- create the SingleImageDisplayInfo object
            SingleImageDisplayInfo displayInfo = new SingleImageDisplayInfo();

            displayInfo.ImagePath = image.ImagePath;

            displayInfo.FullImageDisplayBox  = new System.Drawing.Size(fullWidth, fullHeight);
            displayInfo.ThumbImageDisplayBox = new System.Drawing.Size(thumbWidth, thumbHeight);
            displayInfo.PopupDisplayBox      = new System.Drawing.Size(popWidth, popHeight);

            displayInfo.FullImageDisplayUrl = showLargerPageUrl;

            displayInfo.ThumbDisplayWithLinkTemplate    = withLinkTemplate;
            displayInfo.ThumbDisplayWithoutLinkTemplate = withoutLinkTemplate;

            displayInfo.Caption = image.Caption;
            displayInfo.Credits = image.Credits;

            // -- Multilingual CreditsPromptPrefix
            string creditPrefix = CmsConfig.getConfigValue("SingleImage.CreditsPromptPrefix", "");

            string[] creditPrefixParts = creditPrefix.Split(new char[] { CmsConfig.PerLanguageConfigSplitter }, StringSplitOptions.RemoveEmptyEntries);
            if (creditPrefixParts.Length >= CmsConfig.Languages.Length)
            {
                int index = CmsLanguage.IndexOf(langToRenderFor.shortCode, CmsConfig.Languages);
                if (index >= 0)
                {
                    creditPrefix = creditPrefixParts[index];
                }
            }

            // -- Multilingual ClickToEnlargeText
            string clickToEnlargeText = CmsConfig.getConfigValue("SingleImage.ClickToEnlargeText", "");

            string[] clickToEnlargeTextParts = clickToEnlargeText.Split(new char[] { CmsConfig.PerLanguageConfigSplitter }, StringSplitOptions.RemoveEmptyEntries);
            if (clickToEnlargeTextParts.Length >= CmsConfig.Languages.Length)
            {
                int index = CmsLanguage.IndexOf(langToRenderFor.shortCode, CmsConfig.Languages);
                if (index >= 0)
                {
                    clickToEnlargeText = clickToEnlargeTextParts[index];
                }
            }

            displayInfo.CreditsPromptPrefix = creditPrefix;
            displayInfo.ClickToEnlargeText  = clickToEnlargeText;

            string html = getStandardHtmlView(displayInfo);

            writer.WriteLine(html.ToString());
        } // RenderView
예제 #51
0
 public PagesController(CmsContext context)
 {
     this.context = context;
 }
        public override string Render()
        {
            string searchForFormName   = "searchfor";
            string replaceWithFormName = "replacewith";

            string searchFor   = PageUtils.getFromForm(searchForFormName, "");
            string replaceWith = PageUtils.getFromForm(replaceWithFormName, "");

            //@@TODO: add an option to only replace text (not HTML); use this: http://gallery.msdn.microsoft.com/ScriptJunkie/en-us/jQuery-replaceText-String-ce62ea13

            // -- because javascript regular expressions are used for the replacement, some search expressions will have unintended consequences
            //    note some of these are now escaped using EscapeJSRegex so can be used. "[", "]", "+", "*", "?", "$", "^",".",
            //     ref: http://www.w3schools.com/jsref/jsref_obj_regexp.asp
            string[] invalidSearchItems = new string[] { "{", "}", "\\w", "\\W", "\\d", "\\D", "\\s", "\\S", "\\b", "\\B", "\\0", "\\n", "\\f", "\\r", "\\t", "\\v", "\\x", "\\u" };
            string   _errorMessage      = "";

            if (searchFor.Trim() != "")
            {
                foreach (string s in invalidSearchItems)
                {
                    if (searchFor.IndexOf(s) > -1)
                    {
                        _errorMessage = "Error: searches can not contain \"" + s + "\".";
                    }
                } // foreach
            }

            if (searchFor.Trim() != "" && replaceWith.Trim() != "" && _errorMessage == "")
            {
                StringBuilder script = new StringBuilder();
                script.Append("var langCode = '" + CmsContext.currentLanguage.shortCode + "'; " + Environment.NewLine);
                script.Append("var buttonId = ''; " + Environment.NewLine);
                script.Append("function go(url, lcode, bId){" + Environment.NewLine);
                script.Append(" opener.location.href = url;" + Environment.NewLine);
                script.Append(" langCode = lcode;" + Environment.NewLine);
                script.Append(" buttonId = bId;" + Environment.NewLine);

                // These doesn't work: (doReplace is never called)
                // script.Append(" $(opener).bind('load', doReplace); " + Environment.NewLine);
                // script.Append(" $(opener.window).bind('load', doReplace); " + Environment.NewLine);
                // script.Append(" opener.onload = doReplace; " + Environment.NewLine);
                // script.Append(" opener.document.onload = doReplace; " + Environment.NewLine);
                // script.Append(" opener.window.onload = doReplace; " + Environment.NewLine);


                // This works; we just need to get the timeout correct (which depends on bandwidth
                // http://plugins.jquery.com/project/popupready
                script.Append(" setTimeout(poll, 1000);" + Environment.NewLine);
                script.Append(" function poll() {" + Environment.NewLine);
                script.Append("  var openerlen = jQuery(\"body *\", opener.document).length; " + Environment.NewLine);
                script.Append("  if (openerlen == 0 ) {" + Environment.NewLine);
                script.Append("   setTimeout(poll, 1000);" + Environment.NewLine);
                script.Append("  }" + Environment.NewLine);
                script.Append("  else {" + Environment.NewLine);
                script.Append("  $(opener.document).focus(); " + Environment.NewLine);
                script.Append("   setTimeout(doReplace, 2000); " + Environment.NewLine);
                script.Append("  }" + Environment.NewLine);
                script.Append(" }// poll" + Environment.NewLine);


                script.Append("} // go" + Environment.NewLine);

                script.Append("function numOccurrences(txt){" + Environment.NewLine);
                script.Append(" var r = txt.match(new RegExp('" + EscapeJSRegex(searchFor) + "','gi')); " + Environment.NewLine);
                script.Append(" if (r) return r.length; " + Environment.NewLine);
                script.Append(" return 0;" + Environment.NewLine);
                script.Append("}" + Environment.NewLine);


                script.Append("function setMsg(bodyEl, startNum, endNum, el){" + Environment.NewLine);
                script.Append(" var pos = el.offset(); " + Environment.NewLine);
                script.Append(" var e = $( opener.document.createElement('div') ); var nm =''; var n =1; " + Environment.NewLine);
                script.Append(" if (endNum - startNum > 1){ nm = (startNum+1) + ' - '+(endNum); n = endNum - (startNum); } else { nm= (endNum); }" + Environment.NewLine);
                script.Append(" e.html(nm+\": Replaced '" + searchFor + "' with '" + replaceWith + "' \"+n+\" times \");" + Environment.NewLine);
                script.Append(" e.css({'padding': '5px','font-size':'8pt', 'display':'block','z-index':'5000', 'font-weight':'bold', 'position':'absolute', 'top': pos.top, 'left': pos.left, 'background-color':'yellow', 'border': '2px solid red'});" + Environment.NewLine);

                script.Append(" bodyEl.append(e);" + Environment.NewLine);
                // script.Append(" alert($(document).scrollTop());" + Environment.NewLine);
                // Note: there is a bug in JQuery.offset() function that uses the document's scrollTop, not the context's scrollTop
                //       bug report: http://dev.jquery.com/ticket/6539
                script.Append(" e.css({'top': pos.top - 20 -  $(document).scrollTop() });" + Environment.NewLine);
                script.Append("}" + Environment.NewLine);



                script.Append("function doReplace(){" + Environment.NewLine);
                script.Append(" var bodyEl = $('#lang_'+langCode, opener.document);" + Environment.NewLine);

                script.Append(" var numChanges = 0;" + Environment.NewLine);

                script.Append(" $('#lang_'+langCode+' input:text,#lang_'+langCode+' textarea', opener.document).each(function(){" + Environment.NewLine);

                script.Append("     var ths = $(this); " + Environment.NewLine);
                // script.Append("     alert(ths.val());" + Environment.NewLine);
                script.Append("     if (ths.is(':visible') &&  ths.val().trim() != '' && ths.val().search(new RegExp('" + EscapeJSRegex(searchFor) + "','gi')) > -1 ) {" + Environment.NewLine);
                script.Append("         var startNum = numChanges; " + Environment.NewLine);
                script.Append("         numChanges+= numOccurrences(ths.val());" + Environment.NewLine);
                script.Append("         setMsg(bodyEl, startNum, numChanges, ths);" + Environment.NewLine);
                script.Append("         var v = ths.val().replace(new RegExp('" + EscapeJSRegex(searchFor) + "','gi'), '" + replaceWith + "');" + Environment.NewLine);
                script.Append("         ths.val(v);" + Environment.NewLine);
                script.Append("     }// if visible" + Environment.NewLine);
                script.Append(" });" + Environment.NewLine);

                script.Append(" if(opener.CKEDITOR && (opener.CKEDITOR.status == 'basic_loaded' || opener.CKEDITOR.status == 'basic_ready' || opener.CKEDITOR.status == 'ready') ){ " + Environment.NewLine);
                script.Append("     for(var edName in opener.CKEDITOR.instances) { " + Environment.NewLine);
                script.Append("         if ($('#'+edName, opener.document).closest('#lang_'+langCode, opener.document).is(':visible')) {" + Environment.NewLine);
                script.Append("             var d = opener.CKEDITOR.instances[edName].getData();" + Environment.NewLine);
                script.Append("             var numD = numOccurrences(d); " + Environment.NewLine);
                script.Append("             if (numD > 0) {" + Environment.NewLine);
                script.Append("                 var d2 = d.replace(new RegExp('" + EscapeJSRegex(searchFor) + "','gi'), '" + replaceWith + "'); " + Environment.NewLine);
                script.Append("                 var nStart = numChanges; numChanges += numD;" + Environment.NewLine);
                script.Append("                 setMsg(bodyEl, nStart, numChanges, $('#'+opener.CKEDITOR.instances[edName].container.$.id, opener.document));" + Environment.NewLine);
                script.Append("                 opener.CKEDITOR.instances[edName].setData(d2);" + Environment.NewLine);
                script.Append("             } // if " + Environment.NewLine);
                script.Append("         } // if " + Environment.NewLine);
                // script.Append("         alert('parent: '+$('#'+edName, opener.document).closest('#lang_en', opener.document).is(':visible'));" + Environment.NewLine);
                // window.CKEDITOR.instances['htmlcontent_1_1_en'].getData()
                script.Append("     }// for each editor" + Environment.NewLine);
                script.Append(" }" + Environment.NewLine);


                script.Append("$('#'+buttonId).val(numChanges+' replacements made');" + Environment.NewLine);
                script.Append(" alert('The text on this page has been updated ('+numChanges+' replacements made).\\nPlease save the page to continue.');" + Environment.NewLine);
                script.Append("}" + Environment.NewLine);

                CmsContext.currentPage.HeadSection.AddJSStatements(script.ToString());

                CmsContext.currentPage.HeadSection.AddJavascriptFile(JavascriptGroup.Library, "js/_system/jquery/jquery-1.4.1.min.js");
            }

            StringBuilder html = new StringBuilder();

            html.Append(CmsContext.currentPage.getFormStartHtml("SearchReplaceForm"));
            html.Append("<table>");
            html.Append("<tr>");
            html.Append("<td>Search for:</td>");
            html.Append("<td>" + PageUtils.getInputTextHtml(searchForFormName, searchForFormName, searchFor, 30, 255) + "</td>");
            html.Append("</tr>");

            html.Append("<tr>");
            html.Append("<td>Replace with:</td>");
            html.Append("<td>" + PageUtils.getInputTextHtml(replaceWithFormName, replaceWithFormName, replaceWith, 30, 255) + "</td>");
            html.Append("</tr>");

            html.Append("<tr>");
            html.Append("<td colspan=\"2\"><input type=\"submit\" value=\"Search in all pages\" /> (no replacement of page contents will be done)</td>");
            html.Append("</tr>");

            html.Append("</table>");
            html.Append("<em>Warning! This searches and replaces the raw HTML for a page, so be careful what you search for! The search is not case-sensitive, and the replacement is done exactly.</em>");

            if (_errorMessage != "")
            {
                html.Append("<p style=\"color: red; font-weight: bold;\">" + _errorMessage + "</p>");
            }

            html.Append(PageUtils.getHiddenInputHtml("RunTool", GetType().Name) + EOL);

            html.Append(CmsContext.currentPage.getFormCloseHtml("SearchReplaceForm"));
            // -- do the search
            if (searchFor.Trim() != "" && replaceWith.Trim() != "" && _errorMessage == "")
            {
                html.Append("<table border=\"1\">");
                PageSearchResults[] searchResults = getAllPagesContainingText(searchFor);
                if (searchResults.Length == 0)
                {
                    html.Append("<p><strong>No pages were found that contained \"" + searchFor + "\"</strong></p>");
                }
                else
                {
                    int i = 1;
                    foreach (PageSearchResults searchResult in searchResults)
                    {
                        CmsPage p = searchResult.Page;

                        html.Append("<tr>");
                        html.Append("<td>" + p.getTitle(searchResult.Language) + " (" + searchResult.Language.shortCode + ")</td>");

                        NameValueCollection paramList = new NameValueCollection();
                        paramList.Add("target", p.ID.ToString());
                        string openEditUrl = CmsContext.getUrlByPagePath(CmsConfig.getConfigValue("GotoEditModePath", "/_admin/action/gotoEdit"), paramList, searchResult.Language);

                        string buttonId = "searchReplaceb_" + i.ToString();
                        i++;

                        html.Append("<td>");
                        html.Append("<input id=\"" + buttonId + "\" type=\"button\" onclick=\"go('" + openEditUrl + "', '" + searchResult.Language.shortCode + "','" + buttonId + "'); return false;\" value=\"open page &amp; replace\">");

                        html.Append("</td>");

                        html.Append("</tr>");
                    } // foreach page Id
                }
                html.Append("</table>");
            }
            return(html.ToString());
        }
예제 #53
0
        /// <summary>
        /// 呈现分类页
        /// </summary>
        /// <param name="context"></param>
        /// <param name="tag"></param>
        /// <param name="page"></param>
        public static void RenderCategory(CmsContext context, string catPath, int page)
        {
            //检查缓存
            if (!context.CheckAndSetClientCache())
            {
                return;
            }

            int               siteId = context.CurrentSite.SiteId;
            string            html   = String.Empty;
            CategoryDto       category;
            ICmsPageGenerator cmsPage = new PageGeneratorObject(context);

            category = ServiceCall.Instance.SiteService.GetCategory(siteId, catPath);
            if (!(category.ID > 0))
            {
                RenderNotFound(context); return;
            }

            //获取路径
            string categoryPath = category.Path;
            string appPath      = Cms.Context.SiteAppPath;
            string reqPath      = context.Request.Path.Substring(1);

            if (appPath.Length > 1)
            {
                reqPath = reqPath.Substring(appPath.Length);
            }

            if (!reqPath.StartsWith(categoryPath))
            {
                RenderNotFound(context);
                return;
            }

            /*********************************
            *  @ 单页,跳到第一个特殊文档,
            *  @ 如果未设置则最新创建的文档,
            *  @ 如未添加文档则返回404
            *********************************/
            if (String.IsNullOrEmpty(category.Location))
            {
                html = cmsPage.GetCategory(category, page);
                context.Render(html);
            }
            else
            {
                string url = category.Location;
                if (category.Location.IndexOf("://") != -1)
                {
                    url = category.Location;
                }
                else
                {
                    if (!category.Location.StartsWith("/"))
                    {
                        url = String.Concat(appPath, appPath.Length == 1?String.Empty:"/", category.Location);
                    }
                }
                context.Response.Redirect(url, true);  //302
            }
        }
예제 #54
0
 public ArticleCommentStaffRepository(CmsContext CmsDBContext) : base(CmsDBContext)
 {
 }
        public override void RenderInEditMode(HtmlTextWriter writer, CmsPage page, int identifier, CmsLanguage langToRenderFor, string[] paramList)
        {
            string                placeholderId            = "JobPostingDetails_" + page.Id.ToString() + "_" + identifier.ToString() + langToRenderFor.shortCode;
            string                placeholderIdWithoutLang = "location_JobPostingDetails_" + page.Id.ToString() + "_" + identifier.ToString();
            JobPostingDb          db             = new JobPostingDb();
            JobPostingDetailsData postingDetails = db.getJobPostingDetailsData(page, identifier, langToRenderFor, true);

            JobPostingLocation[] locations    = JobPostingLocation.FetchAll();
            JobPostingLocation   AllLocations = JobPostingLocation.getAllLocations(locations);

            // ------- CHECK THE FORM FOR ACTIONS
            string action = PageUtils.getFromForm(placeholderId + "_Action", "");

            if (action.Trim().ToLower() == "update")
            {
                // save the data to the database

                int    newLocationId = PageUtils.getFromForm("location_" + placeholderId, AllLocations.JobLocationId);
                string dateStr       = PageUtils.getFromForm("RemoveAnonAccessAt_" + placeholderId, "");

                postingDetails.LocationId         = newLocationId;
                postingDetails.RemoveAnonAccessAt = CmsConfig.parseDateInDateInputFormat(dateStr, postingDetails.RemoveAnonAccessAt);

                bool b = db.saveUpdatedJobPostingDetailsData(postingDetails);
                if (!b)
                {
                    writer.Write("Error saving updates to database!");
                }
            }
            StringBuilder html = new StringBuilder();

            html.Append("<div class=\"JobPostingDetails Edit\">");
            html.Append("<table width=\"100%\" border=\"0\">");

            html.Append("<tr>");
            html.Append("<td>Date to remove public access:</td>");
            html.Append("</tr>");
            html.Append("<tr>");
            html.Append("<td>");
            html.Append(PageUtils.getInputTextHtml("RemoveAnonAccessAt_" + placeholderId, "RemoveAnonAccessAt_" + placeholderId, postingDetails.RemoveAnonAccessAt.ToString(CmsConfig.InputDateTimeFormatInfo), 12, 10));
            html.Append(" <em>format: " + CmsConfig.InputDateTimeFormatInfo.ToUpper() + ". ");
            html.Append("Enter '" + DateTime.MaxValue.ToString(CmsConfig.InputDateTimeFormatInfo) + "' for no auto-removal</em>.</td>");
            html.Append("</tr>");

            // -- Job Location drop-down

            html.Append("<tr>");
            html.Append("<td>Job Location:</td>");
            html.Append("</tr>");
            html.Append("<tr>");

            html.Append("<td>" + PageUtils.getDropDownHtml("location_" + placeholderId, "location_" + placeholderId, JobPostingLocation.ToNameValueCollection(locations, langToRenderFor, AllowPostingToAllLocations), postingDetails.LocationId.ToString()));

            try
            {
                CmsPage editLocationPage = CmsContext.getPageByPath("_admin/JobLocation");
                html.Append(" <a href=\"" + editLocationPage.getUrl(langToRenderFor) + "\" onclick=\"window.open(this.href,'" + placeholderIdWithoutLang + "','resizable=1,scrollbars=1,width=800,height=400'); return false;\">(edit)</a>");
            }
            catch (Exception ex)
            {
                html.Append(" <span>Cannot setup Edit Category Link: " + ex.Message + "</span>");
            }

            html.Append("</td>");
            html.Append("</tr>");

            html.Append("</table>" + Environment.NewLine);

            html.Append(PageUtils.getHiddenInputHtml(placeholderId + "_Action", "update"));

            html.Append("</div>" + Environment.NewLine);

            writer.Write(html.ToString());
        } // RenderEdit
예제 #56
0
        protected override void Initialize(System.Web.Routing.RequestContext requestContext)
        {
            if (!Cms.Installed)
            {
                requestContext.HttpContext.Response.Redirect("/install/install.html", true);
                return;
            }

            this.OutputCntext        = AtNet.Cms.Cms.Context;
            this.OutputCntext.Source = this;
            startTime = new TimeSpan(DateTime.Now.Ticks);


            // ==========================================//

            _showDebugInformation = Settings.Opti_Debug;
            if (_showDebugInformation)
            {
                CmsDataBase.Instance.StartNewTotal();
            }
            //如果自动301
            if (Settings.SYS_AUTOWWW)
            {
                const string    mainDomainPattern = "^([^\\.]+)\\.([^\\.]+)$";
                HttpContextBase c       = requestContext.HttpContext;
                string          url     = c.Request.Url.ToString();
                string          protrol = url.Remove(url.IndexOf("://"));
                string          host    = c.Request.Url.Host; // c.Request.ServerVariables["server_name"];
                string          appPath = c.Request.ApplicationPath;


                if (Regex.IsMatch(host, mainDomainPattern))
                {
                    Match match = Regex.Match(host, mainDomainPattern);

                    //检查是否存在于忽略的301列表中
                    //if (Array.Exists(ignoreActions, a => String.Compare(a, requestContext.RouteData.Values["action"].ToString(), true) == 0))
                    //{
                    //    goto initialize;
                    // }
                    string redirectUrl = String.Format("{0}://www.{1}{2}",
                                                       protrol,
                                                       host,
                                                       c.Request.RawUrl
                                                       );

                    c.Response.AppendHeader("Location", redirectUrl);
                    c.Response.Status = "301 Moved Permanently";

                    /*
                     * try
                     * {
                     *  //MONO或IIS集成模式
                     *  c.Response.Headers.Add("Location", redirectUrl);
                     * }
                     * catch(PlatformNotSupportedException ex)
                     * {
                     *  //IIS经典模式
                     *  c.Response.AppendHeader("Location", redirectUrl);
                     * }*/

                    c.Response.End();
                    return;
                }
            }

            //初始化
initialize:

            base.Initialize(requestContext);
        }
예제 #57
0
        private string getHtmlForThumbView(CmsPage page, ImageGalleryData data, string ImageGalleryId, bool inEditMode)
        {
            StringBuilder html            = new StringBuilder();
            string        DirOnDiskToView = getDirOnDiskToView(data);


            if (!Directory.Exists(DirOnDiskToView))
            {
                return("Error with Image Gallery: ImageGallery directory does not exist!");
            }

            string[] JPGFiles = Directory.GetFiles(DirOnDiskToView, "*.jpg");
            if (JPGFiles.Length < 1)
            {
                return("no images are in this image gallery");
            }

            html.Append("<table>");
            int       imgCount         = 0;
            ArrayList formCaptionNames = new ArrayList();

            foreach (string jpg in JPGFiles)
            {
                if (imgCount % data.numThumbsPerRow == 0)
                {
                    html.Append("<tr>");
                }

                string imgFilenameUnderAppPath = data.subDir + Path.GetFileName(jpg);
                string thumbUrl = CmsContext.UserInterface.ShowThumbnailPage.getThumbDisplayUrl(imgFilenameUnderAppPath, data.thumbSize, -1);

                ImageGalleryImageData imgData = data.getImageData(imgFilenameUnderAppPath);

                NameValueCollection imgParams = new NameValueCollection();
                imgParams.Add("galleryMode", Convert.ToInt32(RenderMode.FullSize).ToString());
                imgParams.Add("galleryImg", Path.GetFileName(jpg));

                string fullSizeUrl = CmsContext.getUrlByPagePath(page.Path, imgParams);

                html.Append("<td class=\"ImageGalleryImage_td\">");

                if (!inEditMode)
                {
                    html.Append("<a class=\"ImageGalleryImageLink\" href=\"" + fullSizeUrl + "\">");
                }

                html.Append("<img class=\"ImageGalleryImage\" src=\"" + thumbUrl + "\">");

                if (!inEditMode)
                {
                    html.Append("</a>");
                }

                html.Append("<br>");
                if (inEditMode)
                {
                    string tbName = System.Web.HttpUtility.UrlEncode("imgCaption" + ImageGalleryId + "_" + imgFilenameUnderAppPath);
                    formCaptionNames.Add(tbName);
                    string tb = PageUtils.getInputTextHtml(tbName, tbName, imgData.Caption, 15, 255);
                    tb = "<nobr>caption: " + tb + "</nobr>";
                    html.Append(tb);
                }
                else
                {
                    html.Append(imgData.Caption);
                }
                html.Append("</td>");
                if (imgCount % data.numThumbsPerRow == data.numThumbsPerRow)
                {
                    html.Append("</tr>");
                }

                imgCount++;
            }
            if (imgCount % data.numThumbsPerRow != data.numThumbsPerRow)
            {
                html.Append("</tr>");
            }
            html.Append("</table>");

            if (inEditMode)
            {
                string csv = "";
                foreach (string id in formCaptionNames)
                {
                    csv = csv + id + ",";
                }
                string h = PageUtils.getHiddenInputHtml(ImageGalleryId + "_captions", csv);
                html.Append(h);
            }

            return(html.ToString());
        } // getHtmlForThumbView
예제 #58
0
        private int InsertPage(string filename, string title, string menuTitle, string seDesc, string templateName, int parentPageId, int sortOrdinal, bool showInMenu)
        {
            int     parentId = Convert.ToInt32(parentPageId);
            CmsPage newPage  = new CmsPage();

            // -- setup the page's language info
            List <CmsPageLanguageInfo> langInfos = new List <CmsPageLanguageInfo>();

            foreach (CmsLanguage lang in CmsConfig.Languages)
            {
                CmsPageLanguageInfo langInfo = new CmsPageLanguageInfo();
                langInfo.languageShortCode = lang.shortCode;
                langInfo.name      = filename;
                langInfo.menuTitle = menuTitle;
                langInfo.title     = title;
                langInfo.searchEngineDescription = seDesc;

                langInfos.Add(langInfo);
            } // foreach languages
            newPage.LanguageInfo = langInfos.ToArray();

            newPage.ShowInMenu   = showInMenu;
            newPage.ParentID     = parentId;
            newPage.TemplateName = templateName;
            newPage.ShowInMenu   = showInMenu;

            newPage.SortOrdinal = 0;
            if (sortOrdinal < 0)
            {
                // -- set sortOrdinal
                int highestSiblingSortOrdinal = -1;
                if (parentId >= 0)
                {
                    CmsPage parentPage = CmsContext.getPageById(parentId);
                    foreach (CmsPage sibling in parentPage.ChildPages)
                    {
                        highestSiblingSortOrdinal = Math.Max(sibling.SortOrdinal, highestSiblingSortOrdinal);
                    }
                }
                if (highestSiblingSortOrdinal > -1)
                {
                    newPage.SortOrdinal = highestSiblingSortOrdinal + 1;
                }
            }

            if (CmsContext.childPageWithNameExists(parentId, filename))
            {
                // _errorMessage = "a page with the specified filename and parent already exists!";
                return(-1);
            }
            else
            {
                // -- page does not already exist, so create it
                bool success = CmsPage.InsertNewPage(newPage);
                if (!success)
                {
                    // _errorMessage = "database could not create new page.";
                    return(-1);
                }
                return(newPage.ID);
            }
        }
예제 #59
0
 public static void PortalRequest(CmsContext site, ref bool result)
 {
     HttpContext.Current.Response.Write("cross plugin visite site:" + site.CurrentSite.Name);
     result = true;
 }
예제 #60
0
        public async Task<IEnumerable<Post>> GetPostsByTagAsync(string tagId)
        {
            using (var db = new CmsContext())
            {
                var posts = await db.Posts
                    .Include("Author")
                    .Where(post => post.CombinedTags.Contains(tagId))
                    .ToListAsync();

                return posts.Where(post =>
                    post.Tags.Contains(tagId, StringComparer.CurrentCultureIgnoreCase))
                    .ToList();
            }
        }