public override CmsDependencyMessage[] ValidateDependency()
        {
            string nothing = Guid.NewGuid().ToString();
            List <CmsDependencyMessage> ret = new List <CmsDependencyMessage>();

            switch (_mode)
            {
            case ExistsMode.MustExist:
                if (CmsConfig.getConfigValue(configKey, nothing) == nothing)
                {
                    ret.Add(CmsDependencyMessage.Error("Required configuration key \"" + configKey + "\" is not set in the web.config file"));
                }
                break;

            case ExistsMode.MustNotExist:
                if (CmsConfig.getConfigValue(configKey, nothing) != nothing)
                {
                    ret.Add(CmsDependencyMessage.Error("Configuration key \"" + configKey + "\" should NOT exist in the web.config file"));
                }
                break;

            default: throw new ArgumentException("Error: invalid validation mode"); break;
            }
            return(ret.ToArray());
        }
            public static string RenderPopupLink(string actionConfigPagePathKey, string actionDefaultPagePath, NameValueCollection actionPageParams, CmsPage linkTargetPage, CmsLanguage langToRenderFor, string linkText, int popupWidth, int popupHeight)
            {
                string actionPagePath = CmsConfig.getConfigValue(actionConfigPagePathKey, actionDefaultPagePath);

                actionPageParams.Add("target", linkTargetPage.ID.ToString());
                string toggleEditUrl = CmsContext.getUrlByPagePath(actionPagePath, actionPageParams, langToRenderFor);

                return("<a href=\"" + toggleEditUrl + "\" onclick=\"EditMenuShowModal(this.href," + popupWidth + "," + popupHeight + "); return false;\">" + linkText + "</a>");
            }
            public static string RenderLink(string actionConfigPagePathKey, string actionDefaultPagePath, NameValueCollection actionPageParams, CmsPage linkTargetPage, CmsLanguage langToRenderFor, string linkText)
            {
                string actionPagePath = CmsConfig.getConfigValue(actionConfigPagePathKey, actionDefaultPagePath);

                actionPageParams.Add("target", linkTargetPage.ID.ToString());
                string toggleEditUrl = CmsContext.getUrlByPagePath(actionPagePath, actionPageParams, langToRenderFor);

                return("<a href=\"" + toggleEditUrl + "\">" + linkText + "</a>");
            }
            public static string Logoff(CmsPageEditMenuAction action, CmsPage pageToRenderFor, CmsLanguage langToRenderFor)
            {
                string actionPagePath         = CmsConfig.getConfigValue("LoginPath", "/_login");
                NameValueCollection paramList = new NameValueCollection();

                paramList.Add("action", "logoff");
                string actionUrl = CmsContext.getUrlByPagePath(actionPagePath, paramList, langToRenderFor);

                return("<a href=\"" + actionUrl + "\"><strong>Logoff</strong></a>");
            }
        protected void Application_Error(Object sender, EventArgs e)
        {
            string techEmail  = CmsConfig.getConfigValue("TechnicalAdministratorEmail", "");
            string smtpServer = CmsConfig.getConfigValue("smtpServer", "");

            if (techEmail.IndexOf("@") > 0 && smtpServer.Trim() != "")
            {
                Hatfield.Web.Portal.ApplicationUtils.Application_Error_StandardEmailSender(HttpContext.Current, techEmail, new string[] { techEmail }, smtpServer);
            }
        }
            public static string ExitFromEditing(CmsPageEditMenuAction action, CmsPage pageToRenderFor, CmsLanguage langToRenderFor)
            {
                // return RenderLink("GotoEditModePath", "/_admin/action/gotoView", pageToRenderFor, langToRenderFor, "<strong>Exit from editing</strong>");

                NameValueCollection paramList = new NameValueCollection();

                paramList.Add("target", pageToRenderFor.ID.ToString());
                string url = CmsContext.getUrlByPagePath(CmsConfig.getConfigValue("GotoViewModePath", "/_admin/action/gotoView"), paramList, langToRenderFor);

                return("<input type=\"button\" onclick=\"window.location = '" + url + "';\" value=\"Exit from editing\">");
            }
Beispiel #7
0
 private static bool includePageLanguageInMacro()
 {
     if (CmsConfig.Languages.Length > 1)
     {
         return(CmsConfig.getConfigValue("LinkMacrosIncludeLanguage", false));
     }
     else
     {
         return(false);
     }
 }
Beispiel #8
0
        /// <summary>
        /// Renders the SideNavigation control to the HtmlTextWriter
        /// </summary>
        /// <param name="writer"></param>
        protected override void Render(System.Web.UI.HtmlTextWriter writer)
        {
            CmsPage page = CmsContext.HomePage;

            int maxLevels = 100;

            maxLevels = CmsConfig.getConfigValue("SideNavMaxLevels", maxLevels);

            string html = "<div id=\"SideNav\">\n<ul class=\"level0\">" + Environment.NewLine + recursiveRender(page, 0, maxLevels) + "\n</ul>\n</div>";

            writer.Write(html);
        }         // Render
Beispiel #9
0
        /// <summary>
        /// derive the file storage folder path
        /// </summary>
        /// <param name="aggregatorPage"></param>
        /// <param name="identifier"></param>
        /// <returns></returns>
        public static string getDMSStorageFolderUrl(CmsPage fileDetailsPage, int identifier, CmsLanguage language)
        {
            string DMSFileStorageFolderUrl = CmsConfig.getConfigValue("DMSFileStorageFolderUrl", "");

            DMSFileStorageFolderUrl = VirtualPathUtility.ToAbsolute(DMSFileStorageFolderUrl);
            DMSFileStorageFolderUrl = VirtualPathUtility.AppendTrailingSlash(DMSFileStorageFolderUrl);

            string subDir = "";

            if (CmsConfig.getConfigValue("DMSFileStorageLocationVersion", "V1") == "V2")
            {
                subDir = fileDetailsPage.ID.ToString() + identifier.ToString() + language.shortCode.ToLower() + "/";
            }

            return(DMSFileStorageFolderUrl + subDir);
        }
