diff --git a/src/Umbraco.Core/Configuration/GlobalSettings.cs b/src/Umbraco.Core/Configuration/GlobalSettings.cs new file mode 100644 index 0000000000..4eb22fae1f --- /dev/null +++ b/src/Umbraco.Core/Configuration/GlobalSettings.cs @@ -0,0 +1,837 @@ +using System; +using System.Collections.Generic; +using System.Configuration; +using System.Diagnostics; +using System.Web; +using System.Web.Configuration; +using System.Xml; +using Umbraco.Core.IO; + +namespace Umbraco.Core.Configuration +{ + //NOTE: Do not expose this class ever until we cleanup all configuration including removal of static classes, etc... + // we have this two tasks logged: + // http://issues.umbraco.org/issue/U4-58 + // http://issues.umbraco.org/issue/U4-115 + + //TODO: Re-enable Logging!!!! + + //TODO: Remove checks for if HttpContext is null, why are we doing this? we should be checking if the config setting + // can be read and if not then return the default. + + /// + /// The GlobalSettings Class contains general settings information for the entire Umbraco instance based on information from web.config appsettings + /// + internal class GlobalSettings + { + + private static HttpContextBase _customHttpContext; + + /// + /// Gets/sets the HttpContext object, this is generally used for unit testing. By default this will + /// use the HttpContext.Current + /// + internal static HttpContextBase HttpContext + { + get + { + if (_customHttpContext == null && System.Web.HttpContext.Current != null) + { + //return the current HttpContxt, do NOT store this in the _customHttpContext field + //as it will persist across reqeusts! + return new HttpContextWrapper(System.Web.HttpContext.Current); + } + + if (_customHttpContext == null && System.Web.HttpContext.Current == null) + { + //throw new NullReferenceException("The HttpContext property has not been set or the object execution is not running inside of an HttpContext"); + //NOTE: We should throw an exception here but the legacy code checks for null so we need to stick witht he legacy code for now. + return null; + } + return _customHttpContext; + } + set { _customHttpContext = value; } + } + + #region Private static fields + + // CURRENT UMBRACO VERSION ID + private const string CurrentUmbracoVersion = "4.9.0"; + + private static string _reservedUrlsCache; + private static string _reservedPathsCache; + private static StartsWithContainer _reservedList = new StartsWithContainer(); + + #endregion + + /// + /// Gets the reserved urls from web.config. + /// + /// The reserved urls. + public static string ReservedUrls + { + get + { + if (HttpContext != null) + return ConfigurationManager.AppSettings["umbracoReservedUrls"]; + return String.Empty; + } + } + + /// + /// Gets the reserved paths from web.config + /// + /// The reserved paths. + public static string ReservedPaths + { + get + { + if (HttpContext != null) + return ConfigurationManager.AppSettings["umbracoReservedPaths"]; + return String.Empty; + } + } + + /// + /// Gets the name of the content XML file. + /// + /// The content XML. + public static string ContentXml + { + get + { + try + { + return ConfigurationManager.AppSettings["umbracoContentXML"]; + } + catch + { + return String.Empty; + } + } + } + + /// + /// Gets the path to the storage directory (/data by default). + /// + /// The storage directory. + public static string StorageDirectory + { + get + { + try + { + return ConfigurationManager.AppSettings["umbracoStorageDirectory"]; + } + catch + { + return String.Empty; + } + } + } + + /// + /// Gets the path to umbraco's root directory (/umbraco by default). + /// + /// The path. + public static string Path + { + get + { + + try + { + return IOHelper.ResolveUrl(ConfigurationManager.AppSettings["umbracoPath"]); + } + catch + { + return String.Empty; + } + } + } + + /// + /// Gets the path to umbraco's client directory (/umbraco_client by default). + /// This is a relative path to the Umbraco Path as it always must exist beside the 'umbraco' + /// folder since the CSS paths to images depend on it. + /// + /// The path. + public static string ClientPath + { + get + { + return Path + "/../umbraco_client"; + } + } + + /// + /// Gets the database connection string + /// + /// The database connection string. + public static string DbDsn + { + get + { + try + { + return ConfigurationManager.AppSettings["umbracoDbDSN"]; + } + catch + { + return String.Empty; + } + } + set + { + if (DbDsn != value) + { + SaveSetting("umbracoDbDSN", value); + } + } + } + + /// + /// Gets or sets the configuration status. This will return the version number of the currently installed umbraco instance. + /// + /// The configuration status. + public static string ConfigurationStatus + { + get + { + try + { + return ConfigurationManager.AppSettings["umbracoConfigurationStatus"]; + } + catch + { + return String.Empty; + } + } + set + { + SaveSetting("umbracoConfigurationStatus", value); + } + } + + + /// + /// Forces umbraco to be medium trust compatible + /// + /// If true, umbraco will be medium-trust compatible, no matter what Permission level the server is on. + public static bool UseMediumTrust + { + get + { + try + { + var trustLevel = SystemUtilities.GetCurrentTrustLevel(); + if (trustLevel == AspNetHostingPermissionLevel.High || trustLevel == AspNetHostingPermissionLevel.Unrestricted) + return false; + else + return bool.Parse(ConfigurationManager.AppSettings["umbracoUseMediumTrust"]); + } + catch + { + return false; + } + } + } + + /// + /// Saves a setting into the configuration file. + /// + /// Key of the setting to be saved. + /// Value of the setting to be saved. + internal static void SaveSetting(string key, string value) + { + var webConfig = new WebConfigurationFileMap(); + var vDirs = webConfig.VirtualDirectories; + var vDir = FullpathToRoot; + foreach (VirtualDirectoryMapping v in webConfig.VirtualDirectories) + { + if (v.IsAppRoot) + { + vDir = v.PhysicalDirectory; + } + } + + var doc = new XmlDocument(); + doc.Load(String.Concat(vDir, "web.config")); + var root = doc.DocumentElement; + var setting = doc.SelectSingleNode(String.Concat("//appSettings/add[@key='", key, "']")); + setting.Attributes["value"].InnerText = value; + doc.Save(String.Concat(vDir, "web.config")); + ConfigurationManager.RefreshSection("appSettings"); + } + + /// + /// Gets the full path to root. + /// + /// The fullpath to root. + public static string FullpathToRoot + { + get { return HttpRuntime.AppDomainAppPath; } + } + + /// + /// Gets a value indicating whether umbraco is running in [debug mode]. + /// + /// true if [debug mode]; otherwise, false. + public static bool DebugMode + { + get + { + try + { + return bool.Parse(ConfigurationManager.AppSettings["umbracoDebugMode"]); + } + catch + { + return false; + } + } + } + + /// + /// Gets a value indicating whether the current version of umbraco is configured. + /// + /// true if configured; otherwise, false. + public static bool Configured + { + get + { + try + { + string configStatus = ConfigurationStatus; + string currentVersion = CurrentVersion; + + + if (currentVersion != configStatus) + { + //Log.Add(LogTypes.Debug, User.GetUser(0), -1, + // "CurrentVersion different from configStatus: '" + currentVersion + "','" + configStatus + + // "'"); + } + + + return (configStatus == currentVersion); + } + catch + { + return false; + } + } + } + + /// + /// Gets the time out in minutes. + /// + /// The time out in minutes. + public static int TimeOutInMinutes + { + get + { + try + { + return int.Parse(ConfigurationManager.AppSettings["umbracoTimeOutInMinutes"]); + } + catch + { + return 20; + } + } + } + + /// + /// Gets a value indicating whether umbraco uses directory urls. + /// + /// true if umbraco uses directory urls; otherwise, false. + public static bool UseDirectoryUrls + { + get + { + try + { + return bool.Parse(ConfigurationManager.AppSettings["umbracoUseDirectoryUrls"]); + } + catch + { + return false; + } + } + } + + /// + /// Returns a string value to determine if umbraco should skip version-checking. + /// + /// The version check period in days (0 = never). + public static int VersionCheckPeriod + { + get + { + int versionCheckPeriod = 7; + if (HttpContext != null) + { + if (int.TryParse(ConfigurationManager.AppSettings["umbracoVersionCheckPeriod"], out versionCheckPeriod)) + return versionCheckPeriod; + + } + return versionCheckPeriod; + } + } + + /// + /// Gets the URL forbitten characters. + /// + /// The URL forbitten characters. + public static string UrlForbittenCharacters + { + get + { + if (HttpContext != null) + return ConfigurationManager.AppSettings["umbracoUrlForbittenCharacters"]; + return ""; + } + } + + /// + /// Gets the URL space character. + /// + /// The URL space character. + public static string UrlSpaceCharacter + { + get + { + if (HttpContext != null) + return ConfigurationManager.AppSettings["umbracoUrlSpaceCharacter"]; + return ""; + } + } + + /// + /// Gets the SMTP server IP-address or hostname. + /// + /// The SMTP server. + public static string SmtpServer + { + get + { + try + { + var mailSettings = ConfigurationManager.GetSection("system.net/mailSettings") as System.Net.Configuration.MailSettingsSectionGroup; + + if (mailSettings != null) + return mailSettings.Smtp.Network.Host; + else + return ConfigurationManager.AppSettings["umbracoSmtpServer"]; + } + catch + { + return ""; + } + } + } + + /// + /// Returns a string value to determine if umbraco should disbable xslt extensions + /// + /// "true" if version xslt extensions are disabled, otherwise, "false" + public static string DisableXsltExtensions + { + get + { + if (HttpContext != null) + return ConfigurationManager.AppSettings["umbracoDisableXsltExtensions"]; + return ""; + } + } + + /// + /// Returns a string value to determine if umbraco should use Xhtml editing mode in the wysiwyg editor + /// + /// "true" if Xhtml mode is enable, otherwise, "false" + public static string EditXhtmlMode + { + get + { + if (HttpContext != null) + return ConfigurationManager.AppSettings["umbracoEditXhtmlMode"]; + return ""; + } + } + + /// + /// Gets the default UI language. + /// + /// The default UI language. + public static string DefaultUILanguage + { + get + { + if (HttpContext != null) + return ConfigurationManager.AppSettings["umbracoDefaultUILanguage"]; + return ""; + } + } + + /// + /// Gets the profile URL. + /// + /// The profile URL. + public static string ProfileUrl + { + get + { + if (HttpContext != null) + return ConfigurationManager.AppSettings["umbracoProfileUrl"]; + return ""; + } + } + + /// + /// Gets a value indicating whether umbraco should hide top level nodes from generated urls. + /// + /// + /// true if umbraco hides top level nodes from urls; otherwise, false. + /// + public static bool HideTopLevelNodeFromPath + { + get + { + if (HttpContext != null) + return bool.Parse(ConfigurationManager.AppSettings["umbracoHideTopLevelNodeFromPath"]); + return false; + } + } + + /// + /// Gets the current version. + /// + /// The current version. + public static string CurrentVersion + { + get + { + // change this to be hardcoded in the binary + return CurrentUmbracoVersion; + } + } + + /// + /// Gets the major version number. + /// + /// The major version number. + public static int VersionMajor + { + get + { + string[] version = CurrentVersion.Split(".".ToCharArray()); + return int.Parse(version[0]); + } + } + + /// + /// Gets the minor version number. + /// + /// The minor version number. + public static int VersionMinor + { + get + { + string[] version = CurrentVersion.Split(".".ToCharArray()); + return int.Parse(version[1]); + } + } + + /// + /// Gets the patch version number. + /// + /// The patch version number. + public static int VersionPatch + { + get + { + string[] version = CurrentVersion.Split(".".ToCharArray()); + return int.Parse(version[2]); + } + } + + /// + /// Gets the version comment (like beta or RC). + /// + /// The version comment. + public static string VersionComment + { + get + { + string[] version = CurrentVersion.Split(".".ToCharArray()); + if (version.Length > 3) + return version[3]; + else + return ""; + } + } + + + /// + /// Requests the is in umbraco application directory structure. + /// + /// The context. + /// + public static bool RequestIsInUmbracoApplication(HttpContext context) + { + return context.Request.Path.ToLower().IndexOf(IOHelper.ResolveUrl(SystemDirectories.Umbraco).ToLower()) > -1; + } + + public static bool RequestIsLiveEditRedirector(HttpContext context) + { + return context.Request.Path.ToLower().IndexOf(SystemDirectories.Umbraco.ToLower() + "/liveediting.aspx") > -1; + } + + /// + /// Gets a value indicating whether umbraco should force a secure (https) connection to the backoffice. + /// + /// true if [use SSL]; otherwise, false. + public static bool UseSSL + { + get + { + try + { + return bool.Parse(ConfigurationManager.AppSettings["umbracoUseSSL"]); + } + catch + { + return false; + } + } + } + + /// + /// Gets the umbraco license. + /// + /// The license. + public static string License + { + get + { + string license = + "the open source license MIT. The umbraco UI is freeware licensed under the umbraco license."; + if (HttpContext != null) + { + var versionDoc = new XmlDocument(); + var versionReader = new XmlTextReader(IOHelper.MapPath(SystemDirectories.Umbraco + "/version.xml")); + versionDoc.Load(versionReader); + versionReader.Close(); + + // check for license + try + { + string licenseUrl = + versionDoc.SelectSingleNode("/version/licensing/licenseUrl").FirstChild.Value; + string licenseValidation = + versionDoc.SelectSingleNode("/version/licensing/licenseValidation").FirstChild.Value; + string licensedTo = + versionDoc.SelectSingleNode("/version/licensing/licensedTo").FirstChild.Value; + + if (licensedTo != "" && licenseUrl != "") + { + license = "umbraco Commercial License
Registered to:
" + + licensedTo.Replace("\n", "
") + "
For use with domain:
" + + licenseUrl; + } + } + catch + { + } + } + return license; + } + } + + + /// + /// Developer method to test if configuration settings are loaded properly. + /// + /// true if succesfull; otherwise, false. + internal static bool Test + { + get + { + if (HttpContext != null) + { + HttpContext.Response.Write("ContentXML :" + ContentXml + "\n"); + HttpContext.Response.Write("DbDSN :" + DbDsn + "\n"); + HttpContext.Response.Write("DebugMode :" + DebugMode + "\n"); + HttpContext.Response.Write("DefaultUILanguage :" + DefaultUILanguage + "\n"); + HttpContext.Response.Write("VersionCheckPeriod :" + VersionCheckPeriod + "\n"); + HttpContext.Response.Write("DisableXsltExtensions :" + DisableXsltExtensions + "\n"); + HttpContext.Response.Write("EditXhtmlMode :" + EditXhtmlMode + "\n"); + HttpContext.Response.Write("HideTopLevelNodeFromPath :" + HideTopLevelNodeFromPath + "\n"); + HttpContext.Response.Write("Path :" + Path + "\n"); + HttpContext.Response.Write("ProfileUrl :" + ProfileUrl + "\n"); + HttpContext.Response.Write("ReservedPaths :" + ReservedPaths + "\n"); + HttpContext.Response.Write("ReservedUrls :" + ReservedUrls + "\n"); + HttpContext.Response.Write("StorageDirectory :" + StorageDirectory + "\n"); + HttpContext.Response.Write("TimeOutInMinutes :" + TimeOutInMinutes + "\n"); + HttpContext.Response.Write("UrlForbittenCharacters :" + UrlForbittenCharacters + "\n"); + HttpContext.Response.Write("UrlSpaceCharacter :" + UrlSpaceCharacter + "\n"); + HttpContext.Response.Write("UseDirectoryUrls :" + UseDirectoryUrls + "\n"); + return true; + } + return false; + } + } + + + /// + /// Determines whether the specified URL is reserved or is inside a reserved path. + /// + /// The URL to check. + /// + /// true if the specified URL is reserved; otherwise, false. + /// + public static bool IsReservedPathOrUrl(string url) + { + // check if GlobalSettings.ReservedPaths and GlobalSettings.ReservedUrls are unchanged + if (!object.ReferenceEquals(_reservedPathsCache, GlobalSettings.ReservedPaths) + || !object.ReferenceEquals(_reservedUrlsCache, GlobalSettings.ReservedUrls)) + { + // store references to strings to determine changes + _reservedPathsCache = GlobalSettings.ReservedPaths; + _reservedUrlsCache = GlobalSettings.ReservedUrls; + + string _root = SystemDirectories.Root.Trim().ToLower(); + + // add URLs and paths to a new list + StartsWithContainer _newReservedList = new StartsWithContainer(); + foreach (string reservedUrl in _reservedUrlsCache.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries)) + { + //resolves the url to support tilde chars + string reservedUrlTrimmed = IOHelper.ResolveUrl(reservedUrl).Trim().ToLower(); + if (reservedUrlTrimmed.Length > 0) + _newReservedList.Add(reservedUrlTrimmed); + } + + foreach (string reservedPath in _reservedPathsCache.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries)) + { + bool trimEnd = !reservedPath.EndsWith("/"); + //resolves the url to support tilde chars + string reservedPathTrimmed = IOHelper.ResolveUrl(reservedPath).Trim().ToLower(); + + if (reservedPathTrimmed.Length > 0) + _newReservedList.Add(reservedPathTrimmed + (reservedPathTrimmed.EndsWith("/") ? "" : "/")); + } + + // use the new list from now on + _reservedList = _newReservedList; + } + + string res = ""; + foreach (string st in _reservedList._list.Keys) + res += st + ","; + + Debug.Write("reserverd urls: '" + res + "'"); + + // return true if url starts with an element of the reserved list + return _reservedList.StartsWith(url.ToLower()); + } + + /// + /// Structure that checks in logarithmic time + /// if a given string starts with one of the added keys. + /// + private class StartsWithContainer + { + /// Internal sorted list of keys. + public SortedList _list + = new SortedList(StartsWithComparator.Instance); + + /// + /// Adds the specified new key. + /// + /// The new key. + public void Add(string newKey) + { + // if the list already contains an element that begins with newKey, return + if (String.IsNullOrEmpty(newKey) || StartsWith(newKey)) + return; + + // create a new collection, so the old one can still be accessed + SortedList newList + = new SortedList(_list.Count + 1, StartsWithComparator.Instance); + + // add only keys that don't already start with newKey, others are unnecessary + foreach (string key in _list.Keys) + if (!key.StartsWith(newKey)) + newList.Add(key, null); + // add the new key + newList.Add(newKey, null); + + // update the list (thread safe, _list was never in incomplete state) + _list = newList; + } + + /// + /// Checks if the given string starts with any of the added keys. + /// + /// The target. + /// true if a key is found that matches the start of target + /// + /// Runs in O(s*log(n)), with n the number of keys and s the length of target. + /// + public bool StartsWith(string target) + { + return _list.ContainsKey(target); + } + + /// Comparator that tests if a string starts with another. + /// Not a real comparator, since it is not reflexive. (x==y does not imply y==x) + private sealed class StartsWithComparator : IComparer + { + /// Default string comparer. + private readonly static Comparer _stringComparer = Comparer.Default; + + /// Gets an instance of the StartsWithComparator. + public static readonly StartsWithComparator Instance = new StartsWithComparator(); + + /// + /// Tests if whole begins with all characters of part. + /// + /// The part. + /// The whole. + /// + /// Returns 0 if whole starts with part, otherwise performs standard string comparison. + /// + public int Compare(string part, string whole) + { + // let the default string comparer deal with null or when part is not smaller then whole + if (part == null || whole == null) + return _stringComparer.Compare(part, whole); + + //trim the end '/' of each + part = part.TrimEnd('/'); + whole = whole.TrimEnd('/'); + if (part.Length >= whole.Length) + return _stringComparer.Compare(part, whole); + + // loop through all characters that part and whole have in common + int pos = 0; + bool match; + do + { + match = (part[pos] == whole[pos]); + } while (match && ++pos < part.Length); + + // return result of last comparison + return match ? 0 : (part[pos] < whole[pos] ? -1 : 1); + } + } + } + + } + + + + +} diff --git a/src/Umbraco.Core/Configuration/UmbracoSettings.cs b/src/Umbraco.Core/Configuration/UmbracoSettings.cs new file mode 100644 index 0000000000..268b289e30 --- /dev/null +++ b/src/Umbraco.Core/Configuration/UmbracoSettings.cs @@ -0,0 +1,1303 @@ +using System; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Web; +using System.Web.Caching; +using System.Xml; + +using System.Collections.Generic; + + +namespace Umbraco.Core.Configuration +{ + //NOTE: Do not expose this class ever until we cleanup all configuration including removal of static classes, etc... + // we have this two tasks logged: + // http://issues.umbraco.org/issue/U4-58 + // http://issues.umbraco.org/issue/U4-115 + + //TODO: Re-enable logging !!!! + + /// + /// The UmbracoSettings Class contains general settings information for the entire Umbraco instance based on information from the /config/umbracoSettings.config file + /// + internal class UmbracoSettings + { + internal const string TempFriendlyXmlChildContainerNodename = ""; // "children"; + + /// + /// Gets the umbraco settings document. + /// + /// The _umbraco settings. + internal static XmlDocument UmbracoSettingsXmlDoc + { + get + { + var us = (XmlDocument)HttpRuntime.Cache["umbracoSettingsFile"] ?? EnsureSettingsDocument(); + return us; + } + } + + private static string _path; + + /// + /// Gets/sets the settings file path, the setter can be used in unit tests + /// + internal static string SettingsFilePath + { + get { return _path ?? (_path = GlobalSettings.FullpathToRoot + Path.DirectorySeparatorChar + "config" + Path.DirectorySeparatorChar); } + set { _path = value; } + } + + internal const string Filename = "umbracoSettings.config"; + + internal static XmlDocument EnsureSettingsDocument() + { + var settingsFile = HttpRuntime.Cache["umbracoSettingsFile"]; + + // Check for language file in cache + if (settingsFile == null) + { + var temp = new XmlDocument(); + var settingsReader = new XmlTextReader(SettingsFilePath + Filename); + try + { + temp.Load(settingsReader); + HttpRuntime.Cache.Insert("umbracoSettingsFile", temp, + new CacheDependency(SettingsFilePath + Filename)); + } + catch (XmlException e) + { + throw new XmlException("Your umbracoSettings.config file fails to pass as valid XML. Refer to the InnerException for more information", e); + } + catch (Exception e) + { + Trace.TraceError("Error reading umbracoSettings file: " + e.ToString() + ". ERROR: " + e.Message); + } + settingsReader.Close(); + return temp; + } + else + return (XmlDocument)settingsFile; + } + + internal static void Save() + { + UmbracoSettingsXmlDoc.Save(SettingsFilePath + Filename); + } + + + /// + /// Selects a xml node in the umbraco settings config file. + /// + /// The xpath query to the specific node. + /// If found, it returns the specific configuration xml node. + public static XmlNode GetKeyAsNode(string key) + { + if (key == null) + throw new ArgumentException("Key cannot be null"); + EnsureSettingsDocument(); + if (UmbracoSettingsXmlDoc == null || UmbracoSettingsXmlDoc.DocumentElement == null) + return null; + return UmbracoSettingsXmlDoc.DocumentElement.SelectSingleNode(key); + } + + /// + /// Gets the value of configuration xml node with the specified key. + /// + /// The key. + /// + public static string GetKey(string key) + { + EnsureSettingsDocument(); + + var node = UmbracoSettingsXmlDoc.DocumentElement.SelectSingleNode(key); + if (node == null || node.FirstChild == null || node.FirstChild.Value == null) + return string.Empty; + return node.FirstChild.Value; + } + + /// + /// Gets a value indicating whether the media library will create new directories in the /media directory. + /// + /// + /// true if new directories are allowed otherwise, false. + /// + public static bool UploadAllowDirectories + { + get { return bool.Parse(GetKey("/settings/content/UploadAllowDirectories")); } + } + + /// + /// THIS IS TEMPORARY until we fix up settings all together, this setting is actually not 'settable' but is + /// here for future purposes since we check for thsi settings in the module. + /// + internal static bool EnableBaseRestHandler + { + get { return true; } + } + + /// + /// THIS IS TEMPORARY until we fix up settings all together, this setting is actually not 'settable' but is + /// here for future purposes since we check for thsi settings in the module. + /// + internal static string BootSplashPage + { + get { return "~/default.aspx"; } + } + + /// + /// Gets a value indicating whether logging is enabled in umbracoSettings.config (/settings/logging/enableLogging). + /// + /// true if logging is enabled; otherwise, false. + public static bool EnableLogging + { + get + { + // We return true if no enable logging element is present in + // umbracoSettings (to enable default behaviour when upgrading) + var enableLogging = GetKey("/settings/logging/enableLogging"); + return String.IsNullOrEmpty(enableLogging) || bool.Parse(enableLogging); + } + } + + /// + /// Gets a value indicating whether logging happens async. + /// + /// true if async logging is enabled; otherwise, false. + public static bool EnableAsyncLogging + { + get + { + string value = GetKey("/settings/logging/enableAsyncLogging"); + bool result; + if (!string.IsNullOrEmpty(value) && bool.TryParse(value, out result)) + return result; + return false; + } + } + + /// + /// Gets the assembly of an external logger that can be used to store log items in 3rd party systems + /// + public static string ExternalLoggerAssembly + { + get + { + var value = GetKeyAsNode("/settings/logging/externalLogger"); + return value != null ? value.Attributes["assembly"].Value : ""; + } + } + /// + /// Gets the type of an external logger that can be used to store log items in 3rd party systems + /// + public static string ExternalLoggerType + { + get + { + var value = GetKeyAsNode("/settings/logging/externalLogger"); + return value != null ? value.Attributes["type"].Value : ""; + } + } + + /// + /// Long Audit Trail to external log too + /// + public static bool ExternalLoggerLogAuditTrail + { + get + { + var value = GetKeyAsNode("/settings/logging/externalLogger"); + if (value != null) + { + var logAuditTrail = value.Attributes["logAuditTrail"].Value; + bool result; + if (!string.IsNullOrEmpty(logAuditTrail) && bool.TryParse(logAuditTrail, out result)) + return result; + } + return false; + } + } + + /// + /// Keep user alive as long as they have their browser open? Default is true + /// + public static bool KeepUserLoggedIn + { + get + { + var value = GetKey("/settings/security/keepUserLoggedIn"); + bool result; + if (!string.IsNullOrEmpty(value) && bool.TryParse(value, out result)) + return result; + return true; + } + } + + /// + /// Show disabled users in the tree in the Users section in the backoffice + /// + public static bool HideDisabledUsersInBackoffice + { + get + { + string value = GetKey("/settings/security/hideDisabledUsersInBackoffice"); + bool result; + if (!string.IsNullOrEmpty(value) && bool.TryParse(value, out result)) + return result; + return false; + } + } + + /// + /// Gets a value indicating whether the logs will be auto cleaned + /// + /// true if logs are to be automatically cleaned; otherwise, false + public static bool AutoCleanLogs + { + get + { + string value = GetKey("/settings/logging/autoCleanLogs"); + bool result; + if (!string.IsNullOrEmpty(value) && bool.TryParse(value, out result)) + return result; + return false; + } + } + + /// + /// Gets the value indicating the log cleaning frequency (in miliseconds) + /// + public static int CleaningMiliseconds + { + get + { + string value = GetKey("/settings/logging/cleaningMiliseconds"); + int result; + if (!string.IsNullOrEmpty(value) && int.TryParse(value, out result)) + return result; + return -1; + } + } + + public static int MaxLogAge + { + get + { + string value = GetKey("/settings/logging/maxLogAge"); + int result; + if (!string.IsNullOrEmpty(value) && int.TryParse(value, out result)) + return result; + return -1; + } + } + + /// + /// Gets the disabled log types. + /// + /// The disabled log types. + public static XmlNode DisabledLogTypes + { + get { return GetKeyAsNode("/settings/logging/disabledLogTypes"); } + } + + /// + /// Gets the package server url. + /// + /// The package server url. + public static string PackageServer + { + get { return "packages.umbraco.org"; } + } + + /// + /// Gets a value indicating whether umbraco will use domain prefixes. + /// + /// true if umbraco will use domain prefixes; otherwise, false. + public static bool UseDomainPrefixes + { + get + { + try + { + bool result; + if (bool.TryParse(GetKey("/settings/requestHandler/useDomainPrefixes"), out result)) + return result; + return false; + } + catch + { + return false; + } + } + } + + /// + /// This will add a trailing slash (/) to urls when in directory url mode + /// NOTICE: This will always return false if Directory Urls in not active + /// + public static bool AddTrailingSlash + { + get + { + try + { + if (GlobalSettings.UseDirectoryUrls) + { + bool result; + if (bool.TryParse(GetKey("/settings/requestHandler/addTrailingSlash"), out result)) + return result; + return false; + } + else + { + return false; + } + } + catch + { + return false; + } + } + } + + /// + /// Gets a value indicating whether umbraco will use ASP.NET MasterPages for rendering instead of its propriatary templating system. + /// + /// true if umbraco will use ASP.NET MasterPages; otherwise, false. + public static bool UseAspNetMasterPages + { + get + { + try + { + bool result; + if (bool.TryParse(GetKey("/settings/templates/useAspNetMasterPages"), out result)) + return result; + return false; + } + catch + { + return false; + } + } + } + + + /// + /// Gets a value indicating whether umbraco will attempt to load any skins to override default template files + /// + /// true if umbraco will override templates with skins if present and configured false. + public static bool EnableTemplateFolders + { + get + { + try + { + bool result; + if (bool.TryParse(GetKey("/settings/templates/enableTemplateFolders"), out result)) + return result; + return false; + } + catch + { + return false; + } + } + } + + //TODO: I"m not sure why we need this, need to ask Gareth what the deal is, pretty sure we can remove it or change it, seems like + // massive overkill. + + /// + /// razor DynamicNode typecasting detects XML and returns DynamicXml - Root elements that won't convert to DynamicXml + /// + public static IEnumerable NotDynamicXmlDocumentElements + { + get + { + try + { + List items = new List(); + XmlNode root = GetKeyAsNode("/settings/scripting/razor/notDynamicXmlDocumentElements"); + foreach (XmlNode element in root.SelectNodes(".//element")) + { + items.Add(element.InnerText); + } + return items; + } + catch + { + return new List() { "p", "div" }; + } + } + } + + public static IEnumerable RazorDataTypeModelStaticMapping + { + get + { + if (HttpContext.Current != null && HttpContext.Current.Cache != null && HttpContext.Current.Cache["settings.scripting.razor.dataTypeModelStaticMappings"] != null) + { + return HttpContext.Current.Cache["settings.scripting.razor.dataTypeModelStaticMappings"] as List; + } + /* + + DigibizAdvancedMediaPicker.RazorModel.ModelBinder + DigibizAdvancedMediaPicker.RazorModel.ModelBinder + + */ + List items = new List(); + XmlNode root = GetKeyAsNode("/settings/scripting/razor/dataTypeModelStaticMappings"); + if (root != null) + { + foreach (XmlNode element in root.SelectNodes(".//mapping")) + { + string propertyTypeAlias = null, nodeTypeAlias = null; + Guid? dataTypeGuid = null; + if (!string.IsNullOrEmpty(element.InnerText)) + { + if (element.Attributes["dataTypeGuid"] != null) + { + dataTypeGuid = (Guid?)new Guid(element.Attributes["dataTypeGuid"].Value); + } + if (element.Attributes["propertyTypeAlias"] != null && !string.IsNullOrEmpty(element.Attributes["propertyTypeAlias"].Value)) + { + propertyTypeAlias = element.Attributes["propertyTypeAlias"].Value; + } + if (element.Attributes["nodeTypeAlias"] != null && !string.IsNullOrEmpty(element.Attributes["nodeTypeAlias"].Value)) + { + nodeTypeAlias = element.Attributes["nodeTypeAlias"].Value; + } + items.Add(new RazorDataTypeModelStaticMappingItem() + { + DataTypeGuid = dataTypeGuid, + PropertyTypeAlias = propertyTypeAlias, + NodeTypeAlias = nodeTypeAlias, + TypeName = element.InnerText, + Raw = element.OuterXml + }); + } + } + } + if (HttpContext.Current != null && HttpContext.Current.Cache != null) + { + HttpContext.Current.Cache.Add("settings.scripting.razor.dataTypeModelStaticMappings", items, null, Cache.NoAbsoluteExpiration, new TimeSpan(0, 20, 0), CacheItemPriority.AboveNormal, null); + } + return items; + + } + } + + /// + /// Gets a value indicating whether umbraco will clone XML cache on publish. + /// + /// + /// true if umbraco will clone XML cache on publish; otherwise, false. + /// + public static bool CloneXmlCacheOnPublish + { + get + { + try + { + bool result; + if (bool.TryParse(GetKey("/settings/content/cloneXmlContent"), out result)) + return result; + return false; + } + catch + { + return false; + } + } + } + + /// + /// Gets a value indicating whether rich text editor content should be parsed by tidy. + /// + /// true if content is parsed; otherwise, false. + public static bool TidyEditorContent + { + get { return bool.Parse(GetKey("/settings/content/TidyEditorContent")); } + } + + /// + /// Gets the encoding type for the tidyied content. + /// + /// The encoding type as string. + public static string TidyCharEncoding + { + get + { + string encoding = GetKey("/settings/content/TidyCharEncoding"); + if (String.IsNullOrEmpty(encoding)) + { + encoding = "UTF8"; + } + return encoding; + } + } + + /// + /// Gets the property context help option, this can either be 'text', 'icon' or 'none' + /// + /// The property context help option. + public static string PropertyContextHelpOption + { + get { return GetKey("/settings/content/PropertyContextHelpOption").ToLower(); } + } + + public static string DefaultBackofficeProvider + { + get + { + string defaultProvider = GetKey("/settings/providers/users/DefaultBackofficeProvider"); + if (String.IsNullOrEmpty(defaultProvider)) + defaultProvider = "UsersMembershipProvider"; + + return defaultProvider; + } + } + + /// + /// Whether to force safe aliases (no spaces, no special characters) at businesslogic level on contenttypes and propertytypes + /// + public static bool ForceSafeAliases + { + get + { + string forceSafeAlias = GetKey("/settings/content/ForceSafeAliases"); + if (String.IsNullOrEmpty(forceSafeAlias)) + return true; + else + { + try + { + return bool.Parse(forceSafeAlias); + } + catch + { + return true; + } + } + + } + } + + + /// + /// Gets the allowed image file types. + /// + /// The allowed image file types. + public static string ImageFileTypes + { + get { return GetKey("/settings/content/imaging/imageFileTypes").ToLowerInvariant(); } + } + + /// + /// Gets the allowed script file types. + /// + /// The allowed script file types. + public static string ScriptFileTypes + { + get { return GetKey("/settings/content/scripteditor/scriptFileTypes"); } + } + + /// + /// Gets the duration in seconds to cache queries to umbraco library member and media methods + /// Default is 1800 seconds (30 minutes) + /// + public static int UmbracoLibraryCacheDuration + { + get + { + string libraryCacheDuration = GetKey("/settings/content/UmbracoLibraryCacheDuration"); + if (String.IsNullOrEmpty(libraryCacheDuration)) + return 1800; + else + { + try + { + return int.Parse(libraryCacheDuration); + } + catch + { + return 1800; + } + } + + } + } + + /// + /// Gets the path to the scripts folder used by the script editor. + /// + /// The script folder path. + public static string ScriptFolderPath + { + get { return GetKey("/settings/content/scripteditor/scriptFolderPath"); } + } + + /// + /// Enabled or disable the script/code editor + /// + public static bool ScriptDisableEditor + { + get + { + string _tempValue = GetKey("/settings/content/scripteditor/scriptDisableEditor"); + if (_tempValue != String.Empty) + return bool.Parse(_tempValue); + else + return false; + } + } + + /// + /// Gets the graphic headline format - png or gif + /// + /// The graphic headline format. + public static string GraphicHeadlineFormat + { + get { return GetKey("/settings/content/graphicHeadlineFormat"); } + } + + /// + /// Gets a value indicating whether umbraco will ensure unique node naming. + /// This will ensure that nodes cannot have the same url, but will add extra characters to a url. + /// ex: existingnodename.aspx would become existingnodename(1).aspx if a node with the same name is found + /// + /// true if umbraco ensures unique node naming; otherwise, false. + public static bool EnsureUniqueNaming + { + get + { + try + { + return bool.Parse(GetKey("/settings/content/ensureUniqueNaming")); + } + catch + { + return false; + } + } + } + + /// + /// Gets the notification email sender. + /// + /// The notification email sender. + public static string NotificationEmailSender + { + get { return GetKey("/settings/content/notifications/email"); } + } + + /// + /// Gets a value indicating whether notification-emails are HTML. + /// + /// + /// true if html notification-emails are disabled; otherwise, false. + /// + public static bool NotificationDisableHtmlEmail + { + get + { + var tempValue = GetKey("/settings/content/notifications/disableHtmlEmail"); + return tempValue != String.Empty && bool.Parse(tempValue); + } + } + + /// + /// Gets the allowed attributes on images. + /// + /// The allowed attributes on images. + public static string ImageAllowedAttributes + { + get { return GetKey("/settings/content/imaging/allowedAttributes"); } + } + + public static XmlNode ImageAutoFillImageProperties + { + get { return GetKeyAsNode("/settings/content/imaging/autoFillImageProperties"); } + } + + /// + /// Gets the scheduled tasks as XML + /// + /// The scheduled tasks. + public static XmlNode ScheduledTasks + { + get { return GetKeyAsNode("/settings/scheduledTasks"); } + } + + /// + /// Gets a list of characters that will be replaced when generating urls + /// + /// The URL replacement characters. + public static XmlNode UrlReplaceCharacters + { + get { return GetKeyAsNode("/settings/requestHandler/urlReplacing"); } + } + + /// + /// Whether to replace double dashes from url (ie my--story----from--dash.aspx caused by multiple url replacement chars + /// + public static bool RemoveDoubleDashesFromUrlReplacing + { + get + { + try + { + return bool.Parse(UrlReplaceCharacters.Attributes.GetNamedItem("removeDoubleDashes").Value); + } + catch + { + return false; + } + } + } + + /// + /// Gets a value indicating whether umbraco will use distributed calls. + /// This enables umbraco to share cache and content across multiple servers. + /// Used for load-balancing high-traffic sites. + /// + /// true if umbraco uses distributed calls; otherwise, false. + public static bool UseDistributedCalls + { + get + { + try + { + return bool.Parse(GetKeyAsNode("/settings/distributedCall").Attributes.GetNamedItem("enable").Value); + } + catch + { + return false; + } + } + } + + + /// + /// Gets the ID of the user with access rights to perform the distributed calls. + /// + /// The distributed call user. + public static int DistributedCallUser + { + get + { + try + { + return int.Parse(GetKey("/settings/distributedCall/user")); + } + catch + { + return -1; + } + } + } + + /// + /// Gets the html injected into a (x)html page if Umbraco is running in preview mode + /// + public static string PreviewBadge + { + get + { + try + { + return GetKey("/settings/content/PreviewBadge"); + } + catch + { + return "In Preview Mode - click to end"; + } + } + } + + /// + /// Gets IP or hostnames of the distribution servers. + /// These servers will receive a call everytime content is created/deleted/removed + /// and update their content cache accordingly, ensuring a consistent cache on all servers + /// + /// The distribution servers. + public static XmlNode DistributionServers + { + get + { + try + { + return GetKeyAsNode("/settings/distributedCall/servers"); + } + catch + { + return null; + } + } + } + + /// + /// Gets HelpPage configurations. + /// A help page configuration specify language, user type, application, application url and + /// the target help page url. + /// + public static XmlNode HelpPages + { + get + { + try + { + return GetKeyAsNode("/settings/help"); + } + catch + { + return null; + } + } + } + + /// + /// Gets all repositories registered, and returns them as XmlNodes, containing name, alias and webservice url. + /// These repositories are used by the build-in package installer and uninstaller to install new packages and check for updates. + /// All repositories should have a unique alias. + /// All packages installed from a repository gets the repository alias included in the install information + /// + /// The repository servers. + public static XmlNode Repositories + { + get + { + try + { + return GetKeyAsNode("/settings/repositories"); + } + catch + { + return null; + } + } + } + + /// + /// Gets a value indicating whether umbraco will use the viewstate mover module. + /// The viewstate mover will move all asp.net viewstate information to the bottom of the aspx page + /// to ensure that search engines will index text instead of javascript viewstate information. + /// + /// + /// true if umbraco will use the viewstate mover module; otherwise, false. + /// + public static bool UseViewstateMoverModule + { + get + { + try + { + return + bool.Parse( + GetKeyAsNode("/settings/viewstateMoverModule").Attributes.GetNamedItem("enable").Value); + } + catch + { + return false; + } + } + } + + + /// + /// Tells us whether the Xml Content cache is disabled or not + /// Default is enabled + /// + public static bool IsXmlContentCacheDisabled + { + get + { + try + { + bool xmlCacheEnabled; + string value = GetKey("/settings/content/XmlCacheEnabled"); + if (bool.TryParse(value, out xmlCacheEnabled)) + return !xmlCacheEnabled; + // Return default + return false; + } + catch + { + return false; + } + } + } + + /// + /// Check if there's changes to the umbraco.config xml file cache on disk on each request + /// Makes it possible to updates environments by syncing the umbraco.config file across instances + /// Relates to http://umbraco.codeplex.com/workitem/30722 + /// + public static bool XmlContentCheckForDiskChanges + { + get + { + try + { + bool checkForDiskChanges; + string value = GetKey("/settings/content/XmlContentCheckForDiskChanges"); + if (bool.TryParse(value, out checkForDiskChanges)) + return checkForDiskChanges; + // Return default + return false; + } + catch + { + return false; + } + } + } + + /// + /// If this is enabled, all Umbraco objects will generate data in the preview table (cmsPreviewXml). + /// If disabled, only documents will generate data. + /// This feature is useful if anyone would like to see how data looked at a given time + /// + public static bool EnableGlobalPreviewStorage + { + get + { + try + { + bool globalPreviewEnabled = false; + string value = GetKey("/settings/content/GlobalPreviewStorageEnabled"); + if (bool.TryParse(value, out globalPreviewEnabled)) + return !globalPreviewEnabled; + // Return default + return false; + } + catch + { + return false; + } + } + } + + /// + /// Whether to use the new 4.1 schema or the old legacy schema + /// + /// + /// true if yes, use the old node/data model; otherwise, false. + /// + public static bool UseLegacyXmlSchema + { + get + { + try + { + string value = GetKey("/settings/content/UseLegacyXmlSchema"); + bool result; + if (!string.IsNullOrEmpty(value) && bool.TryParse(value, out result)) + return result; + return true; + } + catch (Exception) + { + //default. TODO: When we change this to a real config section we won't have to worry about parse errors + // and should handle defaults with unit tests properly. + return false; + } + } + } + + [Obsolete("This setting is not used anymore, the only file extensions that are supported are .cs and .vb files")] + public static IEnumerable AppCodeFileExtensionsList + { + get + { + return (from XmlNode x in AppCodeFileExtensions + where !String.IsNullOrEmpty(x.InnerText) + select x.InnerText).ToList(); + } + } + + [Obsolete("This setting is not used anymore, the only file extensions that are supported are .cs and .vb files")] + public static XmlNode AppCodeFileExtensions + { + get + { + XmlNode value = GetKeyAsNode("/settings/developer/appCodeFileExtensions"); + if (value != null) + { + return value; + } + + // default is .cs and .vb + value = UmbracoSettingsXmlDoc.CreateElement("appCodeFileExtensions"); + value.AppendChild(XmlHelper.AddTextNode(UmbracoSettingsXmlDoc, "ext", "cs")); + value.AppendChild(XmlHelper.AddTextNode(UmbracoSettingsXmlDoc, "ext", "vb")); + return value; + } + } + + /// + /// Tells us whether the Xml to always update disk cache, when changes are made to content + /// Default is enabled + /// + public static bool ContinouslyUpdateXmlDiskCache + { + get + { + try + { + bool updateDiskCache; + string value = GetKey("/settings/content/ContinouslyUpdateXmlDiskCache"); + if (bool.TryParse(value, out updateDiskCache)) + return updateDiskCache; + // Return default + return false; + } + catch + { + return true; + } + } + } + + /// + /// Tells us whether to use a splash page while umbraco is initializing content. + /// If not, requests are queued while umbraco loads content. For very large sites (+10k nodes) it might be usefull to + /// have a splash page + /// Default is disabled + /// + public static bool EnableSplashWhileLoading + { + get + { + try + { + bool updateDiskCache; + string value = GetKey("/settings/content/EnableSplashWhileLoading"); + if (bool.TryParse(value, out updateDiskCache)) + return updateDiskCache; + // Return default + return false; + } + catch + { + return false; + } + } + } + + private static bool? _resolveUrlsFromTextString; + public static bool ResolveUrlsFromTextString + { + get + { + if (_resolveUrlsFromTextString == null) + { + try + { + bool enableDictionaryFallBack; + var value = GetKey("/settings/content/ResolveUrlsFromTextString"); + if (value != null) + if (bool.TryParse(value, out enableDictionaryFallBack)) + _resolveUrlsFromTextString = enableDictionaryFallBack; + } + catch (Exception ex) + { + Trace.WriteLine("Could not load /settings/content/ResolveUrlsFromTextString from umbracosettings.config:\r\n {0}", + ex.Message); + + // set url resolving to true (default (legacy) behavior) to ensure we don't keep writing to trace + _resolveUrlsFromTextString = true; + } + } + return _resolveUrlsFromTextString == true; + } + } + + /// + /// Configuration regarding webservices + /// + /// Put in seperate class for more logik/seperation + internal class WebServices + { + /// + /// Gets a value indicating whether this is enabled. + /// + /// true if enabled; otherwise, false. + public static bool Enabled + { + get + { + try + { + return + bool.Parse(GetKeyAsNode("/settings/webservices").Attributes.GetNamedItem("enabled").Value); + } + catch + { + return false; + } + } + } + + #region "Webservice configuration" + + /// + /// Gets the document service users who have access to use the document web service + /// + /// The document service users. + public static string[] DocumentServiceUsers + { + get + { + try + { + return GetKey("/settings/webservices/documentServiceUsers").Split(','); + } + catch + { + return new string[0]; + } + } + } + + /// + /// Gets the file service users who have access to use the file web service + /// + /// The file service users. + public static string[] FileServiceUsers + { + get + { + try + { + return GetKey("/settings/webservices/fileServiceUsers").Split(','); + } + catch + { + return new string[0]; + } + } + } + + + /// + /// Gets the folders used by the file web service + /// + /// The file service folders. + public static string[] FileServiceFolders + { + get + { + try + { + return GetKey("/settings/webservices/fileServiceFolders").Split(','); + } + catch + { + return new string[0]; + } + } + } + + /// + /// Gets the member service users who have access to use the member web service + /// + /// The member service users. + public static string[] MemberServiceUsers + { + get + { + try + { + return GetKey("/settings/webservices/memberServiceUsers").Split(','); + } + catch + { + return new string[0]; + } + } + } + + /// + /// Gets the stylesheet service users who have access to use the stylesheet web service + /// + /// The stylesheet service users. + public static string[] StylesheetServiceUsers + { + get + { + try + { + return GetKey("/settings/webservices/stylesheetServiceUsers").Split(','); + } + catch + { + return new string[0]; + } + } + } + + /// + /// Gets the template service users who have access to use the template web service + /// + /// The template service users. + public static string[] TemplateServiceUsers + { + get + { + try + { + return GetKey("/settings/webservices/templateServiceUsers").Split(','); + } + catch + { + return new string[0]; + } + } + } + + /// + /// Gets the media service users who have access to use the media web service + /// + /// The media service users. + public static string[] MediaServiceUsers + { + get + { + try + { + return GetKey("/settings/webservices/mediaServiceUsers").Split(','); + } + catch + { + return new string[0]; + } + } + } + + + /// + /// Gets the maintenance service users who have access to use the maintance web service + /// + /// The maintenance service users. + public static string[] MaintenanceServiceUsers + { + get + { + try + { + return GetKey("/settings/webservices/maintenanceServiceUsers").Split(','); + } + catch + { + return new string[0]; + } + } + } + + #endregion + } + } +} \ No newline at end of file diff --git a/src/Umbraco.Core/IO/FileSecurityException.cs b/src/Umbraco.Core/IO/FileSecurityException.cs new file mode 100644 index 0000000000..8358b5efd2 --- /dev/null +++ b/src/Umbraco.Core/IO/FileSecurityException.cs @@ -0,0 +1,20 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace Umbraco.Core.IO +{ + public class FileSecurityException : Exception + { + public FileSecurityException() + { + + } + + public FileSecurityException(string message) : base(message) + { + + } + } +} diff --git a/src/Umbraco.Core/IO/IOHelper.cs b/src/Umbraco.Core/IO/IOHelper.cs new file mode 100644 index 0000000000..c0734898d6 --- /dev/null +++ b/src/Umbraco.Core/IO/IOHelper.cs @@ -0,0 +1,206 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using System.Reflection; +using System.Text; +using System.IO; +using System.Configuration; +using System.Web; +using System.Text.RegularExpressions; +using Umbraco.Core.Configuration; + +namespace Umbraco.Core.IO +{ + internal static class IOHelper + { + private static string _rootDir = ""; + // static compiled regex for faster performance + private readonly static Regex ResolveUrlPattern = new Regex("(=[\"\']?)(\\W?\\~(?:.(?![\"\']?\\s+(?:\\S+)=|[>\"\']))+.)[\"\']?", RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace); + + public static char DirSepChar + { + get + { + return Path.DirectorySeparatorChar; + } + } + + //helper to try and match the old path to a new virtual one + public static string FindFile(string virtualPath) + { + string retval = virtualPath; + + if (virtualPath.StartsWith("~")) + retval = virtualPath.Replace("~", SystemDirectories.Root); + + if (virtualPath.StartsWith("/") && !virtualPath.StartsWith(SystemDirectories.Root)) + retval = SystemDirectories.Root + "/" + virtualPath.TrimStart('/'); + + return retval; + } + + //Replaces tildes with the root dir + public static string ResolveUrl(string virtualPath) + { + if (virtualPath.StartsWith("~")) + return virtualPath.Replace("~", SystemDirectories.Root).Replace("//", "/"); + else + return VirtualPathUtility.ToAbsolute(virtualPath, SystemDirectories.Root); + } + + + public static string ResolveUrlsFromTextString(string text) + { + if (UmbracoSettings.ResolveUrlsFromTextString) + { + var sw = new Stopwatch(); + sw.Start(); + Debug.WriteLine("Start: " + sw.ElapsedMilliseconds); + + // find all relative urls (ie. urls that contain ~) + var tags = + ResolveUrlPattern.Matches(text); + Debug.WriteLine("After regex: " + sw.ElapsedMilliseconds); + foreach (Match tag in tags) + { + Debug.WriteLine("-- inside regex: " + sw.ElapsedMilliseconds); + string url = ""; + if (tag.Groups[1].Success) + url = tag.Groups[1].Value; + + // The richtext editor inserts a slash in front of the url. That's why we need this little fix + // if (url.StartsWith("/")) + // text = text.Replace(url, ResolveUrl(url.Substring(1))); + // else + if (!String.IsNullOrEmpty(url)) + { + Debug.WriteLine("---- before resolve: " + sw.ElapsedMilliseconds); + string resolvedUrl = (url.Substring(0, 1) == "/") ? ResolveUrl(url.Substring(1)) : ResolveUrl(url); + Debug.WriteLine("---- after resolve: " + sw.ElapsedMilliseconds); + Debug.WriteLine("---- before replace: " + sw.ElapsedMilliseconds); + text = text.Replace(url, resolvedUrl); + Debug.WriteLine("---- after replace: " + sw.ElapsedMilliseconds); + } + + } + + Debug.WriteLine("total: " + sw.ElapsedMilliseconds); + sw.Stop(); + Debug.WriteLine("Resolve Urls", sw.ElapsedMilliseconds.ToString()); + + } + return text; + } + + public static string MapPath(string path, bool useHttpContext) + { + // Check if the path is already mapped + if (path.Length >= 2 && path[1] == Path.VolumeSeparatorChar) + return path; + + // Check that we even have an HttpContext! otherwise things will fail anyways + // http://umbraco.codeplex.com/workitem/30946 + + if (useHttpContext && HttpContext.Current != null) + { + //string retval; + if (!string.IsNullOrEmpty(path) && (path.StartsWith("~") || path.StartsWith(SystemDirectories.Root))) + return System.Web.Hosting.HostingEnvironment.MapPath(path); + else + return System.Web.Hosting.HostingEnvironment.MapPath("~/" + path.TrimStart('/')); + } + + //var root = (!string.IsNullOrEmpty(System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath)) + // ? System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath.TrimEnd(IOHelper.DirSepChar) + // : getRootDirectorySafe(); + + var root = GetRootDirectorySafe(); + var newPath = path.TrimStart('~', '/').Replace('/', IOHelper.DirSepChar); + var retval = root + IOHelper.DirSepChar.ToString() + newPath; + + return retval; + } + + public static string MapPath(string path) + { + return MapPath(path, true); + } + + //use a tilde character instead of the complete path + public static string ReturnPath(string settingsKey, string standardPath, bool useTilde) + { + string retval = ConfigurationManager.AppSettings[settingsKey]; + + if (string.IsNullOrEmpty(retval)) + retval = standardPath; + + return retval.TrimEnd('/'); + } + + + public static string ReturnPath(string settingsKey, string standardPath) + { + return ReturnPath(settingsKey, standardPath, false); + + } + + + /// + /// Validates if the current filepath matches a directory where the user is allowed to edit a file + /// + /// filepath + /// + /// true if valid, throws a FileSecurityException if not + public static bool ValidateEditPath(string filePath, string validDir) + { + if (!filePath.StartsWith(MapPath(SystemDirectories.Root))) + filePath = MapPath(filePath); + if (!validDir.StartsWith(MapPath(SystemDirectories.Root))) + validDir = MapPath(validDir); + + if (!filePath.StartsWith(validDir)) + throw new FileSecurityException(String.Format("The filepath '{0}' is not within an allowed directory for this type of files", filePath.Replace(MapPath(SystemDirectories.Root), ""))); + + return true; + } + + public static bool ValidateFileExtension(string filePath, List validFileExtensions) + { + if (!filePath.StartsWith(MapPath(SystemDirectories.Root))) + filePath = MapPath(filePath); + var f = new FileInfo(filePath); + + + if (!validFileExtensions.Contains(f.Extension.Substring(1))) + throw new FileSecurityException(String.Format("The extension for the current file '{0}' is not of an allowed type for this editor. This is typically controlled from either the installed MacroEngines or based on configuration in /config/umbracoSettings.config", filePath.Replace(MapPath(SystemDirectories.Root), ""))); + + return true; + } + + + /// + /// Returns the path to the root of the application, by getting the path to where the assembly where this + /// method is included is present, then traversing until it's past the /bin directory. Ie. this makes it work + /// even if the assembly is in a /bin/debug or /bin/release folder + /// + /// + internal static string GetRootDirectorySafe() + { + if (!String.IsNullOrEmpty(_rootDir)) + { + return _rootDir; + } + + var codeBase = Assembly.GetExecutingAssembly().CodeBase; + var uri = new Uri(codeBase); + var path = uri.LocalPath; + var baseDirectory = Path.GetDirectoryName(path); + _rootDir = baseDirectory.Substring(0, baseDirectory.LastIndexOf("bin") - 1); + + return _rootDir; + + } + + } +} diff --git a/src/Umbraco.Core/IO/IMediaFileSystemExtensions.cs b/src/Umbraco.Core/IO/MediaFileSystemExtensions.cs similarity index 90% rename from src/Umbraco.Core/IO/IMediaFileSystemExtensions.cs rename to src/Umbraco.Core/IO/MediaFileSystemExtensions.cs index 5201923dbf..02c031608d 100644 --- a/src/Umbraco.Core/IO/IMediaFileSystemExtensions.cs +++ b/src/Umbraco.Core/IO/MediaFileSystemExtensions.cs @@ -3,11 +3,11 @@ using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; -using umbraco; +using Umbraco.Core.Configuration; namespace Umbraco.Core.IO { - public static class IMediaFileSystemExtensions + public static class MediaFileSystemExtensions { internal static string GetRelativePath(this IMediaFileSystem fs, int propertyId, string fileName) { diff --git a/src/Umbraco.Core/IO/SystemDirectories.cs b/src/Umbraco.Core/IO/SystemDirectories.cs new file mode 100644 index 0000000000..3ee99750d2 --- /dev/null +++ b/src/Umbraco.Core/IO/SystemDirectories.cs @@ -0,0 +1,181 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Configuration; + +using System.Web; +using System.IO; + +namespace Umbraco.Core.IO +{ + //all paths has a starting but no trailing / + internal class SystemDirectories + { + public static string Bin + { + get + { + return IOHelper.ReturnPath("umbracoBinDirectory", "~/bin"); + } + } + + public static string Base + { + get + { + return IOHelper.ReturnPath("umbracoBaseDirectory", "~/base"); + } + } + + public static string Config + { + get + { + return IOHelper.ReturnPath("umbracoConfigDirectory", "~/config"); + } + } + + public static string Css + { + get + { + return IOHelper.ReturnPath("umbracoCssDirectory", "~/css"); + } + } + + public static string Data + { + get + { + return IOHelper.ReturnPath("umbracoStorageDirectory", "~/App_Data"); + } + } + + public static string Install + { + get + { + return IOHelper.ReturnPath("umbracoInstallPath", "~/install"); + } + } + + public static string Masterpages + { + get + { + return IOHelper.ReturnPath("umbracoMasterPagesPath", "~/masterpages"); + } + } + + + public static string Media + { + get + { + return IOHelper.ReturnPath("umbracoMediaPath", "~/media"); + } + } + + [Obsolete("Please use MacroScripts instead!", true)] + public static string Python + { + get + { + return MacroScripts; + } + } + + public static string MacroScripts + { + get + { + // for legacy we test for the python path first, but else we use the new default location + string tempPath = IOHelper.ReturnPath("umbracoPythonPath", "") == String.Empty + ? IOHelper.ReturnPath("umbracoMacroScriptPath", "~/macroScripts") + : IOHelper.ReturnPath("umbracoPythonPath", "~/python"); + return tempPath; + } + } + + public static string Scripts + { + get + { + return IOHelper.ReturnPath("umbracoScriptsPath", "~/scripts"); + } + } + + public static string Umbraco + { + get + { + return IOHelper.ReturnPath("umbracoPath", "~/umbraco"); + } + } + + public static string UmbracoClient + { + get + { + return IOHelper.ReturnPath("umbracoClientPath", "~/umbraco_client"); + } + } + + public static string UserControls + { + get + { + return IOHelper.ReturnPath("umbracoUsercontrolsPath", "~/usercontrols"); + } + } + + public static string WebServices + { + get + { + return IOHelper.ReturnPath("umbracoWebservicesPath", "~/umbraco/webservices"); + } + } + + public static string Xslt + { + get { + return IOHelper.ReturnPath("umbracoXsltPath", "~/xslt"); + } + } + + public static string Packages + { + get + { + //by default the packages folder should exist in the data folder + return IOHelper.ReturnPath("umbracoPackagesPath", Data + IOHelper.DirSepChar + "packages"); + } + } + + public static string Preview + { + get + { + //by default the packages folder should exist in the data folder + return IOHelper.ReturnPath("umbracoPreviewPath", Data + IOHelper.DirSepChar + "preview"); + } + } + + public static string Root + { + get + { + string appPath = HttpRuntime.AppDomainAppVirtualPath ?? string.Empty; + if (appPath == "/") + appPath = string.Empty; + + return appPath; + } + } + } + + + +} diff --git a/src/Umbraco.Core/IO/SystemFiles.cs b/src/Umbraco.Core/IO/SystemFiles.cs new file mode 100644 index 0000000000..59b2debf0a --- /dev/null +++ b/src/Umbraco.Core/IO/SystemFiles.cs @@ -0,0 +1,122 @@ +using System; +using System.Collections.Generic; +using System.Configuration; +using System.IO; +using System.Linq; +using System.Text; +using System.Web; + +namespace Umbraco.Core.IO +{ + internal class SystemFiles + { + + public static string AccessXml + { + get + { + return SystemDirectories.Data + "/access.config"; + } + } + + public static string CreateUiXml + { + get + { + return SystemDirectories.Umbraco + "/config/create/UI.xml"; + } + } + + public static string TinyMceConfig + { + get + { + return SystemDirectories.Config + "/tinyMceConfig.config"; + } + } + + public static string MetablogConfig + { + get + { + return SystemDirectories.Config + "/metablogConfig.config"; + } + } + + public static string DashboardConfig + { + get + { + return SystemDirectories.Config + "/dashboard.config"; + } + } + + public static string XsltextensionsConfig + { + get + { + return SystemDirectories.Config + "/xsltextensions.config"; + } + } + + public static string RestextensionsConfig + { + get + { + return SystemDirectories.Config + "/restextensions.config"; + } + } + + + public static string SkinningXml + { + get + { + return SystemDirectories.Data + "/skinning.config"; + } + } + + public static string NotFoundhandlersConfig + { + get + { + return SystemDirectories.Config + "/404handlers.config"; + } + } + + public static string FeedProxyConfig + { + get + { + return string.Concat(SystemDirectories.Config, "/feedProxy.config"); + } + } + + public static string ContentCacheXml + { + get + { + if (ContentCacheXmlIsEphemeral) + { + return Path.Combine(HttpRuntime.CodegenDir, @"UmbracoData\umbraco.config"); + } + return IOHelper.ReturnPath("umbracoContentXML", "~/App_Data/umbraco.config"); + } + } + + public static bool ContentCacheXmlIsEphemeral + { + get + { + bool returnValue = false; + string configSetting = ConfigurationManager.AppSettings["umbracoContentXMLUseLocalTemp"]; + + if (!string.IsNullOrEmpty(configSetting)) + if(bool.TryParse(configSetting, out returnValue)) + return returnValue; + + return false; + } + } + } +} diff --git a/src/Umbraco.Core/RazorDataTypeModelStaticMappingItem.cs b/src/Umbraco.Core/RazorDataTypeModelStaticMappingItem.cs new file mode 100644 index 0000000000..7cc24bc5b3 --- /dev/null +++ b/src/Umbraco.Core/RazorDataTypeModelStaticMappingItem.cs @@ -0,0 +1,31 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace Umbraco.Core +{ + //NOTE: I'm not sure what this does or what it is used for, have emailed Gareth about it as the name really means nothing to me + // and don't know where this class actually belongs. + + internal class RazorDataTypeModelStaticMappingItem + { + public string Raw { get; set; } + //if all of the set (non null) properties match the property data currently being evaluated + public string PropertyTypeAlias { get; set; } + public string NodeTypeAlias { get; set; } + public Guid? DataTypeGuid { get; set; } + public string TypeName { get; set; } + + public bool Applies(Guid dataTypeGuid, string nodeTypeAlias, string propertyTypeAlias) + { + return + ( + (this.NodeTypeAlias != null || this.PropertyTypeAlias != null || this.DataTypeGuid != null) && + ((this.DataTypeGuid != null && this.DataTypeGuid == dataTypeGuid) || this.DataTypeGuid == null) && + ((this.PropertyTypeAlias != null && this.PropertyTypeAlias == propertyTypeAlias) || this.PropertyTypeAlias == null) && + ((this.NodeTypeAlias != null && this.NodeTypeAlias == nodeTypeAlias) || this.NodeTypeAlias == null) + ); + } + } +} diff --git a/src/Umbraco.Core/SystemUtilities.cs b/src/Umbraco.Core/SystemUtilities.cs new file mode 100644 index 0000000000..5146aade59 --- /dev/null +++ b/src/Umbraco.Core/SystemUtilities.cs @@ -0,0 +1,40 @@ +using System.Security; +using System.Web; + +namespace Umbraco.Core +{ + /// + /// Static helper methods for returning information about the current System + /// + public static class SystemUtilities + { + + /// + /// Get the current trust level of the hosted application + /// + /// + public static AspNetHostingPermissionLevel GetCurrentTrustLevel() + { + foreach (var trustLevel in new[] { + AspNetHostingPermissionLevel.Unrestricted, + AspNetHostingPermissionLevel.High, + AspNetHostingPermissionLevel.Medium, + AspNetHostingPermissionLevel.Low, + AspNetHostingPermissionLevel.Minimal }) + { + try + { + new AspNetHostingPermission(trustLevel).Demand(); + } + catch (SecurityException) + { + continue; + } + + return trustLevel; + } + + return AspNetHostingPermissionLevel.None; + } + } +} \ No newline at end of file diff --git a/src/Umbraco.Core/Umbraco.Core.csproj b/src/Umbraco.Core/Umbraco.Core.csproj index a523522d6e..4107c7258a 100644 --- a/src/Umbraco.Core/Umbraco.Core.csproj +++ b/src/Umbraco.Core/Umbraco.Core.csproj @@ -48,31 +48,34 @@ + + + - + + + + + + - - - - {E469A9CE-1BEC-423F-AC44-713CD72457EA} - umbraco.businesslogic - + ", "", "]]>"); + } + + /// + /// Determines whether the specified string appears to be XML. + /// + /// The XML string. + /// + /// true if the specified string appears to be XML; otherwise, false. + /// + public static bool CouldItBeXml(string xml) + { + if (!string.IsNullOrEmpty(xml)) + { + xml = xml.Trim(); + + if (xml.StartsWith("<") && xml.EndsWith(">")) + { + return true; + } + } + + return false; + } + + /// + /// Splits the specified delimited string into an XML document. + /// + /// The data. + /// The separator. + /// Name of the root. + /// Name of the element. + /// Returns an System.Xml.XmlDocument representation of the delimited string data. + public static XmlDocument Split(string data, string[] separator, string rootName, string elementName) + { + return Split(new XmlDocument(), data, separator, rootName, elementName); + } + + /// + /// Splits the specified delimited string into an XML document. + /// + /// The XML document. + /// The delimited string data. + /// The separator. + /// Name of the root node. + /// Name of the element node. + /// Returns an System.Xml.XmlDocument representation of the delimited string data. + public static XmlDocument Split(XmlDocument xml, string data, string[] separator, string rootName, string elementName) + { + // load new XML document. + xml.LoadXml(string.Concat("<", rootName, "/>")); + + // get the data-value, check it isn't empty. + if (!string.IsNullOrEmpty(data)) + { + // explode the values into an array + var values = data.Split(separator, StringSplitOptions.None); + + // loop through the array items. + foreach (string value in values) + { + // add each value to the XML document. + var xn = XmlHelper.AddTextNode(xml, elementName, value); + xml.DocumentElement.AppendChild(xn); + } + } + + // return the XML node. + return xml; + } + } +} diff --git a/src/umbraco.businesslogic/Exceptions/FileSecurityException.cs b/src/umbraco.businesslogic/Exceptions/FileSecurityException.cs index 407c117d5d..1b9f084003 100644 --- a/src/umbraco.businesslogic/Exceptions/FileSecurityException.cs +++ b/src/umbraco.businesslogic/Exceptions/FileSecurityException.cs @@ -5,14 +5,17 @@ using System.Text; namespace umbraco.businesslogic.Exceptions { - public class FileSecurityException : Exception + [Obsolete("This class has been superceded by Umbraco.Core.UI.FileSecurityException")] + public class FileSecurityException : Umbraco.Core.IO.FileSecurityException { public FileSecurityException() + : base() { } - public FileSecurityException(string message) : base(message) + public FileSecurityException(string message) + : base(message) { } diff --git a/src/umbraco.businesslogic/GlobalSettings.cs b/src/umbraco.businesslogic/GlobalSettings.cs index 9c67f39976..00e312ea08 100644 --- a/src/umbraco.businesslogic/GlobalSettings.cs +++ b/src/umbraco.businesslogic/GlobalSettings.cs @@ -16,34 +16,14 @@ namespace umbraco /// public class GlobalSettings { - #region Private static fields - // CURRENT UMBRACO VERSION ID - private static string _currentVersion = "4.9.0"; - - private static string _reservedUrlsCache; - private static string _reservedPathsCache; - private static StartsWithContainer _reservedList = new StartsWithContainer(); - #endregion - - /// - /// Initializes a new instance of the class. - /// - public GlobalSettings() - { - } - - /// + + /// /// Gets the reserved urls from web.config. /// /// The reserved urls. public static string ReservedUrls { - get - { - if (HttpContext.Current != null) - return ConfigurationManager.AppSettings["umbracoReservedUrls"]; - return String.Empty; - } + get { return Umbraco.Core.Configuration.GlobalSettings.ReservedUrls; } } /// @@ -52,12 +32,7 @@ namespace umbraco /// The reserved paths. public static string ReservedPaths { - get - { - if (HttpContext.Current != null) - return ConfigurationManager.AppSettings["umbracoReservedPaths"]; - return String.Empty; - } + get { return Umbraco.Core.Configuration.GlobalSettings.ReservedPaths; } } /// @@ -66,17 +41,7 @@ namespace umbraco /// The content XML. public static string ContentXML { - get - { - try - { - return ConfigurationManager.AppSettings["umbracoContentXML"]; - } - catch - { - return String.Empty; - } - } + get { return Umbraco.Core.Configuration.GlobalSettings.ContentXml; } } /// @@ -85,17 +50,7 @@ namespace umbraco /// The storage directory. public static string StorageDirectory { - get - { - try - { - return ConfigurationManager.AppSettings["umbracoStorageDirectory"]; - } - catch - { - return String.Empty; - } - } + get { return Umbraco.Core.Configuration.GlobalSettings.StorageDirectory; } } /// @@ -104,18 +59,7 @@ namespace umbraco /// The path. public static string Path { - get - { - - try - { - return IOHelper.ResolveUrl(ConfigurationManager.AppSettings["umbracoPath"]); - } - catch - { - return String.Empty; - } - } + get { return Umbraco.Core.Configuration.GlobalSettings.Path; } } /// @@ -126,10 +70,7 @@ namespace umbraco /// The path. public static string ClientPath { - get - { - return Path + "/../umbraco_client"; - } + get { return Umbraco.Core.Configuration.GlobalSettings.ClientPath; } } /// @@ -138,24 +79,8 @@ namespace umbraco /// The database connection string. public static string DbDSN { - get - { - try - { - return ConfigurationManager.AppSettings["umbracoDbDSN"]; - } - catch - { - return String.Empty; - } - } - set - { - if (DbDSN != value) - { - SaveSetting("umbracoDbDSN", value); - } - } + get { return Umbraco.Core.Configuration.GlobalSettings.DbDsn; } + set { Umbraco.Core.Configuration.GlobalSettings.DbDsn = value; } } /// @@ -164,57 +89,13 @@ namespace umbraco /// The configuration status. public static string ConfigurationStatus { - get - { - try - { - return ConfigurationManager.AppSettings["umbracoConfigurationStatus"]; - } - catch - { - return String.Empty; - } - } - set - { - SaveSetting("umbracoConfigurationStatus", value); - } + get { return Umbraco.Core.Configuration.GlobalSettings.ConfigurationStatus; } + set { Umbraco.Core.Configuration.GlobalSettings.ConfigurationStatus = value; } } - private static AspNetHostingPermissionLevel? m_ApplicationTrustLevel = null; public static AspNetHostingPermissionLevel ApplicationTrustLevel { - get - { - if (!m_ApplicationTrustLevel.HasValue) - { - //set minimum - m_ApplicationTrustLevel = AspNetHostingPermissionLevel.None; - - //determine maximum - foreach (AspNetHostingPermissionLevel trustLevel in - new AspNetHostingPermissionLevel[] { - AspNetHostingPermissionLevel.Unrestricted, - AspNetHostingPermissionLevel.High, - AspNetHostingPermissionLevel.Medium, - AspNetHostingPermissionLevel.Low, - AspNetHostingPermissionLevel.Minimal - }) - { - try - { - new AspNetHostingPermission(trustLevel).Demand(); - m_ApplicationTrustLevel = trustLevel; - break; //we've set the highest permission we can - } - catch (System.Security.SecurityException) - { - continue; - } - } - } - return m_ApplicationTrustLevel.Value; - } + get { return Umbraco.Core.SystemUtilities.GetCurrentTrustLevel(); } } @@ -224,20 +105,7 @@ namespace umbraco /// If true, umbraco will be medium-trust compatible, no matter what Permission level the server is on. public static bool UseMediumTrust { - get - { - try - { - if (ApplicationTrustLevel == AspNetHostingPermissionLevel.High || ApplicationTrustLevel == AspNetHostingPermissionLevel.Unrestricted) - return false; - else - return bool.Parse(ConfigurationManager.AppSettings["umbracoUseMediumTrust"]); - } - catch - { - return false; - } - } + get { return Umbraco.Core.Configuration.GlobalSettings.UseMediumTrust; } } /// @@ -247,24 +115,7 @@ namespace umbraco /// Value of the setting to be saved. protected static void SaveSetting(string key, string value) { - WebConfigurationFileMap webConfig = new WebConfigurationFileMap(); - var vDirs = webConfig.VirtualDirectories; - var vDir = FullpathToRoot; - foreach (VirtualDirectoryMapping v in webConfig.VirtualDirectories) - { - if (v.IsAppRoot) - { - vDir = v.PhysicalDirectory; - } - } - - XmlDocument doc = new XmlDocument(); - doc.Load(String.Concat(vDir, "web.config")); - XmlNode root = doc.DocumentElement; - XmlNode setting = doc.SelectSingleNode(String.Concat("//appSettings/add[@key='", key, "']")); - setting.Attributes["value"].InnerText = value; - doc.Save(String.Concat(vDir, "web.config")); - ConfigurationManager.RefreshSection("appSettings"); + Umbraco.Core.Configuration.GlobalSettings.SaveSetting(key, value); } /// @@ -273,7 +124,7 @@ namespace umbraco /// The fullpath to root. public static string FullpathToRoot { - get { return HttpRuntime.AppDomainAppPath; } + get { return Umbraco.Core.Configuration.GlobalSettings.FullpathToRoot; } } /// @@ -282,17 +133,7 @@ namespace umbraco /// true if [debug mode]; otherwise, false. public static bool DebugMode { - get - { - try - { - return bool.Parse(ConfigurationManager.AppSettings["umbracoDebugMode"]); - } - catch - { - return false; - } - } + get { return Umbraco.Core.Configuration.GlobalSettings.DebugMode; } } /// @@ -301,26 +142,7 @@ namespace umbraco /// true if configured; otherwise, false. public static bool Configured { - get - { - try - { - string configStatus = ConfigurationStatus; - string currentVersion = CurrentVersion; - - - if (currentVersion != configStatus) - Log.Add(LogTypes.Debug, User.GetUser(0), -1, - "CurrentVersion different from configStatus: '" + currentVersion + "','" + configStatus + - "'"); - - return (configStatus == currentVersion); - } - catch - { - return false; - } - } + get { return Umbraco.Core.Configuration.GlobalSettings.Configured; } } /// @@ -329,17 +151,7 @@ namespace umbraco /// The time out in minutes. public static int TimeOutInMinutes { - get - { - try - { - return int.Parse(ConfigurationManager.AppSettings["umbracoTimeOutInMinutes"]); - } - catch - { - return 20; - } - } + get { return Umbraco.Core.Configuration.GlobalSettings.TimeOutInMinutes; } } /// @@ -348,17 +160,7 @@ namespace umbraco /// true if umbraco uses directory urls; otherwise, false. public static bool UseDirectoryUrls { - get - { - try - { - return bool.Parse(ConfigurationManager.AppSettings["umbracoUseDirectoryUrls"]); - } - catch - { - return false; - } - } + get { return Umbraco.Core.Configuration.GlobalSettings.UseDirectoryUrls; } } /// @@ -367,17 +169,7 @@ namespace umbraco /// The version check period in days (0 = never). public static int VersionCheckPeriod { - get - { - int versionCheckPeriod = 7; - if (HttpContext.Current != null) - { - if (int.TryParse(ConfigurationManager.AppSettings["umbracoVersionCheckPeriod"], out versionCheckPeriod)) - return versionCheckPeriod; - - } - return versionCheckPeriod; - } + get { return Umbraco.Core.Configuration.GlobalSettings.VersionCheckPeriod; } } /// @@ -386,12 +178,7 @@ namespace umbraco /// The URL forbitten characters. public static string UrlForbittenCharacters { - get - { - if (HttpContext.Current != null) - return ConfigurationManager.AppSettings["umbracoUrlForbittenCharacters"]; - return ""; - } + get { return Umbraco.Core.Configuration.GlobalSettings.UrlForbittenCharacters; } } /// @@ -400,12 +187,7 @@ namespace umbraco /// The URL space character. public static string UrlSpaceCharacter { - get - { - if (HttpContext.Current != null) - return ConfigurationManager.AppSettings["umbracoUrlSpaceCharacter"]; - return ""; - } + get { return Umbraco.Core.Configuration.GlobalSettings.UrlSpaceCharacter; } } /// @@ -414,22 +196,7 @@ namespace umbraco /// The SMTP server. public static string SmtpServer { - get - { - try - { - System.Net.Configuration.MailSettingsSectionGroup mailSettings = ConfigurationManager.GetSection("system.net/mailSettings") as System.Net.Configuration.MailSettingsSectionGroup; - - if (mailSettings != null) - return mailSettings.Smtp.Network.Host; - else - return ConfigurationManager.AppSettings["umbracoSmtpServer"]; - } - catch - { - return ""; - } - } + get { return Umbraco.Core.Configuration.GlobalSettings.SmtpServer; } } /// @@ -438,12 +205,7 @@ namespace umbraco /// "true" if version xslt extensions are disabled, otherwise, "false" public static string DisableXsltExtensions { - get - { - if (HttpContext.Current != null) - return ConfigurationManager.AppSettings["umbracoDisableXsltExtensions"]; - return ""; - } + get { return Umbraco.Core.Configuration.GlobalSettings.DisableXsltExtensions; } } /// @@ -452,12 +214,7 @@ namespace umbraco /// "true" if Xhtml mode is enable, otherwise, "false" public static string EditXhtmlMode { - get - { - if (HttpContext.Current != null) - return ConfigurationManager.AppSettings["umbracoEditXhtmlMode"]; - return ""; - } + get { return Umbraco.Core.Configuration.GlobalSettings.EditXhtmlMode; } } /// @@ -466,12 +223,7 @@ namespace umbraco /// The default UI language. public static string DefaultUILanguage { - get - { - if (HttpContext.Current != null) - return ConfigurationManager.AppSettings["umbracoDefaultUILanguage"]; - return ""; - } + get { return Umbraco.Core.Configuration.GlobalSettings.DefaultUILanguage; } } /// @@ -480,12 +232,7 @@ namespace umbraco /// The profile URL. public static string ProfileUrl { - get - { - if (HttpContext.Current != null) - return ConfigurationManager.AppSettings["umbracoProfileUrl"]; - return ""; - } + get { return Umbraco.Core.Configuration.GlobalSettings.ProfileUrl; } } /// @@ -496,12 +243,7 @@ namespace umbraco /// public static bool HideTopLevelNodeFromPath { - get - { - if (HttpContext.Current != null) - return bool.Parse(ConfigurationManager.AppSettings["umbracoHideTopLevelNodeFromPath"]); - return false; - } + get { return Umbraco.Core.Configuration.GlobalSettings.HideTopLevelNodeFromPath; } } /// @@ -510,11 +252,7 @@ namespace umbraco /// The current version. public static string CurrentVersion { - get - { - // change this to be hardcoded in the binary - return _currentVersion; - } + get { return Umbraco.Core.Configuration.GlobalSettings.CurrentVersion; } } /// @@ -523,11 +261,7 @@ namespace umbraco /// The major version number. public static int VersionMajor { - get - { - string[] version = CurrentVersion.Split(".".ToCharArray()); - return int.Parse(version[0]); - } + get { return Umbraco.Core.Configuration.GlobalSettings.VersionMajor; } } /// @@ -536,11 +270,7 @@ namespace umbraco /// The minor version number. public static int VersionMinor { - get - { - string[] version = CurrentVersion.Split(".".ToCharArray()); - return int.Parse(version[1]); - } + get { return Umbraco.Core.Configuration.GlobalSettings.VersionMinor; } } /// @@ -549,11 +279,7 @@ namespace umbraco /// The patch version number. public static int VersionPatch { - get - { - string[] version = CurrentVersion.Split(".".ToCharArray()); - return int.Parse(version[2]); - } + get { return Umbraco.Core.Configuration.GlobalSettings.VersionPatch; } } /// @@ -562,14 +288,7 @@ namespace umbraco /// The version comment. public static string VersionComment { - get - { - string[] version = CurrentVersion.Split(".".ToCharArray()); - if (version.Length > 3) - return version[3]; - else - return ""; - } + get { return Umbraco.Core.Configuration.GlobalSettings.VersionComment; } } @@ -580,12 +299,12 @@ namespace umbraco /// public static bool RequestIsInUmbracoApplication(HttpContext context) { - return context.Request.Path.ToLower().IndexOf(IOHelper.ResolveUrl(SystemDirectories.Umbraco).ToLower()) > -1; + return Umbraco.Core.Configuration.GlobalSettings.RequestIsInUmbracoApplication(context); } public static bool RequestIsLiveEditRedirector(HttpContext context) { - return context.Request.Path.ToLower().IndexOf(SystemDirectories.Umbraco.ToLower() + "/liveediting.aspx") > -1; + return Umbraco.Core.Configuration.GlobalSettings.RequestIsLiveEditRedirector(context); } /// @@ -594,17 +313,7 @@ namespace umbraco /// true if [use SSL]; otherwise, false. public static bool UseSSL { - get - { - try - { - return bool.Parse(ConfigurationManager.AppSettings["umbracoUseSSL"]); - } - catch - { - return false; - } - } + get { return Umbraco.Core.Configuration.GlobalSettings.UseSSL; } } /// @@ -613,40 +322,7 @@ namespace umbraco /// The license. public static string License { - get - { - string license = - "the open source license MIT. The umbraco UI is freeware licensed under the umbraco license."; - if (HttpContext.Current != null) - { - XmlDocument versionDoc = new XmlDocument(); - XmlTextReader versionReader = new XmlTextReader(IOHelper.MapPath(SystemDirectories.Umbraco + "/version.xml")); - versionDoc.Load(versionReader); - versionReader.Close(); - - // check for license - try - { - string licenseUrl = - versionDoc.SelectSingleNode("/version/licensing/licenseUrl").FirstChild.Value; - string licenseValidation = - versionDoc.SelectSingleNode("/version/licensing/licenseValidation").FirstChild.Value; - string licensedTo = - versionDoc.SelectSingleNode("/version/licensing/licensedTo").FirstChild.Value; - - if (licensedTo != "" && licenseUrl != "") - { - license = "umbraco Commercial License
Registered to:
" + - licensedTo.Replace("\n", "
") + "
For use with domain:
" + - licenseUrl; - } - } - catch - { - } - } - return license; - } + get { return Umbraco.Core.Configuration.GlobalSettings.License; } } @@ -656,34 +332,7 @@ namespace umbraco /// true if succesfull; otherwise, false. public static bool test { - get - { - try - { - HttpContext.Current.Response.Write("ContentXML :" + ContentXML + "\n"); - HttpContext.Current.Response.Write("DbDSN :" + DbDSN + "\n"); - HttpContext.Current.Response.Write("DebugMode :" + DebugMode + "\n"); - HttpContext.Current.Response.Write("DefaultUILanguage :" + DefaultUILanguage + "\n"); - HttpContext.Current.Response.Write("VersionCheckPeriod :" + VersionCheckPeriod + "\n"); - HttpContext.Current.Response.Write("DisableXsltExtensions :" + DisableXsltExtensions + "\n"); - HttpContext.Current.Response.Write("EditXhtmlMode :" + EditXhtmlMode + "\n"); - HttpContext.Current.Response.Write("HideTopLevelNodeFromPath :" + HideTopLevelNodeFromPath + "\n"); - HttpContext.Current.Response.Write("Path :" + Path + "\n"); - HttpContext.Current.Response.Write("ProfileUrl :" + ProfileUrl + "\n"); - HttpContext.Current.Response.Write("ReservedPaths :" + ReservedPaths + "\n"); - HttpContext.Current.Response.Write("ReservedUrls :" + ReservedUrls + "\n"); - HttpContext.Current.Response.Write("StorageDirectory :" + StorageDirectory + "\n"); - HttpContext.Current.Response.Write("TimeOutInMinutes :" + TimeOutInMinutes + "\n"); - HttpContext.Current.Response.Write("UrlForbittenCharacters :" + UrlForbittenCharacters + "\n"); - HttpContext.Current.Response.Write("UrlSpaceCharacter :" + UrlSpaceCharacter + "\n"); - HttpContext.Current.Response.Write("UseDirectoryUrls :" + UseDirectoryUrls + "\n"); - return true; - } - catch - { - } - return false; - } + get { return Umbraco.Core.Configuration.GlobalSettings.Test; } } @@ -696,48 +345,7 @@ namespace umbraco /// public static bool IsReservedPathOrUrl(string url) { - // check if GlobalSettings.ReservedPaths and GlobalSettings.ReservedUrls are unchanged - if (!object.ReferenceEquals(_reservedPathsCache, GlobalSettings.ReservedPaths) - || !object.ReferenceEquals(_reservedUrlsCache, GlobalSettings.ReservedUrls)) - { - // store references to strings to determine changes - _reservedPathsCache = GlobalSettings.ReservedPaths; - _reservedUrlsCache = GlobalSettings.ReservedUrls; - - string _root = SystemDirectories.Root.Trim().ToLower(); - - // add URLs and paths to a new list - StartsWithContainer _newReservedList = new StartsWithContainer(); - foreach (string reservedUrl in _reservedUrlsCache.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries)) - { - //resolves the url to support tilde chars - string reservedUrlTrimmed = IOHelper.ResolveUrl(reservedUrl).Trim().ToLower(); - if (reservedUrlTrimmed.Length > 0) - _newReservedList.Add(reservedUrlTrimmed); - } - - foreach (string reservedPath in _reservedPathsCache.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries)) - { - bool trimEnd = !reservedPath.EndsWith("/"); - //resolves the url to support tilde chars - string reservedPathTrimmed = IOHelper.ResolveUrl(reservedPath).Trim().ToLower(); - - if (reservedPathTrimmed.Length > 0) - _newReservedList.Add(reservedPathTrimmed + (reservedPathTrimmed.EndsWith("/") ? "" : "/")); - } - - // use the new list from now on - _reservedList = _newReservedList; - } - - string res = ""; - foreach (string st in _reservedList._list.Keys) - res += st + ","; - - HttpContext.Current.Trace.Write("umbracoGlobalsettings", "reserverd urls: '" + res + "'"); - - // return true if url starts with an element of the reserved list - return _reservedList.StartsWith(url.ToLower()); + return Umbraco.Core.Configuration.GlobalSettings.IsReservedPathOrUrl(url); } } @@ -747,6 +355,7 @@ namespace umbraco /// Structure that checks in logarithmic time /// if a given string starts with one of the added keys. ///
+ [Obsolete("Use Umbraco.Core.Configuration.GlobalSettings.StartsWithContainer container instead")] public class StartsWithContainer { /// Internal sorted list of keys. diff --git a/src/umbraco.businesslogic/IO/IOHelper.cs b/src/umbraco.businesslogic/IO/IOHelper.cs index 1ff13ee642..8bd27eab9c 100644 --- a/src/umbraco.businesslogic/IO/IOHelper.cs +++ b/src/umbraco.businesslogic/IO/IOHelper.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.Diagnostics; using System.Linq; +using System.Reflection; using System.Text; using System.IO; using System.Configuration; @@ -12,133 +13,55 @@ using umbraco.businesslogic.Exceptions; namespace umbraco.IO { + [Obsolete("Use Umbraco.Core.IO.IOHelper instead")] public static class IOHelper - { - private static string m_rootDir = ""; - // static compiled regex for faster performance - private readonly static Regex _resolveUrlPattern = new Regex("(=[\"\']?)(\\W?\\~(?:.(?![\"\']?\\s+(?:\\S+)=|[>\"\']))+.)[\"\']?", RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace); - + { public static char DirSepChar { get { - return Path.DirectorySeparatorChar; + return Umbraco.Core.IO.IOHelper.DirSepChar; } } //helper to try and match the old path to a new virtual one public static string FindFile(string virtualPath) { - string retval = virtualPath; - - if (virtualPath.StartsWith("~")) - retval = virtualPath.Replace("~", SystemDirectories.Root); - - if (virtualPath.StartsWith("/") && !virtualPath.StartsWith(SystemDirectories.Root)) - retval = SystemDirectories.Root + "/" + virtualPath.TrimStart('/'); - - return retval; + return Umbraco.Core.IO.IOHelper.FindFile(virtualPath); } //Replaces tildes with the root dir public static string ResolveUrl(string virtualPath) { - if (virtualPath.StartsWith("~")) - return virtualPath.Replace("~", SystemDirectories.Root).Replace("//", "/"); - else - return VirtualPathUtility.ToAbsolute(virtualPath, SystemDirectories.Root); + return Umbraco.Core.IO.IOHelper.ResolveUrl(virtualPath); } public static string ResolveUrlsFromTextString(string text) { - if (UmbracoSettings.ResolveUrlsFromTextString) - { - Stopwatch sw = new Stopwatch(); - sw.Start(); - Debug.WriteLine("Start: " + sw.ElapsedMilliseconds); - - // find all relative urls (ie. urls that contain ~) - MatchCollection tags = - _resolveUrlPattern.Matches(text); - Debug.WriteLine("After regex: " + sw.ElapsedMilliseconds); - foreach (Match tag in tags) - { - Debug.WriteLine("-- inside regex: " + sw.ElapsedMilliseconds); - string url = ""; - if (tag.Groups[1].Success) - url = tag.Groups[1].Value; - - // The richtext editor inserts a slash in front of the url. That's why we need this little fix - // if (url.StartsWith("/")) - // text = text.Replace(url, ResolveUrl(url.Substring(1))); - // else - if (!String.IsNullOrEmpty(url)) - { - Debug.WriteLine("---- before resolve: " + sw.ElapsedMilliseconds); - string resolvedUrl = (url.Substring(0, 1) == "/") ? ResolveUrl(url.Substring(1)) : ResolveUrl(url); - Debug.WriteLine("---- after resolve: " + sw.ElapsedMilliseconds); - Debug.WriteLine("---- before replace: " + sw.ElapsedMilliseconds); - text = text.Replace(url, resolvedUrl); - Debug.WriteLine("---- after replace: " + sw.ElapsedMilliseconds); - } - - } - - Debug.WriteLine("total: " + sw.ElapsedMilliseconds); - sw.Stop(); - System.Web.HttpContext.Current.Trace.Write("Resolve Urls", sw.ElapsedMilliseconds.ToString()); - - } - return text; + return Umbraco.Core.IO.IOHelper.ResolveUrlsFromTextString(text); } public static string MapPath(string path, bool useHttpContext) { - // Check if the path is already mapped - if (path.Length >= 2 && path[1] == Path.VolumeSeparatorChar) - return path; - - if (useHttpContext) - { - //string retval; - if (!string.IsNullOrEmpty(path) && (path.StartsWith("~") || path.StartsWith(SystemDirectories.Root))) - return System.Web.Hosting.HostingEnvironment.MapPath(path); - else - return System.Web.Hosting.HostingEnvironment.MapPath("~/" + path.TrimStart('/')); - } - else - { - string _root = (!String.IsNullOrEmpty(System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath)) ? System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath.TrimEnd(IOHelper.DirSepChar) : getRootDirectorySafe(); - - string _path = path.TrimStart('~', '/').Replace('/', IOHelper.DirSepChar); - - string retval = _root + IOHelper.DirSepChar.ToString() + _path; - - return retval; - } + return Umbraco.Core.IO.IOHelper.MapPath(path, useHttpContext); } public static string MapPath(string path) { - return MapPath(path, true); + return Umbraco.Core.IO.IOHelper.MapPath(path); } //use a tilde character instead of the complete path public static string returnPath(string settingsKey, string standardPath, bool useTilde) { - string retval = ConfigurationManager.AppSettings[settingsKey]; - - if (string.IsNullOrEmpty(retval)) - retval = standardPath; - - return retval.TrimEnd('/'); + return Umbraco.Core.IO.IOHelper.ReturnPath(settingsKey, standardPath, useTilde); } public static string returnPath(string settingsKey, string standardPath) { - return returnPath(settingsKey, standardPath, false); + return Umbraco.Core.IO.IOHelper.ReturnPath(settingsKey, standardPath); } @@ -151,28 +74,12 @@ namespace umbraco.IO /// true if valid, throws a FileSecurityException if not public static bool ValidateEditPath(string filePath, string validDir) { - if (!filePath.StartsWith(MapPath(SystemDirectories.Root))) - filePath = MapPath(filePath); - if (!validDir.StartsWith(MapPath(SystemDirectories.Root))) - validDir = MapPath(validDir); - - if (!filePath.StartsWith(validDir)) - throw new FileSecurityException(String.Format("The filepath '{0}' is not within an allowed directory for this type of files", filePath.Replace(MapPath(SystemDirectories.Root), ""))); - - return true; + return Umbraco.Core.IO.IOHelper.ValidateEditPath(filePath, validDir); } public static bool ValidateFileExtension(string filePath, List validFileExtensions) { - if (!filePath.StartsWith(MapPath(SystemDirectories.Root))) - filePath = MapPath(filePath); - FileInfo f = new FileInfo(filePath); - - - if (!validFileExtensions.Contains(f.Extension.Substring(1))) - throw new FileSecurityException(String.Format("The extension for the current file '{0}' is not of an allowed type for this editor. This is typically controlled from either the installed MacroEngines or based on configuration in /config/umbracoSettings.config", filePath.Replace(MapPath(SystemDirectories.Root), ""))); - - return true; + return Umbraco.Core.IO.IOHelper.ValidateFileExtension(filePath, validFileExtensions); } @@ -184,17 +91,7 @@ namespace umbraco.IO /// private static string getRootDirectorySafe() { - if (!String.IsNullOrEmpty(m_rootDir)) - { - return m_rootDir; - } - - string baseDirectory = - System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().CodeBase.Substring(8)); - m_rootDir = baseDirectory.Substring(0, baseDirectory.LastIndexOf("bin") - 1); - - return m_rootDir; - + return Umbraco.Core.IO.IOHelper.GetRootDirectorySafe(); } } diff --git a/src/umbraco.businesslogic/IO/SystemDirectories.cs b/src/umbraco.businesslogic/IO/SystemDirectories.cs index 0c0ce810e0..b98f59b808 100644 --- a/src/umbraco.businesslogic/IO/SystemDirectories.cs +++ b/src/umbraco.businesslogic/IO/SystemDirectories.cs @@ -9,170 +9,104 @@ using System.IO; namespace umbraco.IO { - //all paths has a starting but no trailing / + [Obsolete("Use Umbraco.Core.UI.SystemDirectories instead")] public class SystemDirectories { public static string Bin { - get - { - return IOHelper.returnPath("umbracoBinDirectory", "~/bin"); - } + get { return global::Umbraco.Core.IO.SystemDirectories.Bin; } } public static string Base { - get - { - return IOHelper.returnPath("umbracoBaseDirectory", "~/base"); - } + get { return global::Umbraco.Core.IO.SystemDirectories.Base; } } public static string Config { - get - { - return IOHelper.returnPath("umbracoConfigDirectory", "~/config"); - } + get { return global::Umbraco.Core.IO.SystemDirectories.Config; } } public static string Css { - get - { - return IOHelper.returnPath("umbracoCssDirectory", "~/css"); - } + get { return global::Umbraco.Core.IO.SystemDirectories.Css; } } public static string Data { - get - { - return IOHelper.returnPath("umbracoStorageDirectory", "~/App_Data"); - } + get { return global::Umbraco.Core.IO.SystemDirectories.Data; } } public static string Install { - get - { - return IOHelper.returnPath("umbracoInstallPath", "~/install"); - } + get { return global::Umbraco.Core.IO.SystemDirectories.Install; } } public static string Masterpages { - get - { - return IOHelper.returnPath("umbracoMasterPagesPath", "~/masterpages"); - } + get { return global::Umbraco.Core.IO.SystemDirectories.Masterpages; } } public static string Media { - get - { - return IOHelper.returnPath("umbracoMediaPath", "~/media"); - } + get { return global::Umbraco.Core.IO.SystemDirectories.Media; } } [Obsolete("Please use MacroScripts instead!", true)] public static string Python { - get - { - return MacroScripts; - } + get { return global::Umbraco.Core.IO.SystemDirectories.MacroScripts; } } public static string MacroScripts { - get - { - // for legacy we test for the python path first, but else we use the new default location - string tempPath = IOHelper.returnPath("umbracoPythonPath", "") == String.Empty - ? IOHelper.returnPath("umbracoMacroScriptPath", "~/macroScripts") - : IOHelper.returnPath("umbracoPythonPath", "~/python"); - return tempPath; - } + get { return global::Umbraco.Core.IO.SystemDirectories.MacroScripts; } } public static string Scripts { - get - { - return IOHelper.returnPath("umbracoScriptsPath", "~/scripts"); - } + get { return global::Umbraco.Core.IO.SystemDirectories.Scripts; } } public static string Umbraco { - get - { - return IOHelper.returnPath("umbracoPath", "~/umbraco"); - } + get { return global::Umbraco.Core.IO.SystemDirectories.Umbraco; } } public static string Umbraco_client { - get - { - return IOHelper.returnPath("umbracoClientPath", "~/umbraco_client"); - } + get { return global::Umbraco.Core.IO.SystemDirectories.UmbracoClient; } } public static string Usercontrols { - get - { - return IOHelper.returnPath("umbracoUsercontrolsPath", "~/usercontrols"); - } + get { return global::Umbraco.Core.IO.SystemDirectories.UserControls; } } public static string Webservices { - get - { - return IOHelper.returnPath("umbracoWebservicesPath", "~/umbraco/webservices"); - } + get { return global::Umbraco.Core.IO.SystemDirectories.WebServices; } } public static string Xslt { - get { - return IOHelper.returnPath("umbracoXsltPath", "~/xslt"); - } + get { return global::Umbraco.Core.IO.SystemDirectories.Xslt; } } public static string Packages { - get - { - //by default the packages folder should exist in the data folder - return IOHelper.returnPath("umbracoPackagesPath", Data + IOHelper.DirSepChar + "packages"); - } + get { return global::Umbraco.Core.IO.SystemDirectories.Packages; } } public static string Preview { - get - { - //by default the packages folder should exist in the data folder - return IOHelper.returnPath("umbracoPreviewPath", Data + IOHelper.DirSepChar + "preview"); - } + get { return global::Umbraco.Core.IO.SystemDirectories.Preview; } } public static string Root { - get - { - string appPath = HttpRuntime.AppDomainAppVirtualPath ?? string.Empty; - if (appPath == "/") - appPath = string.Empty; - - return appPath; - } + get { return global::Umbraco.Core.IO.SystemDirectories.Root; } } } diff --git a/src/umbraco.businesslogic/IO/SystemFiles.cs b/src/umbraco.businesslogic/IO/SystemFiles.cs index b840511e4c..f2915d11a3 100644 --- a/src/umbraco.businesslogic/IO/SystemFiles.cs +++ b/src/umbraco.businesslogic/IO/SystemFiles.cs @@ -8,115 +8,70 @@ using System.Web; namespace umbraco.IO { - public class SystemFiles - { - public static string AccessXml - { - get - { - return SystemDirectories.Data + "/access.config"; - } - } + [Obsolete("Use Umbraco.Core.UI.SystemFiles instead")] + public class SystemFiles + { - public static string CreateUiXml - { - get - { - return SystemDirectories.Umbraco + "/config/create/UI.xml"; - } - } + public static string AccessXml + { + get { return Umbraco.Core.IO.SystemFiles.AccessXml; } + } - public static string TinyMceConfig - { - get - { - return SystemDirectories.Config + "/tinyMceConfig.config"; - } - } + public static string CreateUiXml + { + get { return Umbraco.Core.IO.SystemFiles.CreateUiXml; } + } - public static string MetablogConfig - { - get - { - return SystemDirectories.Config + "/metablogConfig.config"; - } - } + public static string TinyMceConfig + { + get { return Umbraco.Core.IO.SystemFiles.TinyMceConfig; } + } - public static string DashboardConfig - { - get - { - return SystemDirectories.Config + "/dashboard.config"; - } - } + public static string MetablogConfig + { + get { return Umbraco.Core.IO.SystemFiles.MetablogConfig; } + } - public static string XsltextensionsConfig - { - get - { - return SystemDirectories.Config + "/xsltextensions.config"; - } - } + public static string DashboardConfig + { + get { return Umbraco.Core.IO.SystemFiles.DashboardConfig; } + } - public static string RestextensionsConfig - { - get - { - return SystemDirectories.Config + "/restextensions.config"; - } - } + public static string XsltextensionsConfig + { + get { return Umbraco.Core.IO.SystemFiles.XsltextensionsConfig; } + } + + public static string RestextensionsConfig + { + get { return Umbraco.Core.IO.SystemFiles.RestextensionsConfig; } + } - public static string SkinningXml - { - get - { - return SystemDirectories.Data + "/skinning.config"; - } - } + public static string SkinningXml + { + get { return Umbraco.Core.IO.SystemFiles.SkinningXml; } + } - public static string NotFoundhandlersConfig - { - get - { - return SystemDirectories.Config + "/404handlers.config"; - } - } + public static string NotFoundhandlersConfig + { + get { return Umbraco.Core.IO.SystemFiles.NotFoundhandlersConfig; } + } - public static string FeedProxyConfig - { - get - { - return string.Concat(SystemDirectories.Config, "/feedProxy.config"); - } - } + public static string FeedProxyConfig + { + get { return Umbraco.Core.IO.SystemFiles.FeedProxyConfig; } + } - public static string ContentCacheXml - { - get - { - if (ContentCacheXmlIsEphemeral) - { - return Path.Combine(HttpRuntime.CodegenDir, @"UmbracoData\umbraco.config"); - } - return IOHelper.returnPath("umbracoContentXML", "~/App_Data/umbraco.config"); - } - } + public static string ContentCacheXml + { + get { return Umbraco.Core.IO.SystemFiles.ContentCacheXml; } + } - public static bool ContentCacheXmlIsEphemeral - { - get - { - bool returnValue = false; - string configSetting = ConfigurationManager.AppSettings["umbracoContentXMLUseLocalTemp"]; - - if (!string.IsNullOrEmpty(configSetting)) - if(bool.TryParse(configSetting, out returnValue)) - return returnValue; - - return false; - } - } - } + public static bool ContentCacheXmlIsEphemeral + { + get { return Umbraco.Core.IO.SystemFiles.ContentCacheXmlIsEphemeral; } + } + } } diff --git a/src/umbraco.businesslogic/Razor/RazorDataTypeModelStaticMappingItem.cs b/src/umbraco.businesslogic/Razor/RazorDataTypeModelStaticMappingItem.cs index 2bd9cce16b..fab1d4d291 100644 --- a/src/umbraco.businesslogic/Razor/RazorDataTypeModelStaticMappingItem.cs +++ b/src/umbraco.businesslogic/Razor/RazorDataTypeModelStaticMappingItem.cs @@ -5,28 +5,45 @@ using System.Text; namespace umbraco.MacroEngines { + [Obsolete("use Umbraco.Core.RazorDataTypeModelStaticMappingItem instead")] public class RazorDataTypeModelStaticMappingItem - { - public string Raw; + { + private readonly Umbraco.Core.RazorDataTypeModelStaticMappingItem _realMappingItem = new Umbraco.Core.RazorDataTypeModelStaticMappingItem(); + + public string Raw + { + get { return _realMappingItem.Raw; } + set { _realMappingItem.Raw = value; } + } //if all of the set (non null) properties match the property data currently being evaluated - public string PropertyTypeAlias; - public string NodeTypeAlias; - public Guid? DataTypeGuid; + public string PropertyTypeAlias + { + get { return _realMappingItem.PropertyTypeAlias; } + set { _realMappingItem.PropertyTypeAlias = value; } + } - public string TypeName; + public string NodeTypeAlias + { + get { return _realMappingItem.NodeTypeAlias; } + set { _realMappingItem.NodeTypeAlias = value; } + } - public RazorDataTypeModelStaticMappingItem() { } + public Guid? DataTypeGuid + { + get { return _realMappingItem.DataTypeGuid; } + set { _realMappingItem.DataTypeGuid = value; } + } - public bool Applies(Guid dataTypeGuid, string nodeTypeAlias, string propertyTypeAlias) - { - return - ( - (this.NodeTypeAlias != null || this.PropertyTypeAlias != null || this.DataTypeGuid != null) && - ((this.DataTypeGuid != null && this.DataTypeGuid == dataTypeGuid) || this.DataTypeGuid == null) && - ((this.PropertyTypeAlias != null && this.PropertyTypeAlias == propertyTypeAlias) || this.PropertyTypeAlias == null) && - ((this.NodeTypeAlias != null && this.NodeTypeAlias == nodeTypeAlias) || this.NodeTypeAlias == null) - ); - } + public string TypeName + { + get { return _realMappingItem.TypeName; } + set { _realMappingItem.TypeName = value; } + } + + public bool Applies(Guid dataTypeGuid, string nodeTypeAlias, string propertyTypeAlias) + { + return _realMappingItem.Applies(dataTypeGuid, nodeTypeAlias, propertyTypeAlias); + } } } diff --git a/src/umbraco.businesslogic/UmbracoSettings.cs b/src/umbraco.businesslogic/UmbracoSettings.cs index 7a38b42823..855028adfb 100644 --- a/src/umbraco.businesslogic/UmbracoSettings.cs +++ b/src/umbraco.businesslogic/UmbracoSettings.cs @@ -1,6 +1,7 @@ using System; using System.Diagnostics; using System.IO; +using System.Linq; using System.Web; using System.Web.Caching; using System.Xml; @@ -23,55 +24,17 @@ namespace umbraco /// The _umbraco settings. public static XmlDocument _umbracoSettings { - get - { - XmlDocument us = (XmlDocument)HttpRuntime.Cache["umbracoSettingsFile"]; - if (us == null) - us = ensureSettingsDocument(); - return us; - } - } - - private static string _path = GlobalSettings.FullpathToRoot + Path.DirectorySeparatorChar + "config" + - Path.DirectorySeparatorChar; - - private static string _filename = "umbracoSettings.config"; - - private static XmlDocument ensureSettingsDocument() - { - object settingsFile = HttpRuntime.Cache["umbracoSettingsFile"]; - - // Check for language file in cache - if (settingsFile == null) - { - XmlDocument temp = new XmlDocument(); - XmlTextReader settingsReader = new XmlTextReader(_path + _filename); - try - { - temp.Load(settingsReader); - HttpRuntime.Cache.Insert("umbracoSettingsFile", temp, - new CacheDependency(_path + _filename)); - } - catch (XmlException e) - { - throw new XmlException("Your umbracoSettings.config file fails to pass as valid XML. Refer to the InnerException for more information", e); - } - catch (Exception e) - { - Log.Add(LogTypes.Error, new User(0), -1, "Error reading umbracoSettings file: " + e.ToString()); - } - settingsReader.Close(); - return temp; - } - else - return (XmlDocument)settingsFile; - } - - private static void save() - { - _umbracoSettings.Save(_path + _filename); + get { return Umbraco.Core.Configuration.UmbracoSettings.UmbracoSettingsXmlDoc; } } + /// + /// Gets/sets the settings file path, the setter can be used in unit tests + /// + internal static string SettingsFilePath + { + get { return Umbraco.Core.Configuration.UmbracoSettings.SettingsFilePath; } + set { Umbraco.Core.Configuration.UmbracoSettings.SettingsFilePath = value; } + } /// /// Selects a xml node in the umbraco settings config file. @@ -80,12 +43,7 @@ namespace umbraco /// If found, it returns the specific configuration xml node. public static XmlNode GetKeyAsNode(string Key) { - if (Key == null) - throw new ArgumentException("Key cannot be null"); - ensureSettingsDocument(); - if (_umbracoSettings == null || _umbracoSettings.DocumentElement == null) - return null; - return _umbracoSettings.DocumentElement.SelectSingleNode(Key); + return Umbraco.Core.Configuration.UmbracoSettings.GetKeyAsNode(Key); } /// @@ -95,12 +53,7 @@ namespace umbraco /// public static string GetKey(string Key) { - ensureSettingsDocument(); - - XmlNode node = _umbracoSettings.DocumentElement.SelectSingleNode(Key); - if (node == null || node.FirstChild == null || node.FirstChild.Value == null) - return string.Empty; - return node.FirstChild.Value; + return Umbraco.Core.Configuration.UmbracoSettings.GetKey(Key); } /// @@ -111,7 +64,7 @@ namespace umbraco /// public static bool UploadAllowDirectories { - get { return bool.Parse(GetKey("/settings/content/UploadAllowDirectories")); } + get { return Umbraco.Core.Configuration.UmbracoSettings.UploadAllowDirectories; } } /// @@ -120,16 +73,7 @@ namespace umbraco /// true if logging is enabled; otherwise, false. public static bool EnableLogging { - get - { - // We return true if no enable logging element is present in - // umbracoSettings (to enable default behaviour when upgrading) - string m_EnableLogging = GetKey("/settings/logging/enableLogging"); - if (String.IsNullOrEmpty(m_EnableLogging)) - return true; - else - return bool.Parse(m_EnableLogging); - } + get { return Umbraco.Core.Configuration.UmbracoSettings.EnableLogging; } } /// @@ -138,14 +82,7 @@ namespace umbraco /// true if async logging is enabled; otherwise, false. public static bool EnableAsyncLogging { - get - { - string value = GetKey("/settings/logging/enableAsyncLogging"); - bool result; - if (!string.IsNullOrEmpty(value) && bool.TryParse(value, out result)) - return result; - return false; - } + get { return Umbraco.Core.Configuration.UmbracoSettings.EnableAsyncLogging; } } /// @@ -153,30 +90,14 @@ namespace umbraco /// public static string ExternalLoggerAssembly { - get - { - XmlNode value = GetKeyAsNode("/settings/logging/externalLogger"); - if (value != null) - { - return value.Attributes["assembly"].Value; - } - return ""; - } + get { return Umbraco.Core.Configuration.UmbracoSettings.ExternalLoggerAssembly; } } /// /// Gets the type of an external logger that can be used to store log items in 3rd party systems /// public static string ExternalLoggerType { - get - { - XmlNode value = GetKeyAsNode("/settings/logging/externalLogger"); - if (value != null) - { - return value.Attributes["type"].Value; - } - return ""; - } + get { return Umbraco.Core.Configuration.UmbracoSettings.ExternalLoggerType; } } /// @@ -184,18 +105,7 @@ namespace umbraco /// public static bool ExternalLoggerLogAuditTrail { - get - { - XmlNode value = GetKeyAsNode("/settings/logging/externalLogger"); - if (value != null) - { - string logAuditTrail = value.Attributes["logAuditTrail"].Value; - bool result; - if (!string.IsNullOrEmpty(logAuditTrail) && bool.TryParse(logAuditTrail, out result)) - return result; - } - return false; - } + get { return Umbraco.Core.Configuration.UmbracoSettings.ExternalLoggerLogAuditTrail; } } /// @@ -203,14 +113,7 @@ namespace umbraco /// public static bool KeepUserLoggedIn { - get - { - string value = GetKey("/settings/security/keepUserLoggedIn"); - bool result; - if (!string.IsNullOrEmpty(value) && bool.TryParse(value, out result)) - return result; - return true; - } + get { return Umbraco.Core.Configuration.UmbracoSettings.KeepUserLoggedIn; } } /// @@ -218,14 +121,7 @@ namespace umbraco /// public static bool HideDisabledUsersInBackoffice { - get - { - string value = GetKey("/settings/security/hideDisabledUsersInBackoffice"); - bool result; - if (!string.IsNullOrEmpty(value) && bool.TryParse(value, out result)) - return result; - return false; - } + get { return Umbraco.Core.Configuration.UmbracoSettings.HideDisabledUsersInBackoffice; } } /// @@ -234,14 +130,7 @@ namespace umbraco /// true if logs are to be automatically cleaned; otherwise, false public static bool AutoCleanLogs { - get - { - string value = GetKey("/settings/logging/autoCleanLogs"); - bool result; - if (!string.IsNullOrEmpty(value) && bool.TryParse(value, out result)) - return result; - return false; - } + get { return Umbraco.Core.Configuration.UmbracoSettings.AutoCleanLogs; } } /// @@ -249,26 +138,12 @@ namespace umbraco /// public static int CleaningMiliseconds { - get - { - string value = GetKey("/settings/logging/cleaningMiliseconds"); - int result; - if (!string.IsNullOrEmpty(value) && int.TryParse(value, out result)) - return result; - return -1; - } + get { return Umbraco.Core.Configuration.UmbracoSettings.CleaningMiliseconds; } } public static int MaxLogAge { - get - { - string value = GetKey("/settings/logging/maxLogAge"); - int result; - if (!string.IsNullOrEmpty(value) && int.TryParse(value, out result)) - return result; - return -1; - } + get { return Umbraco.Core.Configuration.UmbracoSettings.MaxLogAge; } } /// @@ -277,7 +152,7 @@ namespace umbraco /// The disabled log types. public static XmlNode DisabledLogTypes { - get { return GetKeyAsNode("/settings/logging/disabledLogTypes"); } + get { return Umbraco.Core.Configuration.UmbracoSettings.DisabledLogTypes; } } /// @@ -286,7 +161,7 @@ namespace umbraco /// The package server url. public static string PackageServer { - get { return "packages.umbraco.org"; } + get { return Umbraco.Core.Configuration.UmbracoSettings.PackageServer; } } /// @@ -295,20 +170,7 @@ namespace umbraco /// true if umbraco will use domain prefixes; otherwise, false. public static bool UseDomainPrefixes { - get - { - try - { - bool result; - if (bool.TryParse(GetKey("/settings/requestHandler/useDomainPrefixes"), out result)) - return result; - return false; - } - catch - { - return false; - } - } + get { return Umbraco.Core.Configuration.UmbracoSettings.UseDomainPrefixes; } } /// @@ -317,27 +179,7 @@ namespace umbraco /// public static bool AddTrailingSlash { - get - { - try - { - if (GlobalSettings.UseDirectoryUrls) - { - bool result; - if (bool.TryParse(GetKey("/settings/requestHandler/addTrailingSlash"), out result)) - return result; - return false; - } - else - { - return false; - } - } - catch - { - return false; - } - } + get { return Umbraco.Core.Configuration.UmbracoSettings.AddTrailingSlash; } } /// @@ -346,20 +188,7 @@ namespace umbraco /// true if umbraco will use ASP.NET MasterPages; otherwise, false. public static bool UseAspNetMasterPages { - get - { - try - { - bool result; - if (bool.TryParse(GetKey("/settings/templates/useAspNetMasterPages"), out result)) - return result; - return false; - } - catch - { - return false; - } - } + get { return Umbraco.Core.Configuration.UmbracoSettings.UseAspNetMasterPages; } } @@ -369,20 +198,7 @@ namespace umbraco /// true if umbraco will override templates with skins if present and configured false. public static bool EnableTemplateFolders { - get - { - try - { - bool result; - if (bool.TryParse(GetKey("/settings/templates/enableTemplateFolders"), out result)) - return result; - return false; - } - catch - { - return false; - } - } + get { return Umbraco.Core.Configuration.UmbracoSettings.EnableTemplateFolders; } } /// @@ -390,79 +206,25 @@ namespace umbraco /// public static List NotDynamicXmlDocumentElements { - get - { - try - { - List items = new List(); - XmlNode root = GetKeyAsNode("/settings/scripting/razor/notDynamicXmlDocumentElements"); - foreach (XmlNode element in root.SelectNodes(".//element")) - { - items.Add(element.InnerText); - } - return items; - } - catch - { - return new List() { "p", "div" }; - } - } + get { return Umbraco.Core.Configuration.UmbracoSettings.NotDynamicXmlDocumentElements.ToList(); } } public static List RazorDataTypeModelStaticMapping { - get - { - if (HttpContext.Current != null && HttpContext.Current.Cache != null && HttpContext.Current.Cache["settings.scripting.razor.dataTypeModelStaticMappings"] != null) - { - return HttpContext.Current.Cache["settings.scripting.razor.dataTypeModelStaticMappings"] as List; - } - /* - - DigibizAdvancedMediaPicker.RazorModel.ModelBinder - DigibizAdvancedMediaPicker.RazorModel.ModelBinder - - */ - List items = new List(); - XmlNode root = GetKeyAsNode("/settings/scripting/razor/dataTypeModelStaticMappings"); - if (root != null) - { - foreach (XmlNode element in root.SelectNodes(".//mapping")) - { - string propertyTypeAlias = null, nodeTypeAlias = null; - Guid? dataTypeGuid = null; - if (!string.IsNullOrEmpty(element.InnerText)) - { - if (element.Attributes["dataTypeGuid"] != null) - { - dataTypeGuid = (Guid?)new Guid(element.Attributes["dataTypeGuid"].Value); - } - if (element.Attributes["propertyTypeAlias"] != null && !string.IsNullOrEmpty(element.Attributes["propertyTypeAlias"].Value)) - { - propertyTypeAlias = element.Attributes["propertyTypeAlias"].Value; - } - if (element.Attributes["nodeTypeAlias"] != null && !string.IsNullOrEmpty(element.Attributes["nodeTypeAlias"].Value)) - { - nodeTypeAlias = element.Attributes["nodeTypeAlias"].Value; - } - items.Add(new RazorDataTypeModelStaticMappingItem() - { - DataTypeGuid = dataTypeGuid, - PropertyTypeAlias = propertyTypeAlias, - NodeTypeAlias = nodeTypeAlias, - TypeName = element.InnerText, - Raw = element.OuterXml - }); - } - } - } - if (HttpContext.Current != null && HttpContext.Current.Cache != null) - { - HttpContext.Current.Cache.Add("settings.scripting.razor.dataTypeModelStaticMappings", items, null, Cache.NoAbsoluteExpiration, new TimeSpan(0, 20, 0), CacheItemPriority.AboveNormal, null); - } - return items; - - } + get + { + var mapping = Umbraco.Core.Configuration.UmbracoSettings.RazorDataTypeModelStaticMapping; + + //now we need to map to the old object until we can clean all this nonsense up + return mapping.Select(x => new RazorDataTypeModelStaticMappingItem() + { + DataTypeGuid = x.DataTypeGuid, + NodeTypeAlias = x.NodeTypeAlias, + PropertyTypeAlias = x.PropertyTypeAlias, + Raw = x.Raw, + TypeName = x.TypeName + }).ToList(); + } } /// @@ -473,20 +235,7 @@ namespace umbraco /// public static bool CloneXmlCacheOnPublish { - get - { - try - { - bool result; - if (bool.TryParse(GetKey("/settings/content/cloneXmlContent"), out result)) - return result; - return false; - } - catch - { - return false; - } - } + get { return Umbraco.Core.Configuration.UmbracoSettings.CloneXmlCacheOnPublish; } } /// @@ -495,7 +244,7 @@ namespace umbraco /// true if content is parsed; otherwise, false. public static bool TidyEditorContent { - get { return bool.Parse(GetKey("/settings/content/TidyEditorContent")); } + get { return Umbraco.Core.Configuration.UmbracoSettings.TidyEditorContent; } } /// @@ -504,15 +253,7 @@ namespace umbraco /// The encoding type as string. public static string TidyCharEncoding { - get - { - string encoding = GetKey("/settings/content/TidyCharEncoding"); - if (String.IsNullOrEmpty(encoding)) - { - encoding = "UTF8"; - } - return encoding; - } + get { return Umbraco.Core.Configuration.UmbracoSettings.TidyCharEncoding; } } /// @@ -521,19 +262,12 @@ namespace umbraco /// The property context help option. public static string PropertyContextHelpOption { - get { return GetKey("/settings/content/PropertyContextHelpOption").ToLower(); } + get { return Umbraco.Core.Configuration.UmbracoSettings.PropertyContextHelpOption; } } public static string DefaultBackofficeProvider { - get - { - string defaultProvider = GetKey("/settings/providers/users/DefaultBackofficeProvider"); - if (String.IsNullOrEmpty(defaultProvider)) - defaultProvider = "UsersMembershipProvider"; - - return defaultProvider; - } + get { return Umbraco.Core.Configuration.UmbracoSettings.DefaultBackofficeProvider; } } /// @@ -541,24 +275,7 @@ namespace umbraco /// public static bool ForceSafeAliases { - get - { - string forceSafeAlias = GetKey("/settings/content/ForceSafeAliases"); - if (String.IsNullOrEmpty(forceSafeAlias)) - return true; - else - { - try - { - return bool.Parse(forceSafeAlias); - } - catch - { - return true; - } - } - - } + get { return Umbraco.Core.Configuration.UmbracoSettings.ForceSafeAliases; } } @@ -568,7 +285,7 @@ namespace umbraco /// The allowed image file types. public static string ImageFileTypes { - get { return GetKey("/settings/content/imaging/imageFileTypes").ToLowerInvariant(); } + get { return Umbraco.Core.Configuration.UmbracoSettings.ImageFileTypes; } } /// @@ -577,7 +294,7 @@ namespace umbraco /// The allowed script file types. public static string ScriptFileTypes { - get { return GetKey("/settings/content/scripteditor/scriptFileTypes"); } + get { return Umbraco.Core.Configuration.UmbracoSettings.ScriptFileTypes; } } /// @@ -586,24 +303,7 @@ namespace umbraco /// public static int UmbracoLibraryCacheDuration { - get - { - string libraryCacheDuration = GetKey("/settings/content/UmbracoLibraryCacheDuration"); - if (String.IsNullOrEmpty(libraryCacheDuration)) - return 1800; - else - { - try - { - return int.Parse(libraryCacheDuration); - } - catch - { - return 1800; - } - } - - } + get { return Umbraco.Core.Configuration.UmbracoSettings.UmbracoLibraryCacheDuration; } } /// @@ -612,7 +312,7 @@ namespace umbraco /// The script folder path. public static string ScriptFolderPath { - get { return GetKey("/settings/content/scripteditor/scriptFolderPath"); } + get { return Umbraco.Core.Configuration.UmbracoSettings.ScriptFolderPath; } } /// @@ -620,14 +320,7 @@ namespace umbraco /// public static bool ScriptDisableEditor { - get - { - string _tempValue = GetKey("/settings/content/scripteditor/scriptDisableEditor"); - if (_tempValue != String.Empty) - return bool.Parse(_tempValue); - else - return false; - } + get { return Umbraco.Core.Configuration.UmbracoSettings.ScriptDisableEditor; } } /// @@ -636,7 +329,7 @@ namespace umbraco /// The graphic headline format. public static string GraphicHeadlineFormat { - get { return GetKey("/settings/content/graphicHeadlineFormat"); } + get { return Umbraco.Core.Configuration.UmbracoSettings.GraphicHeadlineFormat; } } /// @@ -647,17 +340,7 @@ namespace umbraco /// true if umbraco ensures unique node naming; otherwise, false. public static bool EnsureUniqueNaming { - get - { - try - { - return bool.Parse(GetKey("/settings/content/ensureUniqueNaming")); - } - catch - { - return false; - } - } + get { return Umbraco.Core.Configuration.UmbracoSettings.EnsureUniqueNaming; } } /// @@ -666,7 +349,7 @@ namespace umbraco /// The notification email sender. public static string NotificationEmailSender { - get { return GetKey("/settings/content/notifications/email"); } + get { return Umbraco.Core.Configuration.UmbracoSettings.NotificationEmailSender; } } /// @@ -677,14 +360,7 @@ namespace umbraco /// public static bool NotificationDisableHtmlEmail { - get - { - string _tempValue = GetKey("/settings/content/notifications/disableHtmlEmail"); - if (_tempValue != String.Empty) - return bool.Parse(_tempValue); - else - return false; - } + get { return Umbraco.Core.Configuration.UmbracoSettings.NotificationDisableHtmlEmail; } } /// @@ -693,12 +369,12 @@ namespace umbraco /// The allowed attributes on images. public static string ImageAllowedAttributes { - get { return GetKey("/settings/content/imaging/allowedAttributes"); } + get { return Umbraco.Core.Configuration.UmbracoSettings.ImageAllowedAttributes; } } public static XmlNode ImageAutoFillImageProperties { - get { return GetKeyAsNode("/settings/content/imaging/autoFillImageProperties"); } + get { return Umbraco.Core.Configuration.UmbracoSettings.ImageAutoFillImageProperties; } } /// @@ -707,7 +383,7 @@ namespace umbraco /// The scheduled tasks. public static XmlNode ScheduledTasks { - get { return GetKeyAsNode("/settings/scheduledTasks"); } + get { return Umbraco.Core.Configuration.UmbracoSettings.ScheduledTasks; } } /// @@ -716,7 +392,7 @@ namespace umbraco /// The URL replacement characters. public static XmlNode UrlReplaceCharacters { - get { return GetKeyAsNode("/settings/requestHandler/urlReplacing"); } + get { return Umbraco.Core.Configuration.UmbracoSettings.UrlReplaceCharacters; } } /// @@ -724,17 +400,7 @@ namespace umbraco /// public static bool RemoveDoubleDashesFromUrlReplacing { - get - { - try - { - return bool.Parse(UrlReplaceCharacters.Attributes.GetNamedItem("removeDoubleDashes").Value); - } - catch - { - return false; - } - } + get { return Umbraco.Core.Configuration.UmbracoSettings.RemoveDoubleDashesFromUrlReplacing; } } /// @@ -745,17 +411,7 @@ namespace umbraco /// true if umbraco uses distributed calls; otherwise, false. public static bool UseDistributedCalls { - get - { - try - { - return bool.Parse(GetKeyAsNode("/settings/distributedCall").Attributes.GetNamedItem("enable").Value); - } - catch - { - return false; - } - } + get { return Umbraco.Core.Configuration.UmbracoSettings.UseDistributedCalls; } } @@ -765,17 +421,7 @@ namespace umbraco /// The distributed call user. public static int DistributedCallUser { - get - { - try - { - return int.Parse(GetKey("/settings/distributedCall/user")); - } - catch - { - return -1; - } - } + get { return Umbraco.Core.Configuration.UmbracoSettings.DistributedCallUser; } } /// @@ -783,17 +429,7 @@ namespace umbraco /// public static string PreviewBadge { - get - { - try - { - return GetKey("/settings/content/PreviewBadge"); - } - catch - { - return "In Preview Mode - click to end"; - } - } + get { return Umbraco.Core.Configuration.UmbracoSettings.PreviewBadge; } } /// @@ -804,17 +440,7 @@ namespace umbraco /// The distribution servers. public static XmlNode DistributionServers { - get - { - try - { - return GetKeyAsNode("/settings/distributedCall/servers"); - } - catch - { - return null; - } - } + get { return Umbraco.Core.Configuration.UmbracoSettings.DistributionServers; } } /// @@ -824,17 +450,7 @@ namespace umbraco /// public static XmlNode HelpPages { - get - { - try - { - return GetKeyAsNode("/settings/help"); - } - catch - { - return null; - } - } + get { return Umbraco.Core.Configuration.UmbracoSettings.HelpPages; } } /// @@ -846,17 +462,7 @@ namespace umbraco /// The repository servers. public static XmlNode Repositories { - get - { - try - { - return GetKeyAsNode("/settings/repositories"); - } - catch - { - return null; - } - } + get { return Umbraco.Core.Configuration.UmbracoSettings.Repositories; } } /// @@ -869,19 +475,7 @@ namespace umbraco /// public static bool UseViewstateMoverModule { - get - { - try - { - return - bool.Parse( - GetKeyAsNode("/settings/viewstateMoverModule").Attributes.GetNamedItem("enable").Value); - } - catch - { - return false; - } - } + get { return Umbraco.Core.Configuration.UmbracoSettings.UseViewstateMoverModule; } } @@ -891,22 +485,7 @@ namespace umbraco /// public static bool isXmlContentCacheDisabled { - get - { - try - { - bool xmlCacheEnabled; - string value = GetKey("/settings/content/XmlCacheEnabled"); - if (bool.TryParse(value, out xmlCacheEnabled)) - return !xmlCacheEnabled; - // Return default - return false; - } - catch - { - return false; - } - } + get { return Umbraco.Core.Configuration.UmbracoSettings.IsXmlContentCacheDisabled; } } /// @@ -916,22 +495,7 @@ namespace umbraco /// public static bool XmlContentCheckForDiskChanges { - get - { - try - { - bool checkForDiskChanges; - string value = GetKey("/settings/content/XmlContentCheckForDiskChanges"); - if (bool.TryParse(value, out checkForDiskChanges)) - return checkForDiskChanges; - // Return default - return false; - } - catch - { - return false; - } - } + get { return Umbraco.Core.Configuration.UmbracoSettings.XmlContentCheckForDiskChanges; } } /// @@ -941,22 +505,7 @@ namespace umbraco /// public static bool EnableGlobalPreviewStorage { - get - { - try - { - bool globalPreviewEnabled = false; - string value = GetKey("/settings/content/GlobalPreviewStorageEnabled"); - if (bool.TryParse(value, out globalPreviewEnabled)) - return !globalPreviewEnabled; - // Return default - return false; - } - catch - { - return false; - } - } + get { return Umbraco.Core.Configuration.UmbracoSettings.EnableGlobalPreviewStorage; } } /// @@ -967,32 +516,18 @@ namespace umbraco /// public static bool UseLegacyXmlSchema { - get - { - string value = GetKey("/settings/content/UseLegacyXmlSchema"); - bool result; - if (!string.IsNullOrEmpty(value) && bool.TryParse(value, out result)) - return result; - return true; - } + get { return Umbraco.Core.Configuration.UmbracoSettings.UseLegacyXmlSchema; } } + public static IEnumerable AppCodeFileExtensionsList + { + get { return Umbraco.Core.Configuration.UmbracoSettings.AppCodeFileExtensionsList; } + } + + [Obsolete("Use AppCodeFileExtensionsList instead")] public static XmlNode AppCodeFileExtensions { - get - { - XmlNode value = GetKeyAsNode("/settings/developer/appCodeFileExtensions"); - if (value != null) - { - return value; - } - - // default is .cs and .vb - value = _umbracoSettings.CreateElement("appCodeFileExtensions"); - value.AppendChild(xmlHelper.addTextNode(_umbracoSettings, "ext", "cs")); - value.AppendChild(xmlHelper.addTextNode(_umbracoSettings, "ext", "vb")); - return value; - } + get { return Umbraco.Core.Configuration.UmbracoSettings.AppCodeFileExtensions; } } /// @@ -1001,22 +536,7 @@ namespace umbraco /// public static bool continouslyUpdateXmlDiskCache { - get - { - try - { - bool updateDiskCache; - string value = GetKey("/settings/content/ContinouslyUpdateXmlDiskCache"); - if (bool.TryParse(value, out updateDiskCache)) - return updateDiskCache; - // Return default - return false; - } - catch - { - return true; - } - } + get { return Umbraco.Core.Configuration.UmbracoSettings.ContinouslyUpdateXmlDiskCache; } } /// @@ -1027,50 +547,12 @@ namespace umbraco /// public static bool EnableSplashWhileLoading { - get - { - try - { - bool updateDiskCache; - string value = GetKey("/settings/content/EnableSplashWhileLoading"); - if (bool.TryParse(value, out updateDiskCache)) - return updateDiskCache; - // Return default - return false; - } - catch - { - return false; - } - } + get { return Umbraco.Core.Configuration.UmbracoSettings.EnableSplashWhileLoading; } } - private static bool? _resolveUrlsFromTextString; public static bool ResolveUrlsFromTextString { - get - { - if (_resolveUrlsFromTextString == null) - { - try - { - bool enableDictionaryFallBack; - var value = GetKey("/settings/content/ResolveUrlsFromTextString"); - if (value != null) - if (bool.TryParse(value, out enableDictionaryFallBack)) - _resolveUrlsFromTextString = enableDictionaryFallBack; - } - catch (Exception ex) - { - Trace.WriteLine("Could not load /settings/content/ResolveUrlsFromTextString from umbracosettings.config:\r\n {0}", - ex.Message); - - // set url resolving to true (default (legacy) behavior) to ensure we don't keep writing to trace - _resolveUrlsFromTextString = true; - } - } - return _resolveUrlsFromTextString == true; - } + get { return Umbraco.Core.Configuration.UmbracoSettings.ResolveUrlsFromTextString; } } /// @@ -1085,18 +567,7 @@ namespace umbraco /// true if enabled; otherwise, false. public static bool Enabled { - get - { - try - { - return - bool.Parse(GetKeyAsNode("/settings/webservices").Attributes.GetNamedItem("enabled").Value); - } - catch - { - return false; - } - } + get { return Umbraco.Core.Configuration.UmbracoSettings.WebServices.Enabled; } } #region "Webservice configuration" @@ -1107,17 +578,7 @@ namespace umbraco /// The document service users. public static string[] documentServiceUsers { - get - { - try - { - return GetKey("/settings/webservices/documentServiceUsers").Split(','); - } - catch - { - return new string[0]; - } - } + get { return Umbraco.Core.Configuration.UmbracoSettings.WebServices.DocumentServiceUsers; } } /// @@ -1126,17 +587,7 @@ namespace umbraco /// The file service users. public static string[] fileServiceUsers { - get - { - try - { - return GetKey("/settings/webservices/fileServiceUsers").Split(','); - } - catch - { - return new string[0]; - } - } + get { return Umbraco.Core.Configuration.UmbracoSettings.WebServices.FileServiceUsers; } } @@ -1146,17 +597,7 @@ namespace umbraco /// The file service folders. public static string[] fileServiceFolders { - get - { - try - { - return GetKey("/settings/webservices/fileServiceFolders").Split(','); - } - catch - { - return new string[0]; - } - } + get { return Umbraco.Core.Configuration.UmbracoSettings.WebServices.FileServiceFolders; } } /// @@ -1165,17 +606,7 @@ namespace umbraco /// The member service users. public static string[] memberServiceUsers { - get - { - try - { - return GetKey("/settings/webservices/memberServiceUsers").Split(','); - } - catch - { - return new string[0]; - } - } + get { return Umbraco.Core.Configuration.UmbracoSettings.WebServices.MemberServiceUsers; } } /// @@ -1184,17 +615,7 @@ namespace umbraco /// The stylesheet service users. public static string[] stylesheetServiceUsers { - get - { - try - { - return GetKey("/settings/webservices/stylesheetServiceUsers").Split(','); - } - catch - { - return new string[0]; - } - } + get { return Umbraco.Core.Configuration.UmbracoSettings.WebServices.StylesheetServiceUsers; } } /// @@ -1203,17 +624,7 @@ namespace umbraco /// The template service users. public static string[] templateServiceUsers { - get - { - try - { - return GetKey("/settings/webservices/templateServiceUsers").Split(','); - } - catch - { - return new string[0]; - } - } + get { return Umbraco.Core.Configuration.UmbracoSettings.WebServices.TemplateServiceUsers; } } /// @@ -1222,17 +633,7 @@ namespace umbraco /// The media service users. public static string[] mediaServiceUsers { - get - { - try - { - return GetKey("/settings/webservices/mediaServiceUsers").Split(','); - } - catch - { - return new string[0]; - } - } + get { return Umbraco.Core.Configuration.UmbracoSettings.WebServices.MediaServiceUsers; } } @@ -1242,17 +643,7 @@ namespace umbraco /// The maintenance service users. public static string[] maintenanceServiceUsers { - get - { - try - { - return GetKey("/settings/webservices/maintenanceServiceUsers").Split(','); - } - catch - { - return new string[0]; - } - } + get { return Umbraco.Core.Configuration.UmbracoSettings.WebServices.MaintenanceServiceUsers; } } #endregion diff --git a/src/umbraco.businesslogic/umbraco.businesslogic.csproj b/src/umbraco.businesslogic/umbraco.businesslogic.csproj index b4bfe1530c..7950351e24 100644 --- a/src/umbraco.businesslogic/umbraco.businesslogic.csproj +++ b/src/umbraco.businesslogic/umbraco.businesslogic.csproj @@ -119,6 +119,10 @@ System.XML + + {31785BC3-256C-4613-B2F5-A1B0BDDED8C1} + Umbraco.Core + {C7CB79F0-1C97-4B33-BFA7-00731B579AE2} umbraco.datalayer diff --git a/src/umbraco.businesslogic/xmlHelper.cs b/src/umbraco.businesslogic/xmlHelper.cs index 3fafbbaf65..5eb07b5309 100644 --- a/src/umbraco.businesslogic/xmlHelper.cs +++ b/src/umbraco.businesslogic/xmlHelper.cs @@ -7,6 +7,7 @@ namespace umbraco /// /// The xmlHelper class contains general helper methods for working with xml in umbraco. /// + [Obsolete("Use Umbraco.Core.XmlHelper instead")] public class xmlHelper { /// @@ -17,8 +18,7 @@ namespace umbraco /// public static XmlNode ImportXmlNodeFromText(string text, ref XmlDocument xmlDoc) { - xmlDoc.LoadXml(text); - return xmlDoc.FirstChild; + return Umbraco.Core.XmlHelper.ImportXmlNodeFromText(text, ref xmlDoc); } /// @@ -28,17 +28,7 @@ namespace umbraco /// Returns a XmlDocument class public static XmlDocument OpenAsXmlDocument(string filePath) { - - XmlTextReader reader = new XmlTextReader(IOHelper.MapPath(filePath)); - - reader.WhitespaceHandling = WhitespaceHandling.All; - XmlDocument xmlDoc = new XmlDocument(); - //Load the file into the XmlDocument - xmlDoc.Load(reader); - //Close off the connection to the file. - reader.Close(); - - return xmlDoc; + return Umbraco.Core.XmlHelper.OpenAsXmlDocument(filePath); } /// @@ -50,9 +40,7 @@ namespace umbraco /// a XmlAttribute public static XmlAttribute addAttribute(XmlDocument Xd, string Name, string Value) { - XmlAttribute temp = Xd.CreateAttribute(Name); - temp.Value = Value; - return temp; + return Umbraco.Core.XmlHelper.AddAttribute(Xd, Name, Value); } /// @@ -64,9 +52,7 @@ namespace umbraco /// a XmlNode public static XmlNode addTextNode(XmlDocument Xd, string Name, string Value) { - XmlNode temp = Xd.CreateNode(XmlNodeType.Element, Name, ""); - temp.AppendChild(Xd.CreateTextNode(Value)); - return temp; + return Umbraco.Core.XmlHelper.AddTextNode(Xd, Name, Value); } /// @@ -78,9 +64,7 @@ namespace umbraco /// A XmlNode public static XmlNode addCDataNode(XmlDocument Xd, string Name, string Value) { - XmlNode temp = Xd.CreateNode(XmlNodeType.Element, Name, ""); - temp.AppendChild(Xd.CreateCDataSection(Value)); - return temp; + return Umbraco.Core.XmlHelper.AddCDataNode(Xd, Name, Value); } /// @@ -90,18 +74,7 @@ namespace umbraco /// the value as a string public static string GetNodeValue(XmlNode n) { - string value = string.Empty; - if (n == null || n.FirstChild == null) - return value; - if (n.FirstChild.Value != null) - { - value = n.FirstChild.Value; - } - else - { - value = n.InnerXml; - } - return value.Replace("", "", "]]>"); + return Umbraco.Core.XmlHelper.GetNodeValue(n); } /// @@ -113,17 +86,7 @@ namespace umbraco /// public static bool CouldItBeXml(string xml) { - if (!string.IsNullOrEmpty(xml)) - { - xml = xml.Trim(); - - if (xml.StartsWith("<") && xml.EndsWith(">")) - { - return true; - } - } - - return false; + return Umbraco.Core.XmlHelper.CouldItBeXml(xml); } /// @@ -136,7 +99,7 @@ namespace umbraco /// Returns an System.Xml.XmlDocument representation of the delimited string data. public static XmlDocument Split(string data, string[] separator, string rootName, string elementName) { - return Split(new XmlDocument(), data, separator, rootName, elementName); + return Umbraco.Core.XmlHelper.Split(data, separator, rootName, elementName); } /// @@ -150,26 +113,7 @@ namespace umbraco /// Returns an System.Xml.XmlDocument representation of the delimited string data. public static XmlDocument Split(XmlDocument xml, string data, string[] separator, string rootName, string elementName) { - // load new XML document. - xml.LoadXml(string.Concat("<", rootName, "/>")); - - // get the data-value, check it isn't empty. - if (!string.IsNullOrEmpty(data)) - { - // explode the values into an array - var values = data.Split(separator, StringSplitOptions.None); - - // loop through the array items. - foreach (string value in values) - { - // add each value to the XML document. - var xn = xmlHelper.addTextNode(xml, elementName, value); - xml.DocumentElement.AppendChild(xn); - } - } - - // return the XML node. - return xml; + return Umbraco.Core.XmlHelper.Split(xml, data, separator, rootName, elementName); } } } diff --git a/src/umbraco.cms/businesslogic/Content.cs b/src/umbraco.cms/businesslogic/Content.cs index f404a06772..9bb9204dd7 100644 --- a/src/umbraco.cms/businesslogic/Content.cs +++ b/src/umbraco.cms/businesslogic/Content.cs @@ -581,7 +581,7 @@ namespace umbraco.cms.businesslogic { if (p.PropertyType.DataTypeDefinition.DataType.Id == uploadField.Id && p.Value.ToString() != "" - && File.Exists(IOHelper.MapPath(p.Value.ToString()))) + && File.Exists(Umbraco.Core.IO.IOHelper.MapPath(p.Value.ToString()))) { isUploadField = true; } diff --git a/src/umbraco.editorControls/tinyMCE3/webcontrol/TinyMCEWebControl.cs b/src/umbraco.editorControls/tinyMCE3/webcontrol/TinyMCEWebControl.cs index 94b076c208..fb77c1b85f 100644 --- a/src/umbraco.editorControls/tinyMCE3/webcontrol/TinyMCEWebControl.cs +++ b/src/umbraco.editorControls/tinyMCE3/webcontrol/TinyMCEWebControl.cs @@ -73,7 +73,7 @@ namespace umbraco.editorControls.tinyMCE3.webcontrol base.Attributes.Add("style", "visibility: hidden"); config.Add("mode", "exact"); config.Add("theme", "umbraco"); - config.Add("umbraco_path", IOHelper.ResolveUrl(SystemDirectories.Umbraco)); + config.Add("umbraco_path", Umbraco.Core.IO.IOHelper.ResolveUrl(Umbraco.Core.IO.SystemDirectories.Umbraco)); CssClass = "tinymceContainer"; plugin.ConfigSection configSection = (plugin.ConfigSection)System.Web.HttpContext.Current.GetSection("TinyMCE"); @@ -218,8 +218,8 @@ namespace umbraco.editorControls.tinyMCE3.webcontrol suffix = "_" + this.mode; outURI = this.InstallPath + "/tiny_mce_src" + suffix + ".js"; - if (!File.Exists(IOHelper.MapPath(outURI))) - throw new Exception("Could not locate TinyMCE by URI:" + outURI + ", Physical path:" + IOHelper.MapPath(outURI) + ". Make sure that you configured the installPath to a valid location in your web.config. This path should be an relative or site absolute URI to where TinyMCE is located."); + if (!File.Exists(Umbraco.Core.IO.IOHelper.MapPath(outURI))) + throw new Exception("Could not locate TinyMCE by URI:" + outURI + ", Physical path:" + Umbraco.Core.IO.IOHelper.MapPath(outURI) + ". Make sure that you configured the installPath to a valid location in your web.config. This path should be an relative or site absolute URI to where TinyMCE is located."); // Collect themes, languages and plugins and build gzip URI // TODO: Make sure gzip is re-enabled @@ -332,7 +332,7 @@ namespace umbraco.editorControls.tinyMCE3.webcontrol // Find the original filename, by removing the might added width and height // NH, 4.8.1 - above replaced by loading the right media file from the db later! orgSrc = - IOHelper.ResolveUrl(orgSrc.Replace("%20", " ")); + Umbraco.Core.IO.IOHelper.ResolveUrl(orgSrc.Replace("%20", " ")); // Check for either id or guid from media string mediaId = getIdFromSource(orgSrc, rootMediaUrl); @@ -364,7 +364,7 @@ namespace umbraco.editorControls.tinyMCE3.webcontrol // Format the tag tempTag = tempTag + " rel=\"" + imageMedia.getProperty("umbracoWidth").Value.ToString() + "," + - imageMedia.getProperty("umbracoHeight").Value.ToString() + "\" src=\"" + IOHelper.ResolveUrl(imageMedia.getProperty("umbracoFile").Value.ToString()) + + imageMedia.getProperty("umbracoHeight").Value.ToString() + "\" src=\"" + Umbraco.Core.IO.IOHelper.ResolveUrl(imageMedia.getProperty("umbracoFile").Value.ToString()) + "\""; tempTag += "/>"; diff --git a/src/umbraco.editorControls/tinymce/tinyMCEImageHelper.cs b/src/umbraco.editorControls/tinymce/tinyMCEImageHelper.cs index f4e31e55bd..79219c0f10 100644 --- a/src/umbraco.editorControls/tinymce/tinyMCEImageHelper.cs +++ b/src/umbraco.editorControls/tinymce/tinyMCEImageHelper.cs @@ -122,7 +122,7 @@ namespace umbraco.editorControls.tinymce { string src = helper.FindAttribute(ht, "src"); //get the media folder, minus the starting '~' - string mediaRoot = SystemDirectories.Media.Replace("~", string.Empty); + string mediaRoot = Umbraco.Core.IO.SystemDirectories.Media.Replace("~", string.Empty); // update orgSrc to remove umbraco reference int mediaRootIndex = src.IndexOf(mediaRoot); diff --git a/src/umbraco.webservices/media/mediaService.cs b/src/umbraco.webservices/media/mediaService.cs index d9fc7df114..fcd4df1399 100644 --- a/src/umbraco.webservices/media/mediaService.cs +++ b/src/umbraco.webservices/media/mediaService.cs @@ -122,9 +122,9 @@ namespace umbraco.webservices.media { Authenticate(username, password); - filename = filename.Replace("/", IOHelper.DirSepChar.ToString()); - filename = filename.Replace(@"\", IOHelper.DirSepChar.ToString()); - filename = filename.Substring(filename.LastIndexOf(IOHelper.DirSepChar) + 1, filename.Length - filename.LastIndexOf(IOHelper.DirSepChar) - 1).ToLower(); + filename = filename.Replace("/", Umbraco.Core.IO.IOHelper.DirSepChar.ToString()); + filename = filename.Replace(@"\", Umbraco.Core.IO.IOHelper.DirSepChar.ToString()); + filename = filename.Substring(filename.LastIndexOf(Umbraco.Core.IO.IOHelper.DirSepChar) + 1, filename.Length - filename.LastIndexOf(Umbraco.Core.IO.IOHelper.DirSepChar) - 1).ToLower(); Media m = new Media(id);