Ejemplo n.º 1
0
        private float GetCurrentAverage(string fullPageName)
        {
            float average = 0;

            try {
                IFilesStorageProviderV40 filesStorageProvider = GetDefaultFilesStorageProvider();

                MemoryStream stream      = new MemoryStream();
                string       fileContent = "";

                if (FileExists(filesStorageProvider, DefaultDirectoryName(), ratingFileName))
                {
                    filesStorageProvider.RetrieveFile(DefaultDirectoryName() + ratingFileName, stream);
                    stream.Seek(0, SeekOrigin.Begin);
                    fileContent = Encoding.UTF8.GetString(stream.ToArray());
                }

                string[] plugins = fileContent.Split(new String[] { "||" }, StringSplitOptions.RemoveEmptyEntries);

                // If the plugin is found return the posizion in the plugins array
                // otherwise return -1
                int pluginIndex = SearchPlugin(plugins, fullPageName);
                if (pluginIndex != -1)
                {
                    string[] pluginDetails = plugins[pluginIndex].Split(new string[] { "|" }, StringSplitOptions.RemoveEmptyEntries);
                    average = (float)int.Parse(pluginDetails[2]) / (float)100;
                }
            }
            catch (Exception ex) {
                LogWarning(String.Format("Exception occurred {0}", ex.ToString()));
            }
            return(average);
        }
Ejemplo n.º 2
0
        private void AddRating(string fullPageName, int rate)
        {
            IFilesStorageProviderV40 filesStorageProvider = GetDefaultFilesStorageProvider();

            MemoryStream stream = new MemoryStream();

            if (FileExists(filesStorageProvider, DefaultDirectoryName(), ratingFileName))
            {
                filesStorageProvider.RetrieveFile(DefaultDirectoryName() + ratingFileName, stream);
                stream.Seek(0, SeekOrigin.Begin);
            }
            string fileContent = Encoding.UTF8.GetString(stream.ToArray());

            string[] plugins = fileContent.Split(new String[] { "||" }, StringSplitOptions.RemoveEmptyEntries);

            StringBuilder sb = new StringBuilder();

            // If the plugin is found return the posizion in the plugins array
            // otherwise return -1
            int pluginIndex = SearchPlugin(plugins, fullPageName);

            if (pluginIndex != -1)
            {
                int numRates   = int.Parse(plugins[pluginIndex].Split(new string[] { "|" }, StringSplitOptions.RemoveEmptyEntries)[1]);
                int average    = int.Parse(plugins[pluginIndex].Split(new string[] { "|" }, StringSplitOptions.RemoveEmptyEntries)[2]);
                int newAverage = ((average * numRates) + (rate * 100)) / (numRates + 1);
                numRates++;
                plugins[pluginIndex] = fullPageName + "|" + numRates + "|" + newAverage;
                foreach (string plugin in plugins)
                {
                    sb.Append(plugin + "||");
                }
            }
            else
            {
                foreach (string plugin in plugins)
                {
                    sb.Append(plugin + "||");
                }
                sb.Append(fullPageName + "|1|" + (rate * 100));
            }

            stream = new MemoryStream(Encoding.UTF8.GetBytes(sb.ToString()));

            filesStorageProvider.StoreFile(DefaultDirectoryName() + ratingFileName, stream, true);
        }
