/// <summary>
    /// Updates information displayed on import form.
    /// </summary>
    private void UpdateImportForm()
    {
        // Get info on next file name
        string nextFileName = GetNextFileName();

        if (!String.IsNullOrEmpty(nextFileName))
        {
            string ext = Path.GetExtension(nextFileName);

            if (!MediaLibraryHelper.IsExtensionAllowed(ext.TrimStart('.')))
            {
                plcMessError.AddError(string.Format(GetString("attach.notallowedextension"), ext, MediaLibraryHelper.GetAllowedExtensions(SiteName).TrimEnd(';').Replace(";", ", ")));
                SetFormEnabled(false);
            }
            else
            {
                SetFormEnabled(true);
                txtImportFileDescription.Text = "";
                txtImportFileName.Text        = URLHelper.GetSafeFileName(Path.GetFileNameWithoutExtension(nextFileName), SiteName, false);
                txtImportFileTitle.Text       = Path.GetFileNameWithoutExtension(nextFileName);

                LoadPreview(nextFileName);
            }
        }
    }
    /// <summary>
    /// Updates information displayed on import form.
    /// </summary>
    private void UpdateImportForm()
    {
        // Get info on next file name
        string nextFileName = GetNextFileName();

        if (!String.IsNullOrEmpty(nextFileName))
        {
            string ext = Path.GetExtension(nextFileName);

            if (!MediaLibraryHelper.IsExtensionAllowed(ext.TrimStart('.')))
            {
                this.lblError.Text    = string.Format(GetString("attach.notallowedextension"), ext, MediaLibraryHelper.GetAllowedExtensions(CMSContext.CurrentSiteName).TrimEnd(';').Replace(";", ", "));
                this.lblError.Visible = true;
                SetFormEnabled(false);
            }
            else
            {
                SetFormEnabled(true);
                this.txtImportFileDescription.Text = "";
                this.txtImportFileName.Text        = URLHelper.GetSafeFileName(Path.GetFileNameWithoutExtension(nextFileName), CMSContext.CurrentSiteName, false);
                this.txtImportFileTitle.Text       = Path.GetFileNameWithoutExtension(nextFileName);

                LoadPreview(nextFileName);
            }

            InitializeImportBreadcrumbs(URLHelper.GetSafeFileName(nextFileName, CMSContext.CurrentSiteName));
        }
    }
    /// <summary>
    /// Displays new file form.
    /// </summary>
    /// <param name="file">File the form is displayed for</param>
    public void DisplayForm(FileInfo file)
    {
        if (file != null)
        {
            string ext = file.Extension;

            if (!MediaLibraryHelper.IsExtensionAllowed(ext.TrimStart('.')))
            {
                this.lblErrorNew.Text    = string.Format(GetString("attach.notallowedextension"), ext, MediaLibraryHelper.GetAllowedExtensions(CMSContext.CurrentSiteName).TrimEnd(';').Replace(";", ", "));
                this.lblErrorNew.Visible = true;
                SetFormVisible(false);
            }
            else
            {
                // If is not in DB fill new file form and show it
                SetFormVisible(true);
                this.txtNewDescripotion.Text = "";
                this.txtNewFileTitle.Text    = Path.GetFileNameWithoutExtension(file.Name);
                this.txtNewFileName.Text     = URLHelper.GetSafeFileName(Path.GetFileNameWithoutExtension(file.Name), CMSContext.CurrentSiteName, false);
            }
        }
    }
    /// <summary>
    /// Handle storing single media file info into the DB.
    /// </summary>
    private void HandleSingleMediaFile()
    {
        string fileName = txtImportFileName.Text.Trim();

        // Check if the filename is in correct format
        if (!ValidationHelper.IsFileName(fileName))
        {
            SetupTexts();

            // Inform user on error
            RaiseOnAction("importerror", GetString("media.rename.wrongformat"));
            return;
        }

        // Get info on current file path
        string currFileName = GetNextFileName();

        if (!String.IsNullOrEmpty(currFileName))
        {
            string ext = Path.GetExtension(currFileName);
            if (!MediaLibraryHelper.IsExtensionAllowed(ext.TrimStart('.')))
            {
                RaiseOnAction("importerror", string.Format(GetString("attach.notallowedextension"), ext, MediaLibraryHelper.GetAllowedExtensions(SiteName).TrimEnd(';').Replace(";", ", ")));
                return;
            }
        }

        try
        {
            // Get info on current file path
            if (!String.IsNullOrEmpty(currFileName))
            {
                string filePath = (string.IsNullOrEmpty(FolderPath)) ? currFileName : DirectoryHelper.CombinePath(FolderPath, currFileName);

                // Get file and library info
                FileInfo currFile = FileInfo.New(MediaFileInfoProvider.GetMediaFilePath(SiteName, LibraryInfo.LibraryFolder, filePath));
                if (currFile != null)
                {
                    // Save media file info on current file
                    RaiseOnSaveRequired(currFile, txtImportFileTitle.Text.Trim(), txtImportFileDescription.Text.Trim(), URLHelper.GetSafeFileName(fileName, SiteName, false), filePath);
                }
            }

            // Update file paths set and store updated version in the ViewState
            int indexOfDel = ImportFilePaths.IndexOf('|');
            ImportFilePaths = (indexOfDel > 0 ? ImportFilePaths.Remove(0, indexOfDel + 1) : String.Empty);

            bool wasLast = String.IsNullOrEmpty(ImportFilePaths);
            if (wasLast)
            {
                FinishImport();
            }
            else
            {
                RaiseOnAction("singlefileimported", null);

                // Increment current file index
                ImportCurrFileIndex++;
            }
        }
        catch (Exception ex)
        {
            SetupTexts();

            // Inform user on error
            RaiseOnAction("importerror", ex.Message);
        }
        finally
        {
            SetupImport();
        }
    }
    /// <summary>
    /// Handles storing of multiple media files at once.
    /// </summary>
    private void HandleMultipleMediaFiles()
    {
        try
        {
            string[] filePaths = ImportFilePaths.Split('|');
            if (filePaths.Length > 0)
            {
                bool   first       = true;
                string description = txtImportFileDescription.Text.Trim();
                string title       = txtImportFileTitle.Text.Trim();
                string name        = txtImportFileName.Text.Trim();

                // Check if the filename is in correct format
                if (!ValidationHelper.IsFileName(name))
                {
                    SetupTexts();

                    // Inform user on error
                    RaiseOnAction("importerror", GetString("media.rename.wrongformat"));
                    return;
                }

                // Go through the files and save one by one
                foreach (string path in filePaths)
                {
                    if (path.Trim() != "")
                    {
                        string filePath = DirectoryHelper.CombinePath(FolderPath, path);
                        string ext      = Path.GetExtension(filePath);
                        if (!MediaLibraryHelper.IsExtensionAllowed(ext.TrimStart('.')))
                        {
                            RaiseOnAction("importerror", string.Format(GetString("attach.notallowedextension"), ext, MediaLibraryHelper.GetAllowedExtensions(SiteName).TrimEnd(';').Replace(";", ", ")));
                            return;
                        }

                        // Get file and library info
                        FileInfo currFile = FileInfo.New(RootFolderPath + DirectoryHelper.CombinePath(LibraryInfo.LibraryFolder, filePath));
                        if (currFile != null)
                        {
                            if (first)
                            {
                                // Save media file info on current file
                                RaiseOnSaveRequired(currFile, title, description, URLHelper.GetSafeFileName(name, SiteName, false), filePath);

                                first = false;
                            }
                            else
                            {
                                string fileName = Path.GetFileNameWithoutExtension(currFile.Name);

                                // Save media file info on current file where title = file name
                                RaiseOnSaveRequired(currFile, fileName, description, URLHelper.GetSafeFileName(fileName, SiteName, false), filePath);
                            }
                        }
                    }
                }

                FinishImport();
            }
            else
            {
                // Inform user on error
                RaiseOnAction("importnofiles", null);
            }
        }
        catch (Exception ex)
        {
            SetupTexts();

            // Inform user on error
            RaiseOnAction("importerror", ex.Message);
        }
        finally
        {
            SetupImport();
        }
    }
    /// <summary>
    /// Save title and description of media file info.
    /// </summary>
    /// <param name="fileName">File name</param>
    /// <param name="title">Title</param>
    /// <param name="description">Description</param>
    private bool metaDataEditor_Save(string fileName, string title, string description)
    {
        bool saved = false;

        if (mediaFileInfo != null)
        {
            try
            {
                if (mediaFileInfo.FileName != fileName)
                {
                    // Get original file path
                    string extension = mediaFileInfo.FileExtension;

                    // New file path
                    string newPath      = DirectoryHelper.CombinePath(Path.GetDirectoryName(mediaFileInfo.FilePath), fileName + extension);
                    string newFullPath  = MediaFileInfoProvider.GetMediaFilePath(mediaFileInfo.FileLibraryID, newPath);
                    string newExtension = Path.GetExtension(newPath);

                    if (!String.IsNullOrEmpty(newExtension))
                    {
                        newExtension = newExtension.TrimStart('.');
                    }

                    if (!MediaLibraryHelper.IsExtensionAllowed(newExtension))
                    {
                        // New extension is not allowed
                        metaDataEditor.ShowError(GetString("dialogs.filesystem.NotAllowedExtension").Replace("%%extensions%%", MediaLibraryHelper.GetAllowedExtensions(SiteName).TrimEnd(';').Replace(";", ", ")));
                        return(false);
                    }

                    // Rename file
                    if (!File.Exists(newFullPath))
                    {
                        MediaFileInfoProvider.MoveMediaFile(SiteName, mediaFileInfo.FileLibraryID, mediaFileInfo.FilePath, newPath);

                        // Move preview file if exists
                        if (MediaLibraryHelper.HasPreview(SiteName, mediaFileInfo.FileLibraryID, mediaFileInfo.FilePath))
                        {
                            MediaLibraryHelper.MoveMediaFilePreview(mediaFileInfo, fileName + extension);
                        }
                    }
                    else
                    {
                        // File already exists.
                        metaDataEditor.ShowError(GetString("img.errors.fileexists"));
                        return(false);
                    }

                    mediaFileInfo.FileName = fileName;

                    string subFolderPath = null;

                    int lastSlash = mediaFileInfo.FilePath.LastIndexOfCSafe('/');
                    if (lastSlash > 0)
                    {
                        subFolderPath = mediaFileInfo.FilePath.Substring(0, lastSlash);
                    }

                    if (!string.IsNullOrEmpty(subFolderPath))
                    {
                        mediaFileInfo.FilePath = String.Format("{0}/{1}{2}", subFolderPath, fileName, extension);
                    }
                    else
                    {
                        mediaFileInfo.FilePath = fileName + extension;
                    }
                }
                mediaFileInfo.FileTitle       = title;
                mediaFileInfo.FileDescription = description;

                // Save new data
                MediaFileInfoProvider.SetMediaFileInfo(mediaFileInfo, false);

                saved = true;
            }
            catch (Exception ex)
            {
                metaDataEditor.ShowError(GetString("metadata.errors.processing"));
                EventLogProvider.LogException("Metadata editor", "SAVE", ex);
            }
        }

        return(saved);
    }
Exemple #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;
            }
        }
    }
    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);
            }
        }
    }