Exemplo n.º 1
0
        /// <summary>
        /// Retrieves a File.
        /// </summary>
        /// <param name="fullName">The full name of the File.</param>
        /// <param name="output">The output stream.</param>
        /// <param name="countHit">A value indicating whether or not to count this retrieval in the statistics.</param>
        /// <returns><c>true</c> if the file is retrieved, <c>false</c> otherwise.</returns>
        public static bool RetrieveFile(string fullName, Stream output, bool countHit)
        {
            if (fullName == null)
            {
                throw new ArgumentNullException("fullName");
            }
            if (fullName.Length == 0)
            {
                throw new ArgumentException("Full Name cannot be empty", "fullName");
            }
            if (output == null)
            {
                throw new ArgumentNullException("output");
            }
            if (!output.CanWrite)
            {
                throw new ArgumentException("Cannot write into Destination Stream", "output");
            }

            fullName = NormalizeFullName(fullName);

            IFilesStorageProviderV30 provider = FindFileProvider(fullName);

            if (provider == null)
            {
                return(false);
            }
            return(provider.RetrieveFile(fullName, output, countHit));
        }
Exemplo n.º 2
0
        /// <summary>
        /// Deletes a directory and de-indexes all its contents.
        /// </summary>
        /// <param name="provider">The provider.</param>
        /// <param name="directory">The directory to delete.</param>
        public static bool DeleteDirectory(IFilesStorageProviderV30 provider, string directory)
        {
            if (provider == null)
            {
                throw new ArgumentNullException("provider");
            }

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

            if (directory.Length == 0 || directory == "/")
            {
                throw new ArgumentException("Cannot delete the root directory", "directory");
            }

            directory = NormalizeFullPath(directory);

            // This must be done BEFORE deleting the directory, otherwise there wouldn't be a way to list contents
            DeletePermissions(provider, directory);
            DeindexDirectory(provider, directory);

            // Delete Directory
            bool done = provider.DeleteDirectory(directory);

            if (!done)
            {
                return(false);
            }

            Host.Instance.OnDirectoryActivity(provider.GetType().FullName, directory, null, FileActivity.DirectoryDeleted);

            return(true);
        }
Exemplo n.º 3
0
        private float GetCurrentAverage(string fullPageName)
        {
            float average = 0;

            try {
                IFilesStorageProviderV30 filesStorageProvider = GetDefaultFilesStorageProvider();

                MemoryStream stream      = new MemoryStream();
                string       fileContent = "";

                if (FileExists(filesStorageProvider, defaultDirectoryName, ratingFileName))
                {
                    filesStorageProvider.RetrieveFile(defaultDirectoryName + ratingFileName, stream, true);
                    stream.Seek(0, SeekOrigin.Begin);
                    fileContent = Encoding.UTF8.GetString(stream.ToArray());
                }

                string[] plugins = fileContent.Split(new String[] { "||" }, StringSplitOptions.RemoveEmptyEntries);

                // If the plugin is found return the posizion in the plugins array
                // otherwise return -1
                int pluginIndex = SearchPlugin(plugins, fullPageName);
                if (pluginIndex != -1)
                {
                    string[] pluginDetails = plugins[pluginIndex].Split(new string[] { "|" }, StringSplitOptions.RemoveEmptyEntries);
                    average = (float)int.Parse(pluginDetails[2]) / (float)100;
                }
            }
            catch (Exception ex) {
                LogWarning(String.Format("Exception occurred {0}", ex.StackTrace));
            }
            return(average);
        }
Exemplo n.º 4
0
        /// <summary>
        /// Gets all the actions for a directory that are denied to a subject.
        /// </summary>
        /// <param name="subject">The subject.</param>
        /// <param name="provider">The provider.</param>
        /// <param name="directory">The directory.</param>
        /// <returns>The denied actions.</returns>
        private static string[] RetrieveDenialsForDirectory(string subject, IFilesStorageProviderV30 provider, string directory)
        {
            if (provider == null)
            {
                throw new ArgumentNullException("provider");
            }

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

            if (directory.Length == 0)
            {
                throw new ArgumentException("Directory cannot be empty", "directory");
            }

            string resourceName = Actions.ForDirectories.ResourceMasterPrefix + AuthTools.GetDirectoryName(provider, directory);

            AclEntry[] entries = SettingsProvider.AclManager.RetrieveEntriesForSubject(subject);

            List <string> result = new List <string>(entries.Length);

            foreach (AclEntry entry in entries)
            {
                if (entry.Value == Value.Deny && entry.Resource == resourceName)
                {
                    result.Add(entry.Action);
                }
            }

            return(result.ToArray());
        }
Exemplo n.º 5
0
        /// <summary>
        /// Retrieves the subjects that have ACL entries set for a directory.
        /// </summary>
        /// <param name="provider">The provider.</param>
        /// <param name="directory">The directory.</param>
        /// <returns>The subjects.</returns>
        public static SubjectInfo[] RetrieveSubjectsForDirectory(IFilesStorageProviderV30 provider, string directory)
        {
            if (provider == null)
            {
                throw new ArgumentNullException("provider");
            }
            if (directory == null)
            {
                throw new ArgumentNullException("directory");
            }
            if (directory.Length == 0)
            {
                throw new ArgumentException("Directory cannot be empty", "directory");
            }

            var entries = SettingsProvider.AclManager.RetrieveEntriesForResource(Actions.ForDirectories.ResourceMasterPrefix + AuthTools.GetDirectoryName(provider, directory));

            var result = new List <SubjectInfo>();

            foreach (var entry in entries)
            {
                SubjectType type = AuthTools.IsGroup(entry.Subject) ? SubjectType.Group : SubjectType.User;

                // Remove the subject qualifier ('U.' or 'G.')
                var name = entry.Subject.Substring(2);

                if (result.Find(delegate(SubjectInfo x) { return(x.Name == name && x.Type == type); }) == null)
                {
                    result.Add(new SubjectInfo(name, type));
                }
            }

            return(result.ToArray());
        }
Exemplo n.º 6
0
        /// <summary>
        /// Retrieves a Page Attachment.
        /// </summary>
        /// <param name="page">The Page Info that owns the Attachment.</param>
        /// <param name="attachmentName">The name of the Attachment, for example "myfile.jpg".</param>
        /// <param name="output">The output stream.</param>
        /// <param name="countHit">A value indicating whether or not to count this retrieval in the statistics.</param>
        /// <returns><c>true</c> if the Attachment is retrieved, <c>false</c> otherwise.</returns>
        public static bool RetrievePageAttachment(PageInfo page, string attachmentName, Stream output, bool countHit)
        {
            if (page == null)
            {
                throw new ArgumentNullException("page");
            }
            if (attachmentName == null)
            {
                throw new ArgumentNullException("attachmentName");
            }
            if (attachmentName.Length == 0)
            {
                throw new ArgumentException("Name cannot be empty", "attachmentName");
            }
            if (output == null)
            {
                throw new ArgumentNullException("output");
            }
            if (!output.CanWrite)
            {
                throw new ArgumentException("Cannot write into Destination Stream", "output");
            }

            IFilesStorageProviderV30 provider = FindPageAttachmentProvider(page, attachmentName);

            if (provider == null)
            {
                return(false);
            }
            return(provider.RetrievePageAttachment(page, attachmentName, output, countHit));
        }
Exemplo n.º 7
0
        /// <summary>
        /// Processes the renaming of a directory.
        /// </summary>
        /// <param name="provider">The provider.</param>
        /// <param name="oldName">The old directory name (full path).</param>
        /// <param name="newName">The new directory name (full path).</param>
        /// <returns><c>true</c> if the operation completed successfully, <c>false</c> otherwise.</returns>
        /// <remarks>The method <b>does not</b> recurse in sub-directories.</remarks>
        public static bool ProcessDirectoryRenaming(IFilesStorageProviderV30 provider, string oldName, string newName)
        {
            if (provider == null)
            {
                throw new ArgumentNullException("provider");
            }

            if (oldName == null)
            {
                throw new ArgumentNullException("oldName");
            }
            if (oldName.Length == 0)
            {
                throw new ArgumentException("Old Name cannot be empty", "oldName");
            }

            if (newName == null)
            {
                throw new ArgumentNullException("newName");
            }
            if (newName.Length == 0)
            {
                throw new ArgumentException("New Name cannot be empty", "newName");
            }

            return(SettingsProvider.AclManager.RenameResource(
                       Actions.ForDirectories.ResourceMasterPrefix + AuthTools.GetDirectoryName(provider, oldName),
                       Actions.ForDirectories.ResourceMasterPrefix + AuthTools.GetDirectoryName(provider, newName)));
        }
