Beispiel #1
0
 static void Pipeline_PreHandleImage(System.Web.IHttpModule sender, System.Web.HttpContext context, Caching.IResponseArgs e)
 {
     if (!Config.Current.Plugins.Has <Trial>())
     {
         new Trial().Install(Config.Current);
     }
 }
Beispiel #2
0
        /*  http://developer.yahoo.com/performance/rules.html
         *  http://24x7aspnet.blogspot.com/2009/06/using-cache-methods-httpcacheability-in.html
         *
         *  Redirects should have caching headers.
         *  Expires: is good
         *  Remove ETags, bad server implementation
         */

        void Pipeline_PreHandleImage(System.Web.IHttpModule sender, System.Web.HttpContext context, Caching.IResponseArgs e)
        {
            int mins = c.get("clientcache.minutes", -1);

            //Set the expires value if present
            if (mins > 0)
            {
                e.ResponseHeaders.Expires = DateTime.UtcNow.AddMinutes(mins);
                // Hieu Le: Apr-16-2014:
                // Set MaxAge
                e.ResponseHeaders.MaxAge = new TimeSpan(0, 0, mins, 0);
            }

            //NDJ Jan-16-2013. The last modified date sent in the headers should NOT match the source modified date when using DiskCaching.
            //Setting this will prevent 304s from being sent properly.
            // (Moved to NoCache)

            //Authenticated requests only allow caching on the client.
            //Anonymous requests get caching on the server, proxy and client
            if (context.Request.IsAuthenticated)
            {
                e.ResponseHeaders.CacheControl = System.Web.HttpCacheability.Private;
            }
            else
            {
                e.ResponseHeaders.CacheControl = System.Web.HttpCacheability.Public;
            }
        }
Beispiel #3
0
 void Pipeline_PostRewrite(System.Web.IHttpModule sender, System.Web.HttpContext context, IUrlEventArgs e)
 {
     if (e.QueryString["preset"] != null)
     {
         e.QueryString.Remove("preset");                                  //Remove presets so they aren't processed again during ModifySettings
     }
 }
Beispiel #4
0
        void Pipeline_ImageMissing(System.Web.IHttpModule sender, System.Web.HttpContext context, Configuration.IUrlEventArgs e)
        {
            if (!string.IsNullOrEmpty(e.QueryString["404"]))
            {
                //Resolve the path to virtual or app-relative for
                string path = resolve404Path(e.QueryString["404"]);
                //Resolve to virtual path
                path = Util.PathUtils.ResolveAppRelative(path);

                //Merge commands from the 404 querystring with ones from the original image.
                ResizeSettings imageQuery = new ResizeSettings(e.QueryString);
                imageQuery.Normalize();
                imageQuery.Remove("404"); //Remove the 404 ref

                ResizeSettings i404Query = new ResizeSettings(Util.PathUtils.ParseQueryString(path));
                i404Query.Normalize();
                //Overwrite new with old
                foreach (string key in i404Query.Keys)
                {
                    if (key != null)
                    {
                        imageQuery[key] = i404Query[key];
                    }
                }

                path = PathUtils.AddQueryString(PathUtils.RemoveQueryString(path), PathUtils.BuildQueryString(imageQuery));
                //Redirect
                context.Response.Redirect(path, true);
            }
        }
Beispiel #5
0
 void Pipeline_Rewrite(System.Web.IHttpModule sender, System.Web.HttpContext context, IUrlEventArgs e)
 {
     if (OnlyAllowPresets)
     {
         e.QueryString = FilterQuerystring(e.QueryString, false);
     }
     ApplyPreset(e, settings);
 }
Beispiel #6
0
 /// <summary>
 /// This is where we hijack the resizing process, interrupt it, and send back the json data we created.
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="context"></param>
 /// <param name="e"></param>
 void Pipeline_PreHandleImage(System.Web.IHttpModule sender, System.Web.HttpContext context, Caching.IResponseArgs e)
 {
     if (NameValueCollectionExtensions.Get(e.RewrittenQuerystring, "r.detecteyes", false) ||
         NameValueCollectionExtensions.Get(e.RewrittenQuerystring, "r.getlayout", false))
     {
         DetectionResponse <ObjRect> .InjectExceptionHandler(e as ResponseArgs);
     }
 }
