public CmsTemplate SaveTemplate(CmsTemplate obj)
        {
            if (obj.Name.Trim() == "")
            {
                throw new Exception("Geen template naam ingevoerd.");
            }
            BaseService.CheckLoginAndLicense();
            obj.Site = SessionObject.CurrentSite;
            obj.Save();

            //lijst van ObjectPermissions wordt hier alleen als drager gebruikt.
            //in de licentieserver wordt deze lijst weer gesplitst en in 2 tabellen gezet
            //BaseCollection<ObjectPermission> objPermissions = obj.GetObjectPermissions4LicenseServer();
            //if (objPermissions.Count > 0)
            //{
            //    BitAutorisationService.AutorisationClient client = BitMetaServerServicesHelper.GetClient();
            //    client.SaveObjectPermissions(objPermissions);
            //}
            //update pages
            //Waarom dit ook alweer???? @HJ
            //foreach (CmsPage page in obj.GetPages())
            //{
            //    page.Save();
            //}
            return(obj);
        }
        public CmsTemplate GetTemplateIncludeHeader(string id)
        {
            BaseService.CheckLoginAndLicense();
            CmsTemplate template = CmsTemplate.New();

            if (id != null)
            {
                template = BaseObject.GetById <CmsTemplate>(new Guid(id));
                if (template.HasAutorisation)
                {
                    //BitAutorisationService.AutorisationClient client = BitAutorisationServiceHelper.GetClient();
                    //BitplateUserGroup[] usergroups = client.GetUserGroupsByObjectPermission(template.ID);
                    //template.AutorizedBitplateUserGroups = usergroups;

                    //BitplateUser[] users = client.GetUsersByObjectPermission(template.ID);
                    //template.AutorizedBitplateUsers = users;
                    if (!template.IsAutorized(SessionObject.CurrentBitplateUser))
                    {
                        throw new Exception("U heeft geen rechten voor deze template");
                    }
                }
            }
            else
            {
                template.Site = SessionObject.CurrentSite;
            }
            string tmpHead = "";

            foreach (CmsScript script in template.Scripts)
            {
                tmpHead += script.GetTag() + "\n\r";
            }
            template.Content = template.Content.Replace("[HEAD]", tmpHead).Replace("[SCRIPTS]", "");
            return(template);
        }
Example #3
0
        protected void Page_Load(object sender, EventArgs e)
        {
            oWeb.ValidaSessionAdm();
            if (!IsPostBack)
            {
                CodTemplate.Value = oWeb.GetData("CodTemplate");
                if (!string.IsNullOrEmpty(CodTemplate.Value))
                {
                    DBConn oConn = new DBConn();
                    if (oConn.Open())
                    {
                        CmsTemplate oTemplate = new CmsTemplate(ref oConn);
                        oTemplate.CodTemplate = CodTemplate.Value;
                        DataTable dTemplate = oTemplate.Get();
                        if (dTemplate != null)
                        {
                            if (dTemplate.Rows.Count > 0)
                            {
                                txtTitulo.Text        = dTemplate.Rows[0]["nom_template"].ToString();
                                rdDescripcion.Content = dTemplate.Rows[0]["texto_template"].ToString();
                                rdCmbEstado.Items.FindItemByValue(dTemplate.Rows[0]["est_template"].ToString()).Selected = true;
                            }
                        }
                        dTemplate = null;

                        oConn.Close();
                    }
                }
            }
        }
Example #4
0
        static Cms()
        {
            Version   = CmsVariables.VERSION;
            PyhicPath = AppDomain.CurrentDomain.BaseDirectory;
            //获取编译生成的时间
            //Version ver=typeof(Cms).Assembly.GetName().Version;
            //BuiltTime= new DateTime(2000, 1, 1).AddDays(ver.Build).AddSeconds(ver.Revision * 2);
            //BuiltTime=System.IO.File.GetLastWriteTime(typeof(Cms).Assembly.Location);

            //获取平台

            Int32 platFormId = (Int32)Environment.OSVersion.Platform;

            if (platFormId == 4 || platFormId == 6 || platFormId == 128)
            {
                RunAtMono = true;
            }


            //判断是否已经安装
            FileInfo insLockFile = new FileInfo(String.Format("{0}config/install.lock", Cms.PyhicPath));

            Installed = insLockFile.Exists;

            //初始化
            Plugins  = new CmsPluginContext();
            Template = new CmsTemplate();
            Cache    = CacheFactory.Sington as CmsCache;
            Utility  = new CmsUtility();

            #region  缓存清除

            //
            //UNDONE: 弱引用
            //

            /*
             * WeakRefCache.OnLinkBuilting += () =>
             * {
             *  Cms.Cache.Clear(CacheSign.Link.ToString());
             * };
             *
             * WeakRefCache.OnModuleBuilting += () =>
             * {
             *  Cms.Cache.Clear(CacheSign.Module.ToString());
             * };
             *
             * WeakRefCache.OnPropertyBuilting += () =>
             * {
             *  Cms.Cache.Clear(CacheSign.Property.ToString());
             * };
             *
             * WeakRefCache.OnTemplateBindBuilting += () =>
             * {
             *  Cms.Cache.Clear(CacheSign.TemplateBind.ToString());
             * };
             *
             */
            #endregion
        }
