/// <summary>
    /// Gets direct path for preview image of currently edited media file.
    /// </summary>
    private string GetPrevDirectPath()
    {
        string prevUrl = "";

        // Direct path
        string previewPath   = null;
        string previewFolder = null;

        if (Path.GetDirectoryName(FileInfo.FilePath).EndsWithCSafe(MediaLibraryHelper.GetMediaFileHiddenFolder(CMSContext.CurrentSiteName)))
        {
            previewFolder = Path.GetDirectoryName(FileInfo.FilePath) + "\\" + MediaLibraryHelper.GetPreviewFileName(FileInfo.FileName, FileInfo.FileExtension, ".*", CMSContext.CurrentSiteName);
            previewPath   = MediaLibraryInfoProvider.GetMediaLibraryFolderPath(FileInfo.FileLibraryID) + "\\" + previewFolder;
        }
        else
        {
            previewFolder = Path.GetDirectoryName(FileInfo.FilePath) + "\\" + MediaLibraryHelper.GetMediaFileHiddenFolder(CMSContext.CurrentSiteName) + "\\" + MediaLibraryHelper.GetPreviewFileName(FileInfo.FileName, FileInfo.FileExtension, ".*", CMSContext.CurrentSiteName);
            previewPath   = MediaLibraryInfoProvider.GetMediaLibraryFolderPath(FileInfo.FileLibraryID) + "\\" + previewFolder;
        }
        if (Directory.Exists(Path.GetDirectoryName(previewPath)))
        {
            string[] files = Directory.GetFiles(Path.GetDirectoryName(previewPath), Path.GetFileName(previewPath));
            if (files.Length > 0)
            {
                previewFolder = Path.GetDirectoryName(previewFolder).Replace('\\', '/').TrimStart('/');
                string prevFileName = Path.GetFileName(files[0]);

                prevUrl = MediaFileInfoProvider.GetMediaFileUrl(CMSContext.CurrentSiteName, LibraryInfo.LibraryFolder, previewFolder + '/' + prevFileName);
                prevUrl = URLHelper.ResolveUrl(prevUrl);
            }
        }

        return(prevUrl);
    }
    /// <summary>
    /// Validates form entries.
    /// </summary>
    /// <param name="action">Action type</param>
    /// <param name="siteName">Site name</param>
    public string ValidateForm(string action, string siteName)
    {
        string newFolderName = txtFolderName.Text.Trim();

        string errMsg = new Validator().NotEmpty(newFolderName, GetString("media.error.FolderNameIsEmpty")).
                        IsFolderName(newFolderName, GetString("media.error.FolderNameIsNotValid")).Result;

        if (String.IsNullOrEmpty(errMsg))
        {
            // Check special folder names
            if ((newFolderName == ".") || (newFolderName == ".."))
            {
                errMsg = GetString("media.error.FolderNameIsRelative");
            }

            if (String.IsNullOrEmpty(errMsg))
            {
                // Make a note that we are renaming existing folder
                bool mustExist = String.IsNullOrEmpty(Action) || (Action.ToLowerCSafe().Trim() != "new");

                // Check if folder with specified name exists already if required
                if (mustExist)
                {
                    // Existing folder is being renamed
                    if (!Directory.Exists(MediaLibraryInfoProvider.GetMediaLibraryFolderPath(siteName, DirectoryHelper.CombinePath(LibraryFolder, FolderPath))))
                    {
                        errMsg = GetString("media.error.FolderDoesNotExist");
                    }
                }

                if (String.IsNullOrEmpty(errMsg))
                {
                    string hiddenFolderName = MediaLibraryHelper.GetMediaFileHiddenFolder(siteName);
                    // Check if folder name is not reserved
                    if (string.Equals(hiddenFolderName, newFolderName, StringComparison.InvariantCultureIgnoreCase) || ValidationHelper.IsSpecialFolderName(newFolderName))
                    {
                        errMsg = String.Format(GetString("media.error.FolderNameIsReserved"), newFolderName);
                    }

                    if (String.IsNullOrEmpty(errMsg))
                    {
                        // Get new folder path
                        GetNewFolderPath(mustExist);

                        if (Path.EnsureForwardSlashes(FolderPath) != Path.EnsureForwardSlashes(mNewFolderPath))
                        {
                            // Check if new folder doesn't exist yet
                            if (Directory.Exists(MediaLibraryInfoProvider.GetMediaLibraryFolderPath(siteName, DirectoryHelper.CombinePath(LibraryFolder, mNewFolderPath))))
                            {
                                errMsg = GetString("media.error.FolderExists");
                            }
                        }
                    }
                }
            }
        }

        return(errMsg);
    }
Exemplo n.º 3
0
    /// <summary>
    /// Ensures the physical file.
    /// </summary>
    /// <param name="file">Output file</param>
    public bool EnsurePhysicalFile(CMSOutputMediaFile file)
    {
        if (file == null)
        {
            return(false);
        }

        // Try to link to file system
        if (String.IsNullOrEmpty(file.Watermark) && (file.MediaFile != null) && (file.MediaFile.FileID > 0))
        {
            SiteInfo si = SiteInfoProvider.GetSiteInfo(file.MediaFile.FileSiteID);
            if (si != null)
            {
                bool   generateThumbnails = ValidationHelper.GetBoolean(SettingsKeyInfoProvider.GetStringValue(si.SiteName + ".CMSGenerateThumbnails"), true);
                string filePath           = null;
                string libraryFolder      = Path.EnsureEndBackslash(MediaLibraryInfoProvider.GetMediaLibraryFolderPath(file.MediaFile.FileLibraryID));

                if (file.Resized && generateThumbnails)
                {
                    filePath = libraryFolder + MediaFileInfoProvider.EnsureThumbnailFile(file.MediaFile, file.SiteName, Width, Height, MaxSideSize, file.UsePreview);
                }
                else
                {
                    if (file.UsePreview)
                    {
                        // Get file path
                        string path             = MediaFileInfoProvider.GetMediaFilePath(file.MediaFile.FileLibraryID, file.MediaFile.FilePath);
                        string pathDirectory    = Path.GetDirectoryName(path);
                        string hiddenFolderPath = MediaLibraryHelper.GetMediaFileHiddenFolder(CurrentSiteName);
                        string folderPath       = String.Format("{0}\\{1}", pathDirectory, hiddenFolderPath);

                        // Ensure hidden folder exists
                        DirectoryHelper.EnsureDiskPath(folderPath, pathDirectory);
                        // Get preview file
                        string[] files = Directory.GetFiles(folderPath, MediaLibraryHelper.GetPreviewFileName(file.MediaFile.FileName, file.MediaFile.FileExtension, ".*", CurrentSiteName));
                        if (files.Length > 0)
                        {
                            filePath = files[0];
                        }
                    }
                    else
                    {
                        filePath = libraryFolder + file.MediaFile.FilePath;
                    }
                }

                if (filePath != null)
                {
                    // Link to the physical file
                    file.PhysicalFile = filePath;
                    return(true);
                }
            }
        }

        file.PhysicalFile = "";
        return(false);
    }
Exemplo n.º 4
0
    /// <summary>
    /// Processes the specified file.
    /// </summary>
    /// <param name="fileGuid">File guid</param>
    /// <param name="preview">Use preview</param>
    protected void ProcessFile(Guid fileGuid, bool preview)
    {
        // Get the file info if doesn't retrieved yet
        fileInfo = (fileInfo ?? MediaFileInfoProvider.GetMediaFileInfo(fileGuid, CurrentSiteName));
        if (fileInfo != null)
        {
            if (preview)
            {
                // Get file path
                string path             = MediaFileInfoProvider.GetMediaFilePath(fileInfo.FileLibraryID, fileInfo.FilePath);
                string pathDirectory    = Path.GetDirectoryName(path);
                string hiddenFolderPath = MediaLibraryHelper.GetMediaFileHiddenFolder(CurrentSiteName);
                string folderPath       = DirectoryHelper.CombinePath(pathDirectory, hiddenFolderPath);


                // Ensure hidden folder exists
                DirectoryHelper.EnsureDiskPath(folderPath, pathDirectory);
                // Get preview file
                string[] files = Directory.GetFiles(folderPath, MediaLibraryHelper.GetPreviewFileName(fileInfo.FileName, fileInfo.FileExtension, ".*", CurrentSiteName));
                if (files.Length > 0)
                {
                    bool resizeImage = (ImageHelper.IsImage(Path.GetExtension(files[0])) && MediaFileInfoProvider.CanResizeImage(files[0], Width, Height, MaxSideSize));

                    // Get the data
                    if ((outputFile == null) || (outputFile.MediaFile == null))
                    {
                        outputFile               = NewOutputFile(fileInfo, null);
                        outputFile.UsePreview    = true;
                        outputFile.Width         = Width;
                        outputFile.Height        = Height;
                        outputFile.MaxSideSize   = MaxSideSize;
                        outputFile.Resized       = resizeImage;
                        outputFile.FileExtension = Path.GetExtension(files[0]);
                        outputFile.MimeType      = MimeTypeHelper.GetMimetype(outputFile.FileExtension);
                    }
                }
            }
            else
            {
                bool resizeImage = (ImageHelper.IsImage(fileInfo.FileExtension) && MediaFileInfoProvider.CanResizeImage(fileInfo, Width, Height, MaxSideSize));

                // Get the data
                if ((outputFile == null) || (outputFile.MediaFile == null))
                {
                    outputFile             = NewOutputFile(fileInfo, null);
                    outputFile.Width       = Width;
                    outputFile.Height      = Height;
                    outputFile.MaxSideSize = MaxSideSize;
                    outputFile.Resized     = resizeImage;
                }
            }
        }
    }