Exemplo n.º 8
0
        /// <summary>
        /// Migrates all the stored files and page attachments from a Provider to another.
        /// </summary>
        /// <param name="source">The source Provider.</param>
        /// <param name="destination">The destination Provider.</param>
        /// <param name="settingsProvider">The settings storage provider that handles permissions.</param>
        public static void MigrateFilesStorageProviderData(IFilesStorageProviderV30 source, IFilesStorageProviderV30 destination, ISettingsStorageProviderV30 settingsProvider)
        {
            // Directories
            MigrateDirectories(source, destination, "/", settingsProvider);

            // Attachments
            foreach (string page in source.GetPagesWithAttachments())
            {
                PageInfo pageInfo = new PageInfo(page, null, DateTime.Now);

                string[] attachments = source.ListPageAttachments(pageInfo);

                foreach (string attachment in attachments)
                {
                    // Copy file content
                    using (MemoryStream ms = new MemoryStream(1048576)) {
                        source.RetrievePageAttachment(pageInfo, attachment, ms, false);
                        ms.Seek(0, SeekOrigin.Begin);
                        destination.StorePageAttachment(pageInfo, attachment, ms, false);
                    }

                    // Copy download count
                    FileDetails fileDetails = source.GetPageAttachmentDetails(pageInfo, attachment);
                    destination.SetPageAttachmentRetrievalCount(pageInfo, attachment, fileDetails.RetrievalCount);

                    // Delete attachment
                    source.DeletePageAttachment(pageInfo, attachment);
                }
            }
        }
Exemplo n.º 9
0
        /// <summary>
        /// Recursively re-indexes all the contents of the old (renamed) directory to the new one.
        /// </summary>
        /// <param name="provider">The provider.</param>
        /// <param name="oldDirectory">The old directory.</param>
        /// <param name="newDirectory">The new directory.</param>
        private static void ReindexDirectory(IFilesStorageProviderV30 provider, string oldDirectory, string newDirectory)
        {
            oldDirectory = NormalizeFullPath(oldDirectory);
            newDirectory = NormalizeFullPath(newDirectory);

            // At this point the directory has been already renamed,
            // thus we must list on the new directory and construct the old name
            // Example: /directory/one/ renamed to /directory/two-two/
            // List on /directory/two-two/
            //     dir1
            //     dir2
            // oldSub = /directory/one/dir1/

            foreach (string sub in provider.ListDirectories(newDirectory))
            {
                string oldSub = oldDirectory + sub.Substring(newDirectory.Length);
                ReindexDirectory(provider, oldSub, sub);
            }

            foreach (string file in provider.ListFiles(newDirectory))
            {
                string oldFile = oldDirectory + file.Substring(newDirectory.Length);
                SearchClass.RenameFile(provider.GetType().FullName + "|" + oldFile, provider.GetType().FullName + "|" + file);
            }
        }
Exemplo n.º 10
0
 /// <summary>
 ///     Initializes a new instance of the <see cref="T:StFileInfo" /> class.
 /// </summary>
 /// <param name="size">The size of the file in bytes.</param>
 /// <param name="lastModified">The last modification date/time.</param>
 /// <param name="downloadCount">The download count.</param>
 /// <param name="fullName">The full name of the file, for example <b>/dir/sub/file.txt</b> or <b>/file.txt</b>.</param>
 /// <param name="provider">The provider that handles the file.</param>
 public StFileInfo(long size, DateTime lastModified, int downloadCount, string fullName,
                   IFilesStorageProviderV30 provider)
     : base(size, lastModified, downloadCount)
 {
     FullName = fullName;
     Provider = provider;
 }
Exemplo n.º 11
0
        /// <summary>
        /// Removes all the ACL Entries for a directory that are bound to a subject.
        /// </summary>
        /// <param name="subject">The subject.</param>
        /// <param name="provider">The provider.</param>
        /// <param name="directory">The directory.</param>
        /// <returns><c>true</c> if the operation succeeded, <c>false</c> otherwise.</returns>
        private static bool RemoveEntriesForDirectory(string subject, IFilesStorageProviderV30 provider, string directory)
        {
            if (provider == null)
            {
                throw new ArgumentNullException("provider");
            }
            if (directory == null)
            {
                throw new ArgumentNullException("directory");
            }
            if (directory.Length == 0)
            {
                throw new ArgumentException("Directory cannot be empty", "directory");
            }

            string resourceName = Actions.ForDirectories.ResourceMasterPrefix + AuthTools.GetDirectoryName(provider, directory);

            AclEntry[] entries = SettingsProvider.AclManager.RetrieveEntriesForSubject(subject);

            foreach (AclEntry entry in entries)
            {
                if (entry.Resource == resourceName)
                {
                    // This call automatically logs the operation result
                    bool done = SetPermissionForDirectory(AuthStatus.Delete, provider, directory, entry.Action, subject);
                    if (!done)
                    {
                        return(false);
                    }
                }
            }

            return(true);
        }
Exemplo n.º 12
0
        /// <summary>
        /// Gets the proper full name for a directory.
        /// </summary>
        /// <param name="prov">The provider.</param>
        /// <param name="name">The directory name.</param>
        /// <returns>The full name (<b>not</b> prepended with <see cref="Actions.ForDirectories.ResourceMasterPrefix" />.</returns>
        public static string GetDirectoryName(IFilesStorageProviderV30 prov, string name)
        {
            if(prov == null) throw new ArgumentNullException("prov");
            if(name == null) throw new ArgumentNullException("name");
            if(name.Length == 0) throw new ArgumentException("Name cannot be empty", "name");

            return "(" + prov.GetType().FullName + ")" + name;
        }
        public void Init( )
        {
            IFilesStorageProviderV30 prov = GetProvider( );

            prov.Init(MockHost( ), ConnString + InitialCatalog);

            Assert.IsNotNull(prov.Information, "Information should not be null");
        }
Exemplo n.º 14
0
        /// <summary>
        /// Stores and indexes a file.
        /// </summary>
        /// <param name="provider">The destination provider.</param>
        /// <param name="fullName">The full name.</param>
        /// <param name="source">The source stream.</param>
        /// <param name="overwrite"><c>true</c> to overwrite the existing file, <c>false</c> otherwise.</param>
        /// <returns><c>true</c> if the file was stored, <c>false</c> otherwise.</returns>
        public static bool StoreFile(IFilesStorageProviderV30 provider, string fullName, Stream source, bool overwrite)
        {
            if (provider == null)
            {
                throw new ArgumentNullException("provider");
            }

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

            if (fullName.Length == 0)
            {
                throw new ArgumentException("Full Name cannot be empty", "fullName");
            }

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

            fullName = NormalizeFullName(fullName);

            bool done = provider.StoreFile(fullName, source, overwrite);

            if (!done)
            {
                return(false);
            }

            if (overwrite)
            {
                SearchClass.UnindexFile(provider.GetType().FullName + "|" + fullName);
            }

            // Index the attached file
            string tempDir = Path.Combine(Environment.GetEnvironmentVariable("TEMP"), Guid.NewGuid().ToString());

            if (!Directory.Exists(tempDir))
            {
                Directory.CreateDirectory(tempDir);
            }

            string tempFile = Path.Combine(tempDir, Path.GetFileName(fullName));

            source.Seek(0, SeekOrigin.Begin);
            using (FileStream temp = File.Create(tempFile))
            {
                source.CopyTo(temp);
            }
            SearchClass.IndexFile(provider.GetType().FullName + "|" + fullName, tempFile);
            Directory.Delete(tempDir, true);

            Host.Instance.OnFileActivity(provider.GetType().FullName, fullName, null, FileActivity.FileUploaded);

            return(true);
        }
