public static byte[] add_custom_cover(Guid applicationId, Guid currentUserId, byte[] pdfContent, Guid coverId, Guid ownerNodeId) { DocFileInfo pdfCover = null; pdfCover = DocumentsController.get_file(applicationId, coverId); if (pdfCover == null || string.IsNullOrEmpty(pdfCover.Extension) || pdfCover.Extension.ToLower() != "pdf") { pdfCover = null; } byte[] coverContent = pdfContent == null ? null : pdfCover.toByteArray(applicationId); if (coverContent == null || coverContent.Length == 0) { return(pdfContent); } Dictionary <string, string> dic = CNAPI.get_replacement_dictionary(applicationId, currentUserId, ownerNodeId, true); List <FormElement> tempElems = dic.Keys.ToList().Select(key => new FormElement() { Name = key, Type = FormElementTypes.Text, TextValue = dic[key] }).ToList(); byte[] cover = PDFTemplates.fill_template(coverContent, tempElems); return(PDFUtil.merge_documents(new List <object>() { cover, pdfContent })); }
protected void get_page(int?pageNumber, DocFileInfo destFile) { if (!pageNumber.HasValue) { pageNumber = 1; } try { ImageFormat imageFormat = ImageFormat.Png; destFile.FileName = pageNumber.ToString(); destFile.Extension = imageFormat.ToString().ToLower(); byte[] fileBytes = !destFile.exists(paramsContainer.ApplicationID) ? File.ReadAllBytes(PublicMethods.map_path(PublicConsts.NoPDFPage)) : destFile.toByteArray(paramsContainer.ApplicationID); HttpContext.Current.Response.ContentType = "application/octet-stream"; HttpContext.Current.Response.AddHeader("Content-Disposition", string.Format("attachment;filename=\"{0}\"", pageNumber.ToString() + "." + imageFormat.ToString().ToLower())); HttpContext.Current.Response.AddHeader("Content-Length", fileBytes.Length.ToString()); HttpContext.Current.Response.BinaryWrite(fileBytes); HttpContext.Current.Response.End(); } catch { } }
public static string extract_file_content(Guid applicationId, DocFileInfo file) { ISolrOperations <SolrDoc> solr = get_solr_operator(); using (Stream content = new MemoryStream(file.toByteArray(applicationId))) { ExtractResponse response = solr.Extract(new ExtractParameters(content, PublicMethods.get_random_number().ToString(), PublicMethods.random_string(10)) { ExtractOnly = true, ExtractFormat = ExtractFormat.Text }); return(response.Content); } }
private void activate_node_type_icon(Guid applicationId, string id) { Guid?templateNodeTypeId = IDs.get_id_from_template(id); if (!templateNodeTypeId.HasValue) { return; } DocFileInfo pic = new DocFileInfo() { FileID = templateNodeTypeId, Extension = "jpg", FileName = templateNodeTypeId.ToString(), FolderName = FolderNames.Icons }; byte[] fileContent = pic.toByteArray(RaaiVanSettings.ReferenceTenantID); if (fileContent.Length == 0) { return; } Guid?newFileId = IDs.new_id(id); DocFileInfo newPic = new DocFileInfo() { FileID = newFileId, Extension = "jpg", FileName = newFileId.ToString(), FolderName = FolderNames.Icons }; newPic.store(applicationId, fileContent); }
protected void handle_imported_file(DocFileInfo file, ref string responseText) { //Privacy Check: OK if (!paramsContainer.GBEdit) { return; } if (!AuthorizationManager.has_right(AccessRoleName.DataImport, paramsContainer.CurrentUserID)) { responseText = "{\"ErrorText\":\"" + Messages.AccessDenied + "\"}"; return; } if (!file.exists(paramsContainer.Tenant.Id)) { responseText = "{\"ErrorText\":\"" + Messages.OperationFailed + "\"}"; return; } XmlDocument xmlDoc = new XmlDocument(); try { using (MemoryStream stream = new MemoryStream(file.toByteArray(paramsContainer.Tenant.Id))) xmlDoc.Load(stream); } catch (Exception ex) { responseText = "{\"ErrorText\":\"" + Messages.OperationFailed + "\"}"; return; } string docName = xmlDoc.DocumentElement.Name.ToLower(); bool result = false; switch (docName) { case "nodes": result = update_nodes(ref xmlDoc); break; case "nodeids": result = update_node_ids(ref xmlDoc); break; case "removenodes": result = remove_nodes(ref xmlDoc); break; case "users": result = update_users(ref xmlDoc); break; case "members": result = update_members(ref xmlDoc); break; case "experts": result = update_experts(ref xmlDoc); break; case "relations": result = update_relations(ref xmlDoc); break; case "authors": result = update_authors(ref xmlDoc); break; case "userconfidentialities": result = update_user_confidentialities(ref xmlDoc); break; case "permissions": result = update_permissions(ref xmlDoc); break; } responseText = result ? "{\"Succeed\":\"" + Messages.OperationCompletedSuccessfully + "\"}" : "{\"ErrorText\":\"" + Messages.OperationFailed + "\"}"; }
public override IList <IElement> End(IWorkerContext ctx, Tag tag, IList <IElement> currentContent) { IDictionary <string, string> attributes = tag.Attributes; string src; if (!attributes.TryGetValue(itsXmlHtml.HTML.Attribute.SRC, out src)) { return(new List <IElement>(1)); } if (string.IsNullOrEmpty(src)) { return(new List <IElement>(1)); } //convert url to base64 image if (!src.StartsWith("data:image/", StringComparison.InvariantCultureIgnoreCase)) { int index = src.ToLower().IndexOf("fileid="); if (index >= 0) { string newSrc = src.Substring(index + "fileid=".Length); if (newSrc.IndexOf("&") > 0) { newSrc = newSrc.Substring(0, newSrc.IndexOf("&")); } Guid? fileId = PublicMethods.parse_guid(newSrc); DocFileInfo fi = DocumentsController.get_file(ApplicationID, fileId.Value); if (fi != null) { fi.refresh_folder_name(); } if (!fi.exists(ApplicationID)) { try { System.Drawing.Image img = null; using (MemoryStream stream = new MemoryStream(fi.toByteArray(ApplicationID))) img = System.Drawing.Bitmap.FromStream(stream); string strWidth = tag == null || tag.CSS == null || !tag.CSS.ContainsKey("width") ? string.Empty : tag.CSS["width"]; string strHeight = tag == null || tag.CSS == null || !tag.CSS.ContainsKey("height") ? string.Empty : tag.CSS["height"]; if (!string.IsNullOrEmpty(strWidth)) { strWidth = strWidth.ToLower().Replace("px", ""); } if (!string.IsNullOrEmpty(strHeight)) { strHeight = strHeight.ToLower().Replace("px", ""); } int width = 0, height = 0, maxWidth = 650, maxHeight = 900; if (string.IsNullOrEmpty(strWidth) || !int.TryParse(strWidth, out width) || width < 0) { width = img.Width; } if (string.IsNullOrEmpty(strHeight) || !int.TryParse(strHeight, out height) || height < 0) { height = img.Height; } double coeff = Math.Min(width <= maxWidth ? 1 : (double)maxWidth / (double)width, height <= maxHeight ? 1 : (double)maxHeight / (double)height); width = (int)Math.Floor(coeff * (double)width); height = (int)Math.Floor(coeff * (double)height); if (width != img.Width || height != img.Height) { string msg = string.Empty; if (RVGraphics.make_thumbnail(img, width, height, 0, 0, ref img, ref msg)) { tag.CSS["width"] = (width = img.Width).ToString() + "px"; tag.CSS["height"] = (height = img.Height).ToString() + "px"; } } newSrc = PublicMethods.image_to_base64(img, System.Drawing.Imaging.ImageFormat.Png); if (!string.IsNullOrEmpty(newSrc)) { src = "data:image/png;base64," + newSrc; } } catch { } } } } //end of convert url to base64 image if (src.StartsWith("data:image/", StringComparison.InvariantCultureIgnoreCase)) { // data:[<MIME-type>][;charset=<encoding>][;base64],<data> var base64Data = src.Substring(src.IndexOf(",") + 1); var imagedata = Convert.FromBase64String(base64Data); var image = iTextSharp.text.Image.GetInstance(imagedata); image.ScaleToFitLineWhenOverflow = true; image.ScaleToFitHeight = false; var list = new List <IElement>(); var htmlPipelineContext = GetHtmlPipelineContext(ctx); IElement imgElement = GetCssAppliers().Apply(new Chunk((iTextSharp.text.Image)GetCssAppliers() .Apply(image, tag, htmlPipelineContext), 0, 0, true), tag, htmlPipelineContext); list.Add(imgElement); return(list); } else { return(base.End(ctx, tag, currentContent)); } }
protected void send_file(DocFileInfo file, bool logNeeded, bool addPDFCover = false, bool addPDFFooter = false, Guid?coverId = null, string pdfPassword = null, string contentType = null, bool isAttachment = true) { byte[] fileContent = file.toByteArray(paramsContainer.ApplicationID); if (fileContent.Length == 0) { send_empty_response(); return; } //Save Log if (logNeeded && paramsContainer.CurrentUserID.HasValue) { LogController.save_log(paramsContainer.Tenant.Id, new Log() { UserID = paramsContainer.CurrentUserID, Date = DateTime.Now, HostAddress = PublicMethods.get_client_ip(HttpContext.Current), HostName = PublicMethods.get_client_host_name(HttpContext.Current), Action = Modules.Log.Action.Download, SubjectID = file.FileID, Info = file.toJson(paramsContainer.Tenant.Id), ModuleIdentifier = ModuleIdentifier.DCT }); } //end of Save Log if (file.Extension.ToLower() == "pdf") { addPDFCover = addPDFCover && file.OwnerNodeID.HasValue && coverId.HasValue && paramsContainer.ApplicationID.HasValue && paramsContainer.CurrentUserID.HasValue; if (addPDFFooter || addPDFCover) { bool invalidPassword = false; fileContent = PDFUtil.get_pdf_content(paramsContainer.Tenant.Id, fileContent, pdfPassword, ref invalidPassword); if (invalidPassword) { string responseText = "{\"InvalidPassword\":" + true.ToString().ToLower() + "}"; paramsContainer.return_response(ref responseText); return; } } if (addPDFFooter) { User currentUser = !paramsContainer.CurrentUserID.HasValue ? null : UsersController.get_user(paramsContainer.Tenant.Id, paramsContainer.CurrentUserID.Value); if (currentUser == null) { currentUser = new User() { UserID = Guid.NewGuid(), UserName = "******", FirstName = "[anonymous]", LastName = "[anonymous]" }; } DownloadedFileMeta meta = new DownloadedFileMeta(PublicMethods.get_client_ip(HttpContext.Current), currentUser.UserName, currentUser.FirstName, currentUser.LastName, null); fileContent = PDFTemplates.append_footer(fileContent, meta.toString()); } if (addPDFCover) { fileContent = Wiki2PDF.add_custom_cover(paramsContainer.Tenant.Id, paramsContainer.CurrentUserID.Value, fileContent, coverId.Value, file.OwnerNodeID.Value); } if (!string.IsNullOrEmpty(pdfPassword)) { fileContent = PDFUtil.set_password(fileContent, pdfPassword); } } string retFileName = file.FileName + (string.IsNullOrEmpty(file.Extension) ? string.Empty : "." + file.Extension); paramsContainer.file_response(fileContent, retFileName, contentType: contentType, isAttachment: isAttachment); }
public static bool import_form(Guid applicationId, Guid?instanceId, DocFileInfo uploadedFile, Dictionary <string, object> map, Guid currentUserId, ref List <FormElement> savedElements, List <FormElement> nodeElements, ref string errorMessage) { if (!instanceId.HasValue || uploadedFile == null || !uploadedFile.FileID.HasValue) { return(false); } if (!uploadedFile.exists(applicationId)) { return(false); } if (map.ContainsKey("sub")) { map = (Dictionary <string, object>)map["sub"]; } FormType formInstance = FGController.get_form_instance(applicationId, instanceId.Value); if (formInstance == null || !formInstance.InstanceID.HasValue || !formInstance.FormID.HasValue) { return(false); } List <FormElement> formElements = FGController.get_form_instance_elements(applicationId, instanceId.Value).OrderBy(u => u.SequenceNumber).ToList(); if (formElements == null || formElements.Count == 0) { return(false); } XmlDocument doc = new XmlDocument(); try { using (MemoryStream stream = new MemoryStream(uploadedFile.toByteArray(applicationId))) doc.Load(stream); } catch (Exception ex) { LogController.save_error_log(applicationId, currentUserId, "FG_ImportForm_LoadFile", ex, ModuleIdentifier.FG); errorMessage = Messages.OperationFailed.ToString(); return(false); } XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable); if (!string.IsNullOrEmpty(doc.DocumentElement.GetNamespaceOfPrefix(""))) { nsmgr.AddNamespace(DEFAULTPREFIX, doc.DocumentElement.GetNamespaceOfPrefix("")); nsmgr.AddNamespace("", doc.DocumentElement.GetNamespaceOfPrefix("")); } foreach (XmlAttribute attr in doc.SelectSingleNode("/*").Attributes) { if (attr.Prefix == "xmlns") { nsmgr.AddNamespace(attr.LocalName, attr.Value); } } List <FormElement> theElements = new List <FormElement>(); //add node elements if (nodeElements == null) { nodeElements = new List <FormElement>(); } foreach (FormElement e in nodeElements) { e.Type = FormElementTypes.Text; formElements.Add(e); } //end of add node elements foreach (string name in map.Keys) { List <FormElement> newElems = _parse_imported_form(applicationId, doc.DocumentElement, get_child_nodes(doc.DocumentElement, name, nsmgr), nsmgr, map[name], formElements, map); if (newElems != null && newElems.Count > 0) { theElements.AddRange(newElems); } } //remove node elements foreach (FormElement e in nodeElements) { FormElement elem = theElements.Where( u => (u.ElementID == e.ElementID || u.RefElementID == e.ElementID) && u.Name == e.Name).FirstOrDefault(); if (elem != null) { e.TextValue = elem.TextValue; theElements.Remove(elem); } } //end of remove node elements List <FormType> newFormInstances = new List <FormType>(); List <FormElement> newElements = new List <FormElement>(); List <DocFileInfo> newFiles = new List <DocFileInfo>(); get_save_items(formInstance, theElements, ref newFormInstances, ref newElements, ref newFiles); //set_national_ids(ref newElements); set_identity_values(ref newElements); //remove empty text elements newElements = newElements .Where(u => u.Type != FormElementTypes.Text || !string.IsNullOrEmpty(u.TextValue)).ToList(); //end of remove empty text elements if (newFiles != null) { newFiles.ForEach(f => f.move(applicationId, FolderNames.TemporaryFiles, FolderNames.Attachments)); } bool result = newFormInstances == null || newFormInstances.Count == 0 || FGController.create_form_instances(applicationId, newFormInstances, currentUserId); result = result && FGController.save_form_instance_elements(applicationId, ref newElements, new List <Guid>(), currentUserId, ref errorMessage); if (!result && newFiles != null) { newFiles.ForEach(f => f.move(applicationId, FolderNames.Attachments, FolderNames.TemporaryFiles)); } if (result) { savedElements = theElements; } return(result); }
public bool ProcessTenantIndependentRequest(HttpContext context) { if (!RaaiVanSettings.SAASBasedMultiTenancy && !paramsContainer.ApplicationID.HasValue) { paramsContainer.return_response(PublicConsts.NullTenantResponse); return(true); } string responseText = string.Empty; string command = !string.IsNullOrEmpty(context.Request.Params["cmd"]) ? context.Request.Params["cmd"].ToLower() : (string.IsNullOrEmpty(context.Request.Params["Command"]) ? "uploadfile" : context.Request.Params["Command"].ToLower()); Guid userId = string.IsNullOrEmpty(context.Request.Params["UserID"]) ? PublicMethods.get_current_user_id() : Guid.Parse(context.Request.Params["UserID"]); Guid ownerId = string.IsNullOrEmpty(context.Request.Params["OwnerID"]) ? Guid.Empty : Guid.Parse(context.Request.Params["OwnerID"]); FileOwnerTypes ownerType = FileOwnerTypes.None; if (!Enum.TryParse <FileOwnerTypes>(context.Request.Params["OwnerType"], out ownerType)) { ownerType = FileOwnerTypes.None; } Guid?applicationId = paramsContainer.ApplicationID; switch (command) { case "uploadicon": { Guid iconId = string.IsNullOrEmpty(context.Request.Params["IconID"]) ? Guid.Empty : Guid.Parse(context.Request.Params["IconID"]); IconType iconType = IconType.None; if (!Enum.TryParse <IconType>(context.Request.Params["Type"], true, out iconType)) { iconType = IconType.None; } if (iconType == IconType.ApplicationIcon || (RaaiVanSettings.SAASBasedMultiTenancy && (iconType == IconType.ProfileImage || iconType == IconType.CoverPhoto))) { applicationId = null; } else if (!applicationId.HasValue) { responseText = PublicConsts.NullTenantResponse; break; } DocFileInfo uploaded = new DocFileInfo() { FileID = iconId, OwnerID = ownerId, OwnerType = ownerType, FolderName = FolderNames.TemporaryFiles }; byte[] fileContent = new byte[0]; bool succeed = _attach_file_command(applicationId, uploaded, ref responseText, ref fileContent, dontStore: true); if (!succeed || fileContent == null || fileContent.Length == 0) { break; } if (iconType == IconType.ProfileImage && iconId == Guid.Empty) { iconId = userId; } string errorMessage = string.Empty; IconMeta meta = null; succeed = RVGraphics.create_icon(applicationId, iconId, iconType, fileContent, ref errorMessage, ref meta); if (succeed && meta != null) { responseText = responseText.Replace("\"~[[MSG]]\"", meta.toJson(applicationId)); } else { responseText = responseText.Replace("\"~[[MSG]]\"", errorMessage); } try { string tempRes = string.Empty; if (succeed) { remove_file(uploaded, ref tempRes); } } catch { } break; } case "deleteicon": { Guid iconId = string.IsNullOrEmpty(context.Request.Params["IconID"]) ? Guid.Empty : Guid.Parse(context.Request.Params["IconID"]); IconType iconType = IconType.None; if (!Enum.TryParse <IconType>(context.Request.Params["Type"], true, out iconType)) { iconType = IconType.None; } if (iconType == IconType.ApplicationIcon || (RaaiVanSettings.SAASBasedMultiTenancy && (iconType == IconType.ProfileImage || iconType == IconType.CoverPhoto))) { applicationId = null; } else if (!applicationId.HasValue) { responseText = PublicConsts.NullTenantResponse; break; } if (iconType == IconType.ProfileImage && iconId == Guid.Empty) { iconId = userId; } FolderNames folderName = FolderNames.ProfileImages; FolderNames highQualityFolderName = FolderNames.HighQualityProfileImage; string defaultIconUrl = string.Empty; bool isValid = DocumentUtilities.get_icon_parameters(applicationId, iconType, ref folderName, ref highQualityFolderName, ref defaultIconUrl); if (!isValid) { responseText = PublicConsts.NullTenantResponse; break; } new DocFileInfo() { FileID = iconId, Extension = "jpg", OwnerID = ownerId, OwnerType = ownerType, FolderName = folderName }.delete(paramsContainer.ApplicationID); new DocFileInfo() { FileID = iconId, Extension = "jpg", OwnerID = ownerId, OwnerType = ownerType, FolderName = highQualityFolderName }.delete(paramsContainer.ApplicationID); responseText = "{\"Succeed\":\"" + Messages.OperationCompletedSuccessfully + "\"" + ",\"DefaultIconURL\":\"" + defaultIconUrl + "\"}"; break; } case "cropicon": { Guid iconId = string.IsNullOrEmpty(context.Request.Params["IconID"]) ? Guid.Empty : Guid.Parse(context.Request.Params["IconID"]); IconType iconType = IconType.None; if (!Enum.TryParse <IconType>(context.Request.Params["Type"], true, out iconType)) { iconType = IconType.None; } if (iconType == IconType.ApplicationIcon || (RaaiVanSettings.SAASBasedMultiTenancy && (iconType == IconType.ProfileImage || iconType == IconType.CoverPhoto))) { applicationId = null; } else if (!applicationId.HasValue) { responseText = PublicConsts.NullTenantResponse; break; } int iconWidth = 100, iconHeight = 100; FolderNames imageFolder = FolderNames.ProfileImages, highQualityImageFolder = FolderNames.HighQualityProfileImage; if (iconType == IconType.ProfileImage && iconId == Guid.Empty) { iconId = userId; } bool isValid = DocumentUtilities.get_icon_parameters(applicationId, iconType, ref iconWidth, ref iconHeight, ref imageFolder, ref highQualityImageFolder); if (!isValid) { break; } DocFileInfo highQualityFile = new DocFileInfo() { FileID = iconId, Extension = "jpg", FolderName = highQualityImageFolder }; DocFileInfo file = new DocFileInfo() { FileID = iconId, Extension = "jpg", FolderName = imageFolder }; int x = string.IsNullOrEmpty(context.Request.Params["X"]) ? -1 : int.Parse(context.Request.Params["X"]); int y = string.IsNullOrEmpty(context.Request.Params["Y"]) ? -1 : int.Parse(context.Request.Params["Y"]); int width = string.IsNullOrEmpty(context.Request.Params["Width"]) ? -1 : (int)double.Parse(context.Request.Params["Width"]); int height = string.IsNullOrEmpty(context.Request.Params["Height"]) ? -1 : (int)double.Parse(context.Request.Params["Height"]); IconMeta meta = null; RVGraphics.extract_thumbnail(applicationId, highQualityFile, highQualityFile.toByteArray(applicationId), file, x, y, width, height, iconWidth, iconHeight, ref responseText, ref meta); break; } } if (!string.IsNullOrEmpty(responseText)) { paramsContainer.return_response(ref responseText); } return(!string.IsNullOrEmpty(responseText)); }
public static PdfReader open_pdf_file(Guid applicationId, DocFileInfo pdf, string password, ref bool invalidPassword) { return(open_pdf_file(applicationId, pdf.toByteArray(applicationId), password, ref invalidPassword)); }