Esempio n. 1
0
        public static string IncrementNameSuffixToLastName(string currentName, int parentNodeId)
        {
            currentName = RepositoryPath.GetFileName(currentName);
            var    ext = Path.GetExtension(currentName);
            string nameBase;
            bool   inValidNumber;
            var    fileName = Path.GetFileNameWithoutExtension(currentName);

            ContentNamingHelper.ParseSuffix(fileName, out nameBase, out inValidNumber);
            var lastName = DataProvider.Current.GetNameOfLastNodeWithNameBase(parentNodeId, nameBase, ext);

            // if there is no suffixed name in db, return with first variant
            if (lastName == null)
            {
                return(String.Format("{0}(1){1}", nameBase, ext));
            }

            // there was a suffixed name in db in the form namebase(x), increment it
            // car(5)-> car(6), car(test)(5) -> car(test)(6), car(test) -> car(guid)
            string newNameBase;
            var    newName = ContentNamingHelper.IncrementNameSuffix(lastName, out newNameBase);

            // incremented name base differs from original name base (for example 'car(hello)(2)' and 'car(5)')
            // edge case, use guid with original namebase
            if (newNameBase != nameBase)
            {
                return(String.Format("{0}({1}){2}", nameBase, Guid.NewGuid().ToString(), ext));
            }

            // incremented name base and original name base are equal, so incremented name is correct (eg 'car(2)')
            return(newName);
        }
        protected async Task <Content> EnsureContentAsync(string path, string typeName, Action <Content> setProperties)
        {
            var content = await Content.LoadAsync(path);

            if (content == null)
            {
                var parentPath = RepositoryPath.GetParentPath(path);
                var name       = RepositoryPath.GetFileName(path);
                content = Content.CreateNew(parentPath, typeName, name);
                if (setProperties == null)
                {
                    await content.SaveAsync();

                    return(content);
                }
            }

            if (setProperties != null)
            {
                setProperties(content);
                await content.SaveAsync();
            }

            return(content);
        }
Esempio n. 3
0
        public void HandleMethod()
        {
            var parentPath = RepositoryPath.GetParentPath(_handler.GlobalPath);
            var folderName = RepositoryPath.GetFileName(_handler.GlobalPath);

            WebDavProvider.Current.AssertCreateContent(parentPath, folderName, "Folder");

            try
            {
                var f = new Folder(Node.LoadNode(parentPath))
                {
                    Name = folderName
                };
                f.Save();

                _handler.Context.Response.StatusCode = 201;
            }
            catch (System.Security.SecurityException e) //logged
            {
                Logger.WriteException(e);
                _handler.Context.Response.StatusCode = 403;
            }
            catch (ContentRepository.Storage.Security.SecurityException ee) //logged
            {
                Logger.WriteException(ee);
                _handler.Context.Response.StatusCode = 403;
            }
            catch (Exception eee) //logged
            {
                Logger.WriteError(Portal.EventId.WebDav.FolderError, "Could not save folder. Error: " + eee.Message, properties: new Dictionary <string, object> {
                    { "Parent path", parentPath }, { "Folder name", folderName }
                });
                _handler.Context.Response.StatusCode = 405;
            }
        }
Esempio n. 4
0
        /* ===================================================================================== TOOLS */

        public byte[] GetBlobBytes(string repositoryPath, string propertyTypeName = null)
        {
            string fileContent;

            if (repositoryPath.StartsWith("/Root/System/Schema/ContentTypes/", StringComparison.OrdinalIgnoreCase))
            {
                var ctdName = RepositoryPath.GetFileName(repositoryPath);
                ContentTypeDefinitions.TryGetValue(ctdName, out fileContent);
            }
            else
            {
                var key = $"{propertyTypeName ?? "Binary"}:{repositoryPath}";
                Blobs.TryGetValue(key, out fileContent);
            }
            if (fileContent == null)
            {
                return(Array.Empty <byte>());
            }

            if (GetAndRemoveHeader(ref fileContent) == "[bytes]")
            {
                // bytes
                return(ParseHexDump(fileContent));
            }

            // text
            var byteCount = Encoding.UTF8.GetByteCount(fileContent);
            var bom       = Encoding.UTF8.GetPreamble();
            var bytes     = new byte[bom.Length + byteCount];

            bom.CopyTo(bytes, 0);
            Encoding.UTF8.GetBytes(fileContent, 0, fileContent.Length, bytes, bom.Length);

            return(bytes);
        }