Exemplo n.º 15
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                // Localized strings for JavaScript
                StringBuilder sb = new StringBuilder();
                sb.Append(@"<script type=""text/javascript"">" + "\r\n<!--\n");
                sb.Append("var ConfirmMessage = '");
                sb.Append(Properties.Messages.ConfirmOperation);
                sb.Append("';\r\n");
                sb.AppendFormat("var UploadControl = '{0}';\r\n", fileUpload.ClientID);
                //sb.AppendFormat("var RefreshCommandParameter = '{0}';\r\n", btnRefresh.UniqueID);
                sb.AppendFormat("var OverwriteControl = '{0}';\r\n", chkOverwrite.ClientID);
                sb.Append("// -->\n</script>\n");
                lblStrings.Text = sb.ToString();

                // Setup upload information (max file size, allowed file types)
                lblUploadFilesInfo.Text = lblUploadFilesInfo.Text.Replace("$1", Tools.BytesToString(Settings.MaxFileSize * 1024));
                sb = new StringBuilder();
                string[] aft = Settings.AllowedFileTypes;
                for (int i = 0; i < aft.Length; i++)
                {
                    sb.Append(aft[i].ToUpper());
                    if (i != aft.Length - 1)
                    {
                        sb.Append(", ");
                    }
                }
                lblUploadFilesInfo.Text = lblUploadFilesInfo.Text.Replace("$2", sb.ToString());

                // Load Providers
                foreach (IFilesStorageProviderV30 prov in Collectors.FilesProviderCollector.AllProviders)
                {
                    ListItem item = new ListItem(prov.Information.Name, prov.GetType().FullName);
                    if (item.Value == Settings.DefaultFilesProvider)
                    {
                        item.Selected = true;
                    }
                    lstProviders.Items.Add(item);
                }

                if (CurrentPage == null)
                {
                    btnUpload.Enabled = false;
                }
            }

            // Set provider
            provider = Collectors.FilesProviderCollector.GetProvider(lstProviders.SelectedValue);

            if (!Page.IsPostBack)
            {
                rptItems.DataBind();
            }

            DetectPermissions();
            SetupControls();
        }
Exemplo n.º 16
0
        /// <summary>
        /// Adds some ACL entries for a subject.
        /// </summary>
        /// <param name="subject">The subject.</param>
        /// <param name="provider">The provider.</param>
        /// <param name="directory">The directory.</param>
        /// <param name="grants">The granted actions.</param>
        /// <param name="denials">The denies actions.</param>
        /// <returns><c>true</c> if the operation succeeded, <c>false</c> otherwise.</returns>
        private bool AddAclEntriesForDirectory(string subject, IFilesStorageProviderV30 provider, string directory, string[] grants, string[] denials)
        {
            bool isGroup = subject.StartsWith("G.");

            subject = subject.Substring(2);

            UserGroup group = null;
            UserInfo  user  = null;

            if (isGroup)
            {
                group = Users.FindUserGroup(subject);
            }
            else
            {
                user = Users.FindUser(subject);
            }

            foreach (string action in grants)
            {
                bool done = false;
                if (isGroup)
                {
                    done = AuthWriter.SetPermissionForDirectory(AuthStatus.Grant,
                                                                provider, directory, action, group);
                }
                else
                {
                    done = AuthWriter.SetPermissionForDirectory(AuthStatus.Grant,
                                                                provider, directory, action, user);
                }
                if (!done)
                {
                    return(false);
                }
            }

            foreach (string action in denials)
            {
                bool done = false;
                if (isGroup)
                {
                    done = AuthWriter.SetPermissionForDirectory(AuthStatus.Deny,
                                                                provider, directory, action, group);
                }
                else
                {
                    done = AuthWriter.SetPermissionForDirectory(AuthStatus.Deny,
                                                                provider, directory, action, user);
                }
                if (!done)
                {
                    return(false);
                }
            }

            return(true);
        }
Exemplo n.º 17
0
        /// <summary>
        /// Sets a permission for a directory.
        /// </summary>
        /// <param name="status">The authorization status.</param>
        /// <param name="provider">The provider that handles the directory.</param>
        /// <param name="directory">The directory.</param>
        /// <param name="action">The action of which to modify the authorization status.</param>
        /// <param name="group">The group subject of the authorization change.</param>
        /// <returns><c>true</c> if the authorization status is changed, <c>false</c> otherwise.</returns>
        public static bool SetPermissionForDirectory(AuthStatus status, IFilesStorageProviderV30 provider, string directory, string action, UserGroup group)
        {
            if (group == null)
            {
                throw new ArgumentNullException("group");
            }

            return(SetPermissionForDirectory(status, provider, directory, action, AuthTools.PrepareGroup(group.Name)));
        }
Exemplo n.º 18
0
        /// <summary>
        /// Gets all the actions for a directory that are denied to a user.
        /// </summary>
        /// <param name="user">The user.</param>
        /// <param name="provider">The provider.</param>
        /// <param name="directory">The directory.</param>
        /// <returns>The denied actions.</returns>
        public static string[] RetrieveDenialsForDirectory(UserInfo user, IFilesStorageProviderV30 provider, string directory)
        {
            if (user == null)
            {
                throw new ArgumentNullException("user");
            }

            return(RetrieveDenialsForDirectory(AuthTools.PrepareUsername(user.Username), provider, directory));
        }
Exemplo n.º 19
0
        /// <summary>
        /// Gets all the actions for a directory that are denied to a group.
        /// </summary>
        /// <param name="group">The user group.</param>
        /// <param name="provider">The provider.</param>
        /// <param name="directory">The directory.</param>
        /// <returns>The denied actions.</returns>
        public static string[] RetrieveDenialsForDirectory(UserGroup group, IFilesStorageProviderV30 provider, string directory)
        {
            if (group == null)
            {
                throw new ArgumentNullException("group");
            }

            return(RetrieveDenialsForDirectory(AuthTools.PrepareGroup(group.Name), provider, directory));
        }
Exemplo n.º 20
0
        /// <summary>
        /// Sets a permission for a directory.
        /// </summary>
        /// <param name="status">The authorization status.</param>
        /// <param name="provider">The provider that handles the directory.</param>
        /// <param name="directory">The directory.</param>
        /// <param name="action">The action of which to modify the authorization status.</param>
        /// <param name="user">The user subject of the authorization change.</param>
        /// <returns><c>true</c> if the authorization status is changed, <c>false</c> otherwise.</returns>
        public static bool SetPermissionForDirectory(AuthStatus status, IFilesStorageProviderV30 provider, string directory, string action, UserInfo user)
        {
            if (user == null)
            {
                throw new ArgumentNullException("user");
            }

            return(SetPermissionForDirectory(status, provider, directory, action, AuthTools.PrepareUsername(user.Username)));
        }
Exemplo n.º 21
0
        private void SetProvider()
        {
            string p = Request["Provider"];

            if (string.IsNullOrEmpty(p))
            {
                p = Settings.DefaultFilesProvider;
            }
            provider = Collectors.FilesProviderCollector.GetProvider(p);
        }
Exemplo n.º 22
0
        /// <summary>
        /// Clears all the ACL entries for a directory.
        /// </summary>
        /// <param name="provider">The provider.</param>
        /// <param name="directory">The directory.</param>
        public static void ClearEntriesForDirectory(IFilesStorageProviderV30 provider, string directory)
        {
            if(provider == null) throw new ArgumentNullException("provider");

            if(directory == null) throw new ArgumentNullException("directory");
            if(directory.Length == 0) throw new ArgumentException("Directory cannot be empty", "directory");

            string resourceName = Actions.ForDirectories.ResourceMasterPrefix + AuthTools.GetDirectoryName(provider, directory);

            SettingsProvider.AclManager.DeleteEntriesForResource(resourceName);
        }
Exemplo n.º 23
0
        /// <summary>
        /// Deletes the permissions of a directory.
        /// </summary>
        /// <param name="provider">The provider.</param>
        /// <param name="directory">The directory.</param>
        private static void DeletePermissions(IFilesStorageProviderV30 provider, string directory)
        {
            directory = NormalizeFullPath(directory);

            foreach (string sub in provider.ListDirectories(directory))
            {
                DeletePermissions(provider, sub);
            }

            AuthWriter.ClearEntriesForDirectory(provider, directory);
        }
 public void Init_InvalidConnString(string c)
 {
     bool.TryParse(Environment.GetEnvironmentVariable("APPVEYOR"), out bool isAppveyor);
     Console.WriteLine($"isAppveyor is {isAppveyor.ToString()}");
     Console.WriteLine($"ConnString is {ConnString}");
     Assert.Throws <InvalidConfigurationException>(() =>
     {
         IFilesStorageProviderV30 prov = GetProvider();
         prov.Init(MockHost(), c);
     });
 }
Exemplo n.º 25
0
        protected void btnMigrateFiles_Click(object sender, EventArgs e)
        {
            IFilesStorageProviderV30 from = Collectors.FilesProviderCollector.GetProvider(lstFilesSource.SelectedValue);
            IFilesStorageProviderV30 to   = Collectors.FilesProviderCollector.GetProvider(lstFilesDestination.SelectedValue);

            Log.LogEntry("Files data migration requested from " + from.Information.Name + " to " + to.Information.Name, EntryType.General, SessionFacade.CurrentUsername);

            DataMigrator.MigrateFilesStorageProviderData(from, to, Settings.Provider);

            lblMigrateFilesResult.CssClass = "resultok";
            lblMigrateFilesResult.Text     = Properties.Messages.DataMigrated;
        }
