/// 3. Taiin e yek file az DB ke mantnash estekhraj nashode ast.
        /// 4. Estekhraj e matn e file.
        /// 5. Zakhire ye matn e estekhraj shode dar DB (movaffagh ya Na movaffagh)
        public static void ExtractOneDocument(Guid applicationId, ref bool notExist)
        {
            //Taiin e yek file az DB ke mantnash estekhraj nashode ast.
            DocFileInfo file = DocumentsController.get_not_extracted_files(applicationId,
                                                                           "pdf,doc,docx,xlsx,ppt,pptx,txt,xml,htm,html", ',', 1).FirstOrDefault();

            if (file == null || !file.FileID.HasValue)
            {
                notExist = true;
                return;
            }

            // vojoode file dar folder ha
            file.refresh_folder_name();

            bool find = file.exists(applicationId);

            //estekhraje mant e file ba farakhani method e "ExtractFileContent"
            string content        = string.Empty;
            bool   NotExtractable = false;
            double duration       = 0;

            string errorText = string.Empty;

            if (find)
            {
                DateTime dtBegin = DateTime.Now;
                content  = FileContentExtractor.ExtractFileContent(applicationId, file, ref errorText);
                duration = DateTime.Now.Subtract(dtBegin).TotalMilliseconds;
            }

            if (!find)
            {
                find = false;
            }
            else if (string.IsNullOrEmpty(content))
            {
                NotExtractable = true;
            }

            // Zakhire ye matn e estekhraj shode dar DB dar halate movaffagh boodan.
            DocumentsController.save_file_content(applicationId,
                                                  file.FileID.Value, content, NotExtractable, !find, duration, errorText);
        }
Esempio n. 2
0
        public void ProcessRequest(HttpContext context)
        {
            //Privacy Check: OK
            paramsContainer = new ParamsContainer(context, nullTenantResponse: true);
            if (!paramsContainer.ApplicationID.HasValue)
            {
                return;
            }

            string responseText = string.Empty;

            string command = PublicMethods.parse_string(context.Request.Params["Command"], false);

            if (string.IsNullOrEmpty(command))
            {
                return;
            }

            Guid currentUserId = paramsContainer.CurrentUserID.HasValue ? paramsContainer.CurrentUserID.Value : Guid.Empty;

            Guid        fileId = string.IsNullOrEmpty(context.Request.Params["FileID"]) ? Guid.Empty : Guid.Parse(context.Request.Params["FileID"]);
            DocFileInfo file   = DocumentsController.get_file(paramsContainer.Tenant.Id, fileId);

            if (file == null)
            {
                paramsContainer.return_response(PublicConsts.BadRequestResponse);
                return;
            }

            bool isTemporary =
                PublicMethods.parse_string(HttpContext.Current.Request.Params["Category"], false).ToLower() == "temporary";

            bool hasAccess = isTemporary || PublicMethods.is_system_admin(paramsContainer.Tenant.Id, currentUserId);

            PrivacyObjectType pot = file.OwnerType == FileOwnerTypes.Node ? PrivacyObjectType.Node : PrivacyObjectType.None;

            hasAccess = hasAccess || PrivacyController.check_access(paramsContainer.Tenant.Id,
                                                                    paramsContainer.CurrentUserID, file.OwnerID.Value, pot, PermissionType.View);

            if (!hasAccess && currentUserId != Guid.Empty &&
                CNController.is_node(paramsContainer.Tenant.Id, file.OwnerID.Value))
            {
                bool isCreator = false, isContributor = false, isExpert = false, isMember = false, isAdminMember = false,
                     isServiceAdmin = false, isAreaAdmin = false, perCreatorLevel = false;

                CNController.get_user2node_status(paramsContainer.Tenant.Id, paramsContainer.CurrentUserID.Value,
                                                  file.OwnerID.Value, ref isCreator, ref isContributor, ref isExpert, ref isMember, ref isAdminMember,
                                                  ref isServiceAdmin, ref isAreaAdmin, ref perCreatorLevel);

                hasAccess = isServiceAdmin || isAreaAdmin || isCreator || isContributor || isExpert || isMember;
            }

            if (!hasAccess)
            {
                paramsContainer.return_response("{\"ErrorText\":\"" + Messages.AccessDenied.ToString() + "\"}");
            }

            if (isTemporary)
            {
                file.FolderName = FolderNames.TemporaryFiles;
            }
            else
            {
                file.refresh_folder_name();
            }

            if (!file.exists(paramsContainer.Tenant.Id))
            {
                _return_response(ref responseText);
            }

            DocFileInfo destFile = new DocFileInfo()
            {
                FileID = file.FileID, FolderName = FolderNames.PDFImages
            };

            switch (command)
            {
            case "Convert2Image":
                convert2image(file,
                              PublicMethods.parse_string(context.Request.Params["PS"]),
                              destFile,
                              PublicMethods.parse_bool(context.Request.Params["Repair"]), ref responseText);
                _return_response(ref responseText);
                return;

            case "GetPagesCount":
                get_pages_count(file,
                                PublicMethods.parse_string(context.Request.Params["PS"]),
                                destFile, ref responseText);
                _return_response(ref responseText);
                return;

            case "GetPage":
                get_page(PublicMethods.parse_int(context.Request.Params["Page"], 1), destFile);
                return;
            }

            paramsContainer.return_response(PublicConsts.BadRequestResponse);
        }