Exemplo n.º 5
0
    /// <summary>
    /// Gets direct path for preview image of currently edited media file.
    /// </summary>
    private string GetPreviewDirectPath()
    {
        string prevUrl = "";

        string hiddenFolder = String.Empty;

        if (!Path.GetDirectoryName(FileInfo.FilePath).EndsWithCSafe(MediaLibraryHelper.GetMediaFileHiddenFolder(SiteContext.CurrentSiteName)))
        {
            hiddenFolder = MediaLibraryHelper.GetMediaFileHiddenFolder(SiteContext.CurrentSiteName);
        }

        // Get relative folder under media library when file is located
        string dirName = Path.GetDirectoryName(FileInfo.FilePath);
        // Get preview file searching pattern
        string previewFilePattern = MediaLibraryHelper.GetPreviewFileName(FileInfo.FileName, FileInfo.FileExtension, ".*", SiteContext.CurrentSiteName);

        // Create path for thumbnails searching
        string previewFolder = String.Format("{0}{1}{2}", String.IsNullOrEmpty(dirName) ? String.Empty : dirName + "\\",
                                             String.IsNullOrEmpty(hiddenFolder) ? String.Empty : hiddenFolder + "\\", previewFilePattern);

        // Get absolute path
        string previewPath = MediaLibraryInfoProvider.GetMediaLibraryFolderPath(FileInfo.FileLibraryID) + "\\" + previewFolder;

        if (Directory.Exists(Path.GetDirectoryName(previewPath)))
        {
            string[] files = Directory.GetFiles(Path.GetDirectoryName(previewPath), Path.GetFileName(previewPath));
            if (files.Length > 0)
            {
                previewFolder = Path.EnsureSlashes(Path.GetDirectoryName(previewFolder), true);
                string prevFileName = Path.GetFileName(files[0]);

                prevUrl = MediaFileInfoProvider.GetMediaFileUrl(SiteContext.CurrentSiteName, LibraryInfo.LibraryFolder, previewFolder + '/' + prevFileName);
                prevUrl = UrlResolver.ResolveUrl(prevUrl);
            }
        }

        return(prevUrl);
    }