Esempio n. 5
0
        //===========================================================================================================

        public void HandleMethod()
        {
            var parentPath = RepositoryPath.GetParentPath(_handler.GlobalPath);
            var fileName   = RepositoryPath.GetFileName(_handler.GlobalPath);
            var parentNode = Node.LoadNode(parentPath);
            var node       = Node.LoadNode(_handler.GlobalPath);

            switch (_handler.WebdavType)
            {
            case WebdavType.File:
            case WebdavType.Folder:
            case WebdavType.Page:
                if (node == null || node is IFile)
                {
                    HandleFile(parentPath, fileName, parentNode, node);
                }
                return;

            case WebdavType.Content:
                HandleContent(parentPath, fileName, parentNode, node);
                return;

            case WebdavType.ContentType:
                InstallContentType();
                return;

            default:
                throw new NotImplementedException("Unknown WebdavType" + _handler.WebdavType);
            }
        }
Esempio n. 6
0
        /* ===================================================================================== TOOLS */

        public byte[] GetBlobBytes(string repositoryPath, string propertyTypeName = null)
        {
            string fileContent = null;

            if (repositoryPath.StartsWith("/Root/System/Schema/ContentTypes/", StringComparison.OrdinalIgnoreCase))
            {
                var ctdName = RepositoryPath.GetFileName(repositoryPath);
                ContentTypeDefinitions.TryGetValue(ctdName, out fileContent);
            }
            else
            {
                var key = $"{propertyTypeName}:{repositoryPath}";
                Blobs.TryGetValue(key, out fileContent);
            }
            if (fileContent == null)
            {
                return(new byte[0]);
            }

            var byteCount = Encoding.UTF8.GetByteCount(fileContent);
            var bom       = Encoding.UTF8.GetPreamble();
            var bytes     = new byte[bom.Length + byteCount];

            bom.CopyTo(bytes, 0);
            Encoding.UTF8.GetBytes(fileContent, 0, fileContent.Length, bytes, bom.Length);

            return(bytes);
        }
Esempio n. 7
0
        public void HandleMethod()
        {
            var parentPath = RepositoryPath.GetParentPath(_handler.GlobalPath);
            var folderName = RepositoryPath.GetFileName(_handler.GlobalPath);

            try
            {
                var f = new Folder(Node.LoadNode(parentPath))
                {
                    Name = folderName
                };
                f.Save();

                _handler.Context.Response.StatusCode = 201;
            }
            catch (SecurityException e) //logged
            {
                Logger.WriteException(e);
                _handler.Context.Response.StatusCode = 403;
            }
            catch (SenseNetSecurityException ee) //logged
            {
                Logger.WriteException(ee);
                _handler.Context.Response.StatusCode = 403;
            }
            catch (Exception eee) //logged
            {
                Logger.WriteException(eee);
                _handler.Context.Response.StatusCode = 405;
            }
            _handler.Context.Response.Flush();
        }