Beispiel #7
0
 void Pipeline_PostAuthorizeRequestStart(System.Web.IHttpModule sender, System.Web.HttpContext context)
 {
     //Only work with blob images
     //This allows us to resize database images without putting ".jpg" after the ID in the path.
     if ((!RequireImageExtension || UntrustedData) && Belongs(c.Pipeline.PreRewritePath))
     {
         c.Pipeline.SkipFileTypeCheck = true; //Skip the file extension check. FakeExtensions will still be stripped.
     }
 }
Beispiel #8
0
 void Pipeline_PostRewrite(System.Web.IHttpModule sender, System.Web.HttpContext context, Configuration.IUrlEventArgs e)
 {
     //Only work with database images
     //If the data is untrusted, always re-encode each file.
     if (UntrustedData && Belongs(e.VirtualPath))
     {
         e.QueryString["process"] = ImageResizer.ProcessWhen.Always.ToString();
     }
 }
Beispiel #9
0
        /// <summary>
        /// This is where we hijack the resizing process, interrupt it, and send
        /// back the JSON data we created.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="context"></param>
        /// <param name="e"></param>
        void Pipeline_PreHandleImage(System.Web.IHttpModule sender, System.Web.HttpContext context, Caching.IResponseArgs e)
        {
            if (!this.IsDiagnosticRequest(e.RewrittenQuerystring))
            {
                return;
            }

            AlternateResponseException.InjectExceptionHandler(e as ImageResizer.Caching.ResponseArgs);
        }
Beispiel #10
0
 void Pipeline_RewriteDefaults(System.Web.IHttpModule sender, System.Web.HttpContext context, Configuration.IUrlEventArgs e)
 {
     //Only works with blob provided files
     //Non-images will be served as-is
     //Cache all file types, whether they are processed or not.
     if (CacheUnmodifiedFiles && Belongs(e.VirtualPath))
     {
         e.QueryString["cache"] = ServerCacheMode.Always.ToString();
     }
 }
Beispiel #11
0
        /// <summary>
        /// This is where we hijack the resizing process, interrupt it, and send back the json data we created.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="context"></param>
        /// <param name="e"></param>
        void Pipeline_PreHandleImage(System.Web.IHttpModule sender, System.Web.HttpContext context, Caching.IResponseArgs e)
        {
            bool detect    = NameValueCollectionExtensions.Get(e.RewrittenQuerystring, "f.detect", false);
            bool getlayout = NameValueCollectionExtensions.Get(e.RewrittenQuerystring, "f.getlayout", false);

            if (!detect && !getlayout)
            {
                return;
            }

            DetectionResponse <Face> .InjectExceptionHandler(e as ResponseArgs);
        }
Beispiel #12
0
        void Pipeline_PreHandleImage(System.Web.IHttpModule sender, System.Web.HttpContext context, Caching.IResponseArgs e)
        {
            string info = e.RewrittenQuerystring["getinfo"];

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

            ResponseArgs ra = e as ResponseArgs;

            e.ResponseHeaders.ContentType = "application/json; charset=utf-8";

            NameValueCollection d = new NameValueCollection();

            ra.ResizeImageToStream = new ResizeImageDelegate(delegate(Stream s) {
                try {
                    using (Stream src = ra.GetSourceImage()) {
                        bool attemptFastMode = src.CanSeek;
                        long orig            = attemptFastMode ? src.Position : 0;
                        bool trySlowMode     = !attemptFastMode;
                        if (attemptFastMode)
                        {
                            try {
                                using (Image i = System.Drawing.Image.FromStream(src, false, false)) {
                                    d["width"]  = i.Width.ToString();
                                    d["height"] = i.Height.ToString();
                                }
                            } catch {
                                trySlowMode = true;
                            }
                        }
                        if (trySlowMode)
                        {
                            if (attemptFastMode)
                            {
                                src.Seek(orig, SeekOrigin.Begin);
                            }
                            using (Bitmap b = c.CurrentImageBuilder.LoadImage(src, new ResizeSettings(ra.RewrittenQuerystring))){
                                d["width"]  = b.Width.ToString();
                                d["height"] = b.Height.ToString();
                            }
                        }
                        SimpleJson(s, d, e.RewrittenQuerystring["jsonp"]);
                    }
                } catch (FileNotFoundException) {
                    d["result"] = "404";
                    SimpleJson(s, d, e.RewrittenQuerystring["jsonp"]);
                }
            });
        }
