private void ExecuteUsingOfficeOpenXml(TempFileForActions tempFile, CleanActionPropertySet elementsToClean)
        {
            try
            {
                m_elementsToClean = GetElementsNotRemovedByDomClean(GetListOfEnabledElementsToClean(elementsToClean));
                using (BinaryData bData = new BinaryData(tempFile.GetMemoryStream()))
                {
                    using (XlsxDocumentReader reader = new XlsxDocumentReader(bData))
                    {
                        using (Stream str = GetOutputStream())
                        {
                            reader.CleanTo(str, m_elementsToClean);
                            File.Copy(InterimTempFileName, tempFile.TempFile, true);
                        }
                    }
                }
            }
            catch (System.Exception ex)
            {
				Logger.LogError(ex);
				throw;
            }
            finally
            {
                CleanUp();
            }
        }
        protected static List<Exclusion> GetListOfExcludedElements(CleanActionPropertySet elementsToClean)
        {
            List<Exclusion> listExclusions = new List<Exclusion>();
            List<string> excludedMetawallPropNames = elementsToClean.GetExcludedMetawallPropertyList();

            foreach (KeyValuePair<string, IActionProperty> kvp in elementsToClean)
            {
                string key = kvp.Key;
                IActionProperty property = kvp.Value;

                if (!excludedMetawallPropNames.Contains(key))
                    continue;

                string excludeKey = CleanActionPropertySet.ExcludedKeyToName(key);
                Exclusion exclusion = new Exclusion();

                if (exclusion != null)
                {
                    exclusion.Name = excludeKey; // property.DefaultDisplayName;
                    exclusion.Value = property.Value;
                    listExclusions.Add(exclusion);
                }
            }
            return listExclusions;
        }
        public override void RemoveMetadata(TempFileForActions tempFile, CleanActionPropertySet cleanProperties)
        {
            try
            {
                m_elementsToClean = GetListOfEnabledElementsToClean(cleanProperties);
                List<Exclusion> listExclusion = GetListOfExcludedElements(cleanProperties);
                using (BinaryData bData = new BinaryData(tempFile.GetMemoryStream()))
                {
                    using (PptxDocumentReader reader = new PptxDocumentReader(bData))
                    {
                        using (Stream str = GetOutputStream())
                        {
                            reader.CleanTo(str, m_elementsToClean, listExclusion);
                            File.Copy(InterimTempFileName, tempFile.TempFile, true);
                        }
                    }
                }
            }
            catch (System.Exception ex)
            {
                Logger.LogError("PowerpointX cleaning failed");
                Logger.LogError(ex);
				throw;
            }
            finally
            {
                CleanUp();
            }
        }
        public override void RemoveMetadata(TempFileForActions tempFile, CleanActionPropertySet elementsToClean)
        {
            if (!(bool)elementsToClean[CleanOption.SkipDomCleaning].Value)
            {
                ExecuteWithDisabledOptions(() => DoDomRemoval(tempFile.TempFile, elementsToClean), elementsToClean, CleanOption.Macros);
            }

            // For elements not removed by DOM clean
            ExecuteUsingOfficeOpenXml(tempFile, elementsToClean);
        }
        public override void RemoveMetadata(object document, CleanActionPropertySet cleanProperties)
        {
            CMetadataElements elementsToClean = GetMetaDataElementsToClean(cleanProperties);
            CExcludedMetadataElements excludedElements = GetMetaDataElementsToExclude(cleanProperties);

            if (ExecuteUsingOptimisingAddin(document, elementsToClean, excludedElements))
                return;

            ExecuteStrategy2(new System.Runtime.InteropServices.DispatchWrapper(document), elementsToClean, excludedElements, m_domStripperProgId);
        }
        public LightSpeedCleanUIController(LightSpeedCleanUserControl control, CleanActionPropertySet properties, string fileType)
		{
            if (!FileTypeValid(fileType))
            {
                Utilities.ErrorMessage errorMessage = new Utilities.ErrorMessage("NOT_VALID_OFFICE_DOC", "Workshare.Policy.Actions.Properties.LanguageResources", Assembly.GetExecutingAssembly());
				Logger.LogError(errorMessage.LogString);
				throw new CleanUserActionException(errorMessage.DisplayString);
            }
            m_control = control;
            m_fileType = fileType;
			m_properties = properties;
            m_lowSurface = m_control.lowRiskTableLayoutPanel;
            m_medSurface = m_control.mediumRiskTableLayoutPanel;
            m_highSurface = m_control.highRiskTableLayoutPanel;
            m_internalController.ApplyToAll += new EventHandler(m_internalController_ApplyToAll);
        }