Exemplo n.º 26
0
        protected void btnSave_Click(object sender, EventArgs e)
        {
            string subject = lstSubjects.SelectedValue;

            bool done = false;

            switch (CurrentResourceType)
            {
            case AclResources.Namespaces:
                // Remove old values, add new ones
                done = RemoveAllAclEntriesForNamespace(subject, CurrentResourceName);
                if (done)
                {
                    done = AddAclEntriesForNamespace(subject, CurrentResourceName,
                                                     aclActionsSelector.GrantedActions, aclActionsSelector.DeniedActions);
                }
                break;

            case AclResources.Pages:
                // Remove old values, add new ones
                done = RemoveAllAclEntriesForPage(subject, CurrentResourceName);
                if (done)
                {
                    done = AddAclEntriesForPage(subject, CurrentResourceName,
                                                aclActionsSelector.GrantedActions, aclActionsSelector.DeniedActions);
                }
                break;

            case AclResources.Directories:
                // Remove old values, add new ones
                IFilesStorageProviderV30 prov = Collectors.FilesProviderCollector.GetProvider(CurrentFilesProvider);
                done = RemoveAllAclEntriesForDirectory(subject, prov, CurrentResourceName);
                if (done)
                {
                    done = AddAclEntriesForDirectory(subject, prov, CurrentResourceName,
                                                     aclActionsSelector.GrantedActions, aclActionsSelector.DeniedActions);
                }
                break;

            default:
                throw new NotSupportedException();
            }

            if (done)
            {
                PopulateSubjectsList();
            }
            else
            {
                lblSaveResult.CssClass = "resulterror";
                lblSaveResult.Text     = Properties.Messages.CouldNotStorePermissions;
            }
        }
Exemplo n.º 27
0
 private bool DirectoryExists(IFilesStorageProviderV30 filesStorageProvider, string directoryName)
 {
     string[] directoryList = filesStorageProvider.ListDirectories("/");
     foreach (string dir in directoryList)
     {
         if (dir == directoryName)
         {
             return(true);
         }
     }
     return(false);
 }
Exemplo n.º 28
0
 private bool FileExists(IFilesStorageProviderV30 filesStorageProvider, string directory, string fileName)
 {
     string[] filesList = filesStorageProvider.ListFiles(directory);
     foreach (string file in filesList)
     {
         if (file == directory + fileName)
         {
             return(true);
         }
     }
     return(false);
 }
Exemplo n.º 29
0
        private string ReadAttachment(string name, PageInfo currentPage)
        {
            IFilesStorageProviderV30 filesStorageProvider = GetDefaultFilesStorageProvider();
            string content;

            using (var stream = new MemoryStream())
            {
                filesStorageProvider.RetrievePageAttachment(currentPage, name + ".htm", stream, false);
                content = StreamToString(stream);
            }
            return(content);
        }
Exemplo n.º 30
0
        /// <summary>
        /// Deletes and de-indexes a page attachment.
        /// </summary>
        /// <param name="provider">The provider.</param>
        /// <param name="pageFullName">The page full name.</param>
        /// <param name="name">The attachment name.</param>
        /// <returns><c>true</c> if the attachment was deleted, <c>false</c> otherwise.</returns>
        public static bool DeletePageAttachment(IFilesStorageProviderV30 provider, string pageFullName, string name)
        {
            if (provider == null)
            {
                throw new ArgumentNullException("provider");
            }

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

            if (pageFullName.Length == 0)
            {
                throw new ArgumentException("Page Full Name cannot be empty", "pageFullName");
            }

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

            if (name.Length == 0)
            {
                throw new ArgumentException("Name cannot be empty", "name");
            }

            PageInfo pageInfo = Pages.FindPage(pageFullName);

            if (pageInfo == null)
            {
                return(false);
            }
            PageContent page = Content.GetPageContent(pageInfo, false);

            if (page == null)
            {
                return(false);
            }

            bool done = provider.DeletePageAttachment(pageInfo, name);

            if (!done)
            {
                return(false);
            }

            SearchClass.UnindexPageAttachment(name, page);

            Host.Instance.OnAttachmentActivity(provider.GetType().FullName, name, pageFullName, null, FileActivity.AttachmentDeleted);

            return(true);
        }
Exemplo n.º 31
0
        /// <summary>
        /// Tries to enter a directory.
        /// </summary>
        /// <param name="provider">The provider.</param>
        /// <param name="directory">The full path of the directory.</param>
        public void TryEnterDirectory(string provider, string directory)
        {
            if(string.IsNullOrEmpty(directory) || string.IsNullOrEmpty(provider)) return;

            if(!directory.StartsWith("/")) directory = "/" + directory;
            if(!directory.EndsWith("/")) directory += "/";
            directory = directory.Replace("//", "/");

            LoadProviders();

            IFilesStorageProviderV30 realProvider = Collectors.FilesProviderCollector.GetProvider(provider);
            if(realProvider == null) return;
            this.provider = realProvider;

            // Detect existence
            try {
                realProvider.ListDirectories(directory);
            }
            catch(ArgumentException) {
                return;
            }

            bool canListThisSubDir = AuthChecker.CheckActionForDirectory(realProvider, directory, Actions.ForDirectories.List,
                SessionFacade.GetCurrentUsername(), SessionFacade.GetCurrentGroupNames());
            if(!canListThisSubDir) {
                return;
            }

            lstProviders.SelectedIndex = -1;
            foreach(ListItem item in lstProviders.Items) {
                if(item.Value == provider) {
                    item.Selected = true;
                    break;
                }
            }
            //lstProviders_SelectedIndexChanged(this, null);

            string parent = "/";
            string trimmedDirectory = directory.TrimEnd('/');
            if(trimmedDirectory.Length > 0) {
                int lastSlash = trimmedDirectory.LastIndexOf("/");
                if(lastSlash != -1) {
                    parent = "/" + trimmedDirectory.Substring(0, lastSlash) + "/";
                }
            }

            if(parent != directory) {
                CurrentDirectory = parent;
                EnterDirectory(Tools.ExtractDirectoryName(directory));
            }
        }
Exemplo n.º 32
0
        protected void rptItems_DataBinding(object sender, EventArgs e)
        {
            provider = Collectors.FilesProviderCollector.GetProvider(lstProviders.SelectedValue);

            if (provider == null || CurrentPage == null)
            {
                return;
            }

            // Build a DataTable containing the proper information
            var table = new DataTable("Items");

            table.Columns.Add("Name");
            table.Columns.Add("Size");
            table.Columns.Add("Editable", typeof(bool));
            table.Columns.Add("Page");
            table.Columns.Add("Link");
            table.Columns.Add("Downloads");
            table.Columns.Add("CanDelete", typeof(bool));
            table.Columns.Add("CanDownload", typeof(bool));

            var attachments = provider.ListPageAttachments(CurrentPage);

            foreach (var s in attachments)
            {
                FileDetails details = provider.GetPageAttachmentDetails(CurrentPage, s);

                DataRow row = table.NewRow();
                var     ext = Path.GetExtension(s).ToLowerInvariant();
                row["Name"]     = s;
                row["Size"]     = Tools.BytesToString(details.Size);
                row["Editable"] = canUpload && canDelete && (ext == ".jpg" || ext == ".jpeg" || ext == ".png");
                row["Page"]     = CurrentPage.FullName;
                if (canDownload)
                {
                    row["Link"] = "GetFile.aspx?File=" + Tools.UrlEncode(s).Replace("'", "&#39;") + "&amp;AsStreamAttachment=1&amp;Provider=" +
                                  provider.GetType().FullName + "&amp;IsPageAttachment=1&amp;Page=" +
                                  Tools.UrlEncode(CurrentPage.FullName) + "&amp;NoHit=1";
                }
                else
                {
                    row["Link"] = "";
                }
                row["Downloads"]   = details.RetrievalCount.ToString();
                row["CanDelete"]   = canDelete;
                row["CanDownload"] = canDownload;
                table.Rows.Add(row);
            }

            rptItems.DataSource = table;
        }
Exemplo n.º 33
0
        /// <summary>
        /// De-indexes all contents of a directory.
        /// </summary>
        /// <param name="provider">The provider.</param>
        /// <param name="directory">The directory.</param>
        private static void DeindexDirectory(IFilesStorageProviderV30 provider, string directory)
        {
            directory = NormalizeFullPath(directory);

            foreach (string sub in provider.ListDirectories(directory))
            {
                DeindexDirectory(provider, sub);
            }

            foreach (string file in provider.ListFiles(directory))
            {
                SearchClass.UnindexFile(provider.GetType().FullName + "|" + file);
            }
        }