Ejemplo n.º 3
0
        private void ResizeImage()
        {
            SetProvider();
            SetInputData();

            // Contains the image bytes
            MemoryStream ms = new MemoryStream(1048576);

            // Load from provider
            if (string.IsNullOrEmpty(page))
            {
                if (!provider.RetrieveFile(file, ms))
                {
                    Response.StatusCode = 404;
                    Response.Write("File not found.");
                    return;
                }
            }
            else
            {
                PageContent pageContent = Pages.FindPage(currentWiki, page);
                if (pageContent == null)
                {
                    Response.StatusCode = 404;
                    Response.WriteFile("Page not found.");
                    return;
                }

                if (!provider.RetrievePageAttachment(pageContent.FullName, file, ms))
                {
                    Response.StatusCode = 404;
                    Response.WriteFile("File not found.");
                    return;
                }
            }

            // Setup new file name and image format
            if (!Page.IsPostBack)
            {
                string ext = Path.GetExtension(file);
                txtNewName.Text = Path.GetFileNameWithoutExtension(file) + "-2" + ext;
                switch (ext.ToLowerInvariant())
                {
                case ".jpg":
                case ".jpeg":
                    rdoPng.Checked        = false;
                    rdoJpegHigh.Checked   = true;
                    rdoJpegMedium.Checked = false;
                    break;

                default:
                    rdoPng.Checked        = true;
                    rdoJpegHigh.Checked   = false;
                    rdoJpegMedium.Checked = false;
                    break;
                }
            }

            ms.Seek(0, SeekOrigin.Begin);

            // Load the source image
            System.Drawing.Image source = System.Drawing.Image.FromStream(ms);

            lblCurrentSize.Text = string.Format("{0}x{1}", source.Width, source.Height);
            if (!Page.IsPostBack)
            {
                txtWidth.Text  = source.Width.ToString();
                txtHeight.Text = source.Height.ToString();
            }

            // Put dimension in script
            lblDimensions.Text = "<script type=\"text/javascript\"><!--\r\nvar width = " +
                                 source.Width.ToString() +
                                 ";\r\nvar height = " + source.Height.ToString() +
                                 ";\r\n// -->\r\n</script>";

            int resultWidth  = source.Width;
            int resultHeight = source.Height;

            if (rdoPercentage.Checked)
            {
                // Resize by percentage
                int dim = 100;
                if (string.IsNullOrEmpty(txtPercentage.Text))
                {
                    dim = 100;
                }
                else
                {
                    try {
                        dim = int.Parse(txtPercentage.Text);
                    }
                    catch (FormatException) { }
                }

                // Possible final preview dimensions
                resultWidth  = source.Width * dim / 100;
                resultHeight = source.Height * dim / 100;
            }
            else
            {
                // Resize by pixel
                if (!string.IsNullOrEmpty(txtWidth.Text) && !string.IsNullOrEmpty(txtHeight.Text))
                {
                    try {
                        resultWidth  = int.Parse(txtWidth.Text);
                        resultHeight = int.Parse(txtHeight.Text);
                    }
                    catch (FormatException) { }
                }
            }

            int rotation = GetSelectedRotation();

            // Draw preview
            if (resultWidth > 290 || resultHeight > 290)
            {
                int previewWidth  = resultWidth;
                int previewHeight = resultHeight;

                // Max preview dimension 290x290
                if (resultWidth > resultHeight)
                {
                    previewWidth  = 290;
                    previewHeight = (int)((float)290 / (float)resultWidth * (float)resultHeight);
                    lblScale.Text = string.Format("{0:N0}", (float)290 / (float)resultWidth * 100);
                }
                else
                {
                    previewHeight = 290;
                    previewWidth  = (int)((float)290 / (float)resultHeight * (float)resultWidth);
                    lblScale.Text = string.Format("{0:N0}", (float)290 / (float)resultHeight * 100);
                }
                imgPreview.ImageUrl = "Thumb.aspx?File=" + Request["File"] +
                                      @"&Size=imgeditprev&Width=" + previewWidth + @"&Height=" + previewHeight +
                                      @"&Page=" + (string.IsNullOrEmpty(page) ? "" : page) +
                                      (!rdoNoRotation.Checked ? ("&Rot=" + rotation.ToString()) : "");
            }
            else
            {
                lblScale.Text       = "100";
                imgPreview.ImageUrl = "Thumb.aspx?File=" + Request["File"] +
                                      @"&Size=imgeditprev&Width=" + resultWidth + @"&Height=" + resultHeight +
                                      @"&Page=" + (string.IsNullOrEmpty(page) ? "" : page) +
                                      (!rdoNoRotation.Checked ? ("&Rot=" + rotation.ToString()) : "");
            }

            // Destination bitmap
            Bitmap result = new Bitmap(
                rotation != 90 && rotation != 270 ? resultWidth : resultHeight,
                rotation != 90 && rotation != 270 ? resultHeight : resultWidth,
                System.Drawing.Imaging.PixelFormat.Format32bppArgb);

            // Get Graphics object for destination bitmap
            Graphics g = Graphics.FromImage(result);

            g.Clear(Color.Transparent);

            g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
            g.SmoothingMode     = SmoothingMode.HighQuality;
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBilinear;

            g.TranslateTransform(result.Width / 2, result.Height / 2);
            g.RotateTransform(rotation);
            g.TranslateTransform(-result.Width / 2, -result.Height / 2);

            // Draw bitmap
            g.DrawImage(source, GetImageRectangle(result.Width, result.Height,
                                                  rotation != 90 && rotation != 270 ? source.Width : source.Height,
                                                  rotation != 90 && rotation != 270 ? source.Height : source.Width,
                                                  rotation == 90 || rotation == 270));

            // Prepare encoder parameters
            string format = GetCurrentFormat();

            resultMemStream = new MemoryStream(1048576);

            // Only JPEG and PNG images are editable
            if (format == "image/jpeg")
            {
                EncoderParameters encoderParams = new EncoderParameters(1);
                encoderParams.Param[0] = new EncoderParameter(Encoder.Quality, rdoJpegHigh.Checked ? 100L : 60L);

                result.Save(resultMemStream, GetEncoderInfo(format), encoderParams);
            }
            else
            {
                result.Save(resultMemStream, ImageFormat.Png);
            }

            resultMemStream.Seek(0, SeekOrigin.Begin);

            // Dispose of source and result bitmaps
            source.Dispose();
            g.Dispose();
            result.Dispose();
        }