Example #7
0
 protected void ExecuteWithDisabledOptions(System.Action action, CleanActionPropertySet propertySet, params string[] optionsToTemporaryDisable)
 {
     var oldValues = new Dictionary<string, object>();
     try
     {
         optionsToTemporaryDisable.ToList().ForEach(key =>
             {
                 oldValues[key] = propertySet[key].Value;
                 propertySet[key].Value = false;
             });
         action();
     }
     finally
     {
         oldValues.ToList().ForEach(p => propertySet[p.Key].Value = oldValues[p.Key]);
     }
 }
        public override void RemoveMacros(TempFileForActions tempFile, CleanActionPropertySet cleanProperties)
        {
            if ((bool)cleanProperties[CleanOption.Macros].Value == true)
            {
                try
                {
                    using (CWordBinaryMacroCleaner wordMacroCleaner = new CWordBinaryMacroCleaner())
                    {
                        wordMacroCleaner.Clean(tempFile.TempFile);
                    }
                }
                catch (System.Exception ex)
                {
                    Logger.LogError("Word Binary macro cleaning failed");
					Logger.LogError(ex);
                    throw;
                }
            }
        }
        protected static List<ContentType> GetListOfEnabledElementsToClean(CleanActionPropertySet elementsToClean)
        {
            Dictionary<ContentType, string> fcsContentTypeDict = elementsToClean.GetFCSContentTypeDict();
            List<ContentType> elements = new List<ContentType>();
            elements.Add(ContentType.ContentRule);//we need this for multiple types to work correctly in cleaning

            foreach (KeyValuePair<string, IActionProperty> outerKvp in elementsToClean)
            {
                IActionProperty property = outerKvp.Value;
                foreach (KeyValuePair<ContentType, string> internalKvp in fcsContentTypeDict)
                {
                    if (String.Compare(internalKvp.Value, outerKvp.Key, true, System.Globalization.CultureInfo.InvariantCulture) == 0 &&
                        ((bool)property.Value) &&
                        !elements.Contains(internalKvp.Key))
                    {
                        elements.Add(internalKvp.Key);
                    }
                }
            }
            return elements;
        }
 public virtual void RemoveMacros(TempFileForActions tempFile, CleanActionPropertySet cleanProperties)
 {
 }
        protected static CExcludedMetadataElements GetMetaDataElementsToExclude(CleanActionPropertySet exProperties)
        {
            CExcludedMetadataElements ExcludedMetaDataElements = null;
            using (new WsActivationContext())
            {
                ExcludedMetaDataElements = new CExcludedMetadataElementsClass();

                List<string> excludedMetawallPropNames = exProperties.GetExcludedMetawallPropertyList();

                foreach (KeyValuePair<string, IActionProperty> kvp in exProperties)
                {
                    string key = kvp.Key;
                    IActionProperty property = kvp.Value;

                    if (!excludedMetawallPropNames.Contains(key))
                        continue;

                    string excludeKey = CleanActionPropertySet.ExcludedKeyToName(key);
                    IMWExcludedMetadataElement element = ExcludedMetaDataElements[excludeKey];

                    if (element != null)
                    {
                        element.Name = excludeKey; // property.DefaultDisplayName;
                        element.Value = property.Value;
                    }
                }
            }
            return ExcludedMetaDataElements;
        }
        protected CMetadataElements GetMacrosMetaDataElementToClean(CleanActionPropertySet properties)
        {
            CMetadataElements MetaDataElements = null;
            using (new WsActivationContext())
            {
                MetaDataElements = new CMetadataElementsClass();

                List<string> metawallPropNames = properties.GetMetawallPropertyList();

                foreach (KeyValuePair<string, IActionProperty> kvp in properties)
                {
                    string key = kvp.Key;
                    if (key == CleanOption.Macros)
                    {
                        IActionProperty property = kvp.Value;

                        if (!metawallPropNames.Contains(key))
                            continue;

                        IMWMetadataElement element = MetaDataElements[key];
                        if (element != null)
                        {
                            element.Enabled = (bool)property.Value;
                        }
                    }
                }
            }
            return MetaDataElements;
        }
        internal List<ContentType> GetRationalizedElementsToClean(List<ContentType> elements, CleanActionPropertySet.TargetApplication app)
        {
            List<ContentType> rationalized = new List<ContentType>();
            rationalized.AddRange(elements);

            if (app == CleanActionPropertySet.TargetApplication.Word)
            {
                if (rationalized.Contains(ContentType.Hyperlink) && !rationalized.Contains(ContentType.Field))
                    rationalized.Remove(ContentType.Hyperlink);
            }

            return rationalized;
        }
