Пример #1
0
        private void MoveADObjectIfNecessary(DirectoryEntry entry, SyncTree entrySyncTree, Node node, string newPath)
        {
            if (!_config.AllowMove)
            {
                return;
            }

            // ebben a synctree-ben van
            var oldSyncTree = entrySyncTree;

            // ebben a synctree-ben kell lennie
            var newSyncTree = GetSyncTreeContainingPortalPath(newPath);

            // itt már csak azonos szerveren történő moveolás lehetséges (különböző szerverre történő moveolás feljebb történik)
            // a sync tartományok esetleg különbözhetnek
            var assumedPortalParentPath = oldSyncTree.GetPortalParentPath(entry.Path);
            var portalParentPath        = RepositoryPath.GetParentPath(newPath);

            // változott a path, moveolni kell
            if (assumedPortalParentPath != portalParentPath)
            {
                var parentEntryName = newSyncTree.GetADPath(portalParentPath);
                using (DirectoryEntry parentEntry = newSyncTree.ConnectToObject(parentEntryName))
                {
                    entry.MoveTo(parentEntry);
                }
            }
        }
Пример #2
0
        private static TreeNode[] CreateForest(IEnumerable <Content> contents)
        {
            var treeNodes = contents.Select(c => new TreeNode {
                Content = c
            }).ToList();
            var rootNodes = new List <TreeNode>();

            foreach (var treeNode in treeNodes)
            {
                var parentPath = RepositoryPath.GetParentPath(treeNode.Content.Path);
                if (parentPath == _contentTypeRoot)
                {
                    rootNodes.Add(treeNode);
                }
                else
                {
                    var parent = treeNodes.FirstOrDefault(t => t.Content.Path == parentPath);
                    if (parent != null)
                    {
                        treeNode.SetParent(parent);
                    }
                }
            }
            return(rootNodes.ToArray());
        }
Пример #3
0
        public CommentInfo(List <Node> comments, List <Node> likesForComments, string markupStr)
        {
            var commentsMarkup = new StringBuilder();
            var hiddenComments = new StringBuilder();

            var index = 0;

            foreach (var comment in comments)
            {
                var likesForComment = likesForComments.Where(l => RepositoryPath.GetParentPath(RepositoryPath.GetParentPath(l.Path)) == comment.Path).ToList();

                var commentGc       = comment as GenericContent;
                var commentLikeInfo = new LikeInfo(likesForComment, commentGc.Id);
                var commentMarkup   = WallHelper.GetCommentMarkup(markupStr, commentGc.CreationDate, commentGc.CreatedBy as User, commentGc.Description, commentGc.Id, commentLikeInfo, comment);

                // if it is one of the last two comments, add it to visible comments list, otherwise to hidden comments list
                if (index < comments.Count - 2)
                {
                    hiddenComments.Append(commentMarkup);
                }
                else
                {
                    commentsMarkup.Append(commentMarkup);
                }
                index++;
            }

            CommentsMarkup       = commentsMarkup.ToString();
            HiddenCommentsMarkup = hiddenComments.ToString();
            CommentCount         = comments.Count;
        }
Пример #4
0
        public string GetGlobalPath(string path)
        {
            if (path.StartsWith("/Root"))
            {
                return(path);
            }

            if (path.StartsWith("Root"))
            {
                return(string.Concat(RepositoryPath.PathSeparator, path));
            }

            //bring the path to the correct format
            path = path.TrimEnd('/');

            //check if path is almost full, only without the '/Root' prefix (because of network drive mapping)
            var pathProbe = RepositoryPath.Combine("/Root", path);

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

            // Check parent path. If it exists, this path is correct, only the node does not exist yet.
            if (Node.Exists(RepositoryPath.GetParentPath(pathProbe)))
            {
                return(pathProbe);
            }

            //site-relative path
            return(PortalContext.Current == null
                ? (path.StartsWith(RepositoryPath.PathSeparator) ? path : string.Concat(RepositoryPath.PathSeparator, path)) //this will not happen
                : RepositoryPath.Combine(PortalContext.Current.Site.Path, path));
        }