Esempio n. 8
0
        private void EnsureNode(SystemFolder testRoot, string relativePath)
        {
            string path = DecodePath(testRoot, relativePath);

            if (Node.Exists(path))
            {
                return;
            }

            string name       = RepositoryPath.GetFileName(path);
            string parentPath = RepositoryPath.GetParentPath(path);

            EnsureNode(testRoot, parentPath);

            switch (name)
            {
            case "ContentList":
            case "SourceContentList":
                CreateContentList(parentPath, name, _listDef1);
                break;

            case "TargetContentList":
                CreateContentList(parentPath, name, _listDef2);
                break;

            case "Folder":
            case "Folder1":
            case "Folder2":
            case "SourceFolder":
            case "SourceItemFolder":
            case "SourceItemFolder1":
            case "SourceItemFolder2":
            case "TargetFolder":
            case "TargetFolder1":
            case "TargetFolder2":
            case "TargetItemFolder":
                CreateNode(parentPath, name, "Folder");
                break;

            case "(apps)":
            case "SystemFolder":
            case "SystemFolder1":
            case "SystemFolder2":
            case "SystemFolder3":
                CreateNode(parentPath, name, "SystemFolder");
                break;

            case "SourceContentListItem":
                CreateContentListItem(parentPath, name, "Car");
                break;

            case "SourceNode":
                CreateNode(parentPath, name, "Car");
                break;

            default:
                CreateNode(parentPath, name, "Car");
                break;
            }
        }
Esempio n. 9
0
        internal static int EnsureNode(string path)
        {
            if (Node.Exists(path))
            {
                return(-1);
            }

            var name       = RepositoryPath.GetFileName(path);
            var parentPath = RepositoryPath.GetParentPath(path);

            EnsureNode(parentPath);

            var type = GetLeadingChars(name);

            if (ContentType.GetByName(type) == null)
            {
                throw new InvalidOperationException(String.Concat(type + " type doesn't exist!"));
            }

            switch (type)
            {
            default:
                CreateNode(parentPath, name, type);
                break;
            }

            var node = Node.LoadNode(path);

            return(node.Id);
        }
Esempio n. 10
0
        internal void ProcessCurrent()
        {
            if (_handler.Path == string.Empty)
            {
                ProcessRoot();
                return;
            }

            var node = Node.LoadNode(_handler.GlobalPath);

            if (node == null)
            {
                var parentPath  = RepositoryPath.GetParentPath(_handler.GlobalPath);
                var currentName = RepositoryPath.GetFileName(_handler.GlobalPath);

                node = Node.LoadNode(parentPath);

                var binaryPropertyName = string.Empty;
                var foundNode          = WebDavHandler.GetNodeByBinaryName(node, currentName, out binaryPropertyName);

                if (foundNode != null)
                {
                    node = foundNode;
                }
                else
                {
                    //content type check
                    //LATER: CTD handling
                    //var parentIsContentType = (node != null && node is ContentType);

                    //if (!parentIsContentType)
                    //{

                    // desktop.ini, thumbs.db, and other files that are not present are mocked instead of returning 404
                    if ((Config.MockExistingFiles != null) && (Config.MockExistingFiles.Contains(currentName)))
                    {
                        _writer = Common.GetXmlWriter();
                        _writer.WriteStartElement(XmlNS.DAV_Prefix, "multistatus", XmlNS.DAV);
                        _writer.WriteEndElement(); // multistatus

                        _handler.Context.Response.Flush();
                        return;
                    }
                    _handler.Context.Response.StatusCode = 404;
                    _handler.Context.Response.Flush();
                    return;
                    //}

                    // parent is contenttype, continue operation on parent (foldernode's name is valid CTD name)
                }
            }

            _writer = Common.GetXmlWriter();
            _writer.WriteStartElement(XmlNS.DAV_Prefix, "multistatus", XmlNS.DAV);

            WriteItem(node);

            _writer.WriteEndElement(); // multistatus
        }
Esempio n. 11
0
 /// <summary>
 /// Returns an OData path that can request the entity identified by the given path. This path is part of the OData entity request. For example
 /// "/Root/MyFolder/MyDocument.doc" will be transformed to "/Root/MyFolder('MyDocument.doc')"
 /// </summary>
 /// <param name="path">This path will be transformed</param>
 /// <returns>An OData path.</returns>
 public static string GetODataPath(string path)
 {
     if (String.Compare(path, Repository.Root.Path, true) == 0)
     {
         return(string.Empty);
     }
     return(GetODataPath(RepositoryPath.GetParentPath(path), RepositoryPath.GetFileName(path)));
 }