Example #14
0
        public virtual void RemoveMetadata(TempFileForActions tempFile, CleanActionPropertySet cleanProperties)
        {
			DoDomRemoval(tempFile.TempFile, cleanProperties);

			CMetadataElements elementsToClean = GetMetaDataElementsToClean(cleanProperties);
			CExcludedMetadataElements excludedElements = GetMetaDataElementsToExclude(cleanProperties);
			ExecuteStrategy2(tempFile.TempFile, elementsToClean, excludedElements, "Workshare.OfficeBinaryStripperStrategy");
        }
		private bool SatisfiesTargetApplication(CleanActionPropertySet.TargetApplication targetApplication, string fileType)
		{
            switch (fileType.ToLower(System.Globalization.CultureInfo.InvariantCulture))
            {
                case ".doc":
                case ".docx":
                case ".docm":
                case ".dotx":
                case ".dotm":
                    return (targetApplication & CleanActionPropertySet.TargetApplication.Word) == CleanActionPropertySet.TargetApplication.Word;

                case ".xls":
                case ".xlsx":
                case ".xlsm":
                case ".xltx":
                case ".xltm":
                    return (targetApplication & CleanActionPropertySet.TargetApplication.Excel) == CleanActionPropertySet.TargetApplication.Excel;


                case ".ppt":
                case ".pptx":
                case ".pptm":
                case ".potx":
                case ".potm":
				case ".ppsx":
				case ".ppsm":
                    return (targetApplication & CleanActionPropertySet.TargetApplication.PowerPoint) == CleanActionPropertySet.TargetApplication.PowerPoint;

                default:
                    return false;
            }
		}