Example #5
0
        static Cms()
        {
            PyhicPath = AppDomain.CurrentDomain.BaseDirectory;

            //获得版本号
            //AssemblyFileVersionAttribute ver = (AssemblyFileVersionAttribute)typeof(Cms).Assembly.GetCustomAttributes(typeof(AssemblyFileVersionAttribute), false)[0];

            //string[] verarr = ver.Version.Split('.');
            //Version = String.Format("{0}.{1}.{2}", verarr[0], verarr[1], verarr[2]);

            //获取编译生成的时间
            //Version ver=typeof(Cms).Assembly.GetName().Version;
            //BuiltTime= new DateTime(2000, 1, 1).AddDays(ver.Build).AddSeconds(ver.Revision * 2);
            //BuiltTime=System.IO.File.GetLastWriteTime(typeof(Cms).Assembly.Location);

            //获取平台

            Int32 platFormID = (Int32)Environment.OSVersion.Platform;

            if (platFormID == 4 || platFormID == 6 || platFormID == 128)
            {
                RunAtMono = true;
            }

            //初始化
            Plugins  = new CmsPluginContext();
            Template = new CmsTemplate();
            Cache    = CacheFactory.Sington as CmsCache;
            Utility  = new CmsUtility();

            #region  缓存清除

            //
            //UNDONE: 弱引用
            //

            /*
             * WeakRefCache.OnLinkBuilting += () =>
             * {
             * Cms.Cache.Clear(CacheSign.Link.ToString());
             * };
             *
             * WeakRefCache.OnModuleBuilting += () =>
             * {
             * Cms.Cache.Clear(CacheSign.Module.ToString());
             * };
             *
             * WeakRefCache.OnPropertyBuilting += () =>
             * {
             * Cms.Cache.Clear(CacheSign.Property.ToString());
             * };
             *
             * WeakRefCache.OnTemplateBindBuilting += () =>
             * {
             * Cms.Cache.Clear(CacheSign.TemplateBind.ToString());
             * };
             *
             */
            #endregion
        }
Example #6
0
        protected void btnGrabar_Click(object sender, EventArgs e)
        {
            DBConn oConn = new DBConn();

            if (oConn.Open())
            {
                oConn.BeginTransaction();

                string      cPath     = Server.MapPath(".") + @"\binary\";
                CmsTemplate oTemplate = new CmsTemplate(ref oConn);
                oTemplate.CodTemplate   = CodTemplate.Value;
                oTemplate.NomTemplate   = txtTitulo.Text;
                oTemplate.TextoTemplate = rdDescripcion.Content;
                oTemplate.EstTemplate   = rdCmbEstado.SelectedValue;
                oTemplate.Accion        = (string.IsNullOrEmpty(CodTemplate.Value) ? "CREAR" : "EDITAR");
                oTemplate.Put();
                CodTemplate.Value = oTemplate.CodTemplate;
                if (string.IsNullOrEmpty(oTemplate.Error))
                {
                    oConn.Commit();
                    string sFile = "Template_" + oTemplate.CodTemplate + ".bin";
                    oTemplate.SerializaTemplate(ref oConn, cPath, sFile);
                }
                else
                {
                    oConn.Rollback();
                }

                oConn.Close();
            }
        }
Example #7
0
        static Cms()
        {
            Version   = CmsVariables.VERSION;
            PyhicPath = AppDomain.CurrentDomain.BaseDirectory;

            //获取编译生成的时间
            //DateTime builtDate = new DateTime(2000, 1, 1).AddDays(ver.Build).AddSeconds(ver.Revision*2);
            string filePath = typeof(Cms).Assembly.Location;

            if (String.IsNullOrEmpty(filePath))
            {
                filePath = PyhicPath + CmsVariables.FRAMEWORK_ASSEMBLY_PATH + "jrcms.dll";
            }
            DateTime builtDate = File.GetLastWriteTime(filePath);

            BuiltTime = DateHelper.ToUnix(builtDate);

            //获取平台
            Int32 platFormId = (Int32)Environment.OSVersion.Platform;

            if (platFormId == 4 || platFormId == 6 || platFormId == 128)
            {
                RunAtMono = true;
            }
            //初始化
            Plugins  = new CmsPluginContext();
            Template = new CmsTemplate();
            Cache    = CacheFactory.Sington as CmsCache;
            Utility  = new CmsUtility();
            Language = new CmsLanguagePackage();
            #region  缓存清除

            //
            //UNDONE: 弱引用
            //

            /*
             * WeakRefCache.OnLinkBuilting += () =>
             * {
             *  Cms.Cache.Clear(CacheSign.Link.ToString());
             * };
             *
             * WeakRefCache.OnModuleBuilting += () =>
             * {
             *  Cms.Cache.Clear(CacheSign.Module.ToString());
             * };
             *
             * WeakRefCache.OnPropertyBuilting += () =>
             * {
             *  Cms.Cache.Clear(CacheSign.Property.ToString());
             * };
             *
             * WeakRefCache.OnTemplateBindBuilting += () =>
             * {
             *  Cms.Cache.Clear(CacheSign.TemplateBind.ToString());
             * };
             *
             */
            #endregion
        }
