/// <summary> /// Returns set of files in the file system. /// </summary> private DataSet GetFileSystemDataSource() { fileSystemDataSource.Path = LibraryPath + "/" + MediaLibraryHelper.EnsurePath(FolderPath) + "/"; fileSystemDataSource.Path = fileSystemDataSource.Path.Replace("/", "\\").Replace("|", "\\"); return((DataSet)fileSystemDataSource.DataSource); }
/// <summary> /// Stores new media file info into the DB. /// </summary> /// <param name="fi">Info on file to be stored</param> /// <param name="description">Description of new media file</param> /// <param name="name">Name of new media file</param> public MediaFileInfo SaveNewFile(FileInfo fi, string title, string description, string name, string filePath) { string path = MediaLibraryHelper.EnsurePath(filePath); string fileName = name; string fullPath = fi.FullName; string extension = URLHelper.GetSafeFileName(fi.Extension, CMSContext.CurrentSiteName); // Check if filename is changed ad move file if necessary if (fileName + extension != fi.Name) { string oldPath = path; fullPath = MediaLibraryHelper.EnsureUniqueFileName(Path.GetDirectoryName(fullPath) + "\\" + fileName + extension); path = MediaLibraryHelper.EnsurePath(Path.GetDirectoryName(path) + "/" + Path.GetFileName(fullPath)).TrimStart('/'); MediaFileInfoProvider.MoveMediaFile(CMSContext.CurrentSiteName, MediaLibraryID, oldPath, path, true); fileName = Path.GetFileNameWithoutExtension(fullPath); } // Create media file info MediaFileInfo fileInfo = new MediaFileInfo(fullPath, LibraryInfo.LibraryID, MediaLibraryHelper.EnsurePath(Path.GetDirectoryName(path)), 0, 0, 0); fileInfo.FileTitle = title; fileInfo.FileDescription = description; // Save media file info MediaFileInfoProvider.ImportMediaFileInfo(fileInfo); // Save FileID in ViewState FileID = fileInfo.FileID; FilePath = fileInfo.FilePath; return(fileInfo); }
/// <summary> /// Ensures that the path is ready to be used as an node ID. /// </summary> /// <param name="path">Path to use</param> private string EnsurePath(string path) { if (!string.IsNullOrEmpty(path)) { path = MediaLibraryHelper.EnsurePath(path); path = EnsureFolderId(path); path = ScriptHelper.EscapeJQueryCharacters(path); } return(path); }
/// <summary> /// Edit file event handler. /// </summary> protected void btnEdit_Click(object sender, EventArgs e) { // Check 'File modify' permission if (!MediaLibraryInfoProvider.IsUserAuthorizedPerLibrary(LibraryInfo, "filemodify")) { ShowError(MediaLibraryHelper.GetAccessDeniedMessage("filemodify")); SetupTexts(); SetupEdit(); // Update form pnlUpdateFileInfo.Update(); return; } FileInfo fi = CMS.IO.FileInfo.New(MediaFileInfoProvider.GetMediaFilePath(CMSContext.CurrentSiteName, LibraryInfo.LibraryFolder, FilePath)); if ((fi != null) && (LibraryInfo != null)) { // Check if the file exists if (!fi.Exists) { ShowError(GetString("media.error.FileDoesNotExist")); return; } string path = MediaLibraryHelper.EnsurePath(FilePath); string fileName = URLHelper.GetSafeFileName(txtEditName.Text.Trim(), CMSContext.CurrentSiteName, false); string origFileName = Path.GetFileNameWithoutExtension(fi.FullName); Validator fileNameValidator = new Validator() .NotEmpty(fileName, GetString("media.error.FileNameIsEmpty")) .IsFileName(fileName, GetString("media.error.FileNameIsNotValid")) .MatchesCondition(fileName, x => x != "." && x != "..", GetString("media.error.FileNameIsRelative")); if (!fileNameValidator.IsValid) { ShowError(HTMLHelper.HTMLEncode(fileNameValidator.Result)); return; } if (FileInfo != null) { if ((CMSContext.CurrentUser != null) && (!CMSContext.CurrentUser.IsPublic())) { FileInfo.FileModifiedWhen = CMSContext.CurrentUser.DateTimeNow; FileInfo.FileModifiedByUserID = CMSContext.CurrentUser.UserID; } else { FileInfo.FileModifiedWhen = DateTime.Now; } // Check if filename is changed ad move file if necessary if (fileName != origFileName) { try { // Check if file with new file name exists string newFilePath = Path.GetDirectoryName(fi.FullName) + "\\" + fileName + fi.Extension; if (!File.Exists(newFilePath)) { string newPath = (string.IsNullOrEmpty(Path.GetDirectoryName(path)) ? "" : Path.GetDirectoryName(path) + "/") + fileName + FileInfo.FileExtension; MediaFileInfoProvider.MoveMediaFile(CMSContext.CurrentSiteName, FileInfo.FileLibraryID, path, newPath, false); FileInfo.FilePath = MediaLibraryHelper.EnsurePath(newPath); } else { ShowError(GetString("media.error.FileExists")); return; } } catch (Exception ex) { ShowError(GetString("media.error.RenameFileException"), ex.Message, null); return; } } // Set media file info FileInfo.FileName = fileName; FileInfo.FileTitle = txtEditTitle.Text; FileInfo.FileDescription = txtEditDescription.Text; // Save MediaFileInfoProvider.SetMediaFileInfo(FileInfo); FilePath = FileInfo.FilePath; // Update file modified if not moving physical file if (fileName == origFileName) { fi.LastWriteTime = FileInfo.FileModifiedWhen; } // Inform user on success ShowChangesSaved(); SetupEdit(); pnlUpdateFileInfo.Update(); SetupTexts(); SetupFile(); pnlUpdateGeneral.Update(); SetupPreview(); pnlUpdatePreviewDetails.Update(); SetupVersions(false); pnlUpdateVersions.Update(); RaiseOnAction("rehighlightitem", Path.GetFileName(FileInfo.FilePath)); } } }
private void InitializeInnerControls() { if (MediaLibrary != null) { // If the control was hidden because there were no data on init, show the control and process it if (hidden) { Visible = true; StopProcessing = false; folderTree.StopProcessing = false; fileDataSource.StopProcessing = false; } if (string.IsNullOrEmpty(MediaLibraryPath)) { // If there is no path set folderTree.RootFolderPath = MediaLibraryHelper.GetMediaRootFolderPath(CMSContext.CurrentSiteName); folderTree.MediaLibraryFolder = MediaLibrary.LibraryFolder; } else { // Set root folder with library path folderTree.RootFolderPath = MediaLibraryHelper.GetMediaRootFolderPath(CMSContext.CurrentSiteName) + MediaLibrary.LibraryFolder; folderTree.MediaLibraryFolder = Path.GetFileName(MediaLibraryPath); folderTree.MediaLibraryPath = MediaLibraryHelper.EnsurePath(MediaLibraryPath); } folderTree.FileIDQueryStringKey = FileIDQueryStringKey; folderTree.PathQueryStringKey = PathQueryStringKey; folderTree.FilterMethod = FilterMethod; folderTree.ShowSubfoldersContent = ShowSubfoldersContent; folderTree.DisplayFileCount = DisplayFileCount; // Get media file id from query mMediaFileID = QueryHelper.GetInteger(FileIDQueryStringKey, 0); // Media library sort mediaLibrarySort.OnFilterChanged += FilterChanged; mediaLibrarySort.FileIDQueryStringKey = FileIDQueryStringKey; mediaLibrarySort.SortQueryStringKey = SortQueryStringKey; mediaLibrarySort.FilterMethod = FilterMethod; // File upload properties fileUploader.Visible = AllowUpload; fileUploader.EnableUploadPreview = AllowUploadPreview; fileUploader.PreviewSuffix = PreviewSuffix; fileUploader.LibraryID = MediaLibrary.LibraryID; fileUploader.DestinationPath = folderTree.SelectedPath; fileUploader.OnNotAllowed += fileUploader_OnNotAllowed; fileUploader.OnAfterFileUpload += fileUploader_OnAfterFileUpload; // Data properties fileDataSource.TopN = SelectTopN; fileDataSource.SiteName = CMSContext.CurrentSiteName; fileDataSource.GroupID = MediaLibrary.LibraryGroupID; // UniPager properties UniPagerControl.PageSize = PageSize; UniPagerControl.GroupSize = GroupSize; UniPagerControl.QueryStringKey = QueryStringKey; UniPagerControl.DisplayFirstLastAutomatically = DisplayFirstLastAutomatically; UniPagerControl.DisplayPreviousNextAutomatically = DisplayPreviousNextAutomatically; UniPagerControl.HidePagerForSinglePage = HidePagerForSinglePage; UniPagerControl.PagerMode = PagerMode; mMediaLibraryRoot = MediaLibraryHelper.GetMediaRootFolderPath(CMSContext.CurrentSiteName) + MediaLibrary.LibraryFolder; mMediaLibraryUrl = URLHelper.GetAbsoluteUrl("~/" + CMSContext.CurrentSiteName + "/media/" + MediaLibrary.LibraryFolder); // List properties fileList.HideControlForZeroRows = HideControlForZeroRows; fileList.ZeroRowsText = ZeroRowsText; fileList.ItemDataBound += fileList_ItemDataBound; // Initialize templates for FileList and UniPager InitTemplates(); } // Append filter changed event if folder is hidden or path query string id is set if (!HideFolderTree || !String.IsNullOrEmpty(PathQueryStringKey)) { folderTree.OnFilterChanged += FilterChanged; } // Folder tree if (!HideFolderTree) { if (CultureHelper.IsPreferredCultureRTL()) { folderTree.ImageFolderPath = GetImageUrl("RTL/Design/Controls/Tree", IsLiveSite, true); } else { folderTree.ImageFolderPath = GetImageUrl("Design/Controls/Tree", IsLiveSite, true); } } }
/// <summary> /// Sets filters where condition according to selected path in folder tree. /// </summary> private void SetFilter() { string path = null; if (this.FilterMethod != 0) { // Filter by postback path = RemoveRoot(this.SelectedPath); } else { // Filter by query parameter path = QueryHelper.GetString(this.PathQueryStringKey, ""); } // If in library root if (String.IsNullOrEmpty(this.MediaLibraryPath)) { if (String.IsNullOrEmpty(path)) { // Select only files from root folder this.WhereCondition = "(Filepath LIKE N'%')"; this.CurrentFolder = ""; if (!ShowSubfoldersContent) { // Select only files from root folder this.WhereCondition += " AND (Filepath NOT LIKE N'%/%')"; } } else { // Escape ' and [ (spacial character for LIKE condition) string wPath = MediaLibraryHelper.EnsurePath(path).Replace("'", "''").Replace("[", "[[]"); // Get files from path this.WhereCondition = "(FilePath LIKE N'" + wPath + "/%')"; this.CurrentFolder = MediaLibraryHelper.EnsurePath(path); if (!ShowSubfoldersContent) { // But no from subfolders this.WhereCondition += " AND (FilePath NOT LIKE N'" + wPath + "/%/%')"; } } } else { if (String.IsNullOrEmpty(path)) { // Escape ' and [ (spacial character for LIKE condition) string wPath = MediaLibraryHelper.EnsurePath(this.MediaLibraryPath).Replace("'", "''").Replace("[", "[[]"); // Select files from path folder this.WhereCondition = "(Filepath LIKE N'" + wPath + "/%')"; this.CurrentFolder = MediaLibraryHelper.EnsurePath(this.MediaLibraryPath); if (!ShowSubfoldersContent) { // Select only files from path folder this.WhereCondition += " AND (Filepath NOT LIKE N'" + wPath + "/%/%')"; } } else { // Escape ' and [ (spacial character for LIKE condition) string wPath = MediaLibraryHelper.EnsurePath(this.MediaLibraryPath + "/" + path).Replace("'", "''").Replace("[", "[[]"); // Get files from path this.WhereCondition = "(FilePath LIKE N'" + wPath + "/%')"; this.CurrentFolder = MediaLibraryHelper.EnsurePath(this.MediaLibraryPath) + "/" + MediaLibraryHelper.EnsurePath(path); if (!ShowSubfoldersContent) { // But no from subfolders this.WhereCondition += " AND (FilePath NOT LIKE N'" + wPath + "/%/%')"; } } } this.Where = this.WhereCondition; }
/// <summary> /// Moves document. /// </summary> private void PerformAction(object parameter) { if (Action.ToLower() == "copy") { AddLog(GetString("media.copy.startcopy")); } else { AddLog(GetString("media.move.startmove")); } if (LibraryInfo != null) { // Library path (used in recursive copy process) string libPath = MediaLibraryInfoProvider.GetMediaLibraryFolderPath(CMSContext.CurrentSiteName, LibraryInfo.LibraryFolder); // Ensure libPath is in original path type libPath = Path.GetFullPath(libPath); // Original path on disk from query string origPath = Path.GetFullPath(DirectoryHelper.CombinePath(libPath, FolderPath)); // New path on disk string newPath = null; // Original path in DB string origDBPath = MediaLibraryHelper.EnsurePath(FolderPath); // New path in DB string newDBPath = null; AddLog(NewPath); // Check if requested folder is in library root folder if (!origPath.StartsWith(libPath, StringComparison.CurrentCultureIgnoreCase)) { CurrentError = GetString("media.folder.nolibrary"); AddLog(CurrentError); return; } string origFolderName = Path.GetFileName(origPath); if ((String.IsNullOrEmpty(Files) && !mAllFiles) && string.IsNullOrEmpty(origFolderName)) { NewPath = NewPath + "\\" + LibraryInfo.LibraryFolder; NewPath = NewPath.Trim('\\'); } newPath = NewPath; // Process current folder copy/move action if (String.IsNullOrEmpty(Files) && !AllFiles) { newPath = newPath.TrimEnd('\\') + '\\' + origFolderName; newPath = newPath.Trim('\\'); // Check if moving into same folder if ((Action.ToLower() == "move") && (newPath == FolderPath)) { CurrentError = GetString("media.move.foldermove"); AddLog(CurrentError); return; } // Error if moving folder into itself string newRootPath = Path.GetDirectoryName(newPath).Trim(); string newSubRootFolder = Path.GetFileName(newPath).ToLower().Trim(); string originalSubRootFolder = Path.GetFileName(FolderPath).ToLower().Trim(); if (String.IsNullOrEmpty(Files) && (Action.ToLower() == "move") && newPath.StartsWith(DirectoryHelper.EnsurePathBackSlash(FolderPath)) && (originalSubRootFolder == newSubRootFolder) && (newRootPath == FolderPath)) { CurrentError = GetString("media.move.movetoitself"); AddLog(CurrentError); return; } // Get unique path for copy or move string path = Path.GetFullPath(DirectoryHelper.CombinePath(libPath, newPath)); path = MediaLibraryHelper.EnsureUniqueDirectory(path); newPath = path.Remove(0, (libPath.Length + 1)); // Get new DB path newDBPath = MediaLibraryHelper.EnsurePath(newPath.Replace(DirectoryHelper.EnsurePathBackSlash(libPath), "")); } else { origDBPath = MediaLibraryHelper.EnsurePath(FolderPath); newDBPath = MediaLibraryHelper.EnsurePath(newPath.Replace(libPath, "")).Trim('/'); } // Error if moving folder into its subfolder if ((String.IsNullOrEmpty(Files) && !AllFiles) && (Action.ToLower() == "move") && newPath.StartsWith(DirectoryHelper.EnsurePathBackSlash(FolderPath))) { CurrentError = GetString("media.move.parenttochild"); AddLog(CurrentError); return; } // Error if moving files into same directory if ((!String.IsNullOrEmpty(Files) || AllFiles) && (Action.ToLower() == "move") && (newPath.TrimEnd('\\') == FolderPath.TrimEnd('\\'))) { CurrentError = GetString("media.move.fileserror"); AddLog(CurrentError); return; } NewPath = newPath; refreshScript = "if ((typeof(window.top.opener) != 'undefined') && (typeof(window.top.opener.RefreshLibrary) != 'undefined')) {window.top.opener.RefreshLibrary(" + ScriptHelper.GetString(NewPath.Replace('\\', '|')) + ");} else if ((typeof(window.top.wopener) != 'undefined') && (typeof(window.top.wopener.RefreshLibrary) != 'undefined')) { window.top.wopener.RefreshLibrary(" + ScriptHelper.GetString(NewPath.Replace('\\', '|')) + "); } window.top.close();"; // If mFiles is empty handle directory copy/move if (String.IsNullOrEmpty(Files) && !mAllFiles) { try { switch (Action.ToLower()) { case "move": MediaLibraryInfoProvider.MoveMediaLibraryFolder(CMSContext.CurrentSiteName, MediaLibraryID, origDBPath, newDBPath, false); break; case "copy": MediaLibraryInfoProvider.CopyMediaLibraryFolder(CMSContext.CurrentSiteName, MediaLibraryID, origDBPath, newDBPath, false, CurrentUser.UserID); break; } } catch (UnauthorizedAccessException ex) { CurrentError = GetString("general.erroroccurred") + " " + GetString("media.security.accessdenied"); EventLogProvider ev = new EventLogProvider(); ev.LogEvent("MediaFolder", this.Action, ex); AddLog(CurrentError); return; } catch (ThreadAbortException ex) { string state = ValidationHelper.GetString(ex.ExceptionState, string.Empty); if (state == CMSThread.ABORT_REASON_STOP) { // When canceled CurrentInfo = GetString("general.actioncanceled"); AddLog(CurrentInfo); } else { // Log error CurrentError = GetString("general.erroroccurred") + " " + ex.Message; EventLogProvider ev = new EventLogProvider(); ev.LogEvent("MediaFolder", this.Action, ex); AddLog(CurrentError); return; } } catch (Exception ex) { CurrentError = GetString("general.erroroccurred") + " " + ex.Message; EventLogProvider ev = new EventLogProvider(); ev.LogEvent("MediaFolder", this.Action, ex); AddLog(CurrentError); return; } } else { string origDBFilePath = null; string newDBFilePath = null; if (!mAllFiles) { try { string[] files = Files.Split('|'); foreach (string filename in files) { origDBFilePath = (string.IsNullOrEmpty(origDBPath)) ? filename : origDBPath + "/" + filename; newDBFilePath = (string.IsNullOrEmpty(newDBPath)) ? filename : newDBPath + "/" + filename; AddLog(filename); CopyMove(origDBFilePath, newDBFilePath); } } catch (UnauthorizedAccessException ex) { CurrentError = GetString("general.erroroccurred") + " " + ResHelper.GetString("media.security.accessdenied"); EventLogProvider ev = new EventLogProvider(); ev.LogEvent("MediaFile", this.Action, ex); AddLog(CurrentError); return; } catch (ThreadAbortException ex) { string state = ValidationHelper.GetString(ex.ExceptionState, string.Empty); if (state == CMSThread.ABORT_REASON_STOP) { // When canceled CurrentInfo = GetString("general.actioncanceled"); AddLog(CurrentInfo); } else { // Log error CurrentError = GetString("general.erroroccurred") + " " + ex.Message; EventLogProvider ev = new EventLogProvider(); ev.LogEvent("MediaFile", this.Action, ex); AddLog(CurrentError); return; } } catch (Exception ex) { CurrentError = GetString("general.erroroccurred") + " " + ex.Message; EventLogProvider ev = new EventLogProvider(); ev.LogEvent("MediaFile", this.Action, ex); AddLog(CurrentError); return; } } else { HttpContext context = (parameter as HttpContext); if (context != null) { HttpContext.Current = context; DataSet files = GetFileSystemDataSource(); if (!DataHelper.IsEmpty(files)) { foreach (DataRow file in files.Tables[0].Rows) { string fileName = ValidationHelper.GetString(file["FileName"], ""); AddLog(fileName); origDBFilePath = (string.IsNullOrEmpty(origDBPath)) ? fileName : origDBPath + "/" + fileName; newDBFilePath = (string.IsNullOrEmpty(newDBPath)) ? fileName : newDBPath + "/" + fileName; // Clear current httpcontext for CopyMove action in threat HttpContext.Current = null; try { CopyMove(origDBFilePath, newDBFilePath); } catch (UnauthorizedAccessException ex) { CurrentError = GetString("general.erroroccurred") + " " + ResHelper.GetString("media.security.accessdenied"); EventLogProvider ev = new EventLogProvider(); ev.LogEvent("MediaFile", this.Action, ex); AddLog(CurrentError); return; } catch (ThreadAbortException ex) { string state = ValidationHelper.GetString(ex.ExceptionState, string.Empty); if (state == CMSThread.ABORT_REASON_STOP) { // When canceled CurrentInfo = GetString("general.actioncanceled"); AddLog(CurrentInfo); } else { // Log error CurrentError = GetString("general.erroroccurred") + " " + ex.Message; EventLogProvider ev = new EventLogProvider(); ev.LogEvent("MediaFile", this.Action, ex); AddLog(CurrentError); return; } } catch (Exception ex) { CurrentError = GetString("general.erroroccurred") + " " + ex.Message; EventLogProvider ev = new EventLogProvider(); ev.LogEvent("MediaFile", this.Action, ex); AddLog(CurrentError); return; } } } } } } } }
/// <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();")); } } }
/// <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 : CMSContext.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.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 { // Get folder path string path = Path.GetDirectoryName(DirectoryHelper.CombinePath(MediaLibraryInfoProvider.GetMediaLibraryFolderPath(this.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, false); // 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.Generalized.DataClass); // 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)); } } }
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); } } }
/// <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); }
/// <summary> /// Handles folder actions. /// </summary> public string ProcessFolderAction() { MediaLibraryInfo libInfo = MediaLibraryInfoProvider.GetMediaLibraryInfo(this.LibraryID); if (libInfo != null) { if (this.Action.ToLower().Trim() == "new") { if (this.CheckAdvancedPermissions) { CurrentUserInfo currUser = CMSContext.CurrentUser; // Not a global admin if (!currUser.IsGlobalAdministrator) { // Group library bool isGroupLibrary = (libInfo.LibraryGroupID > 0); if (!(isGroupLibrary && currUser.IsGroupAdministrator(libInfo.LibraryGroupID))) { // Checked resource name string resource = (isGroupLibrary) ? "CMS.Groups" : "CMS.MediaLibrary"; // Check 'CREATE' & 'MANAGE' permissions if (!(currUser.IsAuthorizedPerResource(resource, CMSAdminControl.PERMISSION_MANAGE) || MediaLibraryInfoProvider.IsUserAuthorizedPerLibrary(libInfo, "foldercreate"))) { this.lblError.Text = MediaLibraryHelper.GetAccessDeniedMessage("foldercreate"); this.lblError.Visible = true; return(null); } } } } // Check 'Folder create' permission else if (!MediaLibraryInfoProvider.IsUserAuthorizedPerLibrary(libInfo, "foldercreate")) { this.lblError.Text = MediaLibraryHelper.GetAccessDeniedMessage("foldercreate"); this.lblError.Visible = true; return(null); } } else { // Check 'Folder modify' permission if (!MediaLibraryInfoProvider.IsUserAuthorizedPerLibrary(libInfo, "foldermodify")) { this.lblError.Text = MediaLibraryHelper.GetAccessDeniedMessage("foldermodify"); this.lblError.Visible = true; return(null); } } SiteInfo si = SiteInfoProvider.GetSiteInfo(libInfo.LibrarySiteID); if (si != null) { // Validate form entry string errMsg = ValidateForm(this.Action, si.SiteName); this.ErrorOccurred = !string.IsNullOrEmpty(errMsg); // If validation suceeded if (errMsg == "") { try { // Update info only if folder was renamed if (MediaLibraryHelper.EnsurePath(FolderPath) != MediaLibraryHelper.EnsurePath(mNewFolderPath)) { if (this.Action.ToLower().Trim() == "new") { // Create/Update folder according to action MediaLibraryInfoProvider.CreateMediaLibraryFolder(si.SiteName, LibraryID, mNewFolderPath, false); } else { // Create/Update folder according to action MediaLibraryInfoProvider.RenameMediaLibraryFolder(si.SiteName, LibraryID, FolderPath, mNewFolderPath, false); } // Inform the user on success this.lblInfo.Text = GetString("general.changessaved"); this.lblInfo.Visible = true; // Refresh folder name this.FolderPath = mNewFolderPath; UpdateFolderName(); // Reload media library if (OnFolderChange != null) { OnFolderChange(this.mNewTreePath); } } } catch (Exception ex) { // Display an error to the user this.lblError.Text = GetString("general.erroroccurred") + " " + ex.Message; this.lblError.Visible = true; this.mNewTreePath = null; } } else { // Display an error to the user this.lblError.Text = errMsg; this.lblError.Visible = true; this.mNewTreePath = null; } } } return(this.mNewTreePath); }
/// <summary> /// Sets filters where condition according to selected path in folder tree. /// </summary> private void SetFilter() { string path = null; if (FilterMethod != 0) { // Filter by postback path = RemoveRoot(SelectedPath); } else { // Filter by query parameter path = QueryHelper.GetString(PathQueryStringKey, ""); } // If in library root if (String.IsNullOrEmpty(MediaLibraryPath)) { if (String.IsNullOrEmpty(path)) { // Select only files from root folder WhereCondition = "(Filepath LIKE N'%')"; CurrentFolder = ""; if (!ShowSubfoldersContent) { // Select only files from root folder WhereCondition += " AND (Filepath NOT LIKE N'%/%')"; } } else { // Escape ' and [ (spacial character for LIKE condition) string wPath = MediaLibraryHelper.EnsurePath(path).Replace("'", "''").Replace("[", "[[]"); // Get files from path WhereCondition = String.Format("(FilePath LIKE N'{0}/%')", wPath); CurrentFolder = MediaLibraryHelper.EnsurePath(path); if (!ShowSubfoldersContent) { // But no from subfolders WhereCondition += String.Format(" AND (FilePath NOT LIKE N'{0}/%/%')", wPath); } } } else { if (String.IsNullOrEmpty(path)) { // Escape ' and [ (spacial character for LIKE condition) string wPath = MediaLibraryHelper.EnsurePath(MediaLibraryPath).Replace("'", "''").Replace("[", "[[]"); // Select files from path folder WhereCondition = String.Format("(Filepath LIKE N'{0}/%')", wPath); CurrentFolder = MediaLibraryHelper.EnsurePath(MediaLibraryPath); if (!ShowSubfoldersContent) { // Select only files from path folder WhereCondition += String.Format(" AND (Filepath NOT LIKE N'{0}/%/%')", wPath); } } else { // Escape ' and [ (spacial character for LIKE condition) string wPath = MediaLibraryHelper.EnsurePath(String.Format("{0}/{1}", MediaLibraryPath, path)).Replace("'", "''").Replace("[", "[[]"); // Get files from path WhereCondition = String.Format("(FilePath LIKE N'{0}/%')", wPath); CurrentFolder = String.Format("{0}/{1}", MediaLibraryHelper.EnsurePath(MediaLibraryPath), MediaLibraryHelper.EnsurePath(path)); if (!ShowSubfoldersContent) { // But no from subfolders WhereCondition += String.Format(" AND (FilePath NOT LIKE N'{0}/%/%')", wPath); } } } Where = WhereCondition; }
/// <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(); } } }
/// <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 = MediaLibraryHelper.EnsurePath(DirectoryHelper.CombinePath(Path.GetDirectoryName(mfi.FilePath).TrimEnd('/'), MediaLibraryHelper.GetMediaFileHiddenFolder(si.SiteName))); // Delete old preview files with thumbnails MediaFileInfoProvider.DeleteMediaFilePreview(CMSContext.CurrentSiteName, mli.LibraryID, mfi.FilePath, false); 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 != null ? newName : mfi.FileName); string fileExt = (newExt != null ? newExt : mfi.FileExtension); string newPath = MediaFileInfoProvider.GetMediaFilePath(mfi.FileLibraryID, DirectoryHelper.CombinePath(Path.GetDirectoryName(mfi.FilePath), fileName) + fileExt); string filePath = MediaFileInfoProvider.GetMediaFilePath(mfi.FileLibraryID, mfi.FilePath); // 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; // Ensure new binary if (binary != null) { mfi.FileBinary = binary; mfi.FileSize = binary.Length; } } else { throw new IOExceptions.PathTooLongException(); } } else { baseImageEditor.LblLoadFailed.Visible = true; baseImageEditor.LblLoadFailed.ResourceString = "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 ev = new EventLogProvider(); ev.LogEvent("ImageEditor", "Save file", e); baseImageEditor.LblLoadFailed.Visible = true; baseImageEditor.LblLoadFailed.ResourceString = "img.errors.processing"; ScriptHelper.AppendTooltip(baseImageEditor.LblLoadFailed, e.Message, "help"); SavingFailed = true; // Save original media file info MediaFileInfoProvider.SetMediaFileInfo(originalMfi, false); } } else // User hasn't permissions for save file { baseImageEditor.LblLoadFailed.Visible = true; baseImageEditor.LblLoadFailed.ResourceString = "img.errors.filesystempermissions"; SavingFailed = true; } } } }
/// <summary> /// Edit file event handler. /// </summary> protected void btnEdit_Click(object sender, EventArgs e) { // Check 'File modify' permission if (!MediaLibraryInfoProvider.IsUserAuthorizedPerLibrary(LibraryInfo, "filemodify")) { this.lblErrorEdit.Text = MediaLibraryHelper.GetAccessDeniedMessage("filemodify"); this.lblErrorEdit.Visible = true; SetupTexts(); SetupEdit(); // Update form pnlUpdateEditInfo.Update(); pnlUpdateFileInfo.Update(); return; } FileInfo fi = CMS.IO.FileInfo.New(MediaFileInfoProvider.GetMediaFilePath(CMSContext.CurrentSiteName, this.LibraryInfo.LibraryFolder, this.FilePath)); if ((fi != null) && (this.LibraryInfo != null)) { // Check if the file exists if (!fi.Exists) { this.lblErrorEdit.Text = GetString("general.wasdeleted"); this.lblErrorEdit.Visible = true; this.pnlUpdateEditInfo.Update(); return; } string path = MediaLibraryHelper.EnsurePath(this.FilePath); string fileName = URLHelper.GetSafeFileName(this.txtEditName.Text.Trim(), CMSContext.CurrentSiteName, false); string origFileName = Path.GetFileNameWithoutExtension(fi.FullName); // Check if the filename is in correct format if (!ValidationHelper.IsFileName(fileName)) { this.lblErrorEdit.Text = GetString("media.rename.wrongformat"); this.lblErrorEdit.Visible = true; this.pnlUpdateEditInfo.Update(); return; } if (this.FileInfo != null) { if ((CMSContext.CurrentUser != null) && (!CMSContext.CurrentUser.IsPublic())) { this.FileInfo.FileModifiedWhen = CMSContext.CurrentUser.DateTimeNow; this.FileInfo.FileModifiedByUserID = CMSContext.CurrentUser.UserID; } else { this.FileInfo.FileModifiedWhen = DateTime.Now; } // Check if filename is changed ad move file if necessary if (fileName != origFileName) { try { // Check if file with new file name exists string newFilePath = Path.GetDirectoryName(fi.FullName) + "\\" + fileName + fi.Extension; if (!File.Exists(newFilePath)) { string newPath = (string.IsNullOrEmpty(Path.GetDirectoryName(path)) ? "" : Path.GetDirectoryName(path) + "/") + fileName + this.FileInfo.FileExtension; MediaFileInfoProvider.MoveMediaFile(CMSContext.CurrentSiteName, this.FileInfo.FileLibraryID, path, newPath, false); this.FileInfo.FilePath = CMS.MediaLibrary.MediaLibraryHelper.EnsurePath(newPath); } else { this.lblErrorEdit.Text = GetString("general.fileexists"); this.lblErrorEdit.Visible = true; this.pnlUpdateEditInfo.Update(); return; } } catch (Exception ex) { this.lblErrorEdit.Text = GetString("media.rename.failed") + ": " + ex.Message; this.lblErrorEdit.Visible = true; this.pnlUpdateEditInfo.Update(); return; } } // Set media file info this.FileInfo.FileName = fileName; this.FileInfo.FileTitle = this.txtEditTitle.Text; this.FileInfo.FileDescription = this.txtEditDescription.Text; // Save MediaFileInfoProvider.SetMediaFileInfo(this.FileInfo); this.FilePath = this.FileInfo.FilePath; // Update file modified if not moving physical file if (fileName == origFileName) { fi.LastWriteTime = FileInfo.FileModifiedWhen; } // Inform user on success this.lblInfoEdit.Text = GetString("general.changessaved"); this.lblInfoEdit.Visible = true; this.pnlUpdateEditInfo.Update(); SetupEdit(); this.pnlUpdateFileInfo.Update(); SetupTexts(); SetupFile(); this.pnlUpdateGeneral.Update(); SetupPreview(); this.pnlUpdatePreviewDetails.Update(); SetupVersions(false); pnlUpdateVersions.Update(); RaiseOnAction("rehighlightitem", Path.GetFileName(this.FileInfo.FilePath)); } } }