Example #16
0
 public override void RemoveMetadata(TempFileForActions tempFile, CleanActionPropertySet cleanProperties)
 {
     Workshare.Protect.Api.CMetadataElements elementsToClean = GetMetaDataElementsToClean(cleanProperties);
     DoDomRemoval(tempFile.TempFile, cleanProperties);
 }
			public CleanData(CleanActionPropertySet cleanProperties, TempFileForActions tempFile)
			{
				this.cleanProperties = cleanProperties;
				this.tempFile = tempFile;
			}
		private Stream CallCleanThread(CleanActionPropertySet cleanProperties, Stream input, ref Dictionary<string, string> streamProperties, CleanPropertiesDisplayTranslator strings, bool callingFallbackThread, bool convertFile)
		{
			string originalDisplayName = streamProperties[strings.StrmProp_DisplayName];
			string originalFileName = streamProperties[strings.StrmProp_FileName];

			convertFile = (InstalledProduct.IsProtectEnterpriseClientInstalled() || InstalledProduct.IsProfessionalInstalled()) && FcsFile.IsRtfFile(input);
			if (convertFile)
			{
				input = ConvertToDoc(input, streamProperties, strings);
			}

			string displayName = streamProperties[strings.StrmProp_DisplayName];

			using (TempFileForActions tempFile = new TempFileForActions(Path.GetFileName(displayName), input))
			{
				CleanData cleanData = new CleanData(cleanProperties, tempFile);
				Thread staThread;
				if (callingFallbackThread)
				{
					staThread = new Thread(DoFallbackClean);
					staThread.Name = MethodBase.GetCurrentMethod().DeclaringType.Name + ".DoFallbackClean";
				}
				else
				{
					staThread = new Thread(DoClean);
					staThread.Name = MethodBase.GetCurrentMethod().DeclaringType.Name + ".DoClean";
				}
				staThread.SetApartmentState(ApartmentState.STA);
				staThread.Start(cleanData);
				staThread.Join();
				if (cleanData.ex != null)
				{
					//IActionProperty iap = null;

					if (callingFallbackThread || RunningInServerCtxt(cleanProperties))
					{
						m_fallbackTried = false;
						input.Dispose();
						throw cleanData.ex;
					}
					cleanData.ex = null;
					return CallCleanThread(cleanProperties, input, ref streamProperties, strings, true, convertFile);
				}

				input.Dispose();

				if (!convertFile)
				{
					return tempFile.GetMemoryStream();
				}
				return ConvertFromDoc(tempFile, originalFileName, originalDisplayName, streamProperties, strings);
			}
		}
		private Stream ExecuteStream(Stream input, Dictionary<string, string> sProperties, ActionPropertySet aProperties)
		{
			m_fallbackTried = null;
			if (aProperties == null) throw new ArgumentNullException("aProperties");
			Dictionary<string, string> streamProperties = sProperties;
			CleanActionPropertySet cleanProperties = new CleanActionPropertySet(aProperties);
			cleanProperties[Workshare.ApplicationControllers.PropertyNames.REQUIRES_APPCONTROLLER].Value = false;

			CleanPropertiesDisplayTranslator strings = CleanPropertiesDisplayTranslator.Instance;
			if (!streamProperties.ContainsKey(strings.StrmProp_DisplayName))
			{
				ErrorMessage errorMessage = new ErrorMessage("UNABLE_TO_GET_FILE_IN_STREAM", "Workshare.Policy.Actions.Properties.LanguageResources", Assembly.GetExecutingAssembly());
				Logger.LogError(errorMessage.LogString);
				throw new CleanUserActionException(errorMessage.DisplayString);
			}

			if (aProperties.SystemProperties.ContainsKey(strings.SysProp_FileType))
			{
				if (!m_supportedFiles.Supports(aProperties.SystemProperties[strings.SysProp_FileType].Value as string))
				{
					Utilities.ErrorMessage errorMessage = new Utilities.ErrorMessage("UNABLE_TO_CLEAN_NON_SUPPORTED_FILETYPE", "Workshare.Policy.Actions.Properties.LanguageResources", Assembly.GetExecutingAssembly());
					Logger.LogError(errorMessage.LogString);
					return null;
				}
			}

			return CallCleanThread(cleanProperties, input, ref streamProperties, strings, false, false);
		}
        private void BuildRiskLevelImage(CleanActionPropertySet.RiskRating rating, PictureBox pictureBox)
        {
            Bitmap bmp = pictureBox.Image as Bitmap;
            if (bmp == null)
            {
                bmp = new Bitmap(pictureBox.Width, pictureBox.Height);
            }

            Color startColor = Color.Empty;
            Color endColor = Color.Empty;

            switch (rating)
            {
                case CleanActionPropertySet.RiskRating.Low:
                    startColor = Color.Green;
                    break;
                case CleanActionPropertySet.RiskRating.Medium:
                    startColor = Color.Goldenrod;
                    break;
                case CleanActionPropertySet.RiskRating.High:
                    startColor = Color.Red;
                    break;
            }

            endColor = Color.FromArgb(128, startColor);

            Graphics graphics = Graphics.FromImage(bmp);

            Rectangle[] rectangles = new Rectangle[4];
            Point location = Point.Empty;
            Size size = new Size((bmp.Width - 3) / 4, bmp.Height);
            for (int i = 0; i < rectangles.Length; i++)
            {
                rectangles[i] = new Rectangle(location, size);
                location.X += size.Width + 1;
            }

            using (LinearGradientBrush brush = new LinearGradientBrush(new Rectangle(Point.Empty, bmp.Size),
                startColor, endColor, 0f))
            {
                graphics.FillRectangles(brush, rectangles);
            }

            pictureBox.Image = bmp;
        }