Esempio n. 3
0
        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));
            }
        }
        public void ProcessRequest(HttpContext context)
        {
            //Privacy Check: OK
            paramsContainer = new ParamsContainer(context, nullTenantResponse: false);

            Guid fileId = string.IsNullOrEmpty(context.Request.Params["FileID"]) ?
                          Guid.Empty : Guid.Parse(context.Request.Params["FileID"]);

            if (fileId == Guid.Empty && !Guid.TryParse(context.Request.Params["ATTFID"], out fileId))
            {
                fileId = Guid.Empty;
            }

            string category = PublicMethods.parse_string(context.Request.Params["Category"], false);

            bool   isTemporary = category.ToLower() == FolderNames.TemporaryFiles.ToString().ToLower();
            bool?  addFooter   = PublicMethods.parse_bool(context.Request.Params["Meta"]);
            Guid?  coverId     = PublicMethods.parse_guid(context.Request.Params["CoverID"]);
            string pdfPassword = PublicMethods.parse_string(context.Request.Params["PS"]);

            List <FolderNames> freeFolders = new[] {
                FolderNames.ProfileImages,
                FolderNames.HighQualityProfileImage,
                FolderNames.CoverPhoto,
                FolderNames.HighQualityCoverPhoto,
                FolderNames.Icons,
                FolderNames.HighQualityIcon,
                FolderNames.ApplicationIcons,
                FolderNames.HighQualityApplicationIcon,
                FolderNames.Pictures
            }.ToList();

            bool isFreeFolder = !string.IsNullOrEmpty(category) && freeFolders.Any(f => f.ToString().ToLower() == category.ToLower());

            if (isFreeFolder)
            {
                FolderNames fn = freeFolders.Where(u => u.ToString().ToLower() == category.ToLower()).FirstOrDefault();

                DocFileInfo pic =
                    new DocFileInfo()
                {
                    FileID = fileId, Extension = "jpg", FileName = fileId.ToString(), FolderName = fn
                };

                send_file(pic, false);
            }

            if (!paramsContainer.ApplicationID.HasValue)
            {
                paramsContainer.return_response(PublicConsts.NullTenantResponse);
                return;
            }

            if (isTemporary)
            {
                string ext = PublicMethods.parse_string(context.Request.Params["Extension"]);

                DocFileInfo temp = new DocFileInfo()
                {
                    FileID     = fileId,
                    Extension  = ext,
                    FileName   = fileId.ToString(),
                    FolderName = FolderNames.TemporaryFiles
                };

                send_file(temp, false);
            }
            else
            {
                DocFileInfo AttachFile = DocumentsController.get_file(paramsContainer.Tenant.Id, fileId);

                if (AttachFile == null)
                {
                    paramsContainer.return_response("{\"ErrorText\":\"" + Messages.AccessDenied + "\"}");
                    return;
                }

                PrivacyObjectType pot = AttachFile.OwnerType == FileOwnerTypes.Node ?
                                        PrivacyObjectType.Node : PrivacyObjectType.None;

                DocFileInfo ownerNode = !AttachFile.FileID.HasValue ? null :
                                        DocumentsController.get_file_owner_node(paramsContainer.Tenant.Id, AttachFile.FileID.Value);
                if (ownerNode != null)
                {
                    AttachFile.OwnerNodeID   = ownerNode.OwnerNodeID;
                    AttachFile.OwnerNodeName = ownerNode.OwnerNodeName;
                    AttachFile.OwnerNodeType = ownerNode.OwnerNodeType;
                }

                bool accessDenied =
                    !PrivacyController.check_access(paramsContainer.Tenant.Id,
                                                    paramsContainer.CurrentUserID, AttachFile.OwnerID.Value, pot, PermissionType.View) &&
                    !(
                        paramsContainer.CurrentUserID.HasValue &&
                        new CNAPI()
                {
                    paramsContainer = this.paramsContainer
                }
                        ._is_admin(paramsContainer.Tenant.Id, AttachFile.OwnerID.Value,
                                   paramsContainer.CurrentUserID.Value, CNAPI.AdminLevel.Creator, false)
                        );

                if (accessDenied)
                {
                    //Save Log
                    try
                    {
                        LogController.save_log(paramsContainer.Tenant.Id, new Log()
                        {
                            UserID           = paramsContainer.CurrentUserID,
                            HostAddress      = PublicMethods.get_client_ip(HttpContext.Current),
                            HostName         = PublicMethods.get_client_host_name(HttpContext.Current),
                            Action           = Modules.Log.Action.Download_AccessDenied,
                            SubjectID        = fileId,
                            Info             = "{\"Error\":\"" + Base64.encode(Messages.AccessDenied.ToString()) + "\"}",
                            ModuleIdentifier = ModuleIdentifier.DCT
                        });
                    }
                    catch { }
                    //end of Save Log

                    paramsContainer.return_response("{\"ErrorText\":\"" + Messages.AccessDenied + "\"}");

                    return;
                }

                AttachFile.refresh_folder_name();

                string ext = AttachFile == null || string.IsNullOrEmpty(AttachFile.Extension) ? string.Empty :
                             AttachFile.Extension.ToLower();
                bool isImage = ext == "jpg" || ext == "jpeg" || ext == "png" || ext == "gif" || ext == "bmp";

                if (string.IsNullOrEmpty(AttachFile.Extension) || AttachFile.Extension.ToLower() != "pdf")
                {
                    coverId = null;
                }

                bool   dl          = !isImage || PublicMethods.parse_bool(context.Request.Params["dl"], defaultValue: true) == true;
                string contentType = !dl && isImage?PublicMethods.get_mime_type_by_extension(ext) : null;

                send_file(AttachFile, !isImage, addPDFCover: true,
                          addPDFFooter: addFooter.HasValue && addFooter.Value,
                          coverId: coverId,
                          pdfPassword: pdfPassword,
                          contentType: contentType,
                          isAttachment: dl);
            }
        }