Exemplo n.º 6
0
    /// <summary>
    /// Provides operations necessary to create and store new library file.
    /// </summary>
    private void HandleLibrariesUpload()
    {
        // Get related library info
        if (LibraryInfo != null)
        {
            MediaFileInfo mediaFile = null;

            // Get the site name
            SiteInfo si       = SiteInfoProvider.GetSiteInfo(LibraryInfo.LibrarySiteID);
            string   siteName = (si != null) ? si.SiteName : SiteContext.CurrentSiteName;

            string message = string.Empty;
            try
            {
                // Check the allowed extensions
                CheckAllowedExtensions();

                if (MediaFileID > 0)
                {
                    #region "Check permissions"

                    if (!MediaLibraryInfoProvider.IsUserAuthorizedPerLibrary(LibraryInfo, "FileModify"))
                    {
                        throw new Exception(GetString("media.security.nofilemodify"));
                    }

                    #endregion


                    mediaFile = MediaFileInfoProvider.GetMediaFileInfo(MediaFileID);
                    if (mediaFile != null)
                    {
                        // Ensure object version
                        SynchronizationHelper.EnsureObjectVersion(mediaFile);

                        if (IsMediaThumbnail)
                        {
                            string newFileExt = Path.GetExtension(ucFileUpload.FileName).TrimStart('.');
                            if ((ImageHelper.IsImage(newFileExt)) && (newFileExt.ToLowerCSafe() != "ico") &&
                                (newFileExt.ToLowerCSafe() != "wmf"))
                            {
                                // Update or creation of Media File update
                                string previewSuffix = MediaLibraryHelper.GetMediaFilePreviewSuffix(siteName);

                                if (!String.IsNullOrEmpty(previewSuffix))
                                {
                                    string previewExtension = Path.GetExtension(ucFileUpload.PostedFile.FileName);
                                    string previewName      = Path.GetFileNameWithoutExtension(MediaLibraryHelper.GetPreviewFileName(mediaFile.FileName, mediaFile.FileExtension, previewExtension, siteName, previewSuffix));
                                    string previewFolder    = DirectoryHelper.CombinePath(Path.EnsureSlashes(LibraryFolderPath.TrimEnd('/')), MediaLibraryHelper.GetMediaFileHiddenFolder(siteName));

                                    byte[] previewFileBinary = new byte[ucFileUpload.PostedFile.ContentLength];
                                    ucFileUpload.PostedFile.InputStream.Read(previewFileBinary, 0, ucFileUpload.PostedFile.ContentLength);

                                    // Delete current preview thumbnails
                                    MediaFileInfoProvider.DeleteMediaFilePreview(siteName, mediaFile.FileLibraryID, mediaFile.FilePath);

                                    // Save preview file
                                    MediaFileInfoProvider.SaveFileToDisk(siteName, LibraryInfo.LibraryFolder, previewFolder, previewName, previewExtension, mediaFile.FileGUID, previewFileBinary, false, false);

                                    // Log synchronization task
                                    SynchronizationHelper.LogObjectChange(mediaFile, TaskTypeEnum.UpdateObject);
                                }

                                // Drop the cache dependencies
                                CacheHelper.TouchKeys(MediaFileInfoProvider.GetDependencyCacheKeys(mediaFile, true));
                            }
                            else
                            {
                                message = GetString("media.file.onlyimgthumb");
                            }
                        }
                        else
                        {
                            // Get folder path
                            string path = Path.GetDirectoryName(DirectoryHelper.CombinePath(MediaLibraryInfoProvider.GetMediaLibraryFolderPath(LibraryInfo.LibraryID), mediaFile.FilePath));

                            // If file system permissions are sufficient for file update
                            if (DirectoryHelper.CheckPermissions(path, false, true, true, true))
                            {
                                // Delete existing media file
                                MediaFileInfoProvider.DeleteMediaFile(LibraryInfo.LibrarySiteID, LibraryInfo.LibraryID, mediaFile.FilePath, true);

                                // Update media file preview
                                if (MediaLibraryHelper.HasPreview(siteName, LibraryInfo.LibraryID, mediaFile.FilePath))
                                {
                                    // Get new unique file name
                                    string newName = URLHelper.GetSafeFileName(ucFileUpload.PostedFile.FileName, siteName);

                                    // Get new file path
                                    string newPath = DirectoryHelper.CombinePath(path, newName);
                                    newPath = MediaLibraryHelper.EnsureUniqueFileName(newPath);
                                    newName = Path.GetFileName(newPath);

                                    // Rename preview
                                    MediaLibraryHelper.MoveMediaFilePreview(mediaFile, newName);

                                    // Delete preview thumbnails
                                    MediaFileInfoProvider.DeleteMediaFilePreviewThumbnails(mediaFile);
                                }

                                // Receive media info on newly posted file
                                mediaFile = GetUpdatedFile(mediaFile);

                                // Save media file information
                                MediaFileInfoProvider.SetMediaFileInfo(mediaFile);
                            }
                            else
                            {
                                // Set error message
                                message = String.Format(GetString("media.accessdeniedtopath"), path);
                            }
                        }
                    }
                }
                else
                {
                    #region "Check permissions"

                    // Creation of new media file
                    if (!MediaLibraryInfoProvider.IsUserAuthorizedPerLibrary(LibraryInfo, "FileCreate"))
                    {
                        throw new Exception(GetString("media.security.nofilecreate"));
                    }

                    #endregion


                    // No file for upload specified
                    if (!ucFileUpload.HasFile)
                    {
                        throw new Exception(GetString("media.newfile.errorempty"));
                    }

                    // Create new media file record
                    mediaFile = new MediaFileInfo(ucFileUpload.PostedFile, LibraryID, LibraryFolderPath, ResizeToWidth, ResizeToHeight, ResizeToMaxSideSize, LibraryInfo.LibrarySiteID);

                    mediaFile.FileDescription = "";

                    // Save the new file info
                    MediaFileInfoProvider.SetMediaFileInfo(mediaFile);
                }
            }
            catch (Exception ex)
            {
                // Creation of new media file failed
                message = ex.Message;
            }
            finally
            {
                // Create media file info string
                string mediaInfo = "";
                if ((mediaFile != null) && (mediaFile.FileID > 0) && (IncludeNewItemInfo))
                {
                    mediaInfo = mediaFile.FileID + "|" + LibraryFolderPath.Replace('\\', '>').Replace("'", "\\'");
                }

                // Ensure message text
                message = HTMLHelper.EnsureLineEnding(message, " ");

                if (RaiseOnClick)
                {
                    ScriptHelper.RegisterStartupScript(Page, typeof(Page), "UploaderOnClick", ScriptHelper.GetScript("if (parent.UploaderOnClick) { parent.UploaderOnClick('" + MediaFileName.Replace(" ", "").Replace(".", "").Replace("-", "") + "'); }"));
                }

                string script = String.Format(@"
if (typeof(parent.DFU) !== 'undefined') {{ 
    parent.DFU.OnUploadCompleted('{0}'); 
}} 
if ((window.parent != null) && (/parentelemid={1}/i.test(window.location.href)) && (window.parent.InitRefresh_{1} != null)){{
    window.parent.InitRefresh_{1}({2}, false, '{3}'{4});
}}", QueryHelper.GetString("containerid", ""), ParentElemID, ScriptHelper.GetString(message.Trim()), mediaInfo, (InsertMode ? ", 'insert'" : ", 'update'"));

                // Call function to refresh parent window
                ScriptHelper.RegisterStartupScript(Page, typeof(Page), "RefreshParrent", ScriptHelper.GetScript(script));
            }
        }
    }
Exemplo n.º 7
0
    protected void btnUpload_Click(object sender, EventArgs e)
    {
        MediaLibraryInfo mli = MediaLibraryInfoProvider.GetMediaLibraryInfo(LibraryID);

        if (!MediaLibraryInfoProvider.IsUserAuthorizedPerLibrary(mli, "manage"))
        {
            // Check 'File create' permission
            if (!MediaLibraryInfoProvider.IsUserAuthorizedPerLibrary(mli, "filecreate"))
            {
                RaiseOnNotAllowed("filecreate");
                return;
            }
        }

        if (String.IsNullOrWhiteSpace(fileUploader.FileName) && !fileUploader.HasFile)
        {
            lblError.Text    = GetString("media.selectfile");
            lblError.Visible = true;
            return;
        }

        // Check if preview file is image
        if ((previewUploader.HasFile) &&
            (!ImageHelper.IsImage(Path.GetExtension(previewUploader.FileName))) &&
            (Path.GetExtension(previewUploader.FileName).ToLowerCSafe() != ".ico") &&
            (Path.GetExtension(previewUploader.FileName).ToLowerCSafe() != ".tif") &&
            (Path.GetExtension(previewUploader.FileName).ToLowerCSafe() != ".tiff") &&
            (Path.GetExtension(previewUploader.FileName).ToLowerCSafe() != ".wmf"))
        {
            lblError.Text    = GetString("Media.File.PreviewIsNotImage");
            lblError.Visible = true;
            return;
        }

        // Check if the preview file with given extension is allowed for library module
        // Check if file with given extension is allowed for library module
        string fileExt        = Path.GetExtension(fileUploader.FileName).TrimStart('.');
        string previewFileExt = Path.GetExtension(previewUploader.FileName).TrimStart('.');

        // Check file extension
        if (!MediaLibraryHelper.IsExtensionAllowed(fileExt))
        {
            lblError.Text    = String.Format(GetString("media.newfile.extensionnotallowed"), fileExt);
            lblError.Visible = true;
            return;
        }

        // Check preview extension
        if ((previewFileExt.Trim() != "") && !MediaLibraryHelper.IsExtensionAllowed(previewFileExt))
        {
            lblError.Text    = String.Format(GetString("media.newfile.extensionnotallowed"), previewFileExt);
            lblError.Visible = true;
            return;
        }

        if (mli != null)
        {
            try
            {
                // Create new Media file
                MediaFileInfo mfi = new MediaFileInfo(fileUploader.PostedFile, LibraryID, DestinationPath);

                // Save record to the database
                MediaFileInfoProvider.SetMediaFileInfo(mfi);

                // Save preview if presented
                if (previewUploader.HasFile)
                {
                    // Get preview suffix if not set
                    if (String.IsNullOrEmpty(PreviewSuffix))
                    {
                        PreviewSuffix = MediaLibraryHelper.GetMediaFilePreviewSuffix(SiteContext.CurrentSiteName);
                    }

                    if (!String.IsNullOrEmpty(PreviewSuffix))
                    {
                        // Get physical path within the media library
                        String path;
                        if ((DestinationPath != null) && DestinationPath.TrimEnd('/') != "")
                        {
                            path = DirectoryHelper.CombinePath(Path.EnsureBackslashes(DestinationPath, true), MediaLibraryHelper.GetMediaFileHiddenFolder(SiteContext.CurrentSiteName));
                        }
                        else
                        {
                            path = MediaLibraryHelper.GetMediaFileHiddenFolder(SiteContext.CurrentSiteName);
                        }

                        string previewExtension = Path.GetExtension(previewUploader.PostedFile.FileName);
                        string previewName      = Path.GetFileNameWithoutExtension(MediaLibraryHelper.GetPreviewFileName(mfi.FileName, mfi.FileExtension, previewExtension, SiteContext.CurrentSiteName, PreviewSuffix));

                        // Save preview file
                        MediaFileInfoProvider.SaveFileToDisk(SiteContext.CurrentSiteName, mli.LibraryFolder, path, previewName, previewExtension, mfi.FileGUID, previewUploader.PostedFile.InputStream, false);
                    }
                }

                // Clear cache
                if (PortalContext.CurrentPageManager != null)
                {
                    PortalContext.CurrentPageManager.ClearCache();
                }

                // Display info to the user
                lblInfo.Text    = GetString("media.fileuploaded");
                lblInfo.Visible = true;

                if (OnAfterFileUpload != null)
                {
                    OnAfterFileUpload();
                }
            }
            catch (Exception ex)
            {
                lblError.Visible = true;
                lblError.Text    = ex.Message;
                lblError.ToolTip = ex.StackTrace;
            }
        }
    }
Exemplo n.º 8
0
    /// <summary>
    /// Bind tree view.
    /// </summary>
    /// <param name="dirPath">Directory path</param>
    /// <param name="parentNode">Parent node</param>
    /// <param name="isRoot">Indicates if current parentNode is root</param>
    private void BindTreeView(string dirPath, TreeNode parentNode, bool isRoot = false)
    {
        if (Directory.Exists(dirPath))
        {
            string hidenFolder = "\\" + MediaLibraryHelper.GetMediaFileHiddenFolder(SiteContext.CurrentSiteName);

            // Get directories
            string[] dirs = null;
            try
            {
                dirs = Directory.GetDirectories(dirPath);
            }
            catch (Exception exception)
            {
                // Ignore directories that are not accessible
                if (!(exception is UnauthorizedAccessException || exception is IOExceptions.PathTooLongException))
                {
                    EventLogProvider.LogException("Media library", "READOBJ", exception);
                }
            }
            if (dirs != null)
            {
                int index = 1;
                foreach (string dir in dirs)
                {
                    if (!dir.EndsWithCSafe(hidenFolder, true))
                    {
                        int      dirCount    = 0;
                        string[] directories = null;
                        string[] files       = null;

                        string text = dir.Substring(dir.LastIndexOfCSafe('\\')).Trim('\\');

                        // Get the files and directories
                        try
                        {
                            if (DisplayFilesCount)
                            {
                                files = Directory.GetFiles(dir);
                            }

                            directories = Directory.GetDirectories(dir);
                            if (directories != null)
                            {
                                dirCount = directories.Length;
                            }
                        }
                        catch (Exception exception)
                        {
                            // Ignore files and directories that are not accessible
                            if (!(exception is UnauthorizedAccessException || exception is IOExceptions.PathTooLongException))
                            {
                                EventLogProvider.LogException("Media library", "READOBJ", exception);
                            }
                        }

                        TreeNode node;
                        if (ShowFolder(index))
                        {
                            if (DisplayFilesCount && (files != null))
                            {
                                node = CreateNode("<span class=\"Name\">" + text + " (" + files.Length + ")</span>", text, parentNode, dirCount, index);
                            }
                            else
                            {
                                node = CreateNode("<span class=\"Name\">" + text + "</span>", text, parentNode, dirCount, index);
                            }

                            if (dirCount == 1)
                            {
                                node.PopulateOnDemand = !directories[0].EndsWithCSafe(hidenFolder);
                            }
                            else
                            {
                                node.PopulateOnDemand = (dirCount > 0);
                            }

                            // Check if there is node within the current path to be selected
                            if (!string.IsNullOrEmpty(PathToSelect))
                            {
                                EnsureNodeExpand(parentNode, node);
                            }

                            parentNode.ChildNodes.Add(node);
                        }
                        else
                        {
                            node = CreateNode("<span class=\"Name\">" + GetString("general.seelisting") + "</span>", "", parentNode, 0, index);
                            parentNode.ChildNodes.Add(node);

                            RootHasMore = (isRoot && !CloseListing);
                        }

                        if (ShowFolder(index))
                        {
                            index++;
                        }
                        else
                        {
                            break;
                        }
                    }
                }
            }
        }
    }
    protected void btnOk_Click(object sender, EventArgs e)
    {
        MediaLibraryInfo mli = MediaLibraryInfoProvider.GetMediaLibraryInfo(LibraryID);

        // Check 'File create' permission
        if (!MediaLibraryInfoProvider.IsUserAuthorizedPerLibrary(mli, "filecreate"))
        {
            RaiseOnNotAllowed("filecreate");
            return;
        }

        // No file for upload specified
        if (!FileUpload.HasFile)
        {
            lblError.Text = GetString("media.newfile.errorempty");
            return;
        }

        // Check if preview file is image
        if ((PreviewUpload.HasFile) &&
            (!ImageHelper.IsImage(Path.GetExtension(PreviewUpload.FileName))) &&
            (Path.GetExtension(PreviewUpload.FileName).ToLowerCSafe() != ".ico") &&
            (Path.GetExtension(PreviewUpload.FileName).ToLowerCSafe() != ".tif") &&
            (Path.GetExtension(PreviewUpload.FileName).ToLowerCSafe() != ".tiff") &&
            (Path.GetExtension(PreviewUpload.FileName).ToLowerCSafe() != ".wmf"))
        {
            lblError.Text = GetString("Media.File.PreviewIsNotImage");
            return;
        }

        if (mli != null)
        {
            // Get file extension
            string fileExtension = Path.GetExtension(FileUpload.FileName).TrimStart('.');

            // Check file extension
            if (MediaLibraryHelper.IsExtensionAllowed(fileExtension))
            {
                try
                {
                    // Create new media file record
                    MediaFileInfo mediaFile = new MediaFileInfo(FileUpload.PostedFile, LibraryID, FolderPath);
                    mediaFile.FileDescription = txtFileDescription.Text;

                    // Save the new file info
                    MediaFileInfoProvider.SetMediaFileInfo(mediaFile);

                    // Save preview if presented
                    if (PreviewUpload.HasFile)
                    {
                        string previewSuffix = MediaLibraryHelper.GetMediaFilePreviewSuffix(CMSContext.CurrentSiteName);

                        if (!String.IsNullOrEmpty(previewSuffix))
                        {
                            string previewExtension = Path.GetExtension(PreviewUpload.PostedFile.FileName);
                            string previewName      = Path.GetFileNameWithoutExtension(MediaLibraryHelper.GetPreviewFileName(mediaFile.FileName, mediaFile.FileExtension, previewExtension, CMSContext.CurrentSiteName, previewSuffix));
                            string previewFolder    = MediaLibraryHelper.EnsurePath(FolderPath.TrimEnd('/')) + "/" + MediaLibraryHelper.GetMediaFileHiddenFolder(CMSContext.CurrentSiteName);

                            byte[] previewFileBinary = new byte[PreviewUpload.PostedFile.ContentLength];
                            PreviewUpload.PostedFile.InputStream.Read(previewFileBinary, 0, PreviewUpload.PostedFile.ContentLength);

                            // Save preview file
                            MediaFileInfoProvider.SaveFileToDisk(CMSContext.CurrentSiteName, mli.LibraryFolder, previewFolder, previewName, previewExtension, mediaFile.FileGUID, previewFileBinary, false);

                            // Log synchronization task
                            SynchronizationHelper.LogObjectChange(mediaFile, TaskTypeEnum.UpdateObject);
                        }
                    }

                    string normalizedFolderPath = MediaLibraryHelper.EnsurePath(FolderPath).Trim('/');

                    // If the event was fired by control itself- no save another media file should be proceeded
                    if (e != null)
                    {
                        ltlScript.Text += ScriptHelper.GetScript("RefreshAndClose('" + normalizedFolderPath.Replace("\'", "\\'") + "');");
                    }
                    else
                    {
                        ltlScript.Text += ScriptHelper.GetScript("RefreshParent('" + normalizedFolderPath.Replace("\'", "\\'") + "');");
                    }
                }
                catch (Exception ex)
                {
                    // Creation of new media file failed
                    lblError.Text = GetString("media.newfile.failed") + ": " + ex.Message;
                }
            }
            else
            {
                // The file with extension selected isn't allowed
                lblError.Text = String.Format(GetString("media.newfile.extensionnotallowed"), fileExtension);
            }
        }
    }
Exemplo n.º 10
0
    /// <summary>
    /// Bind tree view.
    /// </summary>
    /// <param name="dirPath">Directory path</param>
    /// <param name="parentNode">Parent node</param>
    private void BindTreeView(string dirPath, TreeNode parentNode, bool isRoot)
    {
        if (Directory.Exists(dirPath))
        {
            string folderImageTag = (DisplayFolderIcon ? "<img src=\"" + GetImageUrl("Design/Controls/Tree/folder.gif") + "\" alt=\"\" style=\"border:0px;vertical-align:middle;\" />" : "");
            string hidenFolder    = "\\" + MediaLibraryHelper.GetMediaFileHiddenFolder(CMSContext.CurrentSiteName);

            // Get directories
            string[] dirs = null;
            try
            {
                dirs = Directory.GetDirectories(dirPath);
            }
            catch (Exception exception)
            {
                // Ignore directories that are not accessible
                if (!(exception is UnauthorizedAccessException || exception is IOExceptions.PathTooLongException))
                {
                    EventLogProvider.LogException("Media library", "READOBJ", exception);
                }
            }
            if (dirs != null)
            {
                int index = 1;
                foreach (string dir in dirs)
                {
                    if (!dir.EndsWithCSafe(hidenFolder))
                    {
                        int      dirCount    = 0;
                        string[] directories = null;
                        string[] files       = null;

                        string text = dir.Substring(dir.LastIndexOfCSafe('\\')).Trim('\\');

                        // Get the files and directories
                        try
                        {
                            if (DisplayFilesCount)
                            {
                                files = Directory.GetFiles(dir);
                            }

                            directories = Directory.GetDirectories(dir);
                            if (directories != null)
                            {
                                dirCount = directories.Length;
                            }
                        }
                        catch (Exception exception)
                        {
                            // Ignore files and directories that are not accessible
                            if (!(exception is UnauthorizedAccessException || exception is IOExceptions.PathTooLongException))
                            {
                                EventLogProvider.LogException("Media library", "READOBJ", exception);
                            }
                        }

                        TreeNode node = null;
                        if (index <= MaxSubFolders)
                        {
                            if (DisplayFilesCount && (files != null))
                            {
                                node = CreateNode(folderImageTag + "<span class=\"Name\">" + text + " (" + files.Length + ")</span>", text, parentNode, dirCount, index);
                            }
                            else
                            {
                                node = CreateNode(folderImageTag + "<span class=\"Name\">" + text + "</span>", text, parentNode, dirCount, index);
                            }

                            if (dirCount == 1)
                            {
                                node.PopulateOnDemand = !directories[0].EndsWithCSafe(hidenFolder);
                            }
                            else
                            {
                                node.PopulateOnDemand = (dirCount > 0);
                            }

                            // Check if there is node within the current path to be selected
                            if (!string.IsNullOrEmpty(PathToSelect))
                            {
                                EnsureNodeExpand(parentNode, node);
                            }

                            parentNode.ChildNodes.Add(node);
                        }
                        else
                        {
                            node = CreateNode("<span class=\"Name\">" + GetString("contenttree.seelisting") + "</span>", "", parentNode, 0, index);
                            parentNode.ChildNodes.Add(node);

                            RootHasMore = (isRoot && !CloseListing);
                        }

                        if (index <= MaxSubFolders)
                        {
                            index++;
                        }
                        else
                        {
                            break;
                        }
                    }
                }
            }
        }
    }
Exemplo n.º 11
0
    /// <summary>
    /// Validates form entries.
    /// </summary>
    /// <param name="action">Action type</param>
    /// <param name="siteName">Site name</param>
    public string ValidateForm(string action, string siteName)
    {
        string errMsg = null;

        string newFolderName = this.txtFolderName.Text.Trim();

        errMsg = new Validator().NotEmpty(newFolderName, GetString("media.folder.foldernameempty")).
                 IsFolderName(newFolderName, GetString("media.folder.foldernameerror")).Result;

        if (String.IsNullOrEmpty(errMsg))
        {
            // Check special folder names
            if ((newFolderName == ".") || (newFolderName == ".."))
            {
                errMsg = GetString("media.folder.foldernameerror");
            }

            if (String.IsNullOrEmpty(errMsg))
            {
                bool mustExist = true;

                // Make a note that we are renaming existing folder
                if ((!String.IsNullOrEmpty(this.Action)) && (this.Action.ToLower().Trim() == "new"))
                {
                    mustExist = false;
                }

                // Check if folder with specified name exists already if required
                if (mustExist)
                {
                    // Existing folder is being renamed
                    if (!Directory.Exists(MediaLibraryInfoProvider.GetMediaLibraryFolderPath(siteName, DirectoryHelper.CombinePath(this.LibraryFolder, this.FolderPath))))
                    {
                        errMsg = GetString("media.folder.folderdoesntexist");
                    }
                }

                if (String.IsNullOrEmpty(errMsg))
                {
                    if ((newFolderName == MediaLibraryHelper.GetMediaFileHiddenFolder(siteName)) || ValidationHelper.IsSpecialFolderName(newFolderName))
                    {
                        errMsg = GetString("media.folder.folderrestricted");
                    }

                    if (String.IsNullOrEmpty(errMsg))
                    {
                        // Get new folder path
                        GetNewFolderPath(mustExist);

                        if (MediaLibraryHelper.EnsurePath(FolderPath) != MediaLibraryHelper.EnsurePath(mNewFolderPath))
                        {
                            // Check if new folder doesn't exist yet
                            if (Directory.Exists(MediaLibraryInfoProvider.GetMediaLibraryFolderPath(siteName, DirectoryHelper.CombinePath(this.LibraryFolder, this.mNewFolderPath))))
                            {
                                errMsg = GetString("media.folder.folderexist");
                            }
                        }
                    }
                }
            }
        }

        return(errMsg);
    }
Exemplo n.º 12
0
        /// <summary>
        /// Provides operations necessary to create and store new files in media library.
        /// </summary>
        /// <param name="args">Upload arguments.</param>
        /// <param name="context">HttpContext instance.</param>
        private void HandleMediaLibraryUpload(UploaderHelper args, HttpContext context)
        {
            string uploadPath = Path.Combine(MediaLibraryInfoProvider.GetMediaLibraryFolderPath(args.MediaLibraryArgs.LibraryID), args.MediaLibraryArgs.FolderPath);
            string filePath   = Path.Combine(uploadPath, args.FileName);

            MediaLibraryInfo mli = MediaLibraryInfoProvider.GetMediaLibraryInfo(args.MediaLibraryArgs.LibraryID);

            if (mli != null)
            {
                MediaFileInfo mediaFile = null;

                // Get the site name
                SiteInfo si       = SiteInfoProvider.GetSiteInfo(mli.LibrarySiteID);
                string   siteName = (si != null) ? si.SiteName : CMSContext.CurrentSiteName;

                try
                {
                    args.IsExtensionAllowed();

                    if (args.MediaLibraryArgs.MediaFileID > 0)
                    {
                        if (!MediaLibraryInfoProvider.IsUserAuthorizedPerLibrary(mli, "FileModify"))
                        {
                            throw new Exception(ResHelper.GetString("media.security.nofilemodify"));
                        }

                        mediaFile = MediaFileInfoProvider.GetMediaFileInfo(args.MediaLibraryArgs.MediaFileID);
                        if (mediaFile != null)
                        {
                            // Ensure object version
                            SynchronizationHelper.EnsureObjectVersion(mediaFile);

                            if (args.MediaLibraryArgs.IsMediaThumbnail)
                            {
                                if ((ImageHelper.IsImage(args.Extension)) && (args.Extension.ToLowerCSafe() != "ico") && (args.Extension.ToLowerCSafe() != "wmf"))
                                {
                                    // Update or creation of Media File update
                                    string previewSuffix = MediaLibraryHelper.GetMediaFilePreviewSuffix(siteName);

                                    if (!String.IsNullOrEmpty(previewSuffix))
                                    {
                                        //string previewExtension = Path.GetExtension(ucFileUpload.PostedFile.FileName);
                                        string previewName   = Path.GetFileNameWithoutExtension(MediaLibraryHelper.GetPreviewFileName(mediaFile.FileName, mediaFile.FileExtension, args.Extension, siteName, previewSuffix));
                                        string previewFolder = String.Format("{0}\\{1}", MediaLibraryHelper.EnsurePath(args.MediaLibraryArgs.FolderPath.TrimEnd('/')), MediaLibraryHelper.GetMediaFileHiddenFolder(siteName));

                                        // This method is limited to 2^32 byte files (4.2 GB)
                                        using (FileStream fs = File.OpenRead(args.FilePath))
                                        {
                                            byte[] previewFileBinary = new byte[fs.Length];
                                            fs.Read(previewFileBinary, 0, Convert.ToInt32(fs.Length));

                                            // Delete current preview thumbnails
                                            MediaFileInfoProvider.DeleteMediaFilePreview(siteName, mediaFile.FileLibraryID, mediaFile.FilePath, false);

                                            // Save preview file
                                            MediaFileInfoProvider.SaveFileToDisk(siteName, mli.LibraryFolder, previewFolder, previewName, args.Extension, mediaFile.FileGUID, previewFileBinary, false, false);

                                            // Log synchronization task
                                            SynchronizationHelper.LogObjectChange(mediaFile, TaskTypeEnum.UpdateObject);
                                            fs.Close();
                                        }
                                    }
                                    // Drop the cache dependencies
                                    CacheHelper.TouchKeys(MediaFileInfoProvider.GetDependencyCacheKeys(mediaFile, true));
                                }
                                else
                                {
                                    args.Message = ResHelper.GetString("media.file.onlyimgthumb");
                                }
                            }
                            else
                            {
                                // Get folder path
                                string path = Path.GetDirectoryName(DirectoryHelper.CombinePath(MediaLibraryInfoProvider.GetMediaLibraryFolderPath(mli.LibraryID), mediaFile.FilePath));

                                // If file system permissions are sufficient for file update
                                if (DirectoryHelper.CheckPermissions(path, false, true, true, true))
                                {
                                    // Delete existing media file
                                    MediaFileInfoProvider.DeleteMediaFile(mli.LibrarySiteID, mli.LibraryID, mediaFile.FilePath, true, false);

                                    // Update media file preview
                                    if (MediaLibraryHelper.HasPreview(siteName, mli.LibraryID, mediaFile.FilePath))
                                    {
                                        // Get new unique file name
                                        string newName = URLHelper.GetSafeFileName(Path.GetFileName(args.Name), siteName);

                                        // Get new file path
                                        string newPath = DirectoryHelper.CombinePath(path, newName);
                                        newPath = MediaLibraryHelper.EnsureUniqueFileName(newPath);
                                        newName = Path.GetFileName(newPath);

                                        // Rename preview
                                        MediaLibraryHelper.MoveMediaFilePreview(mediaFile, newName);

                                        // Delete preview thumbnails
                                        MediaFileInfoProvider.DeleteMediaFilePreviewThumbnails(mediaFile);
                                    }

                                    // Receive media info on newly posted file
                                    mediaFile = GetUpdatedFile(mediaFile.Generalized.DataClass, args, mli);

                                    MediaFileInfoProvider.SetMediaFileInfo(mediaFile);
                                }
                            }
                        }
                    }
                    else
                    {
                        // Check 'File create' permission
                        if (!MediaLibraryInfoProvider.IsUserAuthorizedPerLibrary(mli, "filecreate"))
                        {
                            throw new Exception(ResHelper.GetString("media.security.nofilecreate"));
                        }
                        mediaFile = new MediaFileInfo(args.FilePath, args.MediaLibraryArgs.LibraryID, args.MediaLibraryArgs.FolderPath, args.ResizeToWidth, args.ResizeToHeight, args.ResizeToMaxSide);
                        MediaFileInfoProvider.SetMediaFileInfo(mediaFile);
                    }
                }
                catch (Exception ex)
                {
                    // Creation of new media file failed
                    args.Message = ex.Message;

                    // The CMS.IO library uses reflection to create an instance of file stream
                    if (ex is System.Reflection.TargetInvocationException)
                    {
                        if (ex.InnerException != null && !String.IsNullOrEmpty(ex.Message))
                        {
                            args.Message = ex.InnerException.Message;
                        }
                    }

                    // Log the error
                    EventLogProvider.LogException("MultiFileUploader", "UPLOADMEDIA", ex);
                }
                finally
                {
                    if (args.RaiseOnClick)
                    {
                        args.AfterScript += string.Format(@"
                        if(window.UploaderOnClick) 
                        {{
                            window.UploaderOnClick('{0}');
                        }}", args.MediaLibraryArgs.MediaFileName.Replace(" ", "").Replace(".", "").Replace("-", ""));
                    }

                    // Create media library info string
                    string mediaInfo = ((mediaFile != null) && (mediaFile.FileID > 0) && (args.IncludeNewItemInfo)) ? String.Format("'{0}|{1}', ", mediaFile.FileID, args.MediaLibraryArgs.FolderPath.Replace('\\', '>').Replace("'", "\\'")) : "";

                    // Create after script and return it to the silverlight application, this script will be evaluated by the SL application in the end
                    args.AfterScript += string.Format(@"
                    if (window.InitRefresh_{0})
                    {{
                        window.InitRefresh_{0}('{1}', false, {2});
                    }}
                    else {{ 
                        if ('{1}' != '') {{
                            alert('{1}');
                        }}
                    }}", args.ParentElementID, ScriptHelper.GetString(args.Message.Trim(), false), mediaInfo + (args.IsInsertMode ? "'insert'" : "'update'"));

                    args.AddEventTargetPostbackReference();
                    context.Response.Write(args.AfterScript);
                    context.Response.Flush();
                }
            }
        }
Exemplo n.º 13
0
    /// <summary>
    /// Saves modified image data.
    /// </summary>
    /// <param name="name">Image name</param>
    /// <param name="extension">Image extension</param>
    /// <param name="mimetype">Image mimetype</param>
    /// <param name="title">Image title</param>
    /// <param name="description">Image description</param>
    /// <param name="binary">Image binary data</param>
    /// <param name="width">Image width</param>
    /// <param name="height">Image height</param>
    private void SaveImage(string name, string extension, string mimetype, string title, string description, byte[] binary, int width, int height)
    {
        // Process media file
        if (mfi == null)
        {
            mfi = MediaFileInfoProvider.GetMediaFileInfo(mediafileGuid, CurrentSiteName);
        }

        if (mfi != null)
        {
            MediaLibraryInfo mli = MediaLibraryInfoProvider.GetMediaLibraryInfo(mfi.FileLibraryID);
            if (mli != null)
            {
                string path          = Path.GetDirectoryName(DirectoryHelper.CombinePath(MediaLibraryInfoProvider.GetMediaLibraryFolderPath(mli.LibraryID), mfi.FilePath));
                bool   permissionsOK = DirectoryHelper.CheckPermissions(path, false, true, true, true);

                // Check file write permissions
                FileInfo file = FileInfo.New(MediaFileInfoProvider.GetMediaFilePath(mfi.FileLibraryID, mfi.FilePath));
                if (file != null)
                {
                    permissionsOK = permissionsOK && !file.IsReadOnly;
                }

                if (permissionsOK)
                {
                    MediaFileInfo originalMfi = mfi.Clone(true);

                    try
                    {
                        // Ensure object version
                        SynchronizationHelper.EnsureObjectVersion(mfi);

                        if (isPreview && !String.IsNullOrEmpty(PreviewPath))
                        {
                            SiteInfo si = SiteInfoProvider.GetSiteInfo(mfi.FileSiteID);
                            if (si != null)
                            {
                                string previewExt    = (!String.IsNullOrEmpty(extension) && (extension != OldPreviewExt)) ? extension : OldPreviewExt;
                                string previewName   = Path.GetFileNameWithoutExtension(PreviewPath);
                                string previewFolder = Path.EnsureSlashes(DirectoryHelper.CombinePath(Path.GetDirectoryName(mfi.FilePath).TrimEnd('/'), MediaLibraryHelper.GetMediaFileHiddenFolder(si.SiteName)));

                                // Delete old preview files with thumbnails
                                MediaFileInfoProvider.DeleteMediaFilePreview(SiteContext.CurrentSiteName, mli.LibraryID, mfi.FilePath);
                                MediaFileInfoProvider.DeleteMediaFilePreviewThumbnails(mfi);

                                // Save preview file
                                MediaFileInfoProvider.SaveFileToDisk(si.SiteName, mli.LibraryFolder, previewFolder, previewName, previewExt, mfi.FileGUID, binary, false, false);

                                // Log synchronization task
                                SynchronizationHelper.LogObjectChange(mfi, TaskTypeEnum.UpdateObject);
                            }
                        }
                        else
                        {
                            string newExt  = null;
                            string newName = null;

                            if (!String.IsNullOrEmpty(extension))
                            {
                                newExt = extension;
                            }
                            if (!String.IsNullOrEmpty(mimetype))
                            {
                                mfi.FileMimeType = mimetype;
                            }

                            mfi.FileTitle       = title;
                            mfi.FileDescription = description;

                            if (width > 0)
                            {
                                mfi.FileImageWidth = width;
                            }
                            if (height > 0)
                            {
                                mfi.FileImageHeight = height;
                            }
                            if (binary != null)
                            {
                                mfi.FileBinary = binary;
                                mfi.FileSize   = binary.Length;
                            }
                            // Test all parameters to empty values and update new value if available
                            if (!String.IsNullOrEmpty(name))
                            {
                                newName = name;
                            }
                            // If filename changed move preview file and remove all ald thumbnails
                            if ((!String.IsNullOrEmpty(newName) && (mfi.FileName != newName)) || (!String.IsNullOrEmpty(newExt) && (mfi.FileExtension.ToLowerCSafe() != newExt.ToLowerCSafe())))
                            {
                                SiteInfo si = SiteInfoProvider.GetSiteInfo(mfi.FileSiteID);
                                if (si != null)
                                {
                                    string fileName = (newName ?? mfi.FileName);
                                    string fileExt  = (newExt ?? mfi.FileExtension);

                                    string newPath = MediaFileInfoProvider.GetMediaFilePath(mfi.FileLibraryID, DirectoryHelper.CombinePath(Path.GetDirectoryName(mfi.FilePath), fileName) + fileExt);

                                    // Rename file only if file with same name does not exsists
                                    if (!File.Exists(newPath))
                                    {
                                        // Ensure max length of file path
                                        if (newPath.Length < 260)
                                        {
                                            // Remove old thumbnails
                                            MediaFileInfoProvider.DeleteMediaFileThumbnails(mfi);
                                            MediaFileInfoProvider.DeleteMediaFilePreviewThumbnails(mfi);

                                            // Move media file
                                            MediaFileInfoProvider.MoveMediaFile(si.SiteName, mli.LibraryID, mfi.FilePath, DirectoryHelper.CombinePath(Path.GetDirectoryName(mfi.FilePath), fileName) + fileExt, false);

                                            // Set new file name or extension
                                            mfi.FileName      = fileName;
                                            mfi.FileExtension = fileExt;
                                            mfi.FileMimeType  = MimeTypeHelper.GetMimetype(fileExt);

                                            // Ensure new binary
                                            if (binary != null)
                                            {
                                                mfi.FileBinary = binary;
                                                mfi.FileSize   = binary.Length;
                                            }
                                        }
                                        else
                                        {
                                            throw new IOExceptions.PathTooLongException();
                                        }
                                    }
                                    else
                                    {
                                        baseImageEditor.ShowError(GetString("img.errors.fileexists"));
                                        SavingFailed = true;
                                        return;
                                    }
                                }
                            }
                            else
                            {
                                // Remove old thumbnails
                                MediaFileInfoProvider.DeleteMediaFileThumbnails(mfi);

                                // Remove original media file before save
                                string filePath = MediaFileInfoProvider.GetMediaFilePath(mfi.FileLibraryID, mfi.FilePath);
                                if (File.Exists(filePath))
                                {
                                    File.Delete(filePath);
                                }
                            }

                            // Save new data
                            MediaFileInfoProvider.SetMediaFileInfo(mfi, false);
                        }
                    }
                    catch (Exception e)
                    {
                        // Log exception
                        EventLogProvider.LogException("ImageEditor", "Save file", e);

                        baseImageEditor.ShowError(GetString("img.errors.processing"), tooltipText: e.Message);
                        SavingFailed = true;
                        // Save original media file info
                        MediaFileInfoProvider.SetMediaFileInfo(originalMfi, false);
                    }
                }
                else // User hasn't permissions for save file
                {
                    baseImageEditor.ShowError(GetString("img.errors.filesystempermissions"));
                    SavingFailed = true;
                }
            }
        }
    }
Exemplo n.º 14
0
    /// <summary>
    /// Bind tree view.
    /// </summary>
    /// <param name="dirPath">Directory path</param>
    /// <param name="parentNode">Parent node</param>
    private void BindTreeView(string dirPath, TreeNode parentNode, bool isRoot)
    {
        if (Directory.Exists(dirPath))
        {
            string folderImageTag = (DisplayFolderIcon ? "<img src=\"" + GetImageUrl("Design/Controls/Tree/folder.gif") + "\" alt=\"\" style=\"border:0px;vertical-align:middle;\" />" : "");
            string hidenFolder    = "\\" + MediaLibraryHelper.GetMediaFileHiddenFolder(CMSContext.CurrentSiteName);

            // Get directories
            string[] dirs = null;
            try
            {
                dirs = Directory.GetDirectories(dirPath);
            }
            catch (Exception ex)
            {
                if (!IgnoreAccessDenied)
                {
                    throw new Exception(ex.Message, ex);
                }
            }
            if (dirs != null)
            {
                int index = 1;
                foreach (string dir in dirs)
                {
                    if (!dir.EndsWithCSafe(hidenFolder))
                    {
                        // Add node
                        string   text     = dir.Substring(dir.LastIndexOfCSafe('\\')).Trim('\\');
                        string[] files    = null;
                        int      dirCount = 0;

                        // Get the files and directories
                        try
                        {
                            files = Directory.GetFiles(dir);

                            string[] directories = Directory.GetDirectories(dir);
                            if (directories != null)
                            {
                                dirCount = directories.Length;
                            }
                        }
                        catch (Exception ex)
                        {
                            if (!IgnoreAccessDenied)
                            {
                                throw new Exception(ex.Message, ex);
                            }
                        }

                        TreeNode node = null;
                        if (index <= MaxSubFolders)
                        {
                            if (DisplayFilesCount && (files != null))
                            {
                                node = CreateNode(folderImageTag + "<span class=\"Name\">" + text + " (" + files.Length + ")</span>", text, parentNode, files.Length + dirCount, index);
                            }
                            else
                            {
                                node = CreateNode(folderImageTag + "<span class=\"Name\">" + text + "</span>", text, parentNode, dirCount, index);
                            }
                            parentNode.ChildNodes.Add(node);

                            // Recursive bind
                            BindTreeView(dir, node);
                        }
                        else if (!IsLiveSite)
                        {
                            // Render 'more' node only if not LiveSite
                            node = CreateNode("<span class=\"Name\">" + GetString("contenttree.seelisting") + "</span>", "", parentNode, 0, index);
                            parentNode.ChildNodes.Add(node);

                            RootHasMore = (isRoot && !CloseListing);
                        }

                        if (index <= MaxSubFolders)
                        {
                            index++;
                        }
                        else
                        {
                            break;
                        }
                    }
                }
            }
        }
    }
Exemplo n.º 15
0
    /// <summary>
    /// Bind tree view.
    /// </summary>
    /// <param name="dirPath">Directory path</param>
    /// <param name="parentNode">Parent node</param>
    /// <param name="isRoot">Indicates if root node</param>
    private void BindTreeView(string dirPath, TreeNode parentNode, bool isRoot = false)
    {
        if (Directory.Exists(dirPath))
        {
            string hidenFolder = "\\" + MediaLibraryHelper.GetMediaFileHiddenFolder(SiteContext.CurrentSiteName);

            // Get directories
            string[] dirs = null;
            try
            {
                dirs = Directory.GetDirectories(dirPath);
            }
            catch (Exception ex)
            {
                if (!IgnoreAccessDenied)
                {
                    throw new Exception(ex.Message, ex);
                }
            }
            if (dirs != null)
            {
                int index = 1;
                foreach (string dir in dirs)
                {
                    if (!dir.EndsWithCSafe(hidenFolder, true))
                    {
                        // Add node
                        string   text     = dir.Substring(dir.LastIndexOfCSafe('\\')).Trim('\\');
                        string[] files    = null;
                        int      dirCount = 0;

                        // Get the files and directories
                        try
                        {
                            files = Directory.GetFiles(dir);

                            string[] directories = Directory.GetDirectories(dir);
                            if (directories != null)
                            {
                                dirCount = directories.Length;
                            }
                        }
                        catch (Exception ex)
                        {
                            if (!IgnoreAccessDenied)
                            {
                                throw new Exception(ex.Message, ex);
                            }
                        }

                        TreeNode node;
                        if (index <= MaxSubFolders)
                        {
                            if (DisplayFilesCount && (files != null))
                            {
                                node = CreateNode("<span class=\"Name\">" + text + " (" + files.Length + ")</span>", text, parentNode, files.Length + dirCount, index);
                            }
                            else
                            {
                                node = CreateNode("<span class=\"Name\">" + text + "</span>", text, parentNode, dirCount, index);
                            }
                            parentNode.ChildNodes.Add(node);

                            // Recursive bind
                            BindTreeView(dir, node);
                        }
                        else if (!IsLiveSite)
                        {
                            // Render 'more' node only if not LiveSite
                            node = CreateNode("<span class=\"Name\">" + GetString("general.seelisting") + "</span>", "", parentNode, 0, index);
                            parentNode.ChildNodes.Add(node);

                            RootHasMore = (isRoot && !CloseListing);
                        }

                        if (index <= MaxSubFolders)
                        {
                            index++;
                        }
                        else
                        {
                            break;
                        }
                    }
                }
            }
        }
    }
Exemplo n.º 16
0
    /// <summary>
    /// Provides operations necessary to create and store new library file.
    /// </summary>
    private void HandleLibrariesUpload()
    {
        // Get related library info
        if (LibraryInfo != null)
        {
            MediaFileInfo mediaFile = null;

            // Get the site name
            string   siteName = CMSContext.CurrentSiteName;
            SiteInfo si       = SiteInfoProvider.GetSiteInfo(LibraryInfo.LibrarySiteID);
            if (si != null)
            {
                siteName = si.SiteName;
            }

            string message = string.Empty;
            try
            {
                // Check the allowed extensions
                CheckAllowedExtensions();

                if (MediaFileID > 0)
                {
                    #region "Check permissions"

                    if (!MediaLibraryInfoProvider.IsUserAuthorizedPerLibrary(LibraryInfo, "FileModify"))
                    {
                        throw new Exception(GetString("media.security.nofilemodify"));
                    }

                    #endregion

                    mediaFile = MediaFileInfoProvider.GetMediaFileInfo(MediaFileID);
                    if (mediaFile != null)
                    {
                        // Ensure object version
                        SynchronizationHelper.EnsureObjectVersion(mediaFile);

                        if (IsMediaThumbnail)
                        {
                            string newFileExt = Path.GetExtension(ucFileUpload.FileName).TrimStart('.');
                            if ((ImageHelper.IsImage(newFileExt)) && (newFileExt.ToLower() != "ico") &&
                                (newFileExt.ToLower() != "wmf"))
                            {
                                // Update or creation of Media File update
                                string previewSuffix = MediaLibraryHelper.GetMediaFilePreviewSuffix(siteName);

                                if (!String.IsNullOrEmpty(previewSuffix))
                                {
                                    string previewExtension = Path.GetExtension(ucFileUpload.PostedFile.FileName);
                                    string previewName      = Path.GetFileNameWithoutExtension(MediaLibraryHelper.GetPreviewFileName(mediaFile.FileName, mediaFile.FileExtension, previewExtension, siteName, previewSuffix));
                                    string previewFolder    = DirectoryHelper.CombinePath(MediaLibraryHelper.EnsurePath(LibraryFolderPath.TrimEnd('/')), MediaLibraryHelper.GetMediaFileHiddenFolder(siteName));

                                    byte[] previewFileBinary = new byte[ucFileUpload.PostedFile.ContentLength];
                                    ucFileUpload.PostedFile.InputStream.Read(previewFileBinary, 0, ucFileUpload.PostedFile.ContentLength);

                                    // Delete current preview thumbnails
                                    MediaFileInfoProvider.DeleteMediaFilePreview(siteName, mediaFile.FileLibraryID, mediaFile.FilePath, false);

                                    // Save preview file
                                    MediaFileInfoProvider.SaveFileToDisk(siteName, LibraryInfo.LibraryFolder, previewFolder, previewName, previewExtension, mediaFile.FileGUID, previewFileBinary, false, false);

                                    // Log synchronization task
                                    SynchronizationHelper.LogObjectChange(mediaFile, TaskTypeEnum.UpdateObject);
                                }

                                // Drop the cache dependencies
                                CacheHelper.TouchKeys(MediaFileInfoProvider.GetDependencyCacheKeys(mediaFile, true));
                            }
                            else
                            {
                                message = GetString("media.file.onlyimgthumb");
                            }
                        }
                        else
                        {
                            // Delete existing media file
                            MediaFileInfoProvider.DeleteMediaFile(LibraryInfo.LibrarySiteID, LibraryInfo.LibraryID, mediaFile.FilePath, true, false);

                            // Update media file preview
                            if (MediaLibraryHelper.HasPreview(siteName, LibraryInfo.LibraryID, mediaFile.FilePath))
                            {
                                // Get new file path
                                string newPath = DirectoryHelper.CombinePath(Path.GetDirectoryName(mediaFile.FilePath).TrimEnd('/'), ucFileUpload.PostedFile.FileName);
                                newPath = MediaLibraryHelper.EnsureUniqueFileName(newPath);

                                // Get new unique file name
                                string newName = Path.GetFileName(newPath);

                                // Rename preview
                                MediaLibraryHelper.MoveMediaFilePreview(mediaFile, newName);

                                // Delete preview thumbnails
                                MediaFileInfoProvider.DeleteMediaFilePreviewThumbnails(mediaFile);
                            }

                            // Receive media info on newly posted file
                            mediaFile = GetUpdatedFile(mediaFile.Generalized.DataClass);

                            MediaFileInfoProvider.SetMediaFileInfo(mediaFile);
                        }
                    }
                }
                else
                {
                    // Creation of new media file

                    #region "Check permissions"

                    if (!MediaLibraryInfoProvider.IsUserAuthorizedPerLibrary(LibraryInfo, "FileCreate"))
                    {
                        throw new Exception(GetString("media.security.nofilecreate"));
                    }

                    #endregion

                    // No file for upload specified
                    if (!ucFileUpload.HasFile)
                    {
                        throw new Exception(GetString("media.newfile.errorempty"));
                    }

                    // Create new media file record
                    mediaFile = new MediaFileInfo(ucFileUpload.PostedFile, LibraryID, LibraryFolderPath, ResizeToWidth, ResizeToHeight, ResizeToMaxSideSize, LibraryInfo.LibrarySiteID);

                    mediaFile.FileDescription = "";

                    // Save the new file info
                    MediaFileInfoProvider.SetMediaFileInfo(mediaFile);
                }
            }
            catch (Exception ex)
            {
                // Creation of new media file failed
                message = ex.Message;
            }
            finally
            {
                // Create media file info string
                string mediaInfo = "";
                if ((mediaFile != null) && (mediaFile.FileID > 0) && (IncludeNewItemInfo))
                {
                    mediaInfo = mediaFile.FileID + "|" + LibraryFolderPath.Replace('\\', '>').Replace("'", "\\'");
                }

                // Ensure message text
                message = HTMLHelper.EnsureLineEnding(message, " ");

                // Call function to refresh parent window
                ScriptHelper.RegisterStartupScript(this.Page, typeof(Page), "refresh", ScriptHelper.GetScript("if ((wopener.parent != null) && (wopener.parent.InitRefresh_" + ParentElemID + " != null)){wopener.parent.InitRefresh_" + ParentElemID + "(" + ScriptHelper.GetString(message.Trim()) + ", false" + ((mediaInfo != "") ? ", '" + mediaInfo + "'" : "") + (InsertMode ? ", 'insert'" : ", 'update'") + ");}window.close();"));
            }
        }
    }
Exemplo n.º 17
0
    /// <summary>
    /// Saves modified image data.
    /// </summary>
    /// <param name="name">Image name</param>
    /// <param name="extension">Image extension</param>
    /// <param name="mimetype">Image mimetype</param>
    /// <param name="title">Image title</param>
    /// <param name="description">Image description</param>
    /// <param name="binary">Image binary data</param>
    /// <param name="width">Image width</param>
    /// <param name="height">Image height</param>
    private void SaveImage(string name, string extension, string mimetype, string title, string description, byte[] binary, int width, int height)
    {
        // Process media file
        if (mfi == null)
        {
            mfi = MediaFileInfo.Provider.Get(mediafileGuid, SiteInfoProvider.GetSiteID(CurrentSiteName));
        }

        if (mfi == null)
        {
            return;
        }

        var mli = MediaLibraryInfo.Provider.Get(mfi.FileLibraryID);

        if (mli == null)
        {
            return;
        }

        string path          = Path.GetDirectoryName(DirectoryHelper.CombinePath(MediaLibraryInfoProvider.GetMediaLibraryFolderPath(mli.LibraryID), mfi.FilePath));
        bool   permissionsOK = DirectoryHelper.CheckPermissions(path, false, true, true, true);

        // Check file write permissions
        FileInfo file = FileInfo.New(MediaFileInfoProvider.GetMediaFilePath(mfi.FileLibraryID, mfi.FilePath));

        if (file != null)
        {
            permissionsOK = permissionsOK && !file.IsReadOnly;
        }

        if (!permissionsOK)
        {
            baseImageEditor.ShowError(GetString("img.errors.filesystempermissions"));
            SavingFailed = true;
            return;
        }

        MediaFileInfo originalMfi = mfi.Clone(true);

        try
        {
            var site = SiteInfo.Provider.Get(mfi.FileSiteID);
            if (site == null)
            {
                throw new NullReferenceException("Site of media file not specified.");
            }

            // Ensure object version
            SynchronizationHelper.EnsureObjectVersion(mfi);

            if (isPreview && !String.IsNullOrEmpty(PreviewPath))
            {
                // Save preview file only if it was modified
                if (binary != null)
                {
                    string previewExt    = !String.IsNullOrEmpty(extension) && (extension != OldPreviewExt) ? extension : OldPreviewExt;
                    string previewName   = Path.GetFileNameWithoutExtension(PreviewPath);
                    string previewFolder = Path.EnsureForwardSlashes(DirectoryHelper.CombinePath(Path.GetDirectoryName(mfi.FilePath).TrimEnd('/'), MediaLibraryHelper.GetMediaFileHiddenFolder(site.SiteName)));

                    // Delete old preview files with thumbnails
                    MediaFileInfoProvider.DeleteMediaFilePreview(SiteContext.CurrentSiteName, mli.LibraryID, mfi.FilePath);
                    MediaFileInfoProvider.DeleteMediaFilePreviewThumbnails(mfi);

                    // Save preview file
                    MediaFileInfoProvider.SaveFileToDisk(site.SiteName, mli.LibraryFolder, previewFolder, previewName, previewExt, mfi.FileGUID, binary, false, false);

                    SynchronizationHelper.LogObjectChange(mfi, TaskTypeEnum.UpdateObject);
                }
            }
            else
            {
                if (!String.IsNullOrEmpty(mimetype))
                {
                    mfi.FileMimeType = mimetype;
                }

                mfi.FileTitle       = title;
                mfi.FileDescription = description;

                if (width > 0)
                {
                    mfi.FileImageWidth = width;
                }
                if (height > 0)
                {
                    mfi.FileImageHeight = height;
                }
                if (binary != null)
                {
                    mfi.FileBinary = binary;
                    mfi.FileSize   = binary.Length;
                }

                string newExt  = null;
                string newName = null;
                if (!String.IsNullOrEmpty(extension))
                {
                    newExt = extension;
                }
                if (!String.IsNullOrEmpty(name))
                {
                    newName = name;
                }

                // If file name or extension changed move preview file and remove all ald thumbnails
                if (NameOrExtensionWasModified(newName, newExt))
                {
                    string fileName = (newName ?? mfi.FileName);
                    string fileExt  = (newExt ?? mfi.FileExtension);

                    string newPath = MediaFileInfoProvider.GetMediaFilePath(mfi.FileLibraryID, DirectoryHelper.CombinePath(Path.GetDirectoryName(mfi.FilePath), fileName) + fileExt);

                    // Rename file only if file with same name does not exsists
                    if (File.Exists(newPath))
                    {
                        baseImageEditor.ShowError(GetString("img.errors.fileexists"));
                        SavingFailed = true;
                        return;
                    }

                    // Ensure max length of file path
                    if (newPath.Length >= 260)
                    {
                        throw new IOExceptions.PathTooLongException();
                    }

                    // Remove old thumbnails
                    MediaFileInfoProvider.DeleteMediaFileThumbnails(mfi);
                    MediaFileInfoProvider.DeleteMediaFilePreviewThumbnails(mfi);

                    // Move media file
                    MediaFileInfoProvider.MoveMediaFile(site.SiteName, mli.LibraryID, mfi.FilePath, DirectoryHelper.CombinePath(Path.GetDirectoryName(mfi.FilePath), fileName) + fileExt);

                    // Set new file name or extension
                    mfi.FileName      = fileName;
                    mfi.FileExtension = fileExt;
                    mfi.FileMimeType  = MimeTypeHelper.GetMimetype(fileExt);

                    // Ensure new binary
                    if (binary != null)
                    {
                        mfi.FileBinary = binary;
                        mfi.FileSize   = binary.Length;
                    }
                }
                else
                {
                    // Remove original media file before save if the image was modified
                    if (binary != null)
                    {
                        // Remove old thumbnails
                        MediaFileInfoProvider.DeleteMediaFileThumbnails(mfi);

                        string filePath = MediaFileInfoProvider.GetMediaFilePath(mfi.FileLibraryID, mfi.FilePath);
                        if (File.Exists(filePath))
                        {
                            File.Delete(filePath);
                        }
                    }
                }

                // Save new data
                mfi.EnsureUniqueFileName(false);
                MediaFileInfo.Provider.Set(mfi);
            }
        }
        catch (Exception e)
        {
            // Log exception
            Service.Resolve <IEventLogService>().LogException("ImageEditor", "Save file", e);

            baseImageEditor.ShowError(GetString("img.errors.processing"), tooltipText: e.Message);
            SavingFailed = true;
            // Save original media file info
            originalMfi.EnsureUniqueFileName(false);
            MediaFileInfo.Provider.Set(originalMfi);
        }
    }
Exemplo n.º 18
0
    /// <summary>
    /// Processes the file.
    /// </summary>
    protected void ProcessFile()
    {
        outputFile = null;

        // Get file guid from querystring
        fileGuid = QueryHelper.GetGuid("fileguid", Guid.Empty);
        if (fileGuid == Guid.Empty)
        {
            return;
        }

        // Get the file
        var file = MediaFileInfoProvider.GetMediaFileInfo(fileGuid, CurrentSiteName);

        if (file == null)
        {
            return;
        }

        if (Preview)
        {
            // Get file path
            string path             = MediaFileInfoProvider.GetMediaFilePath(file.FileLibraryID, file.FilePath);
            string pathDirectory    = Path.GetDirectoryName(path);
            string hiddenFolderPath = MediaLibraryHelper.GetMediaFileHiddenFolder(CurrentSiteName);
            string folderPath       = DirectoryHelper.CombinePath(pathDirectory, hiddenFolderPath);


            // Ensure hidden folder exists
            DirectoryHelper.EnsureDiskPath(folderPath, pathDirectory);

            // Get preview file
            string[] files = Directory.GetFiles(folderPath, MediaLibraryHelper.GetPreviewFileName(file.FileName, file.FileExtension, ".*", CurrentSiteName));
            if (files.Length <= 0)
            {
                return;
            }

            bool resizeImage = (ImageHelper.IsImage(Path.GetExtension(files[0])) && MediaFileInfoProvider.CanResizeImage(files[0], Width, Height, MaxSideSize));

            // Get the data
            if ((outputFile == null) || (outputFile.MediaFile == null))
            {
                outputFile               = NewOutputFile(file, null);
                outputFile.UsePreview    = true;
                outputFile.Width         = Width;
                outputFile.Height        = Height;
                outputFile.MaxSideSize   = MaxSideSize;
                outputFile.Resized       = resizeImage;
                outputFile.FileExtension = Path.GetExtension(files[0]);
                outputFile.MimeType      = MimeTypeHelper.GetMimetype(outputFile.FileExtension);
            }
        }
        else
        {
            bool resizeImage = (ImageHelper.IsImage(file.FileExtension) && MediaFileInfoProvider.CanResizeImage(file, Width, Height, MaxSideSize));

            // Get the data
            if ((outputFile == null) || (outputFile.MediaFile == null))
            {
                outputFile             = NewOutputFile(file, null);
                outputFile.Width       = Width;
                outputFile.Height      = Height;
                outputFile.MaxSideSize = MaxSideSize;
                outputFile.Resized     = resizeImage;
            }
        }
    }