Beispiel #10
0
        public static string getDMSStorageFilenameOnDisk(CmsPage pageLinkedToFile, int identifier, CmsLanguage language, string userFilename)
        {
            string prependToFilename = "";

            if (CmsConfig.getConfigValue("DMSFileStorageLocationVersion", "V1") == "V1")
            {
                prependToFilename = pageLinkedToFile.ID.ToString() + identifier.ToString();
            }

            string baseUrl = getDMSStorageFolderUrl(pageLinkedToFile, identifier, language);

            string fn       = baseUrl + prependToFilename + userFilename;
            string fnOnDisk = System.Web.Hosting.HostingEnvironment.MapPath(fn);

            return(fnOnDisk);
        }
            public static string RemoveEditLock(CmsPageEditMenuAction action, CmsPage pageToRenderFor, CmsLanguage langToRenderFor)
            {
                CmsPageLockData     lockData  = pageToRenderFor.getCurrentPageLockData();
                NameValueCollection paramList = new NameValueCollection();
                StringBuilder       html      = new StringBuilder();

                // -- Kill lock link
                if (lockData.LockedByUsername == CmsContext.currentWebPortalUser.UserName || CmsContext.currentUserIsSuperAdmin)
                {
                    paramList.Clear();
                    paramList.Add("target", pageToRenderFor.ID.ToString());
                    paramList.Add("action", "logoff");
                    string killLockLink = CmsContext.getUrlByPagePath(CmsConfig.getConfigValue("KillLockPath", "/_admin/actions/killLock"), paramList);
                    html.Append("<a href=\"#\" onclick=\"EditMenuConfirmModal('Do you really want to remove the edit lock?','" + killLockLink + "',300, 300);\"><strong>Remove</strong> edit lock</a><br />");
                }
                return(html.ToString());
            }
            public static string DeleteThisPage(CmsPageEditMenuAction action, CmsPage pageToRenderFor, CmsLanguage langToRenderFor)
            {
                NameValueCollection paramList = new NameValueCollection();

                paramList.Add("target", pageToRenderFor.ID.ToString());

                string confirmText      = "Do you really want to delete this page?";
                int    numPagesToDelete = pageToRenderFor.getLinearizedPages().Keys.Count;

                if (numPagesToDelete > 1)
                {
                    confirmText = "Do you really want to delete this page and all " + (numPagesToDelete - 1) + " sub-pages?";
                }

                string deletePageUrl = CmsContext.getUrlByPagePath(CmsConfig.getConfigValue("DeletePagePath", "/_admin/actions/deletePage"), paramList, langToRenderFor);

                return("<a href=\"#\" onclick=\"EditMenuConfirmModal('" + confirmText + "','" + deletePageUrl + "',300, 300);\"><strong>Delete</strong> this page</a>");
            }
        /// <summary>
        /// Checks whether a user has write access in this zone.
        /// </summary>
        /// <param name="u"></param>
        /// <returns></returns>
        public bool canWrite(WebPortalUser u)
        {
            if (u != null && u.inRole(CmsConfig.getConfigValue("AdminUserRole", "Administrator")))
            {
                return(true);
            }

            WebPortalUserRole[] roleArray = new WebPortalUserRole[] { WebPortalUserRole.dummyPublicUserRole };
            if (u != null)
            {
                u.AddUserRole(WebPortalUserRole.dummyPublicUserRole); // users are always part of the "public" user role.
                roleArray = u.userRoles;
            }

            CmsZoneUserRoleDb db = new CmsZoneUserRoleDb();

            return(db.fetchRoleMatchingCountForWrite(this, roleArray) > 0);
        }