Exemplo n.º 34
0
        /// <summary>
        /// Backups all the providers (excluded global settings storage provider).
        /// </summary>
        /// <param name="backupZipFileName">The name of the zip file where to store the backup file.</param>
        /// <param name="plugins">The available plugins.</param>
        /// <param name="settingsStorageProvider">The settings storage provider.</param>
        /// <param name="pagesStorageProviders">The pages storage providers.</param>
        /// <param name="usersStorageProviders">The users storage providers.</param>
        /// <param name="filesStorageProviders">The files storage providers.</param>
        /// <returns><c>true</c> if the backup has been succesfull.</returns>
        public static bool BackupAll(string backupZipFileName, string[] plugins, ISettingsStorageProviderV30 settingsStorageProvider, IPagesStorageProviderV30[] pagesStorageProviders, IUsersStorageProviderV30[] usersStorageProviders, IFilesStorageProviderV30[] filesStorageProviders)
        {
            string tempPath = Path.Combine(Environment.GetEnvironmentVariable("TEMP"), Guid.NewGuid().ToString());
            Directory.CreateDirectory(tempPath);

            using(ZipFile backupZipFile = new ZipFile(backupZipFileName)) {

                // Find all namespaces
                List<string> namespaces = new List<string>();
                foreach(IPagesStorageProviderV30 pagesStorageProvider in pagesStorageProviders) {
                    foreach(NamespaceInfo ns in pagesStorageProvider.GetNamespaces()) {
                        namespaces.Add(ns.Name);
                    }
                }

                // Backup settings storage provider
                string zipSettingsBackup = Path.Combine(tempPath, "SettingsBackup-" + settingsStorageProvider.GetType().FullName + ".zip");
                BackupSettingsStorageProvider(zipSettingsBackup, settingsStorageProvider, namespaces.ToArray(), plugins);
                backupZipFile.AddFile(zipSettingsBackup, "");

                // Backup pages storage providers
                foreach(IPagesStorageProviderV30 pagesStorageProvider in pagesStorageProviders) {
                    string zipPagesBackup = Path.Combine(tempPath, "PagesBackup-" + pagesStorageProvider.GetType().FullName + ".zip");
                    BackupPagesStorageProvider(zipPagesBackup, pagesStorageProvider);
                    backupZipFile.AddFile(zipPagesBackup, "");
                }

                // Backup users storage providers
                foreach(IUsersStorageProviderV30 usersStorageProvider in usersStorageProviders) {
                    string zipUsersProvidersBackup = Path.Combine(tempPath, "UsersBackup-" + usersStorageProvider.GetType().FullName + ".zip");
                    BackupUsersStorageProvider(zipUsersProvidersBackup, usersStorageProvider);
                    backupZipFile.AddFile(zipUsersProvidersBackup, "");
                }

                // Backup files storage providers
                foreach(IFilesStorageProviderV30 filesStorageProvider in filesStorageProviders) {
                    string zipFilesProviderBackup = Path.Combine(tempPath, "FilesBackup-" + filesStorageProvider.GetType().FullName + ".zip");
                    BackupFilesStorageProvider(zipFilesProviderBackup, filesStorageProvider, pagesStorageProviders);
                    backupZipFile.AddFile(zipFilesProviderBackup, "");
                }
                backupZipFile.Save();
            }

            Directory.Delete(tempPath, true);
            return true;
        }
Exemplo n.º 35
0
        /// <summary>
        /// Removes all the ACL entries for a subject.
        /// </summary>
        /// <param name="subject">The subject.</param>
        /// <param name="provider">The provider.</param>
        /// <param name="directory">The directory.</param>
        /// <returns><c>true</c> if the operation succeeded, <c>false</c> otherwise.</returns>
        private bool RemoveAllAclEntriesForDirectory(string subject, IFilesStorageProviderV30 provider, string directory)
        {
            bool isGroup = lstSubjects.SelectedValue.StartsWith("G.");
            subject = subject.Substring(2);

            if(isGroup) {
                return AuthWriter.RemoveEntriesForDirectory(
                    Users.FindUserGroup(subject), provider, directory);
            }
            else {
                return AuthWriter.RemoveEntriesForDirectory(
                    Users.FindUser(subject), provider, directory);
            }
        }
Exemplo n.º 36
0
        /// <summary>
        /// Gets all the actions for a directory that are granted to a subject.
        /// </summary>
        /// <param name="subject">The subject.</param>
        /// <param name="provider">The provider.</param>
        /// <param name="directory">The directory.</param>
        /// <returns>The granted actions.</returns>
        private static string[] RetrieveGrantsForDirectory(string subject, IFilesStorageProviderV30 provider, string directory)
        {
            if(provider == null) throw new ArgumentNullException("provider");
            if(directory == null) throw new ArgumentNullException("directory");
            if(directory.Length == 0) throw new ArgumentException("Directory cannot be empty", "directory");

            string resourceName = Actions.ForDirectories.ResourceMasterPrefix + AuthTools.GetDirectoryName(provider, directory);

            AclEntry[] entries = SettingsProvider.AclManager.RetrieveEntriesForSubject(subject);

            List<string> result = new List<string>(entries.Length);

            foreach(AclEntry entry in entries) {
                if(entry.Value == Value.Grant && entry.Resource == resourceName) {
                    result.Add(entry.Action);
                }
            }

            return result.ToArray();
        }
Exemplo n.º 37
0
        /// <summary>
        /// Adds some ACL entries for a subject.
        /// </summary>
        /// <param name="subject">The subject.</param>
        /// <param name="provider">The provider.</param>
        /// <param name="directory">The directory.</param>
        /// <param name="grants">The granted actions.</param>
        /// <param name="denials">The denies actions.</param>
        /// <returns><c>true</c> if the operation succeeded, <c>false</c> otherwise.</returns>
        private bool AddAclEntriesForDirectory(string subject, IFilesStorageProviderV30 provider, string directory, string[] grants, string[] denials)
        {
            bool isGroup = subject.StartsWith("G.");
            subject = subject.Substring(2);

            UserGroup group = null;
            UserInfo user = null;

            if(isGroup) group = Users.FindUserGroup(subject);
            else user = Users.FindUser(subject);

            foreach(string action in grants) {
                bool done = false;
                if(isGroup) {
                    done = AuthWriter.SetPermissionForDirectory(AuthStatus.Grant,
                        provider, directory, action, group);
                }
                else {
                    done = AuthWriter.SetPermissionForDirectory(AuthStatus.Grant,
                        provider, directory, action, user);
                }
                if(!done) return false;
            }

            foreach(string action in denials) {
                bool done = false;
                if(isGroup) {
                    done = AuthWriter.SetPermissionForDirectory(AuthStatus.Deny,
                        provider, directory, action, group);
                }
                else {
                    done = AuthWriter.SetPermissionForDirectory(AuthStatus.Deny,
                        provider, directory, action, user);
                }
                if(!done) return false;
            }

            return true;
        }
Exemplo n.º 38
0
        /// <summary>
        /// Lists all directories in a provider, including the root.
        /// </summary>
        /// <param name="provider">The provider.</param>
        /// <returns>The directories.</returns>
        private static List<string> ListDirectories(IFilesStorageProviderV30 provider)
        {
            List<string> directories = new List<string>(50);
            directories.Add("/");

            ListDirectoriesRecursive(provider, "/", directories);

            return directories;
        }
Exemplo n.º 39
0
        /// <summary>
        /// Sets a permission for a directory.
        /// </summary>
        /// <param name="status">The authorization status.</param>
        /// <param name="provider">The provider that handles the directory.</param>
        /// <param name="directory">The directory.</param>
        /// <param name="action">The action of which to modify the authorization status.</param>
        /// <param name="user">The user subject of the authorization change.</param>
        /// <returns><c>true</c> if the authorization status is changed, <c>false</c> otherwise.</returns>
        public static bool SetPermissionForDirectory(AuthStatus status, IFilesStorageProviderV30 provider, string directory, string action, UserInfo user)
        {
            if(user == null) throw new ArgumentNullException("user");

            return SetPermissionForDirectory(status, provider, directory, action, AuthTools.PrepareUsername(user.Username));
        }
Exemplo n.º 40
0
 protected void lstProviders_SelectedIndexChanged(object sender, EventArgs e)
 {
     provider = Collectors.FilesProviderCollector.GetProvider(lstProviders.SelectedValue);
     GoToRoot();
 }