Example #8
0
        protected void rdTemplate_ItemCommand(object source, Telerik.Web.UI.GridCommandEventArgs e)
        {
            switch (e.CommandName)
            {
            case "cmdEdit":
                string[] cParam = new string[2];
                cParam[0] = e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["cod_template"].ToString();
                Response.Redirect(String.Format("Template.aspx?CodTemplate={0}", cParam));
                break;

            case "cmdDelete":
                string pCodTemplate = e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["cod_template"].ToString();
                DBConn oConn        = new DBConn();
                if (oConn.Open())
                {
                    string sPath = Server.MapPath(".") + @"\binary\Template_" + pCodTemplate + ".bin";
                    File.Delete(sPath);

                    CmsTemplate oTemplate = new CmsTemplate(ref oConn);
                    oTemplate.CodTemplate = pCodTemplate;
                    oTemplate.Accion      = "ELIMINAR";
                    oTemplate.Put();

                    oConn.Close();
                }
                rdTemplate.Rebind();
                break;
            }
        }
Example #9
0
        public List <CmsTemplate> GetAvailableCmsTemplates()
        {
            var accountSettings = _accountsRepository.GetAccountSettings();

            var templateFolderId = accountSettings.TemplateFolderId;

            if (string.IsNullOrEmpty(templateFolderId))
            {
                templateFolderId = Constants.TemplateFolderId;
            }
            var model        = new List <CmsTemplate>();
            var cmsTemplates = GetTemplates(templateFolderId);

            foreach (var template in cmsTemplates)
            {
                var cmsTemplate = new CmsTemplate
                {
                    TemplateName = template.Name,
                    TemplateId   = template.ID.ToString()
                };

                var fields = GetFields(template);
                cmsTemplate.TemplateFields.AddRange(
                    fields.Where(f => !f.Name.StartsWith("__")).Select(f => new CmsTemplateField
                {
                    FieldName = f.Name,
                    FieldId   = f.ID.ToString(),
                    FieldType = f.Type
                }));

                model.Add(cmsTemplate);
            }
            return(model);
        }
        public CmsTemplate GetTemplate(string id, int type)
        {
            BaseService.CheckLoginAndLicense();
            CmsTemplate template = CmsTemplate.New();

            //TODO: NewsletterTemplate service. 0 = PageTemplate & 1 = NewsletterTemplate
            if (type == 1)
            {
                //template.Content = template.Content.Replace("[HEAD]", "");
            }
            if (id != null)
            {
                template = BaseObject.GetById <CmsTemplate>(new Guid(id));
                if (template.HasAutorisation)
                {
                    //BitAutorisationService.AutorisationClient client = BitMetaServerServicesHelper.GetClient();
                    //BitplateUserGroup[] usergroups = client.GetUserGroupsByObjectPermission(template.ID);
                    //template.AutorizedBitplateUserGroups = usergroups;

                    //BitplateUser[] users = client.GetUsersByObjectPermission(template.ID);
                    //template.AutorizedBitplateUsers = users;
                    if (!template.IsAutorized(SessionObject.CurrentBitplateUser))
                    {
                        throw new Exception("U heeft geen rechten voor deze template");
                    }
                }
            }
            else
            {
                template.Site = SessionObject.CurrentSite;
            }
            return(template);
        }
Example #11
0
 public TemplateRenderInformation(IEnumerable <RequestContext> contexts, CmsTemplate template, string contentType, IDictionary <string, object> overrideSettings = null)
 {
     Contexts         = contexts;
     Template         = template;
     ContentType      = contentType;
     OverrideSettings = overrideSettings ?? new Dictionary <string, object>();
 }