Beispiel #14
0
        /// <summary>
        /// Handle PageNotFound (404) errors.
        /// <para>If the useInternal404NotFoundErrorHandler config entry is true, will send the user to the page
        /// specified by Internal404NotFoundErrorHandlerPageUrl config entry.</para>
        /// </summary>
        public static void HandleNotFoundException()
        {
            bool useInternal404NotFoundErrorHandler = CmsConfig.getConfigValue("useInternal404NotFoundErrorHandler", false);

            if (useInternal404NotFoundErrorHandler)
            {
                string defaultUrl = "";
                if (System.Web.HttpContext.Current != null && System.Web.HttpContext.Current.Request != null)
                {
                    defaultUrl = System.Web.HttpContext.Current.Request.Url.PathAndQuery;
                }

                string fromUrl = PageUtils.getFromForm("aspxerrorpath", defaultUrl);
                fromUrl = System.Web.HttpUtility.UrlEncode(fromUrl);

                string Internal404NotFoundErrorHandlerPageUrl = CmsContext.ApplicationPath + "/_internal/error404.aspx?from=" + fromUrl;
                if (CmsConfig.getConfigValue("Internal404NotFoundErrorHandlerPageUrl", "") != "")
                {
                    Internal404NotFoundErrorHandlerPageUrl = String.Format(CmsConfig.getConfigValue("Internal404NotFoundErrorHandlerPageUrl", ""), fromUrl);
                }

                // use Server.Transfer (And not Response.Redirect) to hide the CMS URL from the user.
                System.Web.HttpContext.Current.Server.Transfer(Internal404NotFoundErrorHandlerPageUrl);
                return;
            }
            else
            {
                // <?php header("HTTP/1.1 404 Not Found"); ?>
                // <?php header("Status: 404 Not Found"); ?>

                System.Web.HttpResponse resp = System.Web.HttpContext.Current.Response;
                resp.ClearContent();
                resp.StatusCode = 404;
                resp.AddHeader("Status", "404 Not Found");

                resp.Write("<html><body><strong>The page that you requested does not exist.</strong><p><em>Visit our <a href=\"" + CmsContext.ApplicationPath + "\">home page here</a></em></p></body></html>");
                resp.End();
                return;

                // throw new System.Web.HttpException(404, "File Not Found"); //http://forums.asp.net/t/762031.aspx
            }
        }
            public CmsDependency[] getDependencies()
            {
                List <CmsDependency> ret = new List <CmsDependency>();

                // -- required pages
                ret.Add(new CmsPageDependency(CmsConfig.getConfigValue("KillLockPath", "/_admin/actions/killLock"), CmsConfig.Languages));
                ret.Add(new CmsPageDependency(CmsConfig.getConfigValue("LoginPath", "/_login"), CmsConfig.Languages));
                ret.Add(new CmsPageDependency(CmsConfig.getConfigValue("GotoEditModePath", "/_admin/action/gotoEdit"), CmsConfig.Languages));
                ret.Add(new CmsPageDependency(CmsConfig.getConfigValue("GotoViewModePath", "/_admin/actions/gotoView"), CmsConfig.Languages));
                ret.Add(new CmsPageDependency(CmsConfig.getConfigValue("CreateNewPagePath", "/_admin/createPage"), CmsConfig.Languages));
                ret.Add(new CmsPageDependency(CmsConfig.getConfigValue("RenamePagePath", "/_admin/actions/renamePage"), CmsConfig.Languages));
                ret.Add(new CmsPageDependency(CmsConfig.getConfigValue("MovePagePath", "/_admin/actions/movePage"), CmsConfig.Languages));
                ret.Add(new CmsPageDependency(CmsConfig.getConfigValue("ChangePageTemplatePath", "/_admin/actions/changeTemplate"), CmsConfig.Languages));
                ret.Add(new CmsPageDependency(CmsConfig.getConfigValue("DeletePagePath", "/_admin/actions/deletePage"), CmsConfig.Languages));
                ret.Add(new CmsPageDependency(CmsConfig.getConfigValue("SortSubPagesPath", "/_admin/actions/sortSubPages"), CmsConfig.Languages));
                ret.Add(new CmsPageDependency(CmsConfig.getConfigValue("ChangeMenuVisibilityPath", "/_admin/actions/MenuVisibilityPopup"), CmsConfig.Languages));
                ret.Add(new CmsPageDependency(CmsConfig.getConfigValue("ViewRevisionsPagePath", "/_admin/ViewRevisions"), CmsConfig.Languages));
                ret.Add(new CmsPageDependency(CmsConfig.getConfigValue("AuditPagePath", "/_admin/Audit"), CmsConfig.Languages));
                ret.Add(new CmsPageDependency(CmsConfig.getConfigValue("EditUsersPagePath", "/_admin/EditUsers"), CmsConfig.Languages));
                return(ret.ToArray());
            }
Beispiel #16
0
        public override CmsDependencyMessage[] ValidateDependency()
        {
            List <CmsDependencyMessage> ret = new List <CmsDependencyMessage>();

            switch (_mode)
            {
            case ExistsMode.MustExist:
                if (CmsConfig.KeyExists(configKey) == false)
                {
                    ret.Add(CmsDependencyMessage.Error("Required configuration key \"" + configKey + "\" is not set in the web.config file"));
                }
                break;

            case ExistsMode.MustNotExist:
                if (CmsConfig.KeyExists(configKey) == true)
                {
                    ret.Add(CmsDependencyMessage.Error("Configuration key \"" + configKey + "\" should NOT exist in the web.config file"));
                }
                break;

            default: throw new ArgumentException("Error: invalid validation mode"); break;
            }
            return(ret.ToArray());
        }
        public override string GetApplicationName()
        {
            string siteName = CmsConfig.getConfigValue("SiteName", "Unknown hatCms installation");

            return(siteName + " (hatCms)");
        }