Exemplo n.º 41
0
        private List<TreeElement> BuildImagesSubTree(IFilesStorageProviderV30 provider, string path)
        {
            string[] dirs = new string[0];
            string[] files = new string[0];

            if(chkImageAttachments.Checked) {
                // Load page attachments
                files = provider.ListPageAttachments(currentPage);
            }
            else {
                // Load files
                dirs = provider.ListDirectories(path);
                files = provider.ListFiles(path);
            }

            List<TreeElement> result = new List<TreeElement>(100);

            foreach(string d in dirs) {
                TreeElement item = new TreeElement(d, Tools.ExtractDirectoryName(d),
                    BuildImagesSubTree(provider, d));
                // Do not display empty folders to reduce "noise"
                if(item.SubItems.Count > 0) {
                    result.Add(item);
                }
            }

            foreach(string f in files) {
                if(IsImage(f)) {
                    string name = provider.GetType().ToString() + "|" + f;
                    TreeElement item = new TreeElement(name,
                        @"<img src=""Thumb.aspx?Provider=" + provider.GetType().ToString() +
                        @"&amp;Size=Small&amp;File=" + Tools.UrlEncode(f) +
                        @"&amp;Page=" + (chkImageAttachments.Checked ? Tools.UrlEncode(currentPage.FullName) : "") +
                        @""" alt=""" + name + @""" /><span class=""imageinfo"">" + f.Substring(f.LastIndexOf("/") + 1) + "</span>",
                        "javascript:return SelectImage('" +
                        (chkImageAttachments.Checked ? "(" + currentPage.FullName + ")" : "") + "', '" + f + "', '" +
                        (chkImageAttachments.Checked ? currentPage.FullName : "") + "');");
                    result.Add(item);
                }
            }

            return result;
        }
Exemplo n.º 42
0
 private bool FileExists(IFilesStorageProviderV30 filesStorageProvider, string directory, string fileName)
 {
     string[] filesList = filesStorageProvider.ListFiles(directory);
     foreach(string file in filesList) {
         if(file == directory + fileName) return true;
     }
     return false;
 }
Exemplo n.º 43
0
 private bool DirectoryExists(IFilesStorageProviderV30 filesStorageProvider, string directoryName)
 {
     string[] directoryList = filesStorageProvider.ListDirectories("/");
     foreach(string dir in directoryList) {
         if(dir == directoryName) return true;
     }
     return false;
 }
Exemplo n.º 44
0
        /// <summary>
        /// Processes the renaming of a directory.
        /// </summary>
        /// <param name="provider">The provider.</param>
        /// <param name="oldName">The old directory name (full path).</param>
        /// <param name="newName">The new directory name (full path).</param>
        /// <returns><c>true</c> if the operation completed successfully, <c>false</c> otherwise.</returns>
        /// <remarks>The method <b>does not</b> recurse in sub-directories.</remarks>
        public static bool ProcessDirectoryRenaming(IFilesStorageProviderV30 provider, string oldName, string newName)
        {
            if(provider == null) throw new ArgumentNullException("provider");

            if(oldName == null) throw new ArgumentNullException("oldName");
            if(oldName.Length == 0) throw new ArgumentException("Old Name cannot be empty", "oldName");

            if(newName == null) throw new ArgumentNullException("newName");
            if(newName.Length == 0) throw new ArgumentException("New Name cannot be empty", "newName");

            return SettingsProvider.AclManager.RenameResource(
                Actions.ForDirectories.ResourceMasterPrefix + AuthTools.GetDirectoryName(provider, oldName),
                Actions.ForDirectories.ResourceMasterPrefix + AuthTools.GetDirectoryName(provider, newName));
        }
Exemplo n.º 45
0
        /// <summary>
        /// Traverses a directory tree, indexing all files.
        /// </summary>
        /// <param name="index">The output index.</param>
        /// <param name="provider">The provider.</param>
        /// <param name="currentDir">The current directory.</param>
        private static void TraverseDirectories(InMemoryIndexBase index, IFilesStorageProviderV30 provider, string currentDir)
        {
            // Store files in the index
            foreach(string file in provider.ListFiles(currentDir)) {
                FileDetails details = provider.GetFileDetails(file);
                index.StoreDocument(new FileDocument(file, provider.GetType().FullName, details.LastModified),
                    new string[0], "", null);
            }

            // Recursively process all sub-directories
            foreach(string directory in provider.ListDirectories(currentDir)) {
                TraverseDirectories(index, provider, directory);
            }
        }
Exemplo n.º 46
0
        /// <summary>
        /// Removes all the ACL Entries for a directory that are bound to a user group.
        /// </summary>
        /// <param name="group">The group.</param>
        /// <param name="provider">The provider.</param>
        /// <param name="directory">The directory.</param>
        /// <returns><c>true</c> if the operation succeeded, <c>false</c> otherwise.</returns>
        public static bool RemoveEntriesForDirectory(UserGroup group, IFilesStorageProviderV30 provider, string directory)
        {
            if(group == null) throw new ArgumentNullException("group");

            return RemoveEntriesForDirectory(AuthTools.PrepareGroup(group.Name), provider, directory);
        }
Exemplo n.º 47
0
        /// <summary>
        /// Removes all the ACL Entries for a directory that are bound to a user.
        /// </summary>
        /// <param name="user">The user.</param>
        /// <param name="provider">The provider.</param>
        /// <param name="directory">The directory.</param>
        /// <returns><c>true</c> if the operation succeeded, <c>false</c> otherwise.</returns>
        public static bool RemoveEntriesForDirectory(UserInfo user, IFilesStorageProviderV30 provider, string directory)
        {
            if(user == null) throw new ArgumentNullException("user");

            return RemoveEntriesForDirectory(AuthTools.PrepareUsername(user.Username), provider, directory);
        }
Exemplo n.º 48
0
        /// <summary>
        /// Sets a permission for a directory.
        /// </summary>
        /// <param name="status">The authorization status.</param>
        /// <param name="provider">The provider that handles the directory.</param>
        /// <param name="directory">The directory.</param>
        /// <param name="action">The action of which to modify the authorization status.</param>
        /// <param name="group">The group subject of the authorization change.</param>
        /// <returns><c>true</c> if the authorization status is changed, <c>false</c> otherwise.</returns>
        public static bool SetPermissionForDirectory(AuthStatus status, IFilesStorageProviderV30 provider, string directory, string action, UserGroup group)
        {
            if(group == null) throw new ArgumentNullException("group");

            return SetPermissionForDirectory(status, provider, directory, action, AuthTools.PrepareGroup(group.Name));
        }
Exemplo n.º 49
0
        /// <summary>
        /// Retrieves the subjects that have ACL entries set for a directory.
        /// </summary>
        /// <param name="provider">The provider.</param>
        /// <param name="directory">The directory.</param>
        /// <returns>The subjects.</returns>
        public static SubjectInfo[] RetrieveSubjectsForDirectory(IFilesStorageProviderV30 provider, string directory)
        {
            if(provider == null) throw new ArgumentNullException("provider");
            if(directory == null) throw new ArgumentNullException("directory");
            if(directory.Length == 0) throw new ArgumentException("Directory cannot be empty", "directory");

            AclEntry[] entries = SettingsProvider.AclManager.RetrieveEntriesForResource(Actions.ForDirectories.ResourceMasterPrefix + AuthTools.GetDirectoryName(provider, directory));

            List<SubjectInfo> result = new List<SubjectInfo>(entries.Length);

            for(int i = 0; i < entries.Length; i++) {
                SubjectType type = AuthTools.IsGroup(entries[i].Subject) ? SubjectType.Group : SubjectType.User;

                // Remove the subject qualifier ('U.' or 'G.')
                string name = entries[i].Subject.Substring(2);

                if(result.Find(delegate(SubjectInfo x) { return x.Name == name && x.Type == type; }) == null) {
                    result.Add(new SubjectInfo(name, type));
                }
            }

            return result.ToArray();
        }
Exemplo n.º 50
0
        protected void rptItems_DataBinding(object sender, EventArgs e)
        {
            provider = Collectors.FilesProviderCollector.GetProvider(lstProviders.SelectedValue);

            if(provider == null || CurrentPage == null) {
                return;
            }

            // Build a DataTable containing the proper information
            DataTable table = new DataTable("Items");

            table.Columns.Add("Name");
            table.Columns.Add("Size");
            table.Columns.Add("Editable", typeof(bool));
            table.Columns.Add("Page");
            table.Columns.Add("Link");
            table.Columns.Add("Downloads");
            table.Columns.Add("CanDelete", typeof(bool));
            table.Columns.Add("CanDownload", typeof(bool));

            string[] attachments = provider.ListPageAttachments(CurrentPage);
            foreach(string s in attachments) {
                FileDetails details = provider.GetPageAttachmentDetails(CurrentPage, s);

                DataRow row = table.NewRow();
                string ext = Path.GetExtension(s).ToLowerInvariant();
                row["Name"] = s;
                row["Size"] = Tools.BytesToString(details.Size);
                row["Editable"] = canUpload && canDelete && (ext == ".jpg" || ext == ".jpeg" || ext == ".png");
                row["Page"] = CurrentPage.FullName;
                if(canDownload) {
                    row["Link"] = "GetFile.aspx?File=" + Tools.UrlEncode(s).Replace("'", "&#39;") + "&amp;AsStreamAttachment=1&amp;Provider=" +
                        provider.GetType().FullName + "&amp;IsPageAttachment=1&amp;Page=" +
                        Tools.UrlEncode(CurrentPage.FullName) + "&amp;NoHit=1";
                }
                else {
                    row["Link"] = "";
                }
                row["Downloads"] = details.RetrievalCount.ToString();
                row["CanDelete"] = canDelete;
                row["CanDownload"] = canDownload;
                table.Rows.Add(row);
            }

            rptItems.DataSource = table;
        }
Exemplo n.º 51
0
 private void SetProvider()
 {
     string p = Request["Provider"];
     if(string.IsNullOrEmpty(p)) {
         p = Settings.DefaultFilesProvider;
     }
     provider = Collectors.FilesProviderCollector.GetProvider(p);
 }
Exemplo n.º 52
0
 protected void lstProviders_SelectedIndexChanged(object sender, EventArgs e)
 {
     provider = Collectors.FilesProviderCollector.GetProvider(lstProviders.SelectedValue);
     rptItems.DataBind();
 }
Exemplo n.º 53
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if(!Page.IsPostBack) {
                permissionsManager.CurrentResourceName = "/";

                // Localized strings for JavaScript
                StringBuilder sb = new StringBuilder();
                sb.Append(@"<script type=""text/javascript"">" + "\n<!--\n");
                sb.Append("var ConfirmMessage = '");
                sb.Append(Properties.Messages.ConfirmOperation);
                sb.Append("';\r\n");
                sb.AppendFormat("var CurrentNamespace = \"{0}\";\r\n", Tools.DetectCurrentNamespace());
                sb.Append("// -->\n</script>\n");
                lblStrings.Text = sb.ToString();

                // Setup upload information (max file size, allowed file types)
                lblUploadFilesInfo.Text = lblUploadFilesInfo.Text.Replace("$1", Tools.BytesToString(Settings.MaxFileSize * 1024));
                sb = new StringBuilder();
                string[] aft = Settings.AllowedFileTypes;
                for(int i = 0; i < aft.Length; i++) {
                    sb.Append(aft[i].ToUpper());
                    if(i != aft.Length - 1) sb.Append(", ");
                }
                lblUploadFilesInfo.Text = lblUploadFilesInfo.Text.Replace("$2", sb.ToString());

                LoadProviders();

                permissionsManager.CurrentFilesProvider = lstProviders.SelectedValue;

                // See if a dir is specified in query string
                if(Request["Dir"] != null) {
                    string currDir = Request["Dir"];
                    if(!currDir.StartsWith("/")) currDir = "/" + currDir;
                    if(!currDir.EndsWith("/")) currDir += "/";
                    CurrentDirectory = currDir;
                }
            }

            // Set provider
            provider = Collectors.FilesProviderCollector.GetProvider(lstProviders.SelectedValue);

            // The following actions are verified ***FOR THE CURRENT DIRECTORY***:
            // - List contents
            // - Download files
            // - Upload files
            // - Create directories
            // - Delete/Rename files -> hide/show buttons in repeater
            // - Delete/Rename directories --> hide/show buttons in repeater
            // - Manage Permissions -> avoid setting permissionsManager.CurrentResourceName/CurrentFilesProvider if not authorized
            // - Member of Administrators -> hide/show provider selection
            // ---> recheck everywhere an action is performed

            DetectPermissions();

            if(!Page.IsPostBack) {
                rptItems.DataBind();
            }

            PopulateBreadcrumb();

            SetupControlsForPermissions();
        }
Exemplo n.º 54
0
        private List<TreeElement> BuildFilesSubTree(IFilesStorageProviderV30 provider, string path)
        {
            string[] dirs = new string[0];
            string[] files = new string[0];

            if(chkFilesAttachments.Checked) {
                // Load page attachments
                files = provider.ListPageAttachments(currentPage);
            }
            else {
                // Load files
                dirs = provider.ListDirectories(path);
                files = provider.ListFiles(path);
            }

            List<TreeElement> result = new List<TreeElement>(100);

            foreach(string d in dirs) {
                TreeElement item = new TreeElement(d, Tools.ExtractDirectoryName(d),
                    BuildFilesSubTree(provider, d));
                // Do not display empty folders to reduce "noise"
                if(item.SubItems.Count > 0) {
                    result.Add(item);
                }
            }

            foreach(string f in files) {
                long size = chkFilesAttachments.Checked ? provider.GetPageAttachmentDetails(currentPage, f).Size : provider.GetFileDetails(f).Size;
                TreeElement item = new TreeElement(f, f.Substring(f.LastIndexOf("/") + 1) + " (" + Tools.BytesToString(size) + ")",
                    "javascript:return SelectFile('" +
                    (chkFilesAttachments.Checked ? "(" + currentPage.FullName + ")" : "") + "', '" + f.Replace("'", "\\'") + "');");
                result.Add(item);
            }

            return result;
        }
Exemplo n.º 55
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if(!Page.IsPostBack) {
                // Localized strings for JavaScript
                StringBuilder sb = new StringBuilder();
                sb.Append(@"<script type=""text/javascript"">" + "\r\n<!--\n");
                sb.Append("var ConfirmMessage = '");
                sb.Append(Properties.Messages.ConfirmOperation);
                sb.Append("';\r\n");
                sb.AppendFormat("var UploadControl = '{0}';\r\n", fileUpload.ClientID);
                //sb.AppendFormat("var RefreshCommandParameter = '{0}';\r\n", btnRefresh.UniqueID);
                sb.AppendFormat("var OverwriteControl = '{0}';\r\n", chkOverwrite.ClientID);
                sb.Append("// -->\n</script>\n");
                lblStrings.Text = sb.ToString();

                // Setup upload information (max file size, allowed file types)
                lblUploadFilesInfo.Text = lblUploadFilesInfo.Text.Replace("$1", Tools.BytesToString(Settings.MaxFileSize * 1024));
                sb = new StringBuilder();
                string[] aft = Settings.AllowedFileTypes;
                for(int i = 0; i < aft.Length; i++) {
                    sb.Append(aft[i].ToUpper());
                    if(i != aft.Length - 1) sb.Append(", ");
                }
                lblUploadFilesInfo.Text = lblUploadFilesInfo.Text.Replace("$2", sb.ToString());

                // Load Providers
                foreach(IFilesStorageProviderV30 prov in Collectors.FilesProviderCollector.AllProviders) {
                    ListItem item = new ListItem(prov.Information.Name, prov.GetType().FullName);
                    if(item.Value == Settings.DefaultFilesProvider) {
                        item.Selected = true;
                    }
                    lstProviders.Items.Add(item);
                }

                if(CurrentPage == null) btnUpload.Enabled = false;
            }

            // Set provider
            provider = Collectors.FilesProviderCollector.GetProvider(lstProviders.SelectedValue);

            if(!Page.IsPostBack) {
                rptItems.DataBind();
            }

            DetectPermissions();
            SetupControls();
        }
Exemplo n.º 56
0
        /// <summary>
        /// Backups the files storage provider.
        /// </summary>
        /// <param name="zipFileName">The zip file name where to store the backup.</param>
        /// <param name="filesStorageProvider">The files storage provider.</param>
        /// <param name="pagesStorageProviders">The pages storage providers.</param>
        /// <returns><c>true</c> if the backup file has been succesfully created.</returns>
        public static bool BackupFilesStorageProvider(string zipFileName, IFilesStorageProviderV30 filesStorageProvider, IPagesStorageProviderV30[] pagesStorageProviders)
        {
            JavaScriptSerializer javascriptSerializer = new JavaScriptSerializer();
            javascriptSerializer.MaxJsonLength = javascriptSerializer.MaxJsonLength * 10;

            string tempDir = Path.Combine(Environment.GetEnvironmentVariable("TEMP"), Guid.NewGuid().ToString());
            Directory.CreateDirectory(tempDir);

            DirectoryBackup directoriesBackup = BackupDirectory(filesStorageProvider, tempDir, null);
            FileStream tempFile = File.Create(Path.Combine(tempDir, "Files.json"));
            byte[] buffer = Encoding.Unicode.GetBytes(javascriptSerializer.Serialize(directoriesBackup));
            tempFile.Write(buffer, 0, buffer.Length);
            tempFile.Close();

            // Backup Pages Attachments
            string[] pagesWithAttachment = filesStorageProvider.GetPagesWithAttachments();
            foreach(string pageWithAttachment in pagesWithAttachment) {
                PageInfo pageInfo = FindPageInfo(pageWithAttachment, pagesStorageProviders);
                if(pageInfo != null) {
                    string[] attachments = filesStorageProvider.ListPageAttachments(pageInfo);
                    List<AttachmentBackup> attachmentsBackup = new List<AttachmentBackup>(attachments.Length);
                    foreach(string attachment in attachments) {
                        FileDetails attachmentDetails = filesStorageProvider.GetPageAttachmentDetails(pageInfo, attachment);
                        attachmentsBackup.Add(new AttachmentBackup() {
                            Name = attachment,
                            PageFullName = pageWithAttachment,
                            LastModified = attachmentDetails.LastModified,
                            Size = attachmentDetails.Size
                        });
                        using(MemoryStream stream = new MemoryStream()) {
                            filesStorageProvider.RetrievePageAttachment(pageInfo, attachment, stream, false);
                            stream.Seek(0, SeekOrigin.Begin);
                            byte[] tempBuffer = new byte[stream.Length];
                            stream.Read(tempBuffer, 0, (int)stream.Length);

                            DirectoryInfo dir = Directory.CreateDirectory(Path.Combine(tempDir, Path.Combine("__attachments", pageInfo.FullName)));
                            tempFile = File.Create(Path.Combine(dir.FullName, attachment));
                            tempFile.Write(tempBuffer, 0, tempBuffer.Length);
                            tempFile.Close();
                        }
                    }
                    tempFile = File.Create(Path.Combine(tempDir, Path.Combine("__attachments", Path.Combine(pageInfo.FullName, "Attachments.json"))));
                    buffer = Encoding.Unicode.GetBytes(javascriptSerializer.Serialize(attachmentsBackup));
                    tempFile.Write(buffer, 0, buffer.Length);
                    tempFile.Close();
                }
            }

            tempFile = File.Create(Path.Combine(tempDir, "Version.json"));
            buffer = Encoding.Unicode.GetBytes(javascriptSerializer.Serialize(generateVersionFile("Files")));
            tempFile.Write(buffer, 0, buffer.Length);
            tempFile.Close();

            using(ZipFile zipFile = new ZipFile()) {
                zipFile.AddDirectory(tempDir, "");
                zipFile.Save(zipFileName);
            }
            Directory.Delete(tempDir, true);

            return true;
        }
Exemplo n.º 57
0
 private static void ListDirectoriesRecursive(IFilesStorageProviderV30 provider, string current, List<string> output)
 {
     foreach(string dir in provider.ListDirectories(current)) {
         output.Add(dir);
         ListDirectoriesRecursive(provider, dir, output);
     }
 }
Exemplo n.º 58
0
        private static DirectoryBackup BackupDirectory(IFilesStorageProviderV30 filesStorageProvider, string zipFileName, string directory)
        {
            DirectoryBackup directoryBackup = new DirectoryBackup();

            string[] files = filesStorageProvider.ListFiles(directory);
            List<FileBackup> filesBackup = new List<FileBackup>(files.Length);
            foreach(string file in files) {
                FileDetails fileDetails = filesStorageProvider.GetFileDetails(file);
                filesBackup.Add(new FileBackup() {
                    Name = file,
                    Size = fileDetails.Size,
                    LastModified = fileDetails.LastModified
                });

                FileStream tempFile = File.Create(Path.Combine(zipFileName.Trim('/').Trim('\\'), file.Trim('/').Trim('\\')));
                using(MemoryStream stream = new MemoryStream()) {
                    filesStorageProvider.RetrieveFile(file, stream, false);
                    stream.Seek(0, SeekOrigin.Begin);
                    byte[] buffer = new byte[stream.Length];
                    stream.Read(buffer, 0, buffer.Length);
                    tempFile.Write(buffer, 0, buffer.Length);
                    tempFile.Close();
                }
            }
            directoryBackup.Name = directory;
            directoryBackup.Files = filesBackup;

            string[] directories = filesStorageProvider.ListDirectories(directory);
            List<DirectoryBackup> subdirectoriesBackup = new List<DirectoryBackup>(directories.Length);
            foreach(string d in directories) {
                subdirectoriesBackup.Add(BackupDirectory(filesStorageProvider, zipFileName, d));
            }
            directoryBackup.SubDirectories = subdirectoriesBackup;

            return directoryBackup;
        }
Exemplo n.º 59
0
        /// <summary>
        /// Removes all the ACL Entries for a directory that are bound to a subject.
        /// </summary>
        /// <param name="subject">The subject.</param>
        /// <param name="provider">The provider.</param>
        /// <param name="directory">The directory.</param>
        /// <returns><c>true</c> if the operation succeeded, <c>false</c> otherwise.</returns>
        private static bool RemoveEntriesForDirectory(string subject, IFilesStorageProviderV30 provider, string directory)
        {
            if(provider == null) throw new ArgumentNullException("provider");
            if(directory == null) throw new ArgumentNullException("directory");
            if(directory.Length == 0) throw new ArgumentException("Directory cannot be empty", "directory");

            string resourceName = Actions.ForDirectories.ResourceMasterPrefix + AuthTools.GetDirectoryName(provider, directory);

            AclEntry[] entries = SettingsProvider.AclManager.RetrieveEntriesForSubject(subject);

            foreach(AclEntry entry in entries) {
                if(entry.Resource == resourceName) {
                    // This call automatically logs the operation result
                    bool done = SetPermissionForDirectory(AuthStatus.Delete, provider, directory, entry.Action, subject);
                    if(!done) return false;
                }
            }

            return true;
        }
Exemplo n.º 60
0
        /// <summary>
        /// Sets a permission for a directory.
        /// </summary>
        /// <param name="status">The authorization status.</param>
        /// <param name="provider">The provider that handles the directory.</param>
        /// <param name="directory">The directory.</param>
        /// <param name="action">The action of which to modify the authorization status.</param>
        /// <param name="subject">The subject of the authorization change.</param>
        /// <returns><c>true</c> if the authorization status is changed, <c>false</c> otherwise.</returns>
        private static bool SetPermissionForDirectory(AuthStatus status, IFilesStorageProviderV30 provider, string directory, string action, string subject)
        {
            if(provider == null) throw new ArgumentNullException("provider");
            if(directory == null) throw new ArgumentNullException("directory");
            if(directory.Length == 0) throw new ArgumentException("Directory cannot be empty", "directory");
            if(action == null) throw new ArgumentNullException("action");
            if(action.Length == 0) throw new ArgumentException("Action cannot be empty", "action");
            if(action != Actions.FullControl && !AuthTools.IsValidAction(action, Actions.ForDirectories.All)) {
                throw new ArgumentException("Invalid action", "action");
            }

            string directoryName = AuthTools.GetDirectoryName(provider, directory);

            if(status == AuthStatus.Delete) {
                bool done = SettingsProvider.AclManager.DeleteEntry(Actions.ForDirectories.ResourceMasterPrefix + directoryName,
                    action, subject);

                if(done) {
                    Log.LogEntry(MessageDeleteSuccess + GetLogMessage(Actions.ForDirectories.ResourceMasterPrefix, directoryName,
                        action, subject, Delete), EntryType.General, Log.SystemUsername);
                }
                else {
                    Log.LogEntry(MessageDeleteFailure + GetLogMessage(Actions.ForDirectories.ResourceMasterPrefix, directoryName,
                        action, subject, Delete), EntryType.Error, Log.SystemUsername);
                }

                return done;
            }
            else {
                bool done = SettingsProvider.AclManager.StoreEntry(Actions.ForDirectories.ResourceMasterPrefix + directoryName,
                    action, subject, status == AuthStatus.Grant ? Value.Grant : Value.Deny);

                if(done) {
                    Log.LogEntry(MessageSetSuccess + GetLogMessage(Actions.ForDirectories.ResourceMasterPrefix, directoryName,
                        action, subject, Set + status.ToString()), EntryType.General, Log.SystemUsername);
                }
                else {
                    Log.LogEntry(MessageSetFailure + GetLogMessage(Actions.ForDirectories.ResourceMasterPrefix, directoryName,
                        action, subject, Set + status.ToString()), EntryType.Error, Log.SystemUsername);
                }

                return done;
            }
        }