Esempio n. 12
0
        /// <summary>
        /// Returns an OData path that can request the entity identified by the given path. This path is part of the OData entity request. For example
        /// "/Root/MyFolder/MyDocument.doc" will be transformed to "/Root/MyFolder('MyDocument.doc')"
        /// </summary>
        /// <param name="path">This path will be transformed.</param>
        /// <returns>An OData path.</returns>
        public static string GetODataPath(string path)
        {
            if (string.Compare(path, Identifiers.RootPath, StringComparison.OrdinalIgnoreCase) == 0)
            {
                return(string.Empty);
            }

            return(GetODataPath(RepositoryPath.GetParentPath(path), RepositoryPath.GetFileName(path)));
        }
Esempio n. 13
0
        private Exception GetUniqueUserException(string domainPath)
        {
            var message = string.Format(SR.GetString(SR.Exceptions.User.Error_NonUnique),
                                        RepositoryPath.GetFileName(domainPath.TrimEnd(RepositoryPath.PathSeparator[0])),
                                        Name,
                                        LoginName);

            return(new InvalidOperationException(message));
        }
Esempio n. 14
0
        public void HandleMethod()
        {
            var node = Node.LoadNode(_handler.GlobalPath);
            var binaryPropertyName = "Binary";

            if (node == null)
            {
                var parentPath  = RepositoryPath.GetParentPath(_handler.GlobalPath);
                var currentName = RepositoryPath.GetFileName(_handler.GlobalPath);

                node = Node.LoadNode(parentPath);

                var foundNode = WebDavHandler.GetNodeByBinaryName(node, currentName, out binaryPropertyName);

                if (foundNode != null)
                {
                    node = foundNode;
                }
                else
                {
                    binaryPropertyName = "Binary";

                    // check if parent is contenttype
                    //(contenttypes are listed under their own folder, so the node exists only virtually)
                    var parentIsContentType = (node != null && node is ContentType);

                    if (!parentIsContentType)
                    {
                        _handler.Context.Response.StatusCode = 404;
                        _handler.Context.Response.Flush();
                    }

                    // parent is contenttype, continue operation on parent (foldernode's name is valid CTD name)
                }
            }

            // load specific version
            if (node != null && !string.IsNullOrEmpty(PortalContext.Current.VersionRequest))
            {
                VersionNumber version;
                if (VersionNumber.TryParse(PortalContext.Current.VersionRequest, out version))
                {
                    var nodeVersion = Node.LoadNode(node.Id, version);
                    if (nodeVersion != null && nodeVersion.SavingState == ContentSavingState.Finalized)
                    {
                        node = nodeVersion;
                    }
                }
            }

            ConverterPattern.DoTransform(node, _handler, binaryPropertyName);
            _handler.Context.Response.Flush();

            return;
        }
Esempio n. 15
0
        internal static string GetAttachmentName(Node node, string propertyName)
        {
            var binaryName = RepositoryPath.GetFileName(System.IO.Path.GetFileName(((BinaryData)node[propertyName]).FileName));

            if (string.IsNullOrEmpty(binaryName) || binaryName.StartsWith("."))
            {
                binaryName = node.Name + binaryName;
            }

            return(binaryName);
        }
Esempio n. 16
0
 public string GetFileName(string path)
 {
     if (path.Contains("\\"))
     {
         return(Path.GetFileName(path));
     }
     else
     {
         return(RepositoryPath.GetFileName(path));
     }
 }
Esempio n. 17
0
        protected override void OnModified(object sender, NodeEventArgs e)
        {
            base.OnModified(sender, e);

            var oldName = RepositoryPath.GetFileName(e.OriginalSourcePath);

            if (oldName.CompareTo(e.SourceNode.Name) != 0 || this.DisplayName.CompareTo(_oldDisplayName) != 0)
            {
                WikiTools.RefreshArticlesAsync(this, oldName, _oldDisplayName);
            }
        }
Esempio n. 18
0
        public static void EnsurePath(string path)
        {
            if (!Node.Exists(path))
            {
                var parentPath = RepositoryPath.GetParentPath(path);
                EnsurePath(parentPath);
                Folder folder = new Folder(Node.LoadNode(parentPath));

                folder.Name = RepositoryPath.GetFileName(path);
                folder.Save();
            }
        }