Example #21
0
		protected List<ContentType> GetListOfEnabledElementsToClean(CleanActionPropertySet elementsToClean)
		{
			Dictionary<ContentType, string> fcsContentTypeDict = elementsToClean.GetFCSContentTypeDict();
			List<ContentType> elements = new List<ContentType>();
			elements.Add(ContentType.ContentRule);//we need this for multiple types to work correctly in cleaning

			foreach (KeyValuePair<string, IActionProperty> outerKvp in elementsToClean)
			{
                IActionProperty property = outerKvp.Value;
                bool enabled;
                if (bool.TryParse(property.Value.ToString(), out enabled) && enabled)
				{
					foreach (KeyValuePair<ContentType, string> internalKvp in fcsContentTypeDict)
					{
						if (string.Equals(internalKvp.Value, outerKvp.Key, StringComparison.InvariantCultureIgnoreCase)
							&& !elements.Contains(internalKvp.Key))
						{
							elements.Add(internalKvp.Key);
						}
					}
				}
			}
			return elements;
		}
Example #22
0
        internal virtual ActionPropertySet BuildActionProperties(string sourceFilePath)
        {
            ActionPropertySet result = new ActionPropertySet();

            CleanActionPropertySet temp = new CleanActionPropertySet();
            var dict = temp.GetFCSContentTypeDict();
            foreach (string key in temp.Keys)
            {
                result.Add(new ActionProperty(key, temp[key].Value));
            }

            foreach (MetadataType mdt in m_metadataExclusions)
            {
                ContentType ct = Utils.ConvertContentType(mdt);
                string contentType;
                if (dict.TryGetValue(ct, out contentType))
                {
                    result[contentType].Value = false;
                }
            }

            foreach (CommonFieldType cft in m_fieldExclusions)
            {
                string fieldType = "ExcludeFieldCodes" + Utils.ConvertFieldType(cft);
                result[fieldType].Value = true;
            }

            result[CleanOption.UseWordOptimizingAddin].Value = true;
            result[CleanOption.ExcludeCustomProperties].Value = Normalize(CustomPropertyExclusionList);
            result[CleanOption.ExcludeFieldCodes].Value = Normalize(AdvancedFieldExclusionList);
            result[CleanOption.DeleteFieldCodes].Value = Normalize(FieldDeletionList);
            result[CleanOption.ExcludeDocumentVariables].Value = Normalize(DocumentVariableExclusionList);
            result[CleanOption.HandleFootnotesHiddenData].Value = TreatFootNotesAsMetadata;
            //result.Add(new ActionProperty("EnableFootnotes", true)); // always set this so that the cleaning is controlled by the excluded metadata types

            if (!string.IsNullOrEmpty(sourceFilePath))
            {
                var fileType = ValidateFileType(sourceFilePath);
                result.SystemProperties.Add("FileType", new ActionProperty("FileType", FileTypeBridge.GetFileType(fileType)));
            }

            return result;
        }
        public override void RemoveMetadata(TempFileForActions tempFile, CleanActionPropertySet cleanProperties)
        {
            CMetadataElements elementsToClean = GetMetaDataElementsToClean(cleanProperties);
            CExcludedMetadataElements excludedElements = GetMetaDataElementsToExclude(cleanProperties);
            
            CMetadataElements reviewersOnlyElements = new CMetadataElements();
            reviewersOnlyElements.SelectNoElements();
            reviewersOnlyElements["Reviewers"].Enabled = elementsToClean["Reviewers"].Enabled;

            int lDttm = 0;
            bool bExcludeSaveDate = FieldIsExcluded(excludedElements, "savedate");

            if (elementsToClean["DocumentStatistics"].Enabled && !bExcludeSaveDate)   // if zeroed, do not re-zero
            {
                lDttm = -1; // don't bother with dttm Revision
            }

            // We clean reviews on the binary level first to get ride of them correctly.

            if (!(bool) cleanProperties[CleanOption.SkipDomCleaning].Value)
            {
                lDttm = ExecuteStrategy3(tempFile.TempFile, lDttm, reviewersOnlyElements, excludedElements, "Metawall.WordBinaryStripper");
                DoDomRemoval(tempFile.TempFile, cleanProperties);
            }

            // Clean all binary metadata again, the DOM clean would have inserted some metadata.
            ExecuteStrategy3(tempFile.TempFile, lDttm, elementsToClean, excludedElements, "Metawall.WordBinaryStripper");
        }
 public override void RemoveMetadata(TempFileForActions tempFile, CleanActionPropertySet cleanProperties)
 {
     List<ContentType> listContentTypes = GetListOfEnabledElementsToClean(cleanProperties);
     List<Exclusion> listExclusion = GetListOfExcludedElements(cleanProperties);
     CleanFile(tempFile.TempFile, listContentTypes, listExclusion);
 }