Beispiel #13
0
        void Pipeline_PostAuthorizeRequestStart(System.Web.IHttpModule sender, System.Web.HttpContext context)
        {
            if (!c.Pipeline.PreRewritePath.StartsWith(VirtualPrefix, StringComparison.OrdinalIgnoreCase))
            {
                return;
            }
            //Okay, decrypt
            Stopwatch sw = new Stopwatch();

            sw.Start();
            string both = c.Pipeline.PreRewritePath.Substring(VirtualPrefix.Length); //Strip prefix

            string[] parts = both.Split('/');                                        //Split

            if (parts.Length != 2)
            {
                return;                                         //There must be exactly two parts
            }
            parts[1] = PathUtils.RemoveFullExtension(parts[1]); //Remove the .ashx or .jpg.ashx or whatever it is.

            byte[] iv = PathUtils.FromBase64UToBytes(parts[0]);
            if (iv.Length != 16)
            {
                return;                  //16-byte IV required
            }
            byte[] data = PathUtils.FromBase64UToBytes(parts[1]);

            string result = UTF8Encoding.UTF8.GetString(Enc.Decrypt(data, iv));

            string path;
            string fragment;

            //We do not merge the old and new query strings. We do not accept plaintext additions to an encrypted URL
            c.Pipeline.ModifiedQueryString = PathUtils.ParseQueryString(result, true, out path, out fragment);
            c.Pipeline.PreRewritePath      = path;
            sw.Stop();
        }
Beispiel #14
0
        void Pipeline_Rewrite(System.Web.IHttpModule sender, System.Web.HttpContext context, Configuration.IUrlEventArgs e)
        {
            string file = Path.GetFileName(e.VirtualPath);

            if (activeFilenames.Contains(file))
            {
                string filePhysicalPath = PathUtils.MapPathIfAppRelative("~" + e.VirtualPath);

                if (!File.Exists(filePhysicalPath))
                {
                    string   physicalDirPath = Path.GetDirectoryName(filePhysicalPath);
                    string[] files           = Directory.GetFiles(physicalDirPath, "*.jpg", SearchOption.TopDirectoryOnly);

                    if (files.Length > 0)
                    {
                        Random r     = new Random();
                        int    index = r.Next(0, files.Length);
                        file = files[index];
                        string newVirtualPath = Path.GetDirectoryName(e.VirtualPath).Replace("\\", "/") + "/" + Path.GetFileName(file);
                        e.VirtualPath = newVirtualPath;
                    }
                    else
                    {
                        string fallback = c.get("folderThumb.default", "");
                        e.VirtualPath = "/images/" + fallback;
                    }

                    if (e.QueryString.Count == 0)
                    {
                        var col = new NameValueCollection();
                        col.Add("fthumb", "true");
                        e.QueryString.Add(col);
                    }
                }
            }
        }
Beispiel #15
0
        void Pipeline_ImageMissing(System.Web.IHttpModule sender, System.Web.HttpContext context, Configuration.IUrlEventArgs e)
        {
            if (!string.IsNullOrEmpty(e.QueryString["404"]))
            {
                //Resolve the path to virtual or app-relative for
                string path = resolve404Path(e.QueryString["404"]);
                //Resolve to virtual path
                path = Util.PathUtils.ResolveAppRelative(path);

                // Merge commands from the 404 querystring with ones from the
                // original image.  We start by sanitizing the querystring from
                // the image.
                ResizeSettings imageQuery = new ResizeSettings(e.QueryString);
                imageQuery.Normalize();

                // Use the configured settings by default.
                var filterMode = this.filterMode;
                var except     = this.except;

                // To support querystring-specifiable filter mode and exceptions,
                // uncomment the if block below.
                ////// If the imageQuery includes specific 404 command-filtering,
                ////// (*either* of the values), use those instead of the
                ////// configured defaults.
                ////if (!string.IsNullOrEmpty(e.QueryString["404.filterMode"]) ||
                ////    !string.IsNullOrEmpty(e.QueryString["404.except"]))
                ////{
                ////    filterMode = NameValueCollectionExtensions.Get(e.QueryString, "404.filterMode", FilterMode.ExcludeUnknownCommands);
                ////    except = MatcherCollection.Parse(e.QueryString["404.except"]);
                ////}

                // remove all of the commands we're supposed to remove... we
                // clone the list of keys so that we're not modifying the collection
                // while we enumerate it.
                var shouldRemove = CreateRemovalMatcher(filterMode, except);
                var names        = new List <string>(imageQuery.AllKeys);

                foreach (var name in names)
                {
                    if (shouldRemove(name, imageQuery[name]))
                    {
                        imageQuery.Remove(name);
                    }
                }

                // Always remove the '404', '404.filterMode', and '404.except' settings.
                imageQuery.Remove("404");
                imageQuery.Remove("404.filterMode");
                imageQuery.Remove("404.except");

                ResizeSettings i404Query = new ResizeSettings(Util.PathUtils.ParseQueryString(path));
                i404Query.Normalize();
                //Overwrite new with old
                foreach (string key in i404Query.Keys)
                {
                    if (key != null)
                    {
                        imageQuery[key] = i404Query[key];
                    }
                }

                path = PathUtils.AddQueryString(PathUtils.RemoveQueryString(path), PathUtils.BuildQueryString(imageQuery));
                //Redirect
                context.Response.Redirect(path, true);
            }
        }
