/// <summary> /// Uploads file. /// </summary> public void UploadFile() { if ((uploader.PostedFile != null) && (uploader.PostedFile.ContentLength > 0) && (ObjectID > 0)) { try { MetaFileInfo existing = null; // Check if uploaded file already exists and delete it DataSet ds = MetaFileInfoProvider.GetMetaFiles(ObjectID, ObjectType, Category, null, null); if (!DataHelper.DataSourceIsEmpty(ds)) { // Get existing record ID and delete it existing = new MetaFileInfo(ds.Tables[0].Rows[0]); MetaFileInfoProvider.DeleteMetaFileInfo(existing); } // Create new meta file MetaFileInfo mfi = new MetaFileInfo(uploader.PostedFile, ObjectID, ObjectType, Category); if (existing != null) { // Preserve GUID mfi.MetaFileGUID = existing.MetaFileGUID; mfi.MetaFileTitle = existing.MetaFileTitle; mfi.MetaFileDescription = existing.MetaFileDescription; } mfi.MetaFileSiteID = SiteID; // Save to the database MetaFileInfoProvider.SetMetaFileInfo(mfi); // Set currently handled meta file this.CurrentlyHandledMetaFile = mfi; SetupControls(); } catch (Exception ex) { lblErrorUploader.Visible = true; lblErrorUploader.Text = ex.Message; ViewState["SavingFailed"] = true; SetupControls(); } // File was uploaded, do not delete in one postback mAlreadyUploadedDontDelete = true; } }
/// <summary> /// BtnUpload click event handler. /// </summary> protected void btnUpload_Click(object sender, EventArgs e) { if (!AllowModify || (uploader.PostedFile == null) || (uploader.PostedFile.FileName.Trim() == "")) { return; } try { // Fire before upload event CancelEventArgs beforeUploadArgs = new CancelEventArgs(); if (OnBeforeUpload != null) { OnBeforeUpload(this, beforeUploadArgs); } // If upload was not cancelled if (!beforeUploadArgs.Cancel) { // Create new meta file MetaFileInfo mfi = new MetaFileInfo(uploader.PostedFile, ObjectID, ObjectType, Category) { MetaFileSiteID = SiteID }; // Save meta file MetaFileInfoProvider.SetMetaFileInfo(mfi); // Set currently handled meta file CurrentlyHandledMetaFile = mfi; // Fire after upload event if (OnAfterUpload != null) { OnAfterUpload(this, EventArgs.Empty); } // Reload grid data gridFiles.ReloadData(); } } catch (Exception ex) { lblError.Visible = true; lblError.Text = ex.Message; } }
/// <summary> /// Creates new widget with setting from parent webpart. /// </summary> /// <param name="parentWebpartId">ID of parent webpart</param> /// <param name="categoryId">ID of parent widget category</param> /// <returns>Created widget info</returns> private WidgetInfo NewWidget(int parentWebpartId, int categoryId) { WebPartInfo wpi = WebPartInfoProvider.GetWebPartInfo(parentWebpartId); // Widget cannot be created from inherited webpart if ((wpi != null) && (wpi.WebPartParentID == 0)) { // Set widget according to parent webpart WidgetInfo wi = new WidgetInfo(); wi.WidgetName = FindUniqueWidgetName(wpi.WebPartName, 100); wi.WidgetDisplayName = wpi.WebPartDisplayName; wi.WidgetDescription = wpi.WebPartDescription; wi.WidgetDocumentation = wpi.WebPartDocumentation; wi.WidgetSkipInsertProperties = wpi.WebPartSkipInsertProperties; wi.WidgetIconClass = wpi.WebPartIconClass; wi.WidgetProperties = FormHelper.GetFormFieldsWithDefaultValue(wpi.WebPartProperties, "visible", "false"); wi.WidgetWebPartID = parentWebpartId; wi.WidgetCategoryID = categoryId; // Save new widget to DB WidgetInfoProvider.SetWidgetInfo(wi); // Get thumbnail image from webpart DataSet ds = MetaFileInfoProvider.GetMetaFiles(wpi.WebPartID, WebPartInfo.OBJECT_TYPE, null, null, null, null, 1); if (!DataHelper.DataSourceIsEmpty(ds)) { MetaFileInfo mfi = new MetaFileInfo(ds.Tables[0].Rows[0]); mfi.Generalized.EnsureBinaryData(); mfi.MetaFileID = 0; mfi.MetaFileGUID = Guid.NewGuid(); mfi.MetaFileObjectID = wi.WidgetID; mfi.MetaFileObjectType = WidgetInfo.OBJECT_TYPE; MetaFileInfoProvider.SetMetaFileInfo(mfi); } // Return ID of newly created widget return(wi); } return(null); }
/// <summary> /// Saves metadata and file name of metafile. /// </summary> /// <param name="newFileName">New metafile file name</param> /// <returns>Returns True if metafile was succesfully saved.</returns> private bool SaveMetaFile(string newFileName) { bool saved = false; MetaFileInfo metaFileInfo = InfoObject as MetaFileInfo; if (metaFileInfo != null) { try { // Set title and description metaFileInfo.MetaFileTitle = ObjectTitle; metaFileInfo.MetaFileDescription = ObjectDescription; // Set new file name if (!string.IsNullOrEmpty(newFileName)) { metaFileInfo.MetaFileName = newFileName + ObjectExtension; } // Save new metadata metaFileInfo.AllowPartialUpdate = true; MetaFileInfoProvider.SetMetaFileInfo(metaFileInfo); saved = true; LtlScript.Text = ScriptHelper.GetScript("RefreshMetaFile();"); } catch (Exception ex) { lblError.Text = GetString("metadata.errors.processing"); EventLogProvider.LogException("Metadata editor", "SAVEMETAFILE", ex); } } return(saved); }
/// <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) { LoadInfos(); // Save image data depending to image type switch (baseImageEditor.ImageType) { // Process attachment case ImageHelper.ImageTypeEnum.Attachment: if (ai != null) { // Save new data try { // Get the node TreeNode node = DocumentHelper.GetDocument(ai.AttachmentDocumentID, baseImageEditor.Tree); // Check Create permission when saving temporary attachment, check Modify permission else NodePermissionsEnum permissionToCheck = (ai.AttachmentFormGUID == Guid.Empty) ? NodePermissionsEnum.Modify : NodePermissionsEnum.Create; // Check permission if (MembershipContext.AuthenticatedUser.IsAuthorizedPerDocument(node, permissionToCheck) != AuthorizationResultEnum.Allowed) { baseImageEditor.ShowError(GetString("attach.actiondenied")); SavingFailed = true; return; } if (!IsNameUnique(name, extension)) { baseImageEditor.ShowError(GetString("img.namenotunique")); SavingFailed = true; return; } // Ensure automatic check-in/ check-out bool useWorkflow = false; bool autoCheck = false; WorkflowManager workflowMan = WorkflowManager.GetInstance(baseImageEditor.Tree); if (node != null) { // Get workflow info WorkflowInfo wi = workflowMan.GetNodeWorkflow(node); // Check if the document uses workflow if (wi != null) { useWorkflow = true; autoCheck = !wi.UseCheckInCheckOut(CurrentSiteName); } // Check out the document if (autoCheck) { VersionManager.CheckOut(node, node.IsPublished, true); VersionHistoryID = node.DocumentCheckedOutVersionHistoryID; } // Workflow has been lost, get published attachment if (useWorkflow && (VersionHistoryID == 0)) { ai = AttachmentInfoProvider.GetAttachmentInfo(ai.AttachmentGUID, CurrentSiteName); } // If extension changed update CMS.File extension if ((node.NodeClassName.ToLowerCSafe() == "cms.file") && (node.DocumentExtensions != extension)) { // Update document extensions if no custom are used if (!node.DocumentUseCustomExtensions) { node.DocumentExtensions = extension; } node.SetValue("DocumentType", extension); DocumentHelper.UpdateDocument(node, baseImageEditor.Tree); } } if (ai != null) { // Test all parameters to empty values and update new value if available if (name != "") { if (!name.EndsWithCSafe(extension)) { ai.AttachmentName = name + extension; } else { ai.AttachmentName = name; } } if (extension != "") { ai.AttachmentExtension = extension; } if (mimetype != "") { ai.AttachmentMimeType = mimetype; } ai.AttachmentTitle = title; ai.AttachmentDescription = description; if (binary != null) { ai.AttachmentBinary = binary; ai.AttachmentSize = binary.Length; } if (width > 0) { ai.AttachmentImageWidth = width; } if (height > 0) { ai.AttachmentImageHeight = height; } // Ensure object ai.MakeComplete(true); if (VersionHistoryID > 0) { VersionManager.SaveAttachmentVersion(ai, VersionHistoryID); } else { AttachmentInfoProvider.SetAttachmentInfo(ai); // Log the synchronization and search task for the document if (node != null) { // Update search index for given document if (DocumentHelper.IsSearchTaskCreationAllowed(node)) { SearchTaskInfoProvider.CreateTask(SearchTaskTypeEnum.Update, TreeNode.OBJECT_TYPE, SearchFieldsConstants.ID, node.GetSearchID(), node.DocumentID); } DocumentSynchronizationHelper.LogDocumentChange(node, TaskTypeEnum.UpdateDocument, baseImageEditor.Tree); } } // Check in the document if ((autoCheck) && (VersionManager != null) && (VersionHistoryID > 0) && (node != null)) { VersionManager.CheckIn(node, null); } } } catch (Exception ex) { baseImageEditor.ShowError(GetString("img.errors.processing"), tooltipText: ex.Message); EventLogProvider.LogException("Image editor", "SAVEIMAGE", ex); SavingFailed = true; } } break; case ImageHelper.ImageTypeEnum.PhysicalFile: if (!String.IsNullOrEmpty(filePath)) { var currentUser = MembershipContext.AuthenticatedUser; if ((currentUser != null) && currentUser.IsGlobalAdministrator) { try { string physicalPath = Server.MapPath(filePath); string newPath = physicalPath; // Write binary data to the disk File.WriteAllBytes(physicalPath, binary); // Handle rename of the file if (!String.IsNullOrEmpty(name)) { newPath = DirectoryHelper.CombinePath(Path.GetDirectoryName(physicalPath), name); } if (!String.IsNullOrEmpty(extension)) { string oldExt = Path.GetExtension(physicalPath); newPath = newPath.Substring(0, newPath.Length - oldExt.Length) + extension; } // Move the file if (newPath != physicalPath) { File.Move(physicalPath, newPath); } } catch (Exception ex) { baseImageEditor.ShowError(GetString("img.errors.processing"), tooltipText: ex.Message); EventLogProvider.LogException("Image editor", "SAVEIMAGE", ex); SavingFailed = true; } } else { baseImageEditor.ShowError(GetString("img.errors.rights")); SavingFailed = true; } } break; // Process metafile case ImageHelper.ImageTypeEnum.Metafile: if (mf != null) { if (UserInfoProvider.IsAuthorizedPerObject(mf.MetaFileObjectType, mf.MetaFileObjectID, PermissionsEnum.Modify, CurrentSiteName, MembershipContext.AuthenticatedUser)) { try { // Test all parameters to empty values and update new value if available if (name.CompareToCSafe("") != 0) { if (!name.EndsWithCSafe(extension)) { mf.MetaFileName = name + extension; } else { mf.MetaFileName = name; } } if (extension.CompareToCSafe("") != 0) { mf.MetaFileExtension = extension; } if (mimetype.CompareToCSafe("") != 0) { mf.MetaFileMimeType = mimetype; } mf.MetaFileTitle = title; mf.MetaFileDescription = description; if (binary != null) { mf.MetaFileBinary = binary; mf.MetaFileSize = binary.Length; } if (width > 0) { mf.MetaFileImageWidth = width; } if (height > 0) { mf.MetaFileImageHeight = height; } // Save new data MetaFileInfoProvider.SetMetaFileInfo(mf); if (RefreshAfterAction) { if (String.IsNullOrEmpty(externalControlID)) { baseImageEditor.LtlScript.Text = ScriptHelper.GetScript("Refresh();"); } else { baseImageEditor.LtlScript.Text = ScriptHelper.GetScript(String.Format("InitRefresh({0}, false, false, '{1}', 'refresh')", ScriptHelper.GetString(externalControlID), mf.MetaFileGUID)); } } } catch (Exception ex) { baseImageEditor.ShowError(GetString("img.errors.processing"), tooltipText: ex.Message); EventLogProvider.LogException("Image editor", "SAVEIMAGE", ex); SavingFailed = true; } } else { baseImageEditor.ShowError(GetString("img.errors.rights")); SavingFailed = true; } } break; } }
/// <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) { LoadInfos(); // Save image data depending to image type switch (baseImageEditor.ImageType) { // Process attachment case ImageHelper.ImageTypeEnum.Attachment: if (attachment != null) { if (!CheckAttachmentPermissions()) { ReportSavingNotAuthorized(); return; } try { UpdateAttachmentNameAndExtension(name, extension); if (!IsAttachmentNameUnique()) { baseImageEditor.ShowError(GetString("img.namenotunique")); SavingFailed = true; return; } UpdateAttachmentProperties(mimetype, title, description, binary, width, height); if (attachment.AttachmentFormGUID == Guid.Empty) { SaveDocumentAttachment(); } else { SaveTemporaryAttachment(); } } catch (Exception ex) { ReportSavingFailed(ex); } } break; case ImageHelper.ImageTypeEnum.PhysicalFile: if (!String.IsNullOrEmpty(filePath)) { if (!CheckPhysicalFilePermissions()) { ReportSavingNotAuthorized(); return; } try { string physicalPath = Server.MapPath(filePath); string newPath = physicalPath; // Write binary data to the disk if (binary != null) { File.WriteAllBytes(physicalPath, binary); } // Handle rename of the file if (!String.IsNullOrEmpty(name)) { newPath = DirectoryHelper.CombinePath(Path.GetDirectoryName(physicalPath), name); } if (!String.IsNullOrEmpty(extension)) { string oldExt = Path.GetExtension(physicalPath); newPath = newPath.Substring(0, newPath.Length - oldExt.Length) + extension; } // Move the file if (newPath != physicalPath) { File.Move(physicalPath, newPath); } } catch (Exception ex) { ReportSavingFailed(ex); } } break; // Process metafile case ImageHelper.ImageTypeEnum.Metafile: if (metafile != null) { if (!CheckMetafilePermissions()) { ReportSavingNotAuthorized(); return; } try { UpdateMetafileProperties(name, extension, mimetype, title, description, binary, width, height); // Save new data MetaFileInfoProvider.SetMetaFileInfo(metafile); if (RefreshAfterAction) { InitRefreshAfterAction(metafile.MetaFileGUID); } } catch (Exception ex) { ReportSavingFailed(ex); } } break; } }
private void HandleMetaFileUpload() { string message = string.Empty; MetaFileInfo mfi = null; try { // Check the allowed extensions CheckAllowedExtensions(); if (InsertMode) { // Create new meta file mfi = new MetaFileInfo(FileUploadControl.PostedFile, ObjectID, ObjectType, Category); mfi.MetaFileSiteID = SiteID; } else { if (MetaFileID > 0) { mfi = MetaFileInfoProvider.GetMetaFileInfo(MetaFileID); } else { DataSet ds = MetaFileInfoProvider.GetMetaFilesWithoutBinary(ObjectID, ObjectType, Category, null, null); if (!DataHelper.DataSourceIsEmpty(ds)) { mfi = new MetaFileInfo(ds.Tables[0].Rows[0]); } } if (mfi != null) { string fileExt = Path.GetExtension(FileUploadControl.FileName); // Init the MetaFile data mfi.MetaFileName = URLHelper.GetSafeFileName(FileUploadControl.FileName, null); mfi.MetaFileExtension = fileExt; mfi.MetaFileSize = Convert.ToInt32(FileUploadControl.PostedFile.InputStream.Length); mfi.MetaFileMimeType = MimeTypeHelper.GetMimetype(fileExt); mfi.InputStream = FileUploadControl.PostedFile.InputStream; // Set image properties if (ImageHelper.IsImage(mfi.MetaFileExtension)) { // Make MetaFile binary load from InputStream mfi.MetaFileBinary = null; ImageHelper ih = new ImageHelper(mfi.MetaFileBinary); mfi.MetaFileImageHeight = ih.ImageHeight; mfi.MetaFileImageWidth = ih.ImageWidth; } } } if (mfi != null) { // Save file to the database MetaFileInfoProvider.SetMetaFileInfo(mfi); } } catch (Exception ex) { // Log the exception EventLogProvider.LogException("Uploader", "UploadMetaFile", ex); message = ex.Message; } finally { string afterSaveScript = string.Empty; if (String.IsNullOrEmpty(message)) { if (!string.IsNullOrEmpty(AfterSaveJavascript)) { afterSaveScript = String.Format( @" if (window.{0} != null) {{ window.{0}(files) }} else if ((window.parent != null) && (window.parent.{0} != null)) {{ window.parent.{0}(files) }} ", AfterSaveJavascript ); } else { afterSaveScript = String.Format(@" if ((window.parent != null) && (/parentelemid={0}/i.test(window.location.href)) && (window.parent.InitRefresh_{0})) {{ window.parent.InitRefresh_{0}('{1}', false, false, {2}); }} else {{ if ('{1}' != '') {{ alert('{1}'); }} }}", ParentElemID, ScriptHelper.GetString(message.Trim(), false), mfi.MetaFileID.ToString() + (InsertMode ? ",'insert'" : ",'update'")); } } else { afterSaveScript += ScriptHelper.GetAlertScript(message, false); } ScriptHelper.RegisterStartupScript(this, typeof(string), "afterSaveScript_" + ClientID, afterSaveScript, true); } }
/// <summary> /// Imports default metafiles which were changed in the new version. /// </summary> /// <param name="upgradeFolder">Folder where the generated metafiles.xml file is</param> private static void ImportMetaFiles(string upgradeFolder) { try { // To get the file use Phobos - Generate files button, Metafile settings. // Choose only those object types which had metafiles in previous version and these metafiles changed to the new version. String xmlPath = Path.Combine(upgradeFolder, "metafiles.xml"); if (File.Exists(xmlPath)) { XmlDocument xDoc = new XmlDocument(); xDoc.Load(xmlPath); XmlNode metaFilesNode = xDoc.SelectSingleNode("MetaFiles"); if (metaFilesNode != null) { String filesDirectory = Path.Combine(upgradeFolder, "Metafiles"); using (new CMSActionContext { LogEvents = false }) { foreach (XmlNode metaFile in metaFilesNode) { // Load metafiles information from XML String objType = metaFile.Attributes["ObjectType"].Value; String groupName = metaFile.Attributes["GroupName"].Value; String codeName = metaFile.Attributes["CodeName"].Value; String fileName = metaFile.Attributes["FileName"].Value; String extension = metaFile.Attributes["Extension"].Value; String fileGUID = metaFile.Attributes["FileGUID"].Value; String title = (metaFile.Attributes["Title"] != null) ? metaFile.Attributes["Title"].Value : null; String description = (metaFile.Attributes["Description"] != null) ? metaFile.Attributes["Description"].Value : null; // Try to find correspondent info object BaseInfo infoObject = BaseAbstractInfoProvider.GetInfoByName(objType, codeName); if (infoObject != null) { int infoObjectId = infoObject.Generalized.ObjectID; // Check if metafile exists InfoDataSet <MetaFileInfo> metaFilesSet = MetaFileInfoProvider.GetMetaFilesWithoutBinary(infoObjectId, objType, groupName, "MetaFileGUID = '" + fileGUID + "'", null); if (DataHelper.DataSourceIsEmpty(metaFilesSet)) { // Create new metafile if does not exists String mfFileName = String.Format("{0}.{1}", fileGUID, extension.TrimStart('.')); MetaFileInfo mfInfo = new MetaFileInfo(Path.Combine(filesDirectory, mfFileName), infoObjectId, objType, groupName); mfInfo.MetaFileGUID = ValidationHelper.GetGuid(fileGUID, Guid.NewGuid()); // Set correct properties mfInfo.MetaFileName = fileName; if (title != null) { mfInfo.MetaFileTitle = title; } if (description != null) { mfInfo.MetaFileDescription = description; } // Save new meta file MetaFileInfoProvider.SetMetaFileInfo(mfInfo); } } } // Remove existing files after successful finish String[] files = Directory.GetFiles(upgradeFolder); foreach (String file in files) { File.Delete(file); } } } } } catch (Exception ex) { EventLogProvider.LogException(EventLogSource, "IMPORTMETAFILES", ex); } }
/// <summary> /// Provides operations necessary to create and store new metafile. /// </summary> /// <param name="args">Upload arguments.</param> /// <param name="context">HttpContext instance.</param> private void HandleMetafileUpload(UploaderHelper args, HttpContext context) { MetaFileInfo mfi = null; try { // Check the allowed extensions args.IsExtensionAllowed(); if (args.IsInsertMode) { // Create new metafile info mfi = new MetaFileInfo(args.FilePath, args.MetaFileArgs.ObjectID, args.MetaFileArgs.ObjectType, args.MetaFileArgs.Category); mfi.MetaFileSiteID = args.MetaFileArgs.SiteID; } else { if (args.MetaFileArgs.MetaFileID > 0) { mfi = MetaFileInfoProvider.GetMetaFileInfo(args.MetaFileArgs.MetaFileID); } else { DataSet ds = MetaFileInfoProvider.GetMetaFilesWithoutBinary(args.MetaFileArgs.ObjectID, args.MetaFileArgs.ObjectType, args.MetaFileArgs.Category, null, null); if (!DataHelper.DataSourceIsEmpty(ds)) { mfi = new MetaFileInfo(ds.Tables[0].Rows[0]); } } if (mfi != null) { FileInfo fileInfo = FileInfo.New(args.FilePath); // Init the MetaFile data mfi.MetaFileName = URLHelper.GetSafeFileName(fileInfo.Name, null); mfi.MetaFileExtension = fileInfo.Extension; FileStream file = fileInfo.OpenRead(); mfi.MetaFileSize = Convert.ToInt32(fileInfo.Length); mfi.MetaFileMimeType = MimeTypeHelper.GetMimetype(mfi.MetaFileExtension); mfi.InputStream = file; // Set image properties if (ImageHelper.IsImage(mfi.MetaFileExtension)) { ImageHelper ih = new ImageHelper(mfi.MetaFileBinary); mfi.MetaFileImageHeight = ih.ImageHeight; mfi.MetaFileImageWidth = ih.ImageWidth; } } } if (mfi != null) { MetaFileInfoProvider.SetMetaFileInfo(mfi); } } catch (Exception ex) { args.Message = ex.Message; } finally { if (String.IsNullOrEmpty(args.Message)) { if (!string.IsNullOrEmpty(args.AfterSaveJavascript)) { args.AfterScript = String.Format(@" if (window.{0} != null) {{ window.{0}() }} else if ((window.parent != null) && (window.parent.{0} != null)) {{ window.parent.{0}() }}", args.AfterSaveJavascript); } else { args.AfterScript = String.Format(@" if (window.InitRefresh_{0}) {{ window.InitRefresh_{0}('{1}', false, false, {2}); }} else {{ if ('{1}' != '') {{ alert('{1}'); }} }}", args.ParentElementID, ScriptHelper.GetString(args.Message.Trim(), false), mfi.MetaFileID); } } else { args.AfterScript += ScriptHelper.GetAlertScript(args.Message, false); } args.AddEventTargetPostbackReference(); context.Response.Write(args.AfterScript); context.Response.Flush(); } }