Ejemplo n.º 4
0
        protected void rptIndex_ItemCommand(object sender, CommandEventArgs e)
        {
            Log.LogEntry("Index rebuild requested for " + e.CommandArgument as string, EntryType.General, SessionFacade.GetCurrentUsername(), currentWiki);

            if (e.CommandName == "PagesRebuild")
            {
                // Clear the pages search index for the current wiki
                SearchClass.ClearIndex(currentWiki);

                IPagesStorageProviderV40 pagesProvider = Collectors.CollectorsBox.PagesProviderCollector.GetProvider(e.CommandArgument as string, currentWiki);

                // Index all pages of the wiki
                List <NamespaceInfo> namespaces = new List <NamespaceInfo>(pagesProvider.GetNamespaces());
                namespaces.Add(null);
                foreach (NamespaceInfo nspace in namespaces)
                {
                    // Index pages of the namespace
                    PageContent[] pages = pagesProvider.GetPages(nspace);
                    foreach (PageContent page in pages)
                    {
                        // Index page
                        SearchClass.IndexPage(page);

                        // Index page messages
                        Message[] messages = pagesProvider.GetMessages(page.FullName);
                        foreach (Message message in messages)
                        {
                            SearchClass.IndexMessage(message, page);

                            // Search for replies
                            Message[] replies = message.Replies;
                            foreach (Message reply in replies)
                            {
                                // Index reply
                                SearchClass.IndexMessage(reply, page);
                            }
                        }
                    }
                }
            }

            else if (e.CommandName == "FilesRebuild")
            {
                // Clear the files search index for the current wiki
                SearchClass.ClearFilesIndex(currentWiki);

                IFilesStorageProviderV40 filesProvider = Collectors.CollectorsBox.FilesProviderCollector.GetProvider(e.CommandArgument as string, currentWiki);

                // Index all files of the wiki
                // 1. List all directories (add the root directory: null)
                // 2. List all files in each directory
                // 3. Index each file
                List <string> directories = new List <string>(filesProvider.ListDirectories(null));
                directories.Add(null);
                foreach (string directory in directories)
                {
                    string[] files = filesProvider.ListFiles(directory);
                    foreach (string file in files)
                    {
                        byte[] fileContent;
                        using (MemoryStream stream = new MemoryStream()) {
                            filesProvider.RetrieveFile(file, stream);
                            fileContent = new byte[stream.Length];
                            stream.Seek(0, SeekOrigin.Begin);
                            stream.Read(fileContent, 0, (int)stream.Length);
                        }

                        // Index the file
                        string tempDir = Path.Combine(Environment.GetEnvironmentVariable("TEMP"), Guid.NewGuid().ToString());
                        if (!Directory.Exists(tempDir))
                        {
                            Directory.CreateDirectory(tempDir);
                        }
                        string tempFile = Path.Combine(tempDir, file.Substring(file.LastIndexOf('/') + 1));
                        using (FileStream writer = File.Create(tempFile)) {
                            writer.Write(fileContent, 0, fileContent.Length);
                        }
                        SearchClass.IndexFile(filesProvider.GetType().FullName + "|" + file, tempFile, currentWiki);
                        Directory.Delete(tempDir, true);
                    }
                }

                // Index all attachment of the wiki
                string[] pagesWithAttachments = filesProvider.GetPagesWithAttachments();
                foreach (string page in pagesWithAttachments)
                {
                    string[] attachments = filesProvider.ListPageAttachments(page);
                    foreach (string attachment in attachments)
                    {
                        byte[] fileContent;
                        using (MemoryStream stream = new MemoryStream()) {
                            filesProvider.RetrievePageAttachment(page, attachment, stream);
                            fileContent = new byte[stream.Length];
                            stream.Seek(0, SeekOrigin.Begin);
                            stream.Read(fileContent, 0, (int)stream.Length);
                        }

                        // Index the attached file
                        string tempDir = Path.Combine(Environment.GetEnvironmentVariable("TEMP"), Guid.NewGuid().ToString());
                        if (!Directory.Exists(tempDir))
                        {
                            Directory.CreateDirectory(tempDir);
                        }
                        string tempFile = Path.Combine(tempDir, attachment);
                        using (FileStream writer = File.Create(tempFile)) {
                            writer.Write(fileContent, 0, fileContent.Length);
                        }
                        SearchClass.IndexPageAttachment(attachment, tempFile, Pages.FindPage(currentWiki, page));
                        Directory.Delete(tempDir, true);
                    }
                }
            }

            Log.LogEntry("Index rebuild completed for " + e.CommandArgument as string, EntryType.General, SessionFacade.GetCurrentUsername(), currentWiki);
        }