Esempio n. 19
0
        public static string IncrementNameSuffix(string name, out string nameBase)
        {
            name = RepositoryPath.GetFileName(name);
            var  ext      = Path.GetExtension(name);
            var  fileName = Path.GetFileNameWithoutExtension(name);
            bool inValidNumber;
            var  index   = ContentNamingHelper.ParseSuffix(fileName, out nameBase, out inValidNumber);
            var  newName = (inValidNumber) ?
                           String.Format("{0}({1}){2}", nameBase, Guid.NewGuid().ToString(), ext) :
                           String.Format("{0}({1}){2}", nameBase, ++index, ext);

            return(newName);
        }
Esempio n. 20
0
        public static string RenderIconTagFromPath(string path, string overlay, int size, string title)
        {
            var iconclasses = "sn-icon sn-icon" + size;

            if (string.IsNullOrEmpty(overlay))
            {
                return(string.Format(SimpleFormat, string.Empty, path, iconclasses, title));
            }
            else
            {
                var overlaypath = ResolveIconPath(OverlayPrefix + overlay, size);
                return(string.Format(OverlayFormat, RepositoryPath.GetFileName(path), path, overlay, overlaypath, iconclasses, title));
            }
        }
Esempio n. 21
0
        public static string IncrementNameSuffix(string name)
        {
            name = RepositoryPath.GetFileName(name);
            var ext      = Path.GetExtension(name);
            var fileName = Path.GetFileNameWithoutExtension(name);

            string nameBase;
            var    index = ParseSuffix(fileName, out nameBase);

            if (index < 0)
            {
                index = 0;
            }
            return(String.Format("{0}({1}){2}", nameBase, ++index, ext));
        }
Esempio n. 22
0
        private static Content EnsureContainer(string path, string containerTypeName)
        {
            if (Node.Exists(path))
            {
                return(null);
            }

            var name       = RepositoryPath.GetFileName(path);
            var parentPath = RepositoryPath.GetParentPath(path);

            // recursive call to create parent containers
            EnsureContainer(parentPath, containerTypeName);

            return(CreateContent(parentPath, name, containerTypeName));
        }
Esempio n. 23
0
        public static async Task EnsurePath(string path, string containerTypeName = null)
        {
            if (!await Content.ExistsAsync(path))
            {
                var parentPath = RepositoryPath.GetParentPath(path);

                // ensure parent
                await EnsurePath(parentPath, containerTypeName);

                var name   = RepositoryPath.GetFileName(path);
                var folder = Content.CreateNew(parentPath, containerTypeName ?? "Folder", name);

                await folder.SaveAsync();
            }
        }
Esempio n. 24
0
        private void EnsureNode(string encodedPath, string typeName)
        {
            string path = DecodePath(encodedPath);

            if (Node.Exists(path))
            {
                return;
            }

            string name       = RepositoryPath.GetFileName(path);
            string parentPath = RepositoryPath.GetParentPath(path);

            EnsureNode(parentPath, "Folder");

            CreateNode(parentPath, name, typeName);
        }
Esempio n. 25
0
        private static Content LoadContentOrVirtualChild(ODataRequest odataReq)
        {
            var content = Content.Load(odataReq.RepositoryPath);

            if (content == null)
            {
                // try to load a virtual content
                var parentPath = RepositoryPath.GetParentPath(odataReq.RepositoryPath);
                var name       = RepositoryPath.GetFileName(odataReq.RepositoryPath);
                if (Node.LoadNode(parentPath) is ISupportsVirtualChildren vp)
                {
                    content = vp.GetChild(name);
                }
            }

            return(content);
        }
        public Stream GetStreamForRead(BlobStorageContext context)
        {
            var    path        = (string)context.BlobProviderData;
            string fileContent = null;

            if (path.StartsWith(Repository.ContentTypesFolderPath))
            {
                var ctdName = RepositoryPath.GetFileName(path);
                fileContent = _dataFile.ContentTypeDefinitions[ctdName];
            }
            else
            {
                var key = $"{ActiveSchema.PropertyTypes.GetItemById(context.PropertyTypeId).Name}:{path}";
                _dataFile.Blobs.TryGetValue(key, out fileContent);
            }
            var stream = RepositoryTools.GetStreamFromString(fileContent);

            return(stream);
        }