Пример #5
0
        public static object Import(Content content, string path, object data)
        {
            var jData    = data as JObject;
            var imported = new ImportedContent(jData);
            var name     = imported.Name;
            var type     = imported.Type;

            JObject model = imported.Fields;

            model.Remove("Name");

            string        action;
            List <string> brokenReferences;
            var           messages      = new List <string>();
            var           targetContent = Content.Load(path);

            if (targetContent != null)
            {
                ODataMiddleware.UpdateFields(targetContent, model, true, out brokenReferences);
                targetContent.Save();
                action = "updated";
            }
            else
            {
                var parentPath = RepositoryPath.GetParentPath(path);
                targetContent = ODataMiddleware.CreateNewContent(parentPath, type, null, name, null, false, model, true, out brokenReferences);
                action        = "created";
            }

            SetPermissions(targetContent, imported.Permissions, messages, out var retryPermissions);

            return(new { path, name, type, action, brokenReferences, retryPermissions, messages });
        }
Пример #6
0
        private FieldValidationResult ValidatePaths(List <Node> list, Field field)
        {
            //-- Paths
            if (this.SelectionRoots.Count > 0)
            {
                //-- Convert relative paths to absolute
                var paths = new List <string>();                //-- test equality
                var roots = new List <string>();                //-- ends with PathSeparator
                foreach (string item in this.SelectionRoots)
                {
                    var handler     = field.Content.ContentHandler;
                    var handlerPath = RepositoryPath.Combine(RepositoryPath.GetParentPath(handler.Path), handler.Name);
                    var path        = "/";
                    if (item.StartsWith("/"))
                    {
                        path = item;
                    }
                    else if (item == ".")
                    {
                        path = handlerPath;
                    }
                    else
                    {
                        path = RepositoryPath.Combine(handlerPath, item);
                    }

                    if (path.EndsWith(RepositoryPath.PathSeparator))
                    {
                        paths.Add(path.Substring(0, path.Length - 1));
                        roots.Add(path);
                    }
                    else
                    {
                        paths.Add(path);
                        roots.Add(String.Concat(path, RepositoryPath.PathSeparator));
                    }
                }
                foreach (Node node in list)
                {
                    var ok = false;
                    for (int i = 0; i < paths.Count; i++)
                    {
                        if (node.Path == paths[i] || node.Path.StartsWith(roots[i]))
                        {
                            ok = true;
                            break;
                        }
                    }
                    if (ok)
                    {
                        continue;
                    }

                    var result = new FieldValidationResult(SelectionRootName);
                    result.AddParameter(SelectionRootName, node.Path);
                    return(result);
                }
            }
            return(FieldValidationResult.Successful);
        }
Пример #7
0
        /// <summary>
        /// Loads all settings content with a specified name (or relative path) from the Settings folders
        /// up on the parent chain, starting from the provided context path.
        /// </summary>
        /// <typeparam name="T">The settings type.</typeparam>
        /// <param name="settingsName">Name or relative path of the settings content.</param>
        /// <param name="contextPath">The content where the search for the settings will start.</param>
        /// <returns>List of strongly typed settings content.</returns>
        public static IEnumerable <T> GetAllSettingsByName <T>(string settingsName, string contextPath) where T : Settings
        {
            var settingsList = new List <T>();
            T   setting;

            do
            {
                setting = GetSettingsByName <T>(settingsName, contextPath);
                if (setting == null)
                {
                    continue;
                }

                settingsList.Add(setting);

                // if this is a local setting, try to find the value upwards
                if (!setting.Path.StartsWith(SETTINGSCONTAINERPATH))
                {
                    // find the path above the settings folder
                    contextPath = RepositoryPath.GetParentPath(GetParentContextPath(setting.Path));
                }
                else
                {
                    // found the global setting, skip out of the loop
                    break;
                }
            } while (setting != null);

            return(settingsList);
        }