Beispiel #18
0
        /// <summary>
        /// This gathers dependencies from all placeholders, controls, and core systems.
        /// This function is called when checking for dependencies (during setup or audit).
        /// </summary>
        /// <returns></returns>
        public static CmsDependency[] GatherAllDependencies()
        {
            List <CmsDependency> ret = new List <CmsDependency>();

            // -- tables
            ret.Add(new CmsDatabaseTableDependency(@"
                CREATE TABLE  `pages` (
                  `pageId` int(11) NOT NULL AUTO_INCREMENT,
                  `showInMenu` int(10) unsigned NOT NULL DEFAULT '1',
                  `template` varchar(255) NOT NULL,
                  `parentPageId` int(11) NOT NULL DEFAULT '0',
                  `SortOrdinal` int(11) NOT NULL DEFAULT '0',
                  `CreatedDateTime` datetime NOT NULL,
                  `LastUpdatedDateTime` datetime NOT NULL,
                  `LastModifiedBy` varchar(255) NOT NULL DEFAULT '',
                  `RevisionNumber` int(11) NOT NULL DEFAULT '1',
                  `Deleted` datetime DEFAULT NULL,
                  PRIMARY KEY (`pageId`),
                  KEY `pages_secondary` (`pageId`,`Deleted`),
                  KEY `pages_tertiary` (`parentPageId`,`Deleted`),
                  KEY `pages_quartinary` (`parentPageId`,`Deleted`) USING BTREE
                ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
            "));
            ret.Add(new CmsDatabaseTableDependency(@"
                CREATE TABLE  `pagelocks` (
                  `pageid` int(11) NOT NULL,
                  `LockedByUsername` varchar(255) NOT NULL,
                  `LockExpiresAt` datetime NOT NULL,
                  PRIMARY KEY (`pageid`)
                ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
            "));
            ret.Add(new CmsDatabaseTableDependency(@"
                CREATE TABLE  `pagelanginfo` (
                  `pageId` int(10) unsigned NOT NULL,
                  `langCode` varchar(255) NOT NULL,
                  `name` varchar(255) DEFAULT NULL,
                  `title` varchar(255) NOT NULL,
                  `menuTitle` varchar(255) NOT NULL,
                  `searchEngineDescription` text NOT NULL,
                  PRIMARY KEY (`pageId`,`langCode`)
                ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
            "));

            ret.Add(new CmsDatabaseTableDependency(@"
                CREATE TABLE  `resourceitemmetadata` (
                  `AutoIncId` int(10) unsigned NOT NULL AUTO_INCREMENT,
                  `ResourceId` int(10) unsigned NOT NULL,
                  `ResourceRevisionNumber` int(10) unsigned NOT NULL,
                  `Name` varchar(255) NOT NULL,
                  `Value` longtext NOT NULL,
                  `Deleted` datetime DEFAULT NULL,
                  PRIMARY KEY (`AutoIncId`),
                  KEY `ResourceId` (`ResourceId`)
                ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
                "));

            ret.Add(new CmsDatabaseTableDependency(@"
                CREATE TABLE  `resourceitems` (
                  `AutoIncId` int(10) unsigned NOT NULL AUTO_INCREMENT,
                  `ResourceId` int(11) NOT NULL,
                  `RevisionNumber` int(11) NOT NULL,
                  `Filename` varchar(255) NOT NULL,
                  `FilePath` text NOT NULL,
                  `FileDirectory` text NOT NULL,
                  `FileSize` int(10) unsigned NOT NULL,
                  `FileTimestamp` datetime NOT NULL,
                  `MimeType` varchar(255) NOT NULL,
                  `ModifiedBy` varchar(255) NOT NULL,
                  `ModificationDate` datetime NOT NULL,
                  `Deleted` datetime DEFAULT NULL,
                  PRIMARY KEY (`AutoIncId`),
                  UNIQUE KEY `ResourceItemsUniqueIdRevisionNumber` (`ResourceId`,`RevisionNumber`),
                  KEY `RevisionNumIndex` (`RevisionNumber`,`FileDirectory`(255),`Deleted`)
                ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
                "));

            ret.Add(new CmsDatabaseTableDependency(@"
                    CREATE TABLE `PersistentVariables` (
                      `PersistentVariableId` INT NOT NULL AUTO_INCREMENT ,
                      `Name` VARCHAR(255) NOT NULL ,
                      `PersistedValue` BLOB NULL ,
                      PRIMARY KEY (`PersistentVariableId`) ,
                      UNIQUE INDEX `Name_UNIQUE` (`Name` ASC) );
                "));

            // -- some project directories should be removed from production sites
            #if  !DEBUG
            ret.Add(CmsDirectoryDoesNotExistDependency.UnderAppPath("classes"));
            ret.Add(CmsDirectoryDoesNotExistDependency.UnderAppPath("setup"));
            ret.Add(CmsDirectoryDoesNotExistDependency.UnderAppPath("placeholders"));
            ret.Add(CmsDirectoryDoesNotExistDependency.UnderAppPath("_system/_AdminDocs"));

            if (!Hatfield.Web.Portal.PageUtils.IsRunningOnMono())
            {
                ret.Add(CmsFileDependency.UnderAppPath("bin/XmpToolkit.dll")); // ensure that the XmpToolkit is being copied over
            }
            #endif

            // -- files
            ret.Add(CmsFileDependency.UnderAppPath("default.aspx"));

            foreach (string filePath in CmsConfig.URLsToNotRemap)
            {
                ret.Add(CmsFileDependency.UnderAppPath(filePath));
            }

            // -- config entries
            ret.Add(new CmsConfigItemDependency("URLsToNotRemap"));
            ret.Add(new CmsConfigItemDependency("AdminUserRole"));
            ret.Add(new CmsConfigItemDependency("LoginUserRole"));
            ret.Add(new CmsConfigItemDependency("AuthorAccessUserRole"));
            ret.Add(new CmsConfigItemDependency("TemplateEngineVersion", CmsDependency.ExistsMode.MustNotExist));    // removed Mar 18, 2011. Only v2 templates are now supported.
            ret.Add(new CmsConfigItemDependency("RequireAnonLogin", CmsDependency.ExistsMode.MustNotExist));         // deprecated 10 Feb 2011. Use the Zones system to manage anon logins
            ret.Add(new CmsConfigItemDependency("PathSpaceReplacementChar", CmsDependency.ExistsMode.MustNotExist)); // always set to "+".
            ret.Add(new CmsConfigItemDependency("RewriteEngineOn", CmsDependency.ExistsMode.MustNotExist));          // RewriteEngine is always on.
            ret.Add(new CmsConfigItemDependency("Languages"));
            ret.Add(new CmsConfigItemDependency("useInternal404NotFoundErrorHandler"));

            bool useInternal404NotFoundErrorHandler = CmsConfig.getConfigValue("useInternal404NotFoundErrorHandler", false);
            if (useInternal404NotFoundErrorHandler)
            {
                ret.Add(new CmsConfigItemDependency("Internal404NotFoundErrorHandlerPageUrl"));
                ret.Add(new CmsPageDependency(CmsConfig.getConfigValue("Internal404NotFoundErrorHandlerPageUrl", "/_internal/error404"), CmsConfig.Languages));
            }

            ret.Add(new CmsConfigItemDependency("CreateNewBlogPostPath", CmsDependency.ExistsMode.MustNotExist));     // blogging is no more.
            ret.Add(new CmsConfigItemDependency("blogPostTemplate", CmsDependency.ExistsMode.MustNotExist));          // blogging is no more.
            ret.Add(new CmsConfigItemDependency("DefaultImageThumbnailSize", CmsDependency.ExistsMode.MustNotExist)); // not used any more

            // -- ensure that the HtmlContent placeholders do not have the old link to the showThumb.aspx page (note: this validation is slow, but very useful.)
            ret.Add(new CmsPlaceholderContentDependency("HtmlContent", "_system/showthumb.aspx", CmsDependency.ExistsMode.MustNotExist, StringComparison.CurrentCultureIgnoreCase));

            ret.Add(new CmsControlDependency("_system/internal/EditCalendarCategoriesPopup", CmsDependency.ExistsMode.MustNotExist)); // deprecated. now "EventCalendarCategoryPopup"

            // -- gather all admin tool dependencies
            ret.AddRange(HatCMS.Admin.BaseCmsAdminTool.getAllAdminToolDependencies());

            // -- gather all Module-level dependencies
            ret.AddRange(CmsModuleUtils.getAllModuleLevelDependencies());

            // -- all pages should have valid templates, placeholders and controls
            Dictionary <int, CmsPage> allPages = CmsContext.HomePage.getLinearizedPages();
            foreach (int pageId in allPages.Keys)
            {
                CmsPage page = allPages[pageId];
                ret.Add(new CmsTemplateDependency(page.TemplateName));


                string[] placeholderNames = new string[0];
                try
                {
                    placeholderNames = page.getAllPlaceholderNames();
                }
                catch (Exception ex)
                {
                    ret.Add(new CmsConfigItemDependency("GatherAllDependencies: Could not get page (pageid:" + pageId + ") placeholder names: " + ex.Message));
                }

                foreach (string phName in placeholderNames)
                {
                    ret.Add(new CmsPlaceholderDependency(phName, page.TemplateName));
                    if (PlaceholderUtils.PlaceholderExists(phName))
                    {
                        ret.AddRange(PlaceholderUtils.getDependencies(phName));
                    }
                }

                string[] controlPaths = new string[0];
                try
                {
                    controlPaths = page.getAllControlPaths();
                }
                catch (Exception ex)
                {
                    ret.Add(new CmsConfigItemDependency("GatherAllDependencies: Could not get page control paths (pageid:" + pageId + ") : " + ex.Message));
                }
                foreach (string controlPath in controlPaths)
                {
                    ret.Add(new CmsControlDependency(controlPath));
                    ret.AddRange(CmsContext.currentPage.TemplateEngine.getControlDependencies(controlPath));
                }
            } // foreach page

            // -- all templates should have valid controls and placeholders (regardless of if the template is implemented in a page or not)
            string[] templates = CmsContext.getTemplateNamesForCurrentUser();
            CmsPage  dummyPage = new CmsPage();
            foreach (string template in templates)
            {
                dummyPage.TemplateName = template;

                string[] placeholderNames = dummyPage.getAllPlaceholderNames();

                foreach (string phName in placeholderNames)
                {
                    ret.Add(new CmsPlaceholderDependency(phName, template));
                    if (PlaceholderUtils.PlaceholderExists(phName))
                    {
                        ret.AddRange(PlaceholderUtils.getDependencies(phName));
                    }
                }


                CmsControlDefinition[] controlDefs = dummyPage.TemplateEngine.getAllControlDefinitions();
                foreach (CmsControlDefinition controlDef in controlDefs)
                {
                    ret.Add(new CmsControlDependency(controlDef));
                    ret.AddRange(dummyPage.TemplateEngine.getControlDependencies(controlDef.ControlNameOrPath));
                }
            } // foreach

            // remove all duplicates based on the content of each dependency.

            return(CmsDependency.RemoveDuplicates(ret.ToArray()));
        }
Beispiel #19
0
        /// <summary>
        /// Collect the dependecies embedded in the HatCMS.Core library.
        /// </summary>
        /// <returns></returns>
        private static CmsDependency[] CollectCoreDependencies()
        {
            List <CmsDependency> ret = new List <CmsDependency>();

            // -- tables
            ret.Add(new CmsDatabaseTableDependency(@"
                CREATE TABLE  `pages` (
                  `pageId` int(11) NOT NULL AUTO_INCREMENT,
                  `showInMenu` int(10) unsigned NOT NULL DEFAULT '1',
                  `template` varchar(255) NOT NULL,
                  `parentPageId` int(11) NOT NULL DEFAULT '0',
                  `SortOrdinal` int(11) NOT NULL DEFAULT '0',
                  `CreatedDateTime` datetime NOT NULL,
                  `LastUpdatedDateTime` datetime NOT NULL,
                  `LastModifiedBy` varchar(255) NOT NULL DEFAULT '',
                  `RevisionNumber` int(11) NOT NULL DEFAULT '1',
                  `Deleted` datetime DEFAULT NULL,
                  PRIMARY KEY (`pageId`),
                  KEY `pages_secondary` (`pageId`,`Deleted`),
                  KEY `pages_tertiary` (`parentPageId`,`Deleted`),
                  KEY `pages_quartinary` (`parentPageId`,`Deleted`) USING BTREE
                ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
            "));
            ret.Add(new CmsDatabaseTableDependency(@"
                CREATE TABLE  `pagelocks` (
                  `pageid` int(11) NOT NULL,
                  `LockedByUsername` varchar(255) NOT NULL,
                  `LockExpiresAt` datetime NOT NULL,
                  PRIMARY KEY (`pageid`)
                ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
            "));
            ret.Add(new CmsDatabaseTableDependency(@"
                CREATE TABLE  `pagelanginfo` (
                  `pageId` int(10) unsigned NOT NULL,
                  `langCode` varchar(255) NOT NULL,
                  `name` varchar(255) DEFAULT NULL,
                  `title` varchar(255) NOT NULL,
                  `menuTitle` varchar(255) NOT NULL,
                  `searchEngineDescription` text NOT NULL,
                  PRIMARY KEY (`pageId`,`langCode`)
                ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
            "));

            ret.Add(new CmsDatabaseTableDependency(@"
                CREATE TABLE  `resourceitemmetadata` (
                  `AutoIncId` int(10) unsigned NOT NULL AUTO_INCREMENT,
                  `ResourceId` int(10) unsigned NOT NULL,
                  `ResourceRevisionNumber` int(10) unsigned NOT NULL,
                  `Name` varchar(255) NOT NULL,
                  `Value` longtext NOT NULL,
                  `Deleted` datetime DEFAULT NULL,
                  PRIMARY KEY (`AutoIncId`),
                  KEY `ResourceId` (`ResourceId`)
                ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
                "));

            ret.Add(new CmsDatabaseTableDependency(@"
                CREATE TABLE  `resourceitems` (
                  `AutoIncId` int(10) unsigned NOT NULL AUTO_INCREMENT,
                  `ResourceId` int(11) NOT NULL,
                  `RevisionNumber` int(11) NOT NULL,
                  `Filename` varchar(255) NOT NULL,
                  `FilePath` text NOT NULL,
                  `FileDirectory` text NOT NULL,
                  `FileSize` int(10) unsigned NOT NULL,
                  `FileTimestamp` datetime NOT NULL,
                  `MimeType` varchar(255) NOT NULL,
                  `ModifiedBy` varchar(255) NOT NULL,
                  `ModificationDate` datetime NOT NULL,
                  `Deleted` datetime DEFAULT NULL,
                  PRIMARY KEY (`AutoIncId`),
                  UNIQUE KEY `ResourceItemsUniqueIdRevisionNumber` (`ResourceId`,`RevisionNumber`),
                  KEY `RevisionNumIndex` (`RevisionNumber`,`FileDirectory`(255),`Deleted`)
                ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
                "));

            ret.Add(new CmsDatabaseTableDependency(@"
                    CREATE TABLE `persistentvariables` (
                      `PersistentVariableId` int(11) NOT NULL AUTO_INCREMENT,
                      `Name` varchar(255) NOT NULL,
                      `PersistedValue` longblob,
                      PRIMARY KEY (`PersistentVariableId`),
                      UNIQUE KEY `Name_UNIQUE` (`Name`)
                    ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
                "));

            // -- some project directories should be removed from production sites
            #if  !DEBUG
            if (!Hatfield.Web.Portal.PageUtils.IsRunningOnMono())
            {
                ret.Add(CmsFileDependency.UnderAppPath("bin/XmpToolkit.dll")); // ensure that the XmpToolkit is being copied over
            }
            #endif

            // -- files
            foreach (string filePath in CmsConfig.URLsToNotRemap)
            {
                ret.Add(CmsFileDependency.UnderAppPath(filePath));
            }

            // -- config entries
            ret.Add(new CmsConfigItemDependency("URLsToNotRemap"));
            ret.Add(new CmsConfigItemDependency("AdminUserRole"));
            ret.Add(new CmsConfigItemDependency("LoginUserRole"));
            ret.Add(new CmsConfigItemDependency("AuthorAccessUserRole"));
            ret.Add(new CmsConfigItemDependency("TemplateEngineVersion", CmsDependency.ExistsMode.MustNotExist));    // removed Mar 18, 2011. Only v2 templates are now supported.
            ret.Add(new CmsConfigItemDependency("RequireAnonLogin", CmsDependency.ExistsMode.MustNotExist));         // deprecated 10 Feb 2011. Use the Zones system to manage anon logins
            ret.Add(new CmsConfigItemDependency("PathSpaceReplacementChar", CmsDependency.ExistsMode.MustNotExist)); // always set to "+".
            ret.Add(new CmsConfigItemDependency("RewriteEngineOn", CmsDependency.ExistsMode.MustNotExist));          // RewriteEngine is always on.
            ret.Add(new CmsConfigItemDependency("ThumbImageCacheDirectory", CmsDependency.ExistsMode.MustNotExist)); // thumbnail cache is always in _system/writable/ThumbnailCache
            ret.Add(new CmsConfigItemDependency("Languages"));
            ret.Add(new CmsConfigItemDependency("useInternal404NotFoundErrorHandler"));
            ret.Add(new CmsConfigItemDependency("smtpServer"));
            ret.Add(new CmsConfigItemDependency("TechnicalAdministratorEmail"));


            bool useInternal404NotFoundErrorHandler = CmsConfig.getConfigValue("useInternal404NotFoundErrorHandler", false);
            if (useInternal404NotFoundErrorHandler)
            {
                ret.Add(new CmsConfigItemDependency("Internal404NotFoundErrorHandlerPageUrl"));
                ret.Add(new CmsPageDependency(CmsConfig.getConfigValue("Internal404NotFoundErrorHandlerPageUrl", "/_internal/error404"), CmsConfig.Languages));
            }

            ret.Add(new CmsConfigItemDependency("CreateNewBlogPostPath", CmsDependency.ExistsMode.MustNotExist));     // blogging is no more.
            ret.Add(new CmsConfigItemDependency("blogPostTemplate", CmsDependency.ExistsMode.MustNotExist));          // blogging is no more.
            ret.Add(new CmsConfigItemDependency("DefaultImageThumbnailSize", CmsDependency.ExistsMode.MustNotExist)); // not used any more


            ret.Add(new CmsControlDependency("_system/internal/EditCalendarCategoriesPopup", CmsDependency.ExistsMode.MustNotExist)); // deprecated. now "EventCalendarCategoryPopup"

            ret.Add(new CmsPageDependency("/_admin/actions/deleteNews", CmsConfig.Languages, CmsDependency.ExistsMode.MustNotExist)); // deleteNews page is deprecated; news deletion is handled on the page level.
            ret.Add(new CmsPageDependency("/_admin/actions/deleteJob", CmsConfig.Languages, CmsDependency.ExistsMode.MustNotExist));  // deleteJob page is deprecated; news deletion is handled on the page level.
            ret.Add(new CmsPageDependency(CmsConfig.getConfigValue("LoginPath", "/_login"), CmsConfig.Languages));


            return(ret.ToArray());
        }
        public string RunInlineGlossaryFilter(CmsPage pageBeingFiltered, string placeholderHtml)
        {
            try
            {
                bool enabled = CmsConfig.getConfigValue("GlossaryHighlightFilter:Enable", false); // disabled by default

                if (!enabled || CmsContext.currentEditMode == CmsEditMode.Edit)
                {
                    return(placeholderHtml);
                }

#if DEBUG
                CmsContext.currentPage.HeadSection.AddCSSStyleStatements("span.InlineGlossaryTerm { border-bottom: 1px dotted red; }");
#endif

                // -- get the glossaryID to get data for (language specific)
                int    glossaryId  = 2;
                string glossaryIds = CmsConfig.getConfigValue("GlossaryHighlightFilter:GlossaryId", "");
                try
                {
                    string[] glossaryIdsParts = glossaryIds.Split(new char[] { CmsConfig.PerLanguageConfigSplitter }, StringSplitOptions.RemoveEmptyEntries);
                    if (glossaryIdsParts.Length >= CmsConfig.Languages.Length)
                    {
                        int index = CmsLanguage.IndexOf(CmsContext.currentLanguage.shortCode, CmsConfig.Languages);
                        if (index >= 0)
                        {
                            glossaryId = Convert.ToInt32(glossaryIdsParts[index]);
                        }
                    }
                }
                catch (Exception ex)
                {
                    throw new Exception("Error: GlossaryHighlightFilter is incorrectly configured!");
                }

                // -- get the glossary data from the database. The data is cached so that we don't hit the database for this info every time.
                GlossaryData[] gData;
                string         cacheKey = "GlossaryHighlightFilter_Data_" + glossaryId;
                if (!CmsContext.currentUserIsLoggedIn && System.Web.Hosting.HostingEnvironment.Cache[cacheKey] != null)
                {
                    gData = (GlossaryData[])System.Web.Hosting.HostingEnvironment.Cache[cacheKey];
                }
                else
                {
                    GlossaryDb db = new GlossaryDb();
                    gData = db.getGlossaryData(glossaryId);
                    if (!CmsContext.currentUserIsLoggedIn)
                    {
                        System.Web.Hosting.HostingEnvironment.Cache.Insert(cacheKey, gData, null, DateTime.Now.AddHours(1), System.Web.Caching.Cache.NoSlidingExpiration);
                    }

                    // go through longer words first (longer words/phrases are usually more specific than shorter ones)
                    gData = GlossaryData.SortByWordLength(gData, SortDirection.Descending);
                }

                // -- short-circuit processing if there aren't any glossary terms in the system.
                if (gData.Length == 0)
                {
                    return(placeholderHtml);
                }

                // -- process the placeholderHTML
                string html = placeholderHtml;

                List <string> toSurround = new List <string>();
                List <string> prefixs    = new List <string>();
                List <string> suffixs    = new List <string>();

                foreach (GlossaryData d in gData)
                {
                    int index = html.IndexOf(d.word.Trim(), StringComparison.CurrentCultureIgnoreCase);
                    if (index >= 0 && d.word.Trim().Length > 0)
                    {
                        // string safeDesc = StringUtils.AddSlashes(d.description);
                        string safeDesc = HttpUtility.HtmlEncode(d.word + ": " + d.description);
                        safeDesc = safeDesc.Replace("\n", " ");
                        safeDesc = safeDesc.Replace("\r", " ");
                        safeDesc = safeDesc.Replace("\t", " ");
                        safeDesc = safeDesc.Replace("  ", " ");

                        string prefix = "<span title=\"" + safeDesc + "\" class=\"InlineGlossaryTerm\">";
                        string suffix = "</span>";

                        toSurround.Add(d.word.Trim());
                        prefixs.Add(prefix);
                        suffixs.Add(suffix);
                    }
                } // foreach word

                html = SurroundInHtml(toSurround.ToArray(), prefixs.ToArray(), suffixs.ToArray(), html);

                return(html.ToString());
            }
            catch (Exception ex)
            {
                placeholderHtml += ("<!-- GlossaryHighlightingFilter Error: " + ex.Message + " -->");
            }

            return(placeholderHtml);
        }
        public static CmsCreateNewPageOptions CreateInstanceWithDefaultsForCurrentUser(CmsPage editMenuPage)
        {
            CmsCreateNewPageOptions ret = new CmsCreateNewPageOptions();
            // CreateNewPage_DefaultTemplate; use "~~ParentTemplate~~" for the new page's parent's template
            string defaultTemplate = CmsConfig.getConfigValue("CreateNewPage_DefaultTemplate", editMenuPage.TemplateName);

            if (string.Compare(defaultTemplate, "~~ParentTemplate~~", true) == 0)
            {
                defaultTemplate = editMenuPage.TemplateName;
            }

            if (CmsContext.currentUserIsSuperAdmin)
            {
                ret.PromptUserForFilename   = true;
                ret.PromptUserForTitle      = true;
                ret.PromptUserForMenuTitle  = true;
                ret.PromptUserForShowInMenu = true;
                ret.PromptUserForTemplate   = true;
                ret.PromptUserForParentPage = true;

                List <CmsPageLanguageInfo> langInfos = new List <CmsPageLanguageInfo>();
                foreach (CmsLanguage lang in CmsConfig.Languages)
                {
                    CmsPageLanguageInfo l = new CmsPageLanguageInfo();
                    l.languageShortCode = lang.shortCode;
                    l.name      = "";
                    l.title     = "";
                    l.menuTitle = "";
                    l.searchEngineDescription = "";

                    langInfos.Add(l);
                }

                ret.NewPageLanguageInfos = langInfos.ToArray();

                ret.ShowInMenu   = true;
                ret.Template     = defaultTemplate;
                ret.ParentPageId = editMenuPage.ID;
            }
            else if (editMenuPage.currentUserCanWrite)
            {
                ret.PromptUserForFilename   = true;
                ret.PromptUserForTitle      = true;
                ret.PromptUserForMenuTitle  = false;
                ret.PromptUserForShowInMenu = false;
                ret.PromptUserForTemplate   = false;
                ret.PromptUserForParentPage = false;

                List <CmsPageLanguageInfo> langInfos = new List <CmsPageLanguageInfo>();
                foreach (CmsLanguage lang in CmsConfig.Languages)
                {
                    CmsPageLanguageInfo l = new CmsPageLanguageInfo();
                    l.languageShortCode = lang.shortCode;
                    l.name      = "";
                    l.title     = "";
                    l.menuTitle = "";
                    l.searchEngineDescription = "";

                    langInfos.Add(l);
                }

                ret.NewPageLanguageInfos = langInfos.ToArray();

                ret.ShowInMenu   = true;
                ret.Template     = defaultTemplate;
                ret.ParentPageId = editMenuPage.ID;
            }
            else
            {
                ret.PromptUserForFilename   = false;
                ret.PromptUserForTitle      = false;
                ret.PromptUserForMenuTitle  = false;
                ret.PromptUserForShowInMenu = false;
                ret.PromptUserForTemplate   = false;
                ret.PromptUserForParentPage = false;

                List <CmsPageLanguageInfo> langInfos = new List <CmsPageLanguageInfo>();
                foreach (CmsLanguage lang in CmsConfig.Languages)
                {
                    CmsPageLanguageInfo l = new CmsPageLanguageInfo();
                    l.languageShortCode = lang.shortCode;
                    l.name      = "";
                    l.title     = "";
                    l.menuTitle = "";
                    l.searchEngineDescription = "";

                    langInfos.Add(l);
                }

                ret.NewPageLanguageInfos = langInfos.ToArray();

                ret.ShowInMenu   = true;
                ret.Template     = defaultTemplate;
                ret.ParentPageId = editMenuPage.ID;
            }

            return(ret);
        }
        public void ProcessRequest(HttpContext context)
        {
            string pagePath = "";

            if (context.Request.QueryString["p"] != null)
            {
                pagePath = context.Request.QueryString["p"];
            }
            CmsLanguage pageLang = CmsConfig.Languages[0];

            if (CmsConfig.Languages.Length > 1 && context.Request.QueryString["l"] != null)
            {
                string      langCode = context.Request.QueryString["l"];
                CmsLanguage testLang = CmsLanguage.GetFromHaystack(langCode, CmsConfig.Languages);
                if (!testLang.isInvalidLanguage)
                {
                    pageLang = testLang;
                }
            }

            CmsPage pageToRenderRSSFor = CmsContext.getPageByPath(pagePath, pageLang);

            if (pageToRenderRSSFor.ID < 0 || !pageToRenderRSSFor.currentUserCanRead)
            {
                context.Response.ContentType = "text/plain";
                context.Response.Write("Error: CMS page not found");
                context.Response.Flush();
                context.Response.End();
            }
            else
            {
                // -- generate the RssFeed
                RssFeed rssFeed = new RssFeed(System.Text.UTF8Encoding.UTF8);
                rssFeed.Version = RssVersion.RSS20;


                // -- setup the RSS channel
                string titlePrefix  = CmsConfig.getConfigValue("pageTitlePrefix", "");
                string titlePostfix = CmsConfig.getConfigValue("pageTitlePostfix", "");

                string     rssTitle       = titlePrefix + pageToRenderRSSFor.getTitle(pageLang) + titlePostfix;
                string     rssDescription = pageToRenderRSSFor.getSearchEngineDescription(pageLang);
                Uri        rssLink        = new Uri(pageToRenderRSSFor.getUrl(CmsUrlFormat.FullIncludingProtocolAndDomainName, pageLang), UriKind.RelativeOrAbsolute);
                RssChannel rssChannel     = new RssChannel(rssTitle, rssDescription, rssLink);
                rssChannel.Generator = "HatCMS: https://code.google.com/p/hatcms/";

                // -- call "GetRssFeedItems()" for each placeholder.
                CmsPlaceholderDefinition[] phDefs = pageToRenderRSSFor.getAllPlaceholderDefinitions();

                foreach (CmsPlaceholderDefinition phDef in phDefs)
                {
                    RssItem[] items = Placeholders.PlaceholderUtils.GetRssFeedItems(phDef.PlaceholderType, pageToRenderRSSFor, phDef, pageLang);
                    foreach (RssItem item in items)
                    {
                        rssChannel.Items.Add(item);
                    }
                }

                rssFeed.Channels.Add(rssChannel);

                context.Response.ContentType = "application/rss+xml";
                rssFeed.Write(context.Response.OutputStream);
                context.Response.Flush();
                context.Response.End();
            }
        }