Esempio n. 27
0
        public static string IncrementNameSuffixToLastName(string currentName, int parentNodeId)
        {
            currentName = RepositoryPath.GetFileName(currentName);
            var    ext = Path.GetExtension(currentName);
            string nameBase;
            var    fileName = Path.GetFileNameWithoutExtension(currentName);
            var    count    = ContentNamingHelper.ParseSuffix(fileName, out nameBase);

            var lastName = DataProvider.Current.GetNameOfLastNodeWithNameBase(parentNodeId, nameBase, ext);

            // if there is no suffixed name in db, return with first variant
            if (lastName == null)
            {
                return(String.Format("{0}(1){1}", nameBase, ext));
            }

            // there was a suffixed name in db in the form namebase(x), increment it
            // car(5)-> car(6), car(test)(5) -> car(test)(6), car(test) -> car(guid)
            return(ContentNamingHelper.IncrementNameSuffix(lastName));
        }
Esempio n. 28
0
        public static string IncrementNameSuffixToLastName(string currentName, int parentNodeId)
        {
            currentName = RepositoryPath.GetFileName(currentName);
            var ext      = Path.GetExtension(currentName);
            var fileName = Path.GetFileNameWithoutExtension(currentName);
            var count    = ParseSuffix(fileName, out var nameBase);

            var lastName = DataStore.GetNameOfLastNodeWithNameBaseAsync(parentNodeId, nameBase, ext, CancellationToken.None)
                           .GetAwaiter().GetResult();

            // if there is no suffixed name in db, return with first variant
            if (lastName == null)
            {
                return($"{nameBase}(1){ext}");
            }

            // there was a suffixed name in db in the form namebase(x), increment it
            // car(5)-> car(6), car(test)(5) -> car(test)(6), car(test) -> car(guid)
            return(IncrementNameSuffix(lastName));
        }
Esempio n. 29
0
        public static Folder LoadOrCreateFolder(string path)
        {
            var folder = (Folder)Node.LoadNode(path);

            if (folder != null)
            {
                return(folder);
            }

            var parentPath   = RepositoryPath.GetParentPath(path);
            var parentFolder = (Folder)Node.LoadNode(parentPath) ?? LoadOrCreateFolder(parentPath);

            folder = new Folder(parentFolder)
            {
                Name = RepositoryPath.GetFileName(path)
            };
            folder.Save();

            return(folder);
        }
Esempio n. 30
0
        public void HandleMethod()
        {
            var node = Node.LoadNode(_handler.GlobalPath);
            var binaryPropertyName = "Binary";

            if (node == null)
            {
                var parentPath  = RepositoryPath.GetParentPath(_handler.GlobalPath);
                var currentName = RepositoryPath.GetFileName(_handler.GlobalPath);

                node = Node.LoadNode(parentPath);

                var foundNode = WebDavHandler.GetNodeByBinaryName(node, currentName, out binaryPropertyName);

                if (foundNode != null)
                {
                    node = foundNode;
                }
                else
                {
                    binaryPropertyName = "Binary";

                    // check if parent is contenttype
                    //(contenttypes are listed under their own folder, so the node exists only virtually)
                    var parentIsContentType = (node != null && node is ContentType);

                    if (!parentIsContentType)
                    {
                        _handler.Context.Response.StatusCode = 404;
                        _handler.Context.Response.Flush();
                    }

                    // parent is contenttype, continue operation on parent (foldernode's name is valid CTD name)
                }
            }

            ConverterPattern.DoTransform(node, _handler, binaryPropertyName);
            _handler.Context.Response.Flush();

            return;
        }