Пример #8
0
        private static void ExportByFilterText(ExportContext context, string fsRoot, string queryText)
        {
            var query = ContentQuery.CreateQuery(queryText);

            query.AddClause(@"InTree:""" + context.SourceFsPath + @"""", LogicalOperator.And);
            var result   = query.Execute();
            var maxCount = result.Count;
            var count    = 0;

            foreach (var nodeId in result.Identifiers)
            {
                try
                {
                    var content  = Content.Load(nodeId);
                    var relIndex = RepositoryPath.GetParentPath(context.SourceFsPath).Length + 1;
                    var relPath  = content.Path.Substring(relIndex).Replace("/", "\\");
                    var fsPath   = Path.Combine(fsRoot, relPath);
                    var fsDir    = Path.GetDirectoryName(fsPath);
                    var dirInfo  = new DirectoryInfo(fsDir);
                    if (!dirInfo.Exists)
                    {
                        Directory.CreateDirectory(fsDir);
                    }

                    ExportContent(content, context, fsDir, string.Concat(++count, "/", maxCount, ": ", Path.GetDirectoryName(relPath), "\\"));
                }
                catch (Exception ex)
                {
                    LogException(ex);
                }
            }
        }
Пример #9
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();
        }
Пример #10
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);
            }
        }
Пример #11
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);
        }
Пример #12
0
        private static IEnumerable <NodeHead> ResolveAllByPathsFromCache(IEnumerable <string> paths, bool resolveChildren, string appFolderName)
        {
            var cache = GetCache(appFolderName);
            var heads = new List <NodeHead>();

            foreach (var path in paths)
            {
                foreach (var x in cache)
                {
                    if (resolveChildren)
                    {
                        if (String.Compare(RepositoryPath.GetParentPath(x), path, true) == 0)
                        {
                            var head = NodeHead.Get(x);
                            if (head != null)
                            {
                                heads.Add(head);
                            }
                        }
                    }
                    else
                    {
                        if (String.Compare(x, path, true) == 0)
                        {
                            var head = NodeHead.Get(path);
                            if (head != null)
                            {
                                heads.Add(head);
                            }
                        }
                    }
                }
            }
            return(heads);
        }
Пример #13
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;
            }
        }
Пример #14
0
        /* ==================================================================================== Public Methods */
        public void CreateNewADUser(User user, string newPath, string passwd)
        {
            IUser originalUser = User.Current;

            Common.ChangeToAdminAccount();

            try
            {
                var parentPath = RepositoryPath.GetParentPath(newPath);

                // get containing synctree
                var syncTree = GetSyncTreeContainingPortalPath(parentPath);
                if (syncTree == null)
                {
                    // not synced object
                    return;
                }
                AdLog.LogPortalObject("Creating new AD user", user.Path);

                var parentADPath = syncTree.GetADPath(parentPath);

                CreateADUser(syncTree, parentADPath, user, passwd);
            }
            catch (Exception ex)
            {
                AdLog.LogException(ex);
                throw new Exception(ex.Message, ex);
            }
        }
        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);
        }
Пример #16
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;
            }
        }
Пример #17
0
        public override IEnumerable <string> GetParsableValues(SnCR.Field snField)
        {
            var value      = (string)snField.GetData() ?? String.Empty;
            var parentPath = RepositoryPath.GetParentPath(value.ToLower()) ?? "/";

            return(new[] { parentPath.ToLower() });
        }
Пример #18
0
        protected virtual TNode[] FindNearestItems(string path, Func <string, string> transform)
        {
            var pr = RepositoryPath.IsValidPath(path);

            if (pr != RepositoryPath.PathResult.Correct)
            {
                throw RepositoryPath.GetInvalidPathException(pr, path);
            }

            var p = path.ToLowerInvariant();

            while (true)
            {
                // find all items in the same folder
                var items = Items.Where(kv =>
                                        string.Compare(RepositoryPath.GetParentPath(kv.Key), transform(p), StringComparison.InvariantCultureIgnoreCase) == 0)
                            .Select(kv => kv.Value).ToArray();
                if (items.Length > 0)
                {
                    return(items);
                }
                if (p == "/root" || p == "/" || p == string.Empty)
                {
                    break;
                }
                p = RepositoryPath.GetParentPath(p);
            }
            return(null);
        }
Пример #19
0
        protected virtual TNode FindNearestItem(string path, Func <string, string> transform)
        {
            var pr = RepositoryPath.IsValidPath(path);

            if (pr != RepositoryPath.PathResult.Correct)
            {
                throw RepositoryPath.GetInvalidPathException(pr, path);
            }

            var   p = path.ToLowerInvariant();
            TNode tnode;

            while (true)
            {
                if (Items.TryGetValue(transform(p), out tnode))
                {
                    return(tnode);
                }
                if (p == "/root" || p == "/" || p == string.Empty)
                {
                    break;
                }
                p = RepositoryPath.GetParentPath(p);
            }
            return(null);
        }
Пример #20
0
        public static TrashBag BagThis(GenericContent node)
        {
            var bin = TrashBin.Instance;

            if (bin == null)
            {
                return(null);
            }

            if (node == null)
            {
                throw new ArgumentNullException("node");
            }

            //creating a bag has nothing to do with user permissions: Move will handle that
            TrashBag bag            = null;
            var      wsId           = 0;
            var      wsRelativePath = string.Empty;
            var      ws             = node.Workspace;

            if (ws != null)
            {
                wsId           = ws.Id;
                wsRelativePath = node.Path.Substring(ws.Path.Length);
            }

            using (new SystemAccount())
            {
                bag = new TrashBag(bin)
                {
                    KeepUntil             = DateTime.UtcNow.AddDays(bin.MinRetentionTime),
                    OriginalPath          = RepositoryPath.GetParentPath(node.Path),
                    WorkspaceRelativePath = wsRelativePath,
                    WorkspaceId           = wsId,
                    DisplayName           = node.DisplayName,
                    Link = node
                };
                bag.Save();

                CopyPermissions(node, bag);

                //add delete permission for the owner
                //bag.Security.SetPermission(User.Current, true, PermissionType.Delete, PermissionValue.Allow);
            }

            try
            {
                Node.Move(node.Path, bag.Path);
            }
            catch (Exception ex)
            {
                Logger.WriteException(ex);

                bag.Destroy();

                throw new InvalidOperationException("Error moving item to the trash", ex);
            }

            return(bag);
        }
Пример #21
0
        protected virtual IDictionary <string, T> GetItemsInternal(string path, string skin, string category = null)
        {
            // This method collects all relevant items for a content path. It merges them
            // into a dictionary by name. Local items override inherited ones with the same name.
            // Skin-level item: /Root/Skins/myskin/templates/action/linkbutton.html
            // Local item     : /Root/Sites/Default_Site/MyWorkspace/templates/action/linkbutton.html

            if (string.IsNullOrEmpty(skin))
            {
                throw new ArgumentNullException("skin");
            }

            if (string.IsNullOrEmpty(path) || string.Compare(path, Repository.RootPath, StringComparison.Ordinal) == 0)
            {
                var globalPath = string.IsNullOrEmpty(category)
                    ? RepositoryPath.Combine(RepositoryStructure.SkinRootFolderPath, skin, LocalFolderName)
                    : RepositoryPath.Combine(RepositoryStructure.SkinRootFolderPath, skin, LocalFolderName, category);

                // Collect global templates from under the skin in this category
                // (for example /Root/Skins/myskin/templates/button/...).
                var skinItems = Content.All.DisableAutofilters().Where(c =>
                                                                       c.InTree(globalPath) &&
                                                                       c.TypeIs(typeof(T).Name)).AsEnumerable().Select(c => c.ContentHandler).Cast <T>();

                return(skinItems.ToDictionary(st => st.Name, st => st));
            }

            var localItems = FindNearestItems(path, p => string.IsNullOrEmpty(category)
                ? RepositoryPath.Combine(p, LocalFolderName)
                : RepositoryPath.Combine(p, LocalFolderName, category));

            // no items found in the tree cache, fallback to the skin
            if (localItems == null || localItems.Length == 0)
            {
                return(GetItemsInternal(null, skin, category));
            }

            var localItemNodes = Node.LoadNodes(localItems.Select(t => t.Id));

            // Go upwards in the parent chain 4 levels to search for the next item level.
            // Current item path : /Root/Sites/Default_Site/MyWorkspace/templates/action/linkbutton.html
            // Continue with this: /Root/Sites/Default_Site
            var latestPath = localItemNodes[0].Path;

            for (var i = 0; i < 4; i++)
            {
                latestPath = RepositoryPath.GetParentPath(latestPath);
            }

            // collect inherited items and override the slots that are defined locally
            var inheritedItems = GetItemsInternal(latestPath, skin, category);

            foreach (var node in localItemNodes)
            {
                inheritedItems[node.Name] = (T)node;
            }

            return(inheritedItems);
        }
Пример #22
0
        protected bool Fire <THandler, TArgs>(IEnumerable <Node> eventHandlers, object sender, TArgs args)
            where THandler : RepositoryEventHandlerBase
            where TArgs : RepositoryEventArgs
        {
            var    cancel      = false;
            var    exceptions  = new List <Exception>();
            string finishLevel = null;

            foreach (var eventHandlerNode in eventHandlers)
            {
                var eventHandler = eventHandlerNode as THandler;
                var realSender   = GetSender((RepositoryEventHandlerBase)eventHandlerNode);
                if (eventHandler == null)
                {
                    throw new InvalidCastException(String.Concat("Type of ", this.EventName, " event handler must be ", typeof(THandler), ". Path: ", eventHandlerNode.Path));
                }
                try
                {
                    if (finishLevel != null)
                    {
                        if (!eventHandler.Path.StartsWith(finishLevel))
                        {
                            break;
                        }
                    }

                    if (Cancellable)
                    {
                        InvokeEventHandler(eventHandler as RepositoryCancelEventHandler, realSender, args as RepositoryCancelEventArgs, out cancel);
                    }
                    else
                    {
                        InvokeEventHandler(eventHandler as RepositoryEventHandler, realSender, args as RepositoryEventArgs, out cancel);
                    }

                    if (cancel)
                    {
                        break;
                    }
                    if (args.Handled)
                    {
                        break;
                    }
                    if (eventHandler.StopEventBubbling)
                    {
                        finishLevel = RepositoryPath.GetParentPath(eventHandler.Path) + "/";
                    }
                }
                catch (Exception e)
                {
                    exceptions.Add(e);
                }
            }
            if (exceptions.Count > 0)
            {
                throw new RepositoryEventException(args.ContextNode.Path, this, exceptions);
            }
            return(cancel);
        }
Пример #23
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
        }
Пример #24
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)));
 }
Пример #25
0
        private IList <PageZone> CreateMaster(string oldTemplate, string template, string fileName)
        {
            template = ChangeHead(template);
            template = AddForm(template);

            IList <object> oldFragments = SplitPageTemplate(oldTemplate);
            IList <object> fragments    = SplitPageTemplate(template);

            IList <PageZone> oldZoneList = new List <PageZone>();

            for (int i = 0; i < oldFragments.Count; i++)
            {
                if (oldFragments[i] is PageZone)
                {
                    PageZone oldZone = oldFragments[i] as PageZone;
                    oldZoneList.Add(oldZone);
                }
            }

            IList <PageZone> zoneList = new List <PageZone>();

            StringBuilder master = new StringBuilder();

            master.Append(MASTERHEADER);

            for (int i = 0; i < fragments.Count; i++)
            {
                if (fragments[i] is PageZone)
                {
                    PageZone zone = fragments[i] as PageZone;
                    master.AppendFormat(PLACEHOLDER, zone.Name);
                    zoneList.Add(zone);
                }
                else if (fragments[i] is PageEdit)
                {
                    PageEdit edit = fragments[i] as PageEdit;
                    master.AppendFormat(PAGEEDIT, edit.Name);
                }
                else if (fragments[i] is PageCatalog)
                {
                    // do nothing
                }
                else
                {
                    master.Append((string)fragments[i]);
                }
            }

            _isZoneChange = ZoneChanged(oldZoneList, zoneList);

            // MasterPages will be generated next to PageTemplates with appropriate extension and content type.
            // SaveMasterPage(string.Concat(fileName, MASTER), Repository.PageTemplatesFolderPath, master.ToString());
            var parentPath = RepositoryPath.GetParentPath(this.PageTemplateNode.Path);

            SaveMasterPage(string.Concat(fileName, MASTER), parentPath, master.ToString());

            return(zoneList);
        }
Пример #26
0
        /// <summary>
        /// Returns a setting value by the given key of the specified <see cref="Settings"/>.
        /// </summary>
        /// <typeparam name="T">Type of the return value</typeparam>
        /// <param name="settingsName">Name of the <see cref="Settings"/> (e.g. Indexing or Portal).</param>
        /// <param name="key">The name of the requested value.</param>
        /// <param name="contextPath">The content where the search for the settings will start.</param>
        /// <param name="defaultValue">Value if the "value" is null.</param>
        public static T GetValue <T>(string settingsName, string key, string contextPath = null, T defaultValue = default(T))
        {
            using (new SystemAccount())
            {
                // load the settings file
                Settings settingsFile;

                settingsFile = GetSettingsByName <Settings>(settingsName, contextPath);

                // file not found, even in the global folder
                if (settingsFile == null)
                {
                    SnLog.WriteWarning("Settings file not found: " + settingsName + "." + EXTENSION);
                    return(defaultValue);
                }

                // Try to get setting value from cache
                object settingValue;
                if (settingsFile.SettingValues.TryGetValue(key, out settingValue))
                {
                    return(ConvertSettingValue <T>(settingValue, defaultValue));
                }

                // Load the value from the Binary (xml or json format): this method should return a value
                // that is already converted to type 'T' from string, otherwise the received default value.
                bool found;
                settingValue = settingsFile.GetValueFromBinary(key, defaultValue, out found);

                // the value was found on the settings file
                if (found)
                {
                    settingValue = ConvertSettingValue <T>(settingValue, defaultValue);
                    settingsFile.AddValueToCache(key, settingValue);
                    return((T)settingValue);
                }

                // load the value from a content field if possible
                var settingsContent = Content.Create(settingsFile);
                if (settingsContent.Fields.ContainsKey(key))
                {
                    // NOTE: no need to add to cache here, we suppose that the content fields are already in the memory
                    //       (also, the dynamic fields of Settings are added to the cache in GetProperty)

                    settingValue = ConvertSettingValue <T>(settingsContent[key], defaultValue);
                    return((T)settingValue);
                }

                // if this is a local setting, try to find the value upwards
                if (!settingsFile.Path.StartsWith(SETTINGSCONTAINERPATH))
                {
                    // find the path above the settings folder
                    var newPath = RepositoryPath.GetParentPath(GetParentContextPath(settingsFile.Path));
                    return(GetValue(settingsName, key, newPath, defaultValue));
                }

                return(defaultValue);
            }
        }
Пример #27
0
        protected virtual bool NodeIsValid(Node node)
        {
            if (node == null || node.Name == "(apps)")
            {
                return(false);
            }
            if (TypeNames != null && !TypeNames.Contains(node.NodeType.Name))
            {
                return(false);
            }
            var contentNode = node as GenericContent;

            try
            {
                if (!ShowHiddenPages && ((contentNode != null) && contentNode.Hidden))
                {
                    return(false);
                }
            }
            catch (InvalidOperationException)
            {
                //"Invalid property access attempt"
                //The user has only See permission for this node. Changing to Admin account does not
                //help either, because the node is 'head only' and accessing any of its properties
                //will throw an invalidoperation exception anyway.
                return(false);
            }

            if (ExpandToContext)
            {
                var pathCollection = GetPathCollection(PortalContext.Current.Page.Path).ToList().
                                     Union(GetPathCollection(ContextNode.Path)).
                                     Union(GetPathCollection(PortalContext.Current.ContextNodePath)).
                                     ToArray();

                foreach (var path in pathCollection)
                {
                    if (node.Path.Equals(path) || IsSiblingPath(path, node.Path))
                    {
                        return(true);
                    }
                }

                if (GetContextChildren)
                {
                    var parentPath = RepositoryPath.GetParentPath(node.Path);
                    if (parentPath.Equals(PortalContext.Current.ContextNodePath) ||
                        parentPath.Equals(ContextNode.Path))
                    {
                        return(true);
                    }
                }

                return(false);
            }

            return(true);
        }
Пример #28
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)));
        }
Пример #29
0
        private PermissionInfo GetParentInfo(string path)
        {
            if (path.ToLower() == "/root")
            {
                return(null);
            }

            return(GetFirstInfo(RepositoryPath.GetParentPath(path)));
        }
Пример #30
0
        private void HandleUrlToWebUrl(HttpContext context)
        {
            var path = context.Request.Form["url"];

            var weburl  = path;
            var fileurl = string.Empty;

            // ie.: /Sites or /Sites/Default_Site/workspace/Document/myws/Document_Library/mydoc.docx
            if (path != "/")
            {
                path   = DwsHelper.GetFullPath(path);
                weburl = path;

                var node = Node.LoadNode(path);
                if (node == null)
                {
                    node = Node.LoadNode(RepositoryPath.GetParentPath(path));
                }

                // searching starts from parentpath
                if (node != null)
                {
                    using (new SystemAccount())
                    {
                        var doclib = DwsHelper.GetDocumentLibraryForNode(node);
                        if (doclib != null)
                        {
                            // weburl should be doclibs parent (most of the time currentworkspace)
                            // fileurl should be doclib name and doclib relative path
                            // this will work for /Sites/MySite/Doclib/document.docx, for /Sites/Mysite/myworkspace/Doclib/document.docx and for /Root/Doclib/document.docx
                            weburl  = doclib.ParentPath;
                            fileurl = (path.Length > doclib.ParentPath.Length) ? path.Substring(doclib.ParentPath.Length + 1) : string.Empty;
                        }
                        else
                        {
                            // weburl should be parent's parentpath
                            // fileurl should be parentname + name  -> parent will act as a mocked document library
                            // this will work for /Root/YourDocuments/document.docx
                            if (node.Parent != null)
                            {
                                weburl  = node.Parent.ParentPath;
                                fileurl = RepositoryPath.Combine(node.Parent.Name, node.Name);
                            }
                        }
                    }
                }
            }

            var responseStr = GetFormattedString(string.Format(URLTOWEBURLSTR, weburl, fileurl));

            context.Response.Charset     = "";
            context.Response.ContentType = "application/x-vermeer-rpc";
            context.Response.AddHeader("Content-Length", responseStr.Length.ToString());
            context.Response.Write(responseStr);
            context.Response.Flush();
            context.Response.End();
        }