Example #25
0
		protected void DoDomRemoval(string filename, CleanActionPropertySet cleanProperties)
		{
			OfficeApplicationCache officeApplicationCache = OfficeApplicationCache.Instance;
			object document = TryToOpenDocument(filename, GetAttempts());

			try
			{
				MessageFilter.Register();

			    if (!IsMarkedAsFinal(document))
			    {
			        if (IsReadOnly(document))
			        {
			            Logger.LogInfo(Properties.LanguageResources.THIS_FILE_IS_READ_ONLY);
			            officeApplicationCache.CloseDocument(document, false);
			            throw new Exception(Properties.LanguageResources.THIS_FILE_IS_READ_ONLY);
			        }
			    }

			    bool bFormProtected = IsFormProtected(document);
				bool bTriedToSave = false;
				try
				{
					RemoveMetadata(document, cleanProperties);
					bTriedToSave = true;
					officeApplicationCache.CloseDocument(document, true);
				}
				catch
				{
					if (!bTriedToSave)
					{
						officeApplicationCache.CloseDocument(document, false);
					}
					if (bFormProtected)
					{
						Logger.LogInfo(Properties.LanguageResources.THIS_FILE_IS_FORM_PROTECTED);
						throw new Exception(Properties.LanguageResources.THIS_FILE_IS_FORM_PROTECTED);
					}
					throw;
				}
			}
			finally
			{
				if (document != null)
				{
					Marshal.ReleaseComObject(document);
				}
				MessageFilter.Revoke();
			}
		}
Example #26
0
        public virtual void RemoveMetadata(object document, CleanActionPropertySet cleanProperties)
        {
			CMetadataElements elementsToClean = GetMetaDataElementsToClean(cleanProperties);
			CExcludedMetadataElements excludedElements = GetMetaDataElementsToExclude(cleanProperties);

			ExecuteStrategy2(new DispatchWrapper(document), elementsToClean, excludedElements, m_domStripperProgId);
        }
Example #27
0
		private bool SatisfiesTargetApplication(CleanActionPropertySet.TargetApplication targetApplication, string fileType)
		{
			foreach (string ft in fileType.Split(";".ToCharArray(), StringSplitOptions.RemoveEmptyEntries))
			{
				switch (ft.ToLowerInvariant())
				{
				case ".doc":
				case ".docx":
				case ".docm":
				case ".dotx":
				case ".dotm":
				case ".rtf":
					if ((targetApplication & CleanActionPropertySet.TargetApplication.Word) == CleanActionPropertySet.TargetApplication.Word)
					{
						return true;
					}
					break;

				case ".xls":
				case ".xlsx":
				case ".xlsm":
				case ".xltx":
				case ".xltm":
					if ((targetApplication & CleanActionPropertySet.TargetApplication.Excel) == CleanActionPropertySet.TargetApplication.Excel)
					{
						return true;
					}
					break;

				case ".ppt":
				case ".pptx":
				case ".pptm":
				case ".potx":
				case ".potm":
				case ".ppsx":
				case ".ppsm":
					if ((targetApplication & CleanActionPropertySet.TargetApplication.PowerPoint) == CleanActionPropertySet.TargetApplication.PowerPoint)
					{
						return true;
					}
					break;

				default:
					return false;
				}
			}
			return false;
		}
 public LightSpeedCleanStrategyProxy(CleanActionPropertySet cleanProperties)
 {
     m_cleanProperties = cleanProperties;
 }