Example #12
0
        public static IHtmlString Template(this IFubuPage page, CmsTemplate template, IDictionary <string, object> settings = null, ITheme theme = null)
        {
            var cmsRenderer = page.ServiceLocator.GetInstance <ICmsRenderer>();
            var cmsContext  = page.ServiceLocator.GetInstance <ICmsContext>();

            theme = theme ?? cmsContext.GetCurrentTheme();

            var result = cmsRenderer.RenderTemplate(template, settings, cmsContext, theme);

            return(new HtmlString(result.Read()));
        }
        public void CopyTemplate(Guid TemplateId, string newTemplateName)
        {
            BaseService.CheckLoginAndLicense();
            CmsTemplate template = GetTemplate(TemplateId.ToString()); // BaseObject.GetById<CmsTemplate>(TemplateId);
            CmsTemplate copy     = template.Copy(newTemplateName);

            //BaseCollection<ObjectPermission> objPermissions = copy.GetObjectPermissions4LicenseServer();
            //if (objPermissions.Count > 0)
            //{
            //    BitAutorisationService.AutorisationClient client = BitMetaServerServicesHelper.GetClient();
            //    client.SaveObjectPermissions(objPermissions);
            //}
        }
Example #14
0
        public virtual IRenderResult RenderTemplate(CmsTemplate template, IDictionary <string, object> settings, ICmsContext context, ITheme theme)
        {
            if (!context.CanRender(template, theme))
            {
                return(new RenderResult("text/plain", x => { }, new Dictionary <Guid, RequestContext>(), context));
            }

            var contexts = new Dictionary <Guid, RequestContext>();

            var result = ParseText($"<md>{template.Body}</md>", context, theme);

            return(new RenderResult(string.IsNullOrEmpty(template.ContentType) ? result.ContentType : template.ContentType, x => result.RenderTo(x), contexts, context));
        }
        public void DeleteTemplate(string id)
        {
            BaseService.CheckLoginAndLicense();
            CmsTemplate template = GetTemplate(id);

            if (template.HasAutorisation)
            {
                if (!template.IsAutorized(SessionObject.CurrentBitplateUser))
                {
                    throw new Exception("U heeft geen rechten voor deze template");
                }
            }
            template.Delete();
        }
        public string GetTemplateContent(string templateid)
        {
            BaseService.CheckLoginAndLicense();
            CmsTemplate template = BaseObject.GetById <CmsTemplate>(new Guid(templateid));

            if (template == null)
            {
                return("");
            }
            else
            {
                string html = string.Format(@"<div id='bitEditorTemplate' style='width:100%' class='bitEditor' title='{1}'>
    {0}
</div>
", template.GetBodyContent(), template.Name);
                return(html);
            }
        }
Example #17
0
        protected void rdTemplate_NeedDataSource(object source, Telerik.Web.UI.GridNeedDataSourceEventArgs e)
        {
            DBConn oConn = new DBConn();

            if (oConn.Open())
            {
                CmsTemplate oTemplate = new CmsTemplate(ref oConn);
                oTemplate.Get();

                GridColumn oGridColumn;

                oGridColumn            = rdTemplate.MasterTableView.Columns.FindByUniqueName("NomTemplate");
                oGridColumn.HeaderText = oCulture.GetResource("Template", "NomTemplate");

                oGridColumn            = rdTemplate.MasterTableView.Columns.FindByUniqueName("EstTemplate");
                oGridColumn.HeaderText = oCulture.GetResource("Template", "EstTemplate");

                rdTemplate.DataSource = oTemplate.Get();

                oConn.Close();
            }
        }
Example #18
0
        protected void OnSave_Click(object sender, EventArgs e)
        {
            CurrentSite.Cache.Clear();

            String id = this.ExistingTemplateId.Value;
            CmsTemplate template = TemplateManager.Instance.GetTemplate(Data.EncryptedValue.New(id));
            if (template == null)
            {
                template = new CmsTemplate();
                template.IsGlobalTemplateType = (this.TemplateType.Visible);
                if (template.IsGlobalTemplateType)
                    template.Name = this.TemplateType.SelectedValue;
                else
                    template.Name = this.CustomTemplateType.Text;
                template.SubscriptionGuid = SiteHelper.GetActiveSiteGuid(true).Value;
                template.Theme = theme;
            }

            template.Content = this.TemplateContent.Text;
            template.LastSaved = UtcDateTime.Now;

            IList<String> missingImages = new List<String>();
            TemplateManager.Instance.Save(template, missingImages);

            StringBuilder builder = new StringBuilder();
            builder.Append("Successfully saved template.");
            if (missingImages.Count > 0)
            {
                builder.Append(" The following images could not be found and may need to be uploaded: ");
                builder.Append(String.Join(",", missingImages));
            }

            this.LblStatus.Text = builder.ToString();
        }
Example #19
0
File: Cms.cs Project: lyfb/cms-1
        /// <summary>
        /// 设置应用程序,如在过程中发生异常则重启并提醒!
        /// </summary>
        public static void Init(BootFlag flag, string confPath)
        {
            PrepareCms();
            BeforeInit();
            if (!IsInstalled())
            {
                return;
            }
            //初始化目录
            ChkCreate(CmsVariables.TEMP_PATH);
            // 加载配置
            Configuration.LoadCmsConfig(confPath);
            //设置数据库
            CmsDataBase.Initialize($"{Settings.DB_TYPE}://{Settings.DB_CONN}", Settings.DB_PREFIX, Settings.SQL_PROFILE_TRACE);
            //清空临时文件
            //resetTempFiles();
            // 初始化键值存储
            InitKvDb();
            // 加载其他配置
            LoadOtherConfig();
            //获取静态服务器
            //UpdateServerInfo();
            // 正常模式启动
            if ((flag & BootFlag.Normal) != 0)
            {
                BuildOEM = new BuildOEM();

                //
                //TODO:
                //
                //检查网站激活状态
                //SoftwareActivator.VerifyActivation();

                //如果不存在模板文件夹,则创建目录
                if (!Directory.Exists(PhysicPath + "templates/"))
                {
                    Directory.CreateDirectory(PhysicPath + "templates/").Create();
                    //暂时网络安装默认模板(后可使用资源代替)
                    Updater.InstallTemplate("default", "tpl_default.zip");
                }

                // 初始化模板
                Template = new CmsTemplate(_cache, TemplateNames.FileName);
                // 注册模板
                Template.Register(CmsVariables.TEMPLATE_PATH);
                // 模板管理器
                _templateManager = new TemplateManager(PhysicPath + CmsVariables.TEMPLATE_PATH);

                // 注册插件
                //PluginConfig.PLUGIN_FILE_PARTTERN = "*.dll,*.so";
                PluginConfig.PLUGIN_DIRECTORY         = CmsVariables.PLUGIN_PATH;
                PluginConfig.PLUGIN_TMP_DIRECTORY     = CmsVariables.TEMP_PATH + "plugin/";
                PluginConfig.PLUGIN_LOG_OPENED        = true;
                PluginConfig.PLUGIN_LOG_EXCEPT_FORMAT =
                    "** {time} **:{message}\r\nSource:{source}\r\nAddress:{addr}\r\nStack:{stack}\r\n\r\n";
                var pluginPhysicPath = PhysicPath + PluginConfig.PLUGIN_TMP_DIRECTORY;
                if (!Directory.Exists(pluginPhysicPath))
                {
                    Directory.CreateDirectory(pluginPhysicPath).Create();
                }
                // 连接插件
                //todo: plugin
                //CmsPluginContext.Connect();
                // 设置验证码字体
                VerifyCodeGenerator.SetFontFamily(PhysicPath + CmsVariables.FRAMEWORK_ASSETS_PATH + "fonts/comic.ttf");
            }
            OnInit?.Invoke();
            IsInitFinish = true;
        }
        private void DeployThemes(SitePackage sitepackage, Data.Guid guid, IPackageStatusNotifier notifier)
        {
            //Deploy the themes into the site
            foreach (SitePackageTheme themeWrapper in sitepackage.Themes)
            {
                CmsTheme theme = themeWrapper.Theme;

                Boolean isEnabled = theme.IsEnabled;
                theme = ThemeManager.Instance.Add(guid, theme.Name, theme.Description);

                theme.IsEnabled = isEnabled;
                theme.Header = themeWrapper.Header;
                theme.Footer = themeWrapper.Footer;
                ThemeManager.Instance.Save(theme);

                //Save all of the templates for this theme
                foreach (CmsTemplate template in themeWrapper.Templates)
                {
                    CmsTemplate newTemplate = new CmsTemplate();
                    newTemplate.IsGlobalTemplateType = template.IsGlobalTemplateType;
                    newTemplate.Name = template.Name;
                    newTemplate.SubscriptionGuid = guid.Value;
                    newTemplate.Theme = theme;
                    newTemplate.Content = template.Content;
                    newTemplate.LastSaved = template.LastSaved;

                    TemplateManager.Instance.Save(newTemplate);
                }

                //Save the javascript files for this theme
                foreach (JavascriptFile js in themeWrapper.Javascript)
                {
                    JavascriptManager.Instance.Save(guid, theme, js);
                }

                //Save the css files for this theme
                foreach (CssFile css in themeWrapper.Css)
                {
                    CssManager.Instance.Save(guid, theme, css);
                }

                //Save all the images for this theme
                DoNotify(notifier, "Copying Theme Images to Site (please wait...) ");
                String copyFromImageContainer = SiteHelper.GetStorageKey(SiteHelper.ImagesContainerKey, sitepackage.OriginalSiteGuid.Value);
                String copyToImageContainer = SiteHelper.GetStorageKey(SiteHelper.ImagesContainerKey, guid.Value);

                IStorageClient client = StorageHelper.GetStorageClient();
                client.CopyFromSnapshots(themeWrapper.Images, copyFromImageContainer, copyToImageContainer, theme.ThemeGuid, Permissions.Public);

                SaveImagesToDatabase(notifier, guid, copyToImageContainer, theme.ThemeGuid);
            }
        }
Example #21
0
        public List<String> Import(ImportSiteMessage message)
        {
            Data.Hash importHash = Data.Hash.New(message.ImportHash);
            Data.Guid subscriptionId = Data.Guid.New(message.SubscriptionId);
            Boolean deleteExisting = message.DeleteExisting;

            List<String> status = new List<String>();

            byte[] data;

            AddStatus(importHash, status, "Site import started at " + UtcDateTime.Now.ToString());
            CmsSubscription subscription = SubscriptionManager.GetSubscription(subscriptionId);
            CmsTheme defaultTheme = ThemeManager.Instance.GetDefaultBySite(subscriptionId);

            //Check if the import-template already exists
            CmsTemplate template = TemplateManager.Instance.GetTemplate(subscriptionId, "import-template");
            if (template == null)
            {
                template = new CmsTemplate();
                template.Content = "{content}";
                template.Name = "import-template";
                template.IsGlobalTemplateType = false;
                template.LastSaved = UtcDateTime.Now;
                template.SubscriptionGuid = subscriptionId.Value;
                template.Theme = defaultTheme;

                TemplateManager.Instance.Save(template);
                AddStatus(importHash, status, "Successfully created and associated import template to deafult theme");
            }

            IDictionary<ImportType, IList<ImportedItem>> items = this.GetImportedItems(importHash);

            //Check if we need to delete the existing site
            if (deleteExisting)
            {
                //Erase all of the existing data
                SubscriptionManager.Erase(subscription.Guid, false, false);
                SessionProvider.Instance.Close();
                SessionProvider.Instance.GetOpenSession();

                //Setup the default
                SiteHelper.Configure(subscription.Guid);
            }

            //First, import all of the images
            IList<ImportedItem> images = items[ImportType.Image];
            foreach (ImportedItem image in images)
            {
                CmsUrl uri = new CmsUrl(image.Uri);
                data = SimpleWebClient.GetResponse(uri.ToUri());

                ImageManager.Instance.AddImage(subscriptionId, StorageClientConst.RootFolder, uri.Path, image.ContentType, data);
                AddStatus(importHash, status, "Successfully imported image: " + uri.ToString() + " (" + image.ContentType + ")");
            }

            //Create the sitemap and then add the page itself
            CmsSitePath root = CmsSiteMap.Instance.GetPath(subscriptionId, CmsSiteMap.RootPath);

            Dictionary<CmsUrl, int> cssUses = new Dictionary<CmsUrl, int>();
            Dictionary<CmsUrl, int> jsUses = new Dictionary<CmsUrl, int>();

            IList<ImportedItem> pages = NormalizeImport(items[ImportType.Page]);
            foreach (ImportedItem page in pages)
            {
                try
                {
                    CmsUrl uri = new CmsUrl(page.Uri);
                    CmsUrlWalker walker = new CmsUrlWalker(uri);

                    while (walker.Next())
                    {
                        String parent = walker.GetParentPath();
                        String current = walker.GetIndividualPath();
                        String fullpath = CmsSiteMap.PathCombine(parent, current);
                        int depth = walker.Depth;

                        if (!walker.IsLast)
                        {
                            //Check if the current path exists, if not, create it
                            if (!CmsSiteMap.Instance.Exists(subscriptionId, fullpath))
                                CmsSiteMap.Instance.AddChildDirectory(subscriptionId, parent, current);
                        }
                    }

                    String pageName = walker.GetIndividualPath();
                    CmsPage newpage = GetPage(template.Name, subscription.Culture, pageName, message.ReplacePhoneNumbers, page, cssUses, jsUses);
                    newpage.SubscriptionId = subscriptionId.Value;

                    //Add the page to the cms system
                    PageManager.Instance.AddNewPage(walker.GetParentPath(), pageName, newpage);
                    AddStatus(importHash, status, "Successfully imported page " + page.Uri);
                }
                catch (Exception ex)
                {
                    if (!ex.Message.Contains("404"))
                        Logging.Database.Write("import-site-manager", "Failed to import page: " + page.Uri + ", cause:" + ex.Message + ", stack:" + ex.StackTrace);
                    AddStatus(importHash, status, "Failed to import page " + page.Uri + ", Reason:" + ex.Message);
                }
            }

            //Import the css
            IList<ImportedItem> css = items[ImportType.Css];

            int sortOrder = 0;
            CssManager cssManager = new CssManager(null);
            cssManager.SubscriptionId = subscriptionId;
            foreach (ImportedItem item in css)
            {
                CmsUrl uri = new CmsUrl(item.Uri);
                data = SimpleWebClient.GetResponse(uri.ToUri());

                cssManager.Save(defaultTheme.ThemeGuid, uri.Path, data, true, 0);
                cssManager.UpdateSortInfo(defaultTheme, uri.Path, sortOrder++);
                AddStatus(importHash, status, "Successfully imported css file: " + uri.ToString());
            }

            //Import the javascript
            IList<ImportedItem> js = items[ImportType.Javascript];

            sortOrder = 0;
            JavascriptManager jsManager = new JavascriptManager(null);
            jsManager.SubscriptionId = subscriptionId;
            foreach (ImportedItem item in js)
            {
                CmsUrl uri = new CmsUrl(item.Uri);
                data = SimpleWebClient.GetResponse(uri.ToUri());

                jsManager.Save(defaultTheme.ThemeGuid, uri.Path, data, true, 0);
                jsManager.UpdateSortInfo(defaultTheme, uri.Path, sortOrder++);
                AddStatus(importHash, status, "Successfully imported javascript file: " + uri.ToString());
            }

            //Import any documents
            IList<ImportedItem> documents = items[ImportType.Document];
            foreach (ImportedItem item in documents)
            {
                CmsUrl uri = new CmsUrl(item.Uri);

                ContentFileUploadImpl handler = new ContentFileUploadImpl();
                String filename = uri.Path;
                if (ContentFileUploadImpl.IsValidFileType(filename))
                {
                    data = SimpleWebClient.GetResponse(uri.ToUri());

                    handler.Save(subscriptionId, data, uri.Path, true);
                }
            }

            AddStatus(importHash, status, "Site import completed successfully at " + UtcDateTime.Now.ToString());

            ImportedItemDao dao = new ImportedItemDao();
            dao.DeleteAllByImportHash(importHash);

            return status;
        }
 public void OnGet(int id = 0)
 {
     Template = _tempService.GetModelAsync(m => m.Id == id).Result.data;
 }
Example #23
0
 public async Task <ApiResult <string> > EditTemplate([FromBody] CmsTemplate parm)
 {
     return(await _tempService.UpdateAsync(parm));
 }
Example #24
0
        public void Save(CmsTemplate template, IList<String> missingImages = null)
        {
            if (CurrentSite.IsAvailable)
                CurrentSite.Cache.Clear();

            //Attempt to validate any images and move images if necessary
            IList<String> missing = ImageManager.Instance.ValidateAndMove(template.Content,template.SubscriptionGuid, template.Theme.ThemeGuid, true);
            if (missingImages != null)
            {
                foreach (String item in missing)
                    missingImages.Add(item);
            }

            using (Transaction tx = new Transaction())
            {
                CmsTemplateDao dao = new CmsTemplateDao();
                dao.Save<CmsTemplate>(template);

                tx.Commit();
            }
        }
Example #25
0
        private static void PrepareCms()
        {
#if NETSTANDARD
            IsNetStandard = true;
            if (_cache == null)
            {
                _cache = new MemoryCacheWrapper();
            }
#endif

            Version    = CmsVariables.VERSION;
            PhysicPath = EnvUtil.GetBaseDirectory();

            //获取编译生成的时间
            //DateTime builtDate = new DateTime(2000, 1, 1).AddDays(ver.Build).AddSeconds(ver.Revision*2);
            var filePath = typeof(Cms).Assembly.Location;
            if (string.IsNullOrEmpty(filePath))
            {
                filePath = PhysicPath + CmsVariables.FRAMEWORK_ASSEMBLY_PATH + "jrcms.dll";
            }
            var builtDate = File.GetLastWriteTime(filePath);
            BuiltTime = DateHelper.ToUnix(builtDate);


            //获取平台
            var platFormId = (int)Environment.OSVersion.Platform;
            if (platFormId == 4 || platFormId == 6 || platFormId == 128)
            {
                RunAtMono = true;
            }
            //初始化
            //todo: plugin
            //Plugins = new CmsPluginContext();

            // 初始化缓存工厂
            CmsCacheFactory.Configure(_cache);
            CacheFactory.Configure(_cache);
            // 初始化模板
            Template = new CmsTemplate(_cache, TemplateNames.FileName);
            Cache    = new CmsCache(CmsCacheFactory.Singleton);
            // 初始化内存缓存
            Utility  = new CmsUtility();
            Language = new CmsLanguagePackage();

            #region 缓存清除

            //
            //UNDONE: 弱引用
            //

            /*
             * WeakRefCache.OnLinkBuilting += () =>
             * {
             *  Cms.Cache.Clear(CacheSign.Link.ToString());
             * };
             *
             * WeakRefCache.OnModuleBuilting += () =>
             * {
             *  Cms.Cache.Clear(CacheSign.Module.ToString());
             * };
             *
             * WeakRefCache.OnPropertyBuilting += () =>
             * {
             *  Cms.Cache.Clear(CacheSign.Property.ToString());
             * };
             *
             * WeakRefCache.OnTemplateBindBuilting += () =>
             * {
             *  Cms.Cache.Clear(CacheSign.TemplateBind.ToString());
             * };
             *
             */

            #endregion
        }
Example #26
0
 public async Task <IActionResult> EditTemplate([FromBody] CmsTemplate parm)
 {
     return(Ok(await _tempService.UpdateAsync(parm)));
 }
Example #27
0
        protected void Page_Load(object sender, EventArgs e)
        {
            oWeb.ValidaSessionAdm();
            if (!IsPostBack)
            {
                CodNodo.Value    = oWeb.GetData("CodNodo");
                CodNodoRel.Value = oWeb.GetData("CodNodoRel");
                DBConn oConn = new DBConn();
                if (oConn.Open())
                {
                    CmsTemplate oTemplate = new CmsTemplate(ref oConn);
                    DataTable   dTemplate = oTemplate.Get();
                    if (dTemplate != null)
                    {
                        if (dTemplate.Rows.Count > 0)
                        {
                            rdCmbTemplate.Items.Add(new ListItem("Seleccione Template", ""));
                            foreach (DataRow oRow in dTemplate.Rows)
                            {
                                rdCmbTemplate.Items.Add(new ListItem(oRow["nom_template"].ToString(), oRow["cod_template"].ToString()));
                            }
                        }
                    }
                    dTemplate = null;

                    if (!string.IsNullOrEmpty(CodNodo.Value))
                    {
                        CmsNodos oNodos = new CmsNodos(ref oConn);
                        oNodos.CodNodo = CodNodo.Value;
                        DataTable dNodos = oNodos.Get();
                        if (dNodos != null)
                        {
                            if (dNodos.Rows.Count > 0)
                            {
                                CodNodoRel.Value     = dNodos.Rows[0]["cod_nodo_rel"].ToString();
                                txtTitulo.Text       = dNodos.Rows[0]["titulo_nodo"].ToString();
                                textDescripcion.Text = dNodos.Rows[0]["texto_nodo"].ToString();
                                rdCmbTemplate.Items.FindByValue(dNodos.Rows[0]["cod_template"].ToString()).Selected = true;
                                rdCmbEstado.Items.FindByValue(dNodos.Rows[0]["est_nodo"].ToString()).Selected       = true;
                                chk_inicio.Checked         = (dNodos.Rows[0]["ini_nodo"].ToString() == "V" ? true : false);
                                chk_perfil.Checked         = (dNodos.Rows[0]["pf_nodo"].ToString() == "V" ? true : false);
                                txtTitHeader.Text          = dNodos.Rows[0]["titleheader_nodo"].ToString();
                                txtKeyWords.Text           = dNodos.Rows[0]["keywords_nodo"].ToString();
                                chk_contenido.Checked      = (dNodos.Rows[0]["cont_nodo"].ToString() == "V" ? true : false);
                                chk_privado.Checked        = (dNodos.Rows[0]["prv_nodo"].ToString() == "1" ? true : false);
                                OrdNodo.Value              = dNodos.Rows[0]["ord_nodo"].ToString();
                                chk_asocusrperfil.Checked  = (dNodos.Rows[0]["ini_asoc_usr_nodo"].ToString() == "V" ? true : false);
                                chk_PrivUsrClient.Checked  = (dNodos.Rows[0]["ind_despl_usr_client"].ToString() == "V" ? true : false);
                                chk_olvclave.Checked       = (dNodos.Rows[0]["ind_olvclave_nodo"].ToString() == "V" ? true : false);
                                chk_rstclave.Checked       = (dNodos.Rows[0]["ind_rstclave_nodo"].ToString() == "V" ? true : false);
                                chk_login.Checked          = (dNodos.Rows[0]["ind_login_nodo"].ToString() == "V" ? true : false);
                                chk_PrivUsrSite.Checked    = (dNodos.Rows[0]["ind_despl_usr_site"].ToString() == "V" ? true : false);
                                chk_poltsecure.Checked     = (dNodos.Rows[0]["ind_poltsecure_nodo"].ToString() == "V" ? true : false);
                                chk_termuse.Checked        = (dNodos.Rows[0]["ind_termuse_nodo"].ToString() == "V" ? true : false);
                                chk_registrate.Checked     = (dNodos.Rows[0]["ind_registrate_nodo"].ToString() == "V" ? true : false);
                                chk_pagexito.Checked       = (dNodos.Rows[0]["ind_pagexito_nodo"].ToString() == "V" ? true : false);
                                chk_pagefotos.Checked      = (dNodos.Rows[0]["ind_photo_nodo"].ToString() == "V" ? true : false);
                                chk_ini_nod_phone.Checked  = (dNodos.Rows[0]["ini_nodo_phone"].ToString() == "V" ? true : false);
                                chk_prf_nod_phone.Checked  = (dNodos.Rows[0]["pf_nodo_phone"].ToString() == "V" ? true : false);
                                chk_cont_nod_phone.Checked = (dNodos.Rows[0]["cont_nodo_phone"].ToString() == "V" ? true : false);
                                sAccion.Value              = "EDITAR";
                            }
                        }
                        dTemplate = null;
                    }
                    oConn.Close();
                }
            }
        }
Example #28
0
 public async Task <ApiResult <string> > AddTemplate(CmsTemplate parm)
 {
     return(await _tempService.AddAsync(parm));
 }