Beispiel #16
0
 /// <summary>
 /// We duplicate efforts in PostRewrite to ensure that the DiskCache doesn't block configuration changes.
 /// This won't help CloudFront, however.
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="context"></param>
 /// <param name="e"></param>
 void Pipeline_PostRewrite(System.Web.IHttpModule sender, System.Web.HttpContext context, IUrlEventArgs e)
 {
     e.QueryString = Modify(new ResizeSettings(e.QueryString));
 }
Beispiel #17
0
        void Pipeline_PostAuthorizeRequestStart(System.Web.IHttpModule sender, System.Web.HttpContext context)
        {
            string prefix = HostingEnvironment.ApplicationVirtualPath.TrimEnd('/') + '/';

            if (c.Pipeline.PreRewritePath.Equals(prefix + "ImageHandler.ashx", StringComparison.OrdinalIgnoreCase) &&
                !string.IsNullOrEmpty(context.Request.QueryString["src"]))
            {
                //WebImageResizer: http://webimageresizer.codeplex.com/

                /*src: Key to an image, can be a relative url, guid or whatever you want
                 * width: Width in pixels without any unit specification
                 * height: Height in pixels without any unit specification
                 * format: Formats to output to one of the image formats: png, gif, jpg, tif
                 * greyscale: any non empty value triggers grey scaling
                 * rotate: Invariant Culture floating point number in degrees where 360 is a complete rotation.
                 * zoom: Invariant Culture floating point number indicating scale value. If 2 is specified the output will be double the original size.*/

                //Fix path
                c.Pipeline.PreRewritePath = prefix + c.Pipeline.ModifiedQueryString["src"];
                c.Pipeline.ModifiedQueryString.Remove("src");

                //Grayscale and zoom not supported yet
                if (string.IsNullOrEmpty(c.Pipeline.ModifiedQueryString["s.grayscale"]) &&
                    !string.IsNullOrEmpty(c.Pipeline.ModifiedQueryString["greyscale"]))
                {
                    c.Pipeline.ModifiedQueryString["s.grayscale"] = "true";
                }

                if (string.IsNullOrEmpty(c.Pipeline.ModifiedQueryString["s.invert"]) &&
                    !string.IsNullOrEmpty(c.Pipeline.ModifiedQueryString["invert"]))
                {
                    c.Pipeline.ModifiedQueryString["s.invert"] = "true";
                }


                //Mimic aspect-ratio destruction
                if (string.IsNullOrEmpty(c.Pipeline.ModifiedQueryString["stretch"]) && string.IsNullOrEmpty(c.Pipeline.ModifiedQueryString["mode"]))
                {
                    c.Pipeline.ModifiedQueryString["mode"] = "stretch";
                }
            }
            else if ((c.Pipeline.PreRewritePath.Equals(prefix + "imghandler.ashx", StringComparison.OrdinalIgnoreCase) ||
                      c.Pipeline.PreRewritePath.EndsWith("DAMP_ImagePreview.ashx", StringComparison.OrdinalIgnoreCase)) &&
                     !string.IsNullOrEmpty(context.Request.QueryString["img"]))
            {
                //Image handler for ASP.NET 2.0: http://www.yoursite.com/imghandler.ashx?h=100&w=100&img=yourfolder/yourimage.jpg
                // DAMP: http://our.umbraco.org/projects/backoffice-extensions/digibiz-advanced-media-picker

                bool isDAMP = c.Pipeline.PreRewritePath.EndsWith("DAMP_ImagePreview.ashx", StringComparison.OrdinalIgnoreCase);

                //Fix path
                c.Pipeline.PreRewritePath = prefix + c.Pipeline.ModifiedQueryString["img"];
                //Edit querystring
                c.Pipeline.ModifiedQueryString["width"]  = c.Pipeline.ModifiedQueryString["w"];
                c.Pipeline.ModifiedQueryString["height"] = c.Pipeline.ModifiedQueryString["h"];
                c.Pipeline.ModifiedQueryString.Remove("w");
                c.Pipeline.ModifiedQueryString.Remove("h");
                c.Pipeline.ModifiedQueryString.Remove("img");

                //Mimic aspect-ratio destruction (imghandler only)
                if (!isDAMP && string.IsNullOrEmpty(c.Pipeline.ModifiedQueryString["mode"]) && string.IsNullOrEmpty(c.Pipeline.ModifiedQueryString["stretch"]))
                {
                    c.Pipeline.ModifiedQueryString["mode"] = "stretch";
                }
            }
            else if (c.Pipeline.PreRewritePath.Equals(prefix + "bbimagehandler.ashx", StringComparison.OrdinalIgnoreCase) &&
                     !string.IsNullOrEmpty(context.Request.QueryString["file"]))
            {
                //Only file requests for bbimagehandler are supported. SQL and website thumbnails are not.
                //bbimagehandler.ashx?File=Winter.jpg&width=150&ResizeMode=FitSquare&BackColor=#F58719&border=10"

                /*width: width in pixel of resulting image
                 * height: height in pixel of resulting image
                 * resizemode:
                 * fit: Fit mode maintains the aspect ratio of the original image while ensuring that the dimensions of the result do not exceed the maximum values for the resize transformation. (Needs width or height parameter)
                 * fitsquare: Resizes the image with the given width as its longest side (depending on image direction) and maintains the aspect ratio. The image will be centered in a square area of the chosen background color (Needs width parameter, backcolor optional)
                 * crop: Crop resizes the image and removes parts of it to ensure that the dimensions of the result are exactly as specified by the transformation.(Needs width and height parameter)
                 * backcolor: color of background or/and  border when resizemode is fitsquare or fit.
                 * border: border width in pixels around the image (added to width / height) when resizemode is fitsquare or fit.
                 * format: jpg,png,bmp or gif, defines the format of the resulting image
                 */

                NameValueCollection q = c.Pipeline.ModifiedQueryString;
                //Fix path
                c.Pipeline.PreRewritePath = prefix + q["file"];
                q.Remove("file");

                if ("fit".Equals(q["resizemode"]))
                {
                    q["maxwidth"]  = q["width"];
                    q["maxheight"] = q["height"];
                    q.Remove("width");
                    q.Remove("height");
                    q.Remove("resizemode");
                }
                else if ("fitsquare".Equals(q["resizemode"]))
                {
                    q["height"] = q["width"]; //Copy width, make it a square
                }
                else if ("crop".Equals(q["resizemode"]))
                {
                    q["crop"] = "auto";
                }
                if (!string.IsNullOrEmpty(q["backcolor"]))
                {
                    q["bgcolor"] = q["backcolor"];
                    q.Remove("backcolor");
                }

                if (!string.IsNullOrEmpty(q["border"]))
                {
                    q["borderWidth"] = q["border"];
                    q.Remove("border");
                }
            }
        }
Beispiel #18
0
 void Pipeline_RewriteDefaults(System.Web.IHttpModule sender, System.Web.HttpContext context, Configuration.IUrlEventArgs e)
 {
     //Handles /resize(width,height,format)/ and /resize(width,height)/ syntaxes.
     e.VirtualPath = parseResizeFolderSyntax(e.VirtualPath, e.QueryString);
 }
Beispiel #19
0
 void Pipeline_RewriteDefaults(System.Web.IHttpModule sender, System.Web.HttpContext context, IUrlEventArgs e)
 {
     ApplyPreset(e, defaults);
 }