Ejemplo n.º 5
0
        protected void Page_Load(object sender, EventArgs e)
        {
            string currentWiki = Tools.DetectCurrentWiki();

            string filename = Request["File"];

            if (string.IsNullOrEmpty(filename))
            {
                Response.Write("No file specified.");
                return;
            }

            // Remove ".." sequences that might be a security issue
            filename = filename.Replace("..", "");

            string      page             = Request["Page"];
            PageContent pageContent      = Pages.FindPage(currentWiki, page);
            bool        isPageAttachment = !string.IsNullOrEmpty(page);

            if (isPageAttachment && pageContent == null)
            {
                Response.StatusCode = 404;
                Response.Write("File not found.");
                return;
            }

            IFilesStorageProviderV40 provider = null;

            if (!string.IsNullOrEmpty(Request["Provider"]))
            {
                provider = Collectors.CollectorsBox.FilesProviderCollector.GetProvider(Request["Provider"], currentWiki);
            }
            else
            {
                if (isPageAttachment)
                {
                    provider = FilesAndAttachments.FindPageAttachmentProvider(currentWiki, pageContent.FullName, filename);
                }
                else
                {
                    provider = FilesAndAttachments.FindFileProvider(currentWiki, filename);
                }
            }

            if (provider == null)
            {
                Response.StatusCode = 404;
                Response.Write("File not found.");
                return;
            }

            string size = Request["Size"];

            if (string.IsNullOrEmpty(size))
            {
                size = "small";
            }
            size = size.ToLowerInvariant();

            // Verify permissions
            bool canDownload = false;

            AuthChecker authChecker = new AuthChecker(Collectors.CollectorsBox.GetSettingsProvider(currentWiki));

            if (pageContent != null)
            {
                canDownload = authChecker.CheckActionForPage(pageContent.FullName, Actions.ForPages.DownloadAttachments,
                                                             SessionFacade.GetCurrentUsername(), SessionFacade.GetCurrentGroupNames(currentWiki));
            }
            else
            {
                string dir = Tools.GetDirectoryName(filename);
                canDownload = authChecker.CheckActionForDirectory(provider, dir,
                                                                  Actions.ForDirectories.DownloadFiles, SessionFacade.GetCurrentUsername(),
                                                                  SessionFacade.GetCurrentGroupNames(currentWiki));
            }
            if (!canDownload)
            {
                Response.StatusCode = 401;
            }

            // Contains the image bytes
            MemoryStream ms       = new MemoryStream(1048576);
            long         fileSize = 0;

            // Load from provider
            if (string.IsNullOrEmpty(page))
            {
                bool retrieved = false;
                try {
                    retrieved = provider.RetrieveFile(filename, ms);
                }
                catch (ArgumentException ex) {
                    Log.LogEntry("Attempted to create thumb of inexistent file (" + filename + ")\n" + ex.ToString(), EntryType.Warning, Log.SystemUsername, currentWiki);
                }

                if (!retrieved)
                {
                    Response.StatusCode = 404;
                    Response.Write("File not found.");
                    return;
                }

                fileSize = provider.GetFileDetails(filename).Size;
            }
            else
            {
                if (pageContent == null)
                {
                    Response.StatusCode = 404;
                    Response.Write("Page not found.");
                    return;
                }

                bool retrieved = false;
                try {
                    retrieved = provider.RetrievePageAttachment(pageContent.FullName, filename, ms);
                }
                catch (ArgumentException ex) {
                    Log.LogEntry("Attempted to create thumb of inexistent attachment (" + page + "/" + filename + ")\n" + ex.ToString(), EntryType.Warning, Log.SystemUsername, currentWiki);
                }

                if (!retrieved)
                {
                    Response.StatusCode = 404;
                    Response.Write("File not found.");
                    return;
                }

                fileSize = provider.GetPageAttachmentDetails(pageContent.FullName, filename).Size;
            }

            ms.Seek(0, SeekOrigin.Begin);

            int rotation = 0;

            int.TryParse(Request["Rot"], out rotation);

            // Load the source image
            System.Drawing.Image source = System.Drawing.Image.FromStream(ms);

            // Destination bitmap
            Bitmap result = null;

            System.Drawing.Imaging.PixelFormat pixelFormat = System.Drawing.Imaging.PixelFormat.Format32bppArgb;

            if (size == "big")
            {
                // Big thumb (outer size 200x200)
                result = new Bitmap(200, 200, pixelFormat);
            }
            else if (size == "imgeditprev")
            {
                // Image Editor Preview thumb (outer size from Request["dim"], if null 200x200)
                if (!string.IsNullOrEmpty(Request["Width"]) && !string.IsNullOrEmpty(Request["Height"]))
                {
                    try {
                        result = new Bitmap(
                            rotation != 90 && rotation != 270 ? int.Parse(Request["Width"]) : int.Parse(Request["Height"]),
                            rotation != 90 && rotation != 270 ? int.Parse(Request["Height"]) : int.Parse(Request["Width"]),
                            pixelFormat);
                    }
                    catch (FormatException) {
                        result = new Bitmap(200, 200, pixelFormat);
                    }
                }
                else
                {
                    result = new Bitmap(200, 200, pixelFormat);
                }
            }
            else
            {
                // Small thumb (outer size 48x48)
                result = new Bitmap(48, 48, pixelFormat);
            }

            // Get Graphics object for destination bitmap
            Graphics g = Graphics.FromImage(result);

            if (source.PixelFormat == System.Drawing.Imaging.PixelFormat.Format32bppArgb)
            {
                g.Clear(Color.Transparent);
            }
            else
            {
                g.Clear(Color.White);
            }

            g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
            g.SmoothingMode     = SmoothingMode.HighQuality;
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBilinear;

            g.TranslateTransform(result.Width / 2, result.Height / 2);
            g.RotateTransform(rotation);
            g.TranslateTransform(-result.Width / 2, -result.Height / 2);

            // Draw bitmap
            g.DrawImage(source, GetImageRectangle(result.Width, result.Height,
                                                  rotation != 90 && rotation != 270 ? source.Width : source.Height,
                                                  rotation != 90 && rotation != 270 ? source.Height : source.Width,
                                                  rotation == 90 || rotation == 270));

            if (!string.IsNullOrEmpty(Request["Info"]) && size == "big")
            {
                // Draw image information
                RectangleF   r = new RectangleF(0, 0, result.Width, 20);
                StringFormat f = new StringFormat();
                f.Alignment = StringAlignment.Center;
                //f.LineAlignment = StringAlignment.Center;
                GraphicsPath path = new GraphicsPath();
                path.AddString(string.Format("{0}x{1} - {2}", source.Width, source.Height,
                                             Tools.BytesToString(fileSize)),
                               new FontFamily("Verdana"), 0, 12, new Point(result.Width / 2, 2), f);
                Pen pen = new Pen(Brushes.Black, 2F);
                g.DrawPath(pen, path);
                g.FillPath(Brushes.White, path);
            }

            // Write result in output stream in JPEG or PNG format
            if (source.PixelFormat == System.Drawing.Imaging.PixelFormat.Format32bppArgb)
            {
                Response.ContentType = "image/png";
            }
            else
            {
                Response.ContentType = "image/jpeg";
            }

            // This invariably throws an exception (A generic error occurred in GDI+) - an intermediate buffer is needed
            // The possible cause is that PNG format requires to read from the output stream, and Response.OutputStream does not support reading
            //result.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Png);

            MemoryStream tempStream = new MemoryStream(65536);             // 32 KB

            if (source.PixelFormat == System.Drawing.Imaging.PixelFormat.Format32bppArgb)
            {
                result.Save(tempStream, System.Drawing.Imaging.ImageFormat.Png);
            }
            else
            {
                result.Save(tempStream, System.Drawing.Imaging.ImageFormat.Jpeg);
            }
            Response.OutputStream.Write(tempStream.ToArray(), 0, (int)tempStream.Length);
            tempStream.Dispose();

            ms.Dispose();

            source.Dispose();
            g.Dispose();
            result.Dispose();
        }