Ejemplo n.º 1
0
    /// <summary>
    /// Returns the data which will be served to client depending on minification and compression settings.
    /// </summary>
    /// <param name="context">An HTTPContext object that provides references to the intrinsic server objects used to service HTTP requests</param>
    /// <param name="resource">Data container with the data to serve</param>
    /// <param name="minificationEnabled">True, if the data should be minified, otherwise false</param>
    /// <param name="contentCoding">The content coding to use when sending a response</param>
    /// <returns>Data to serve in a form of a byte block</returns>
    private static byte[] GetOutputData(HttpContext context, CMSOutputResource resource, bool minificationEnabled, out string contentCoding)
    {
        // minification must be allowed by the server and minified data must be available
        bool minified = minificationEnabled && resource.ContainsMinifiedData;

        // compression must be allowed by server, supported by client and compressed data must be available
        bool compressed = RequestHelper.AllowResourceCompression && RequestHelper.IsGZipSupported() && resource.ContainsCompressedData;

        // Set deafult content encoding
        contentCoding = ContentCodingEnum.IDENTITY;

        // Get the proper version of resource to serve based on the settings
        if (!minified && !compressed)
        {
            return(Encoding.UTF8.GetBytes(resource.Data));
        }
        else if (minificationEnabled && !compressed)
        {
            return(Encoding.UTF8.GetBytes(resource.MinifiedData));
        }
        else if (!minified && compressed)
        {
            contentCoding = ContentCodingEnum.DEFLATE;
            return(resource.CompressedData);
        }
        else if (minified && compressed)
        {
            contentCoding = ContentCodingEnum.DEFLATE;
            return(resource.MinifiedCompressedData);
        }
        else
        {
            return(new byte[0]);
        }
    }
Ejemplo n.º 2
0
    /// <summary>
    /// Sends the given file within response.
    /// </summary>
    /// <param name="file">File to send</param>
    protected void SendFile(CMSOutputResource file)
    {
        // Clear response.
        CookieHelper.ClearResponseCookies();
        Response.Clear();

        Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches);

        // Send the file
        if ((file != null) && (file.Data != null))
        {
            // Prepare response
            Response.ContentType = "text/css";

            // Client caching - only on the live site
            if (useClientCache && AllowCache && CacheHelper.CacheImageEnabled(CurrentSiteName) && ETagsMatch(file.Etag, file.LastModified))
            {
                RespondNotModified(file.Etag);
                return;
            }

            if (useClientCache && AllowCache && CacheHelper.CacheImageEnabled(CurrentSiteName))
            {
                SetTimeStamps(file.LastModified);

                Response.Cache.SetETag(file.Etag);
            }

            // Add the file data
            Response.Write(file.Data);
        }

        CompleteRequest();
    }
Ejemplo n.º 3
0
    /// <summary>
    /// Retrieves the stylesheets of the page template from the database.
    /// </summary>
    /// <param name="templateName">Template name</param>
    /// <returns>The stylesheet data (plain version only)</returns>
    private static CMSOutputResource GetTemplate(string templateName)
    {
        // Try to get global one
        PageTemplateInfo templateInfo = PageTemplateInfoProvider.GetPageTemplateInfo(templateName);

        // Try to get site one (ad-hoc) if not found
        if (templateInfo == null)
        {
            templateInfo = PageTemplateInfoProvider.GetPageTemplateInfo(templateName, CMSContext.CurrentSiteID);
        }

        if (templateInfo == null)
        {
            return(null);
        }

        // Build the result
        CMSOutputResource resource = new CMSOutputResource()
        {
            Data         = HTMLHelper.ResolveCSSUrls(templateInfo.PageTemplateCSS, URLHelper.ApplicationPath),
            LastModified = templateInfo.PageTemplateLastModified,
            Etag         = templateInfo.PageTemplateVersionGUID
        };

        return(resource);
    }
Ejemplo n.º 4
0
    /// <summary>
    /// Minify supplied source according to settings.
    /// </summary>
    /// <param name="resource">Resource to minifz</param>
    /// <param name="minifier">Minifier to use when creating minified version of the data</param>
    /// <param name="minificationEnabled">True, if the data should be minified, otherwise false</param>
    /// <param name="compressionEnabled">True, if data should be compressed, otherwise false</param>
    private static void MinifyResource(CMSOutputResource resource, IResourceMinifier minifier, bool minificationEnabled, bool compressionEnabled)
    {
        if (resource == null)
        {
            return;
        }

        // Set up the settings
        if (minificationEnabled && (minifier != null))
        {
            resource.MinifiedData = minifier.Minify(resource.Data);
        }

        // Compress
        if (RequestHelper.AllowResourceCompression && compressionEnabled)
        {
            resource.CompressedData = Compress(resource.Data);
        }

        // Compress and minify
        if (minificationEnabled && RequestHelper.AllowResourceCompression && compressionEnabled)
        {
            resource.MinifiedCompressedData = Compress(resource.MinifiedData);
        }
    }
Ejemplo n.º 5
0
    /// <summary>
    /// Wraps a piece of text in a data container.
    /// </summary>
    /// <param name="resource">Text to wrap</param>
    /// <param name="name">Identifier for the file</param>
    /// <param name="etag">Etag to use for versioning</param>
    /// <param name="lastModified">Timestamp of the last modification of data</param>
    /// <param name="minifier">Minifier to use when creating minified version of the data</param>
    /// <param name="minificationEnabled">True, if the data should be minified, otherwise false</param>
    /// <returns>Data container containing the piece of text</returns>
    private static CMSOutputResource WrapObject(string resource, string name, string etag, DateTime lastModified, IResourceMinifier minifier, bool minificationEnabled)
    {
        if (resource == null)
        {
            return(null);
        }

        // Prepare new output resource object
        CMSOutputResource wrapper = new CMSOutputResource()
        {
            Name         = name,
            Etag         = etag,
            LastModified = lastModified,
            Data         = resource,
        };

        // Set up the settings
        if (minificationEnabled)
        {
            wrapper.MinifiedData = minifier.Minify(wrapper.Data);
        }
        if (RequestHelper.AllowResourceCompression)
        {
            wrapper.CompressedData = Compress(resource);
        }
        if (minificationEnabled && RequestHelper.AllowResourceCompression)
        {
            wrapper.MinifiedCompressedData = Compress(wrapper.MinifiedData);
        }

        return(wrapper);
    }
Ejemplo n.º 6
0
    /// <summary>
    /// Combines the given list of resources into a single resource
    /// </summary>
    /// <param name="resources">Resources to combine</param>
    private static CMSOutputResource CombineResources(List <CMSOutputResource> resources)
    {
        StringBuilder data = new StringBuilder();
        StringBuilder etag = new StringBuilder();

        DateTime lastModified = DateTimeHelper.ZERO_TIME;

        // Build single resource
        foreach (CMSOutputResource resource in resources)
        {
            if (resource != null)
            {
                string newData = resource.Data;

                // Join the data into a single string
                if ((data.Length > 0) && !String.IsNullOrEmpty(newData))
                {
                    // Trim the charset
                    newData = CSSHelper.TrimCharset(newData);
                    if (String.IsNullOrEmpty(newData))
                    {
                        continue;
                    }

                    data.AppendLine();
                    data.AppendLine();
                }

                data.Append(newData);

                // Join e-tags
                if (etag.Length > 0)
                {
                    etag.Append('|');
                }
                etag.Append(resource.Etag);

                // Remember the largest last modified
                if (resource.LastModified > lastModified)
                {
                    lastModified = resource.LastModified;
                }
            }
        }

        // Build the result
        CMSOutputResource result = new CMSOutputResource()
        {
            Data         = data.ToString(),
            Etag         = etag.ToString(),
            LastModified = lastModified
        };

        return(result);
    }
Ejemplo n.º 7
0
    /// <summary>
    /// Checks if this is a revalidation request for a physical file that did not change since the last time.
    /// </summary>
    /// <param name="context">An HTTPContext object that provides references to the intrinsic server objects used to service HTTP requests</param>
    /// <param name="path">Full physical path to the file</param>
    private static void CheckRevalidation(HttpContext context, string path)
    {
        // Virtual resource, used only to check if revalidation can be short-circuited
        CMSOutputResource fileResource = new CMSOutputResource()
        {
            Etag         = GetFileEtag(path),
            LastModified = File.GetLastWriteTime(path)
        };

        if (IsResourceUnchanged(context, fileResource))
        {
            SendNotModifiedResponse(context, fileResource.LastModified, fileResource.Etag, PhysicalFilesCacheMinutes, true);
        }
    }
Ejemplo n.º 8
0
    /// <summary>
    /// Processes the given request.
    /// </summary>
    /// <param name="context">Http context</param>
    /// <param name="settings">CSS Settings</param>
    private static void ProcessRequest(HttpContext context, CMSCssSettings settings)
    {
        CMSOutputResource resource = null;

        // Get cache setting for physical files
        int cacheMinutes       = PhysicalFilesCacheMinutes;
        int clientCacheMinutes = cacheMinutes;

        bool hasVirtualContent = settings.HasVirtualContent();

        if (hasVirtualContent)
        {
            // Use specific cache settings if DB resources are requested
            cacheMinutes       = CacheMinutes;
            clientCacheMinutes = ClientCacheMinutes;
        }

        // Try to get data from cache (or store them if not found)
        using (CachedSection <CMSOutputResource> cachedSection = new CachedSection <CMSOutputResource>(ref resource, cacheMinutes, true, null, "getresource", CMSContext.CurrentSiteName, context.Request.QueryString, URLHelper.IsSSL))
        {
            // Not found in cache; load the data
            if (cachedSection.LoadData)
            {
                // Load the data
                resource = GetResource(settings, URLHelper.Url.ToString(), cachedSection.Cached);

                // Cache the file
                if ((resource != null) && (cachedSection.Cached))
                {
                    cachedSection.CacheDependency = resource.CacheDependency;
                    cachedSection.Data            = resource;
                }
            }
        }

        // Send response if there's something to send
        if (resource != null)
        {
            bool allowCache = (!hasVirtualContent || ClientCacheEnabled) && CacheHelper.AlwaysCacheResources;
            SendResponse(context, resource, MimeTypeHelper.GetMimetype(CSS_FILE_EXTENSION), allowCache, CSSHelper.StylesheetMinificationEnabled, clientCacheMinutes);
        }
        else
        {
            SendNotFoundResponse(context);
        }
    }
Ejemplo n.º 9
0
    /// <summary>
    /// Retrieve the stylesheet either from the database or file if checked out.
    /// </summary>
    /// <param name="stylesheetName">Stylesheet's unique name</param>
    /// <returns>The stylesheet data (plain version only)</returns>
    private static CMSOutputResource GetStylesheet(string stylesheetName)
    {
        // Get the stylesheet
        CssStylesheetInfo stylesheetInfo = CssStylesheetInfoProvider.GetCssStylesheetInfo(stylesheetName);

        if (stylesheetInfo == null)
        {
            return(null);
        }

        // Determine if the stylesheet is checked out or not
        string   checkedOutFile = URLHelper.GetPhysicalPath(stylesheetInfo.StylesheetCheckedOutFilename);
        string   stylesheet;
        DateTime lastModified;

        if ((stylesheetInfo.StylesheetCheckedOutByUserID > 0) &&
            (string.Equals(stylesheetInfo.StylesheetCheckedOutMachineName, HTTPHelper.MachineName, StringComparison.OrdinalIgnoreCase)) &&
            (File.Exists(checkedOutFile)))
        {
            // Read the stylesheet and timestamp from the checked out file
            using (StreamReader reader = StreamReader.New(checkedOutFile))
            {
                stylesheet = reader.ReadToEnd();
            }
            lastModified = File.GetLastWriteTime(checkedOutFile);
        }
        else
        {
            // Read the stylesheet and timestamp from database
            stylesheet   = stylesheetInfo.StylesheetText;
            lastModified = stylesheetInfo.StylesheetLastModified;
        }

        // Build the output
        CMSOutputResource resource = new CMSOutputResource()
        {
            Data         = HTMLHelper.ResolveCSSUrls(stylesheet, URLHelper.ApplicationPath),
            Name         = stylesheetInfo.StylesheetName,
            LastModified = lastModified,
            Etag         = stylesheetName,
        };

        return(resource);
    }
Ejemplo n.º 10
0
    /// <summary>
    /// Retrieves the stylesheets of the web part layout from the database.
    /// </summary>
    /// <param name="layoutFullName">Layout full name</param>
    /// <returns>The stylesheet data (plain version only)</returns>
    private static CMSOutputResource GetTransformation(string transformationFullName)
    {
        TransformationInfo transformationInfo = TransformationInfoProvider.GetTransformation(transformationFullName);

        if (transformationInfo == null)
        {
            return(null);
        }

        // Build the result
        CMSOutputResource resource = new CMSOutputResource()
        {
            Data         = HTMLHelper.ResolveCSSUrls(transformationInfo.TransformationCSS, URLHelper.ApplicationPath),
            LastModified = transformationInfo.TransformationLastModified,
            Etag         = transformationInfo.TransformationVersionGUID
        };

        return(resource);
    }
Ejemplo n.º 11
0
    /// <summary>
    /// Retrieves the stylesheet of the web part from the database.
    /// </summary>
    /// <param name="webPartName">Web part name</param>
    /// <returns>The stylesheet data (plain version only)</returns>
    private static CMSOutputResource GetWebPart(string webPartName)
    {
        WebPartInfo webPartInfo = WebPartInfoProvider.GetWebPartInfo(webPartName);

        if (webPartInfo == null)
        {
            return(null);
        }

        // Build the result
        CMSOutputResource resource = new CMSOutputResource()
        {
            Data         = HTMLHelper.ResolveCSSUrls(webPartInfo.WebPartCSS, URLHelper.ApplicationPath),
            LastModified = webPartInfo.WebPartLastModified,
            Etag         = webPartInfo.WebPartName
        };

        return(resource);
    }
Ejemplo n.º 12
0
    /// <summary>
    /// Retrieves the stylesheets of the layout from the database.
    /// </summary>
    /// <param name="layoutName">Layout name</param>
    /// <returns>The stylesheet data (plain version only)</returns>
    private static CMSOutputResource GetLayout(string layoutName)
    {
        LayoutInfo layoutInfo = LayoutInfoProvider.GetLayoutInfo(layoutName);

        if (layoutInfo == null)
        {
            return(null);
        }

        // Build the result
        CMSOutputResource resource = new CMSOutputResource()
        {
            Data         = HTMLHelper.ResolveCSSUrls(layoutInfo.LayoutCSS, URLHelper.ApplicationPath),
            LastModified = layoutInfo.LayoutLastModified,
            Etag         = layoutInfo.LayoutVersionGUID
        };

        return(resource);
    }
Ejemplo n.º 13
0
    /// <summary>
    /// Retrieves the stylesheets of the web part container from the database.
    /// </summary>
    /// <param name="containerName">Container name</param>
    /// <returns>The stylesheet data (plain version only)</returns>
    private static CMSOutputResource GetContainer(string containerName)
    {
        WebPartContainerInfo containerInfo = WebPartContainerInfoProvider.GetWebPartContainerInfo(containerName);

        if (containerInfo == null)
        {
            return(null);
        }

        // Build the result
        CMSOutputResource resource = new CMSOutputResource()
        {
            Data         = HTMLHelper.ResolveCSSUrls(containerInfo.ContainerCSS, URLHelper.ApplicationPath),
            LastModified = containerInfo.ContainerLastModified,
            Etag         = containerInfo.ContainerName
        };

        return(resource);
    }
Ejemplo n.º 14
0
    /// <summary>
    /// Checks if resource in the client cache matches the server version.
    /// </summary>
    /// <param name="context">An HTTPContext object that provides references to the intrinsic server objects used to service HTTP requests</param>
    /// <param name="resource">Resource to check</param>
    /// <returns>true, if resource is unchanged, otherwise false</returns>
    private static bool IsResourceUnchanged(HttpContext context, CMSOutputResource resource)
    {
        // Determine the last modified date and etag sent from the browser
        string currentETag = RequestHelper.GetHeader("If-None-Match", string.Empty);
        string ifModified  = RequestHelper.GetHeader("If-Modified-Since", string.Empty);

        // If resources match, compare last modification timestamps
        if ((ifModified != string.Empty) && (currentETag == resource.Etag))
        {
            // Get first part of header (colons can delimit additional data)
            DateTime modifiedStamp;
            if (DateTime.TryParse(ifModified.Split(";".ToCharArray())[0], out modifiedStamp))
            {
                return(resource.LastModified <= modifiedStamp.AddSeconds(1));
            }
        }

        return(false);
    }
Ejemplo n.º 15
0
 /// <summary>
 /// Processes the stylesheet.
 /// </summary>
 protected void ProcessStylesheet()
 {
     // Newsletter template stylesheet
     if (!string.IsNullOrEmpty(newsletterTemplateName))
     {
         // Get the template
         et = EmailTemplateInfoProvider.GetEmailTemplateInfo(newsletterTemplateName, SiteContext.CurrentSiteID);
         if (et != null)
         {
             // Create the output file
             outputFile = new CMSOutputResource()
             {
                 Name = RequestContext.URL.ToString(),
                 Data = HTMLHelper.ResolveCSSUrls(et.TemplateStylesheetText, SystemContext.ApplicationPath),
                 Etag = et.TemplateName
             };
         }
     }
 }
Ejemplo n.º 16
0
    /// <summary>
    /// Sends the given file within response.
    /// </summary>
    /// <param name="file">File to send</param>
    protected void SendFile(CMSOutputResource file)
    {
        // Clear response.
        CookieHelper.ClearResponseCookies();
        Response.Clear();

        Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches);

        // Send the file
        if ((file != null) && (file.Data != null))
        {
            // Prepare response
            Response.ContentType = "text/css";

            // Client caching - only on the live site
            if (useClientCache && PortalContext.ViewMode.IsLiveSite() && (CacheHelper.CacheImageEnabled(CurrentSiteName)) && ETagsMatch(file.Etag, file.LastModified))
            {
                RespondNotModified(file.Etag, true);
                return;
            }

            if (useClientCache && PortalContext.ViewMode.IsLiveSite() && (CacheHelper.CacheImageEnabled(CurrentSiteName)))
            {
                DateTime expires = DateTime.Now;

                // Send last modified header to allow client caching
                Response.Cache.SetLastModified(file.LastModified);
                Response.Cache.SetCacheability(HttpCacheability.Public);
                if (DocumentBase.AllowClientCache())
                {
                    expires = DateTime.Now.AddMinutes(CacheHelper.CacheImageMinutes(CurrentSiteName));
                }

                Response.Cache.SetExpires(expires);
                Response.Cache.SetETag(file.Etag);
            }

            // Add the file data
            Response.Write(file.Data);
        }

        CompleteRequest();
    }
Ejemplo n.º 17
0
    /// <summary>
    /// Retrieves the stylesheet from file
    /// </summary>
    /// <param name="url">File URL</param>
    /// <param name="extension">File extension</param>
    /// <returns>The stylesheet data (plain version only)</returns>
    private static CMSOutputResource GetFile(string url, string extension)
    {
        string path = URLHelper.GetPhysicalPath(URLHelper.GetVirtualPath(url));

        // Get the file content
        string fileContent = ReadFile(path, extension);

        fileContent = HTMLHelper.ResolveCSSClientUrls(fileContent, URLHelper.GetAbsoluteUrl(url));

        // Build the result
        CMSOutputResource resource = new CMSOutputResource()
        {
            Data         = fileContent,
            Name         = path,
            Etag         = GetFileEtag(path),
            LastModified = File.GetLastWriteTime(path)
        };

        return(resource);
    }
Ejemplo n.º 18
0
    /// <summary>
    /// Processes a request for a file.
    /// </summary>
    /// <param name="context">An HTTPContext object that provides references to the intrinsic server objects used to service HTTP requests</param>
    /// <param name="queryArgument">Name of the argument whose value specifies the location of the data</param>
    /// <param name="fileExtension">File extension to check against (to prevent serving unauthorized content)</param>
    /// <param name="minifier">Minifier that should be used to transform the original data</param>
    /// <param name="contentType">Content type to use when sending a response</param>
    /// <param name="minificationEnabled">True, if the data should be minified, otherwise false</param>
    private static void ProcessFileRequest(HttpContext context, string queryArgument, string fileExtension, IResourceMinifier minifier, string contentType, bool minificationEnabled)
    {
        // Get URL to the resource file, resolve it in case it's virtual and map to physical path
        string url  = QueryHelper.GetString(queryArgument, string.Empty);
        string path = URLHelper.GetPhysicalPath(URLHelper.GetVirtualPath(url));

        // If this is revalidation request, try quick revalidation check before reading the file
        CheckRevalidation(context, path);

        CMSOutputResource resource = null;

        // Try to get data from cache (or store them if not found)
        using (CachedSection <CMSOutputResource> cachedSection = new CachedSection <CMSOutputResource>(ref resource, PhysicalFilesCacheMinutes, true, null, "getresource", path, URLHelper.IsSSL))
        {
            // Not found in cache; load the data
            if (cachedSection.LoadData)
            {
                // Retrieve the file resource, rebase client URLs and wrap it in output container
                resource = GetFile(url, fileExtension);
                MinifyResource(resource, minifier, minificationEnabled, true);

                // Cache the file
                if ((resource != null) && (cachedSection.Cached))
                {
                    cachedSection.CacheDependency = new CMSCacheDependency(path);
                    cachedSection.Data            = resource;
                }
            }
        }

        // Send response if there's something to send
        if (resource != null)
        {
            bool allowCache = CacheHelper.AlwaysCacheResources;
            SendResponse(context, resource, contentType, allowCache, minificationEnabled, PhysicalFilesCacheMinutes);
        }
        else
        {
            SendNotFoundResponse(context);
        }
    }
Ejemplo n.º 19
0
    /// <summary>
    /// Sends a response containing the requested data.
    /// </summary>
    /// <param name="context">An HTTPContext object that provides references to the intrinsic server objects used to service HTTP requests</param>
    /// <param name="resource">Container with the data to serve</param>
    /// <param name="contentType">Content type to use when sending a response</param>
    /// <param name="allowCache">True, if client caching is enabled, otherwise false</param>
    /// <param name="minificationEnabled">True, if the data can be served minified, otherwise false</param>
    /// <param name="clientCacheMinutes">Number of minutes after which the content in the client cache expires</param>
    private static void SendResponse(HttpContext context, CMSOutputResource resource, string contentType, bool allowCache, bool minificationEnabled, int clientCacheMinutes)
    {
        // Set client cache revalidation
        SetRevalidation(context);

        // Let client use data cached in browser if versions match and there was no change in data
        if (allowCache && IsResourceUnchanged(context, resource))
        {
            SendNotModifiedResponse(context, resource.LastModified, resource.Etag, clientCacheMinutes, true);
            return;
        }
        else
        {
            // Otherwise get content to send
            string contentCoding;
            byte[] content = GetOutputData(context, resource, minificationEnabled, out contentCoding);

            // Set client caching
            if (allowCache)
            {
                SetClientCaching(context, allowCache, resource.LastModified, resource.Etag, clientCacheMinutes);
            }

            if (contentCoding != ContentCodingEnum.IDENTITY)
            {
                context.Response.AppendHeader("Content-Encoding", contentCoding);
                context.Response.AppendHeader("Vary", "Content-Encoding");
            }

            context.Response.ContentType = contentType;

            // Do not send output if there's none
            if (content.Length > 0)
            {
                context.Response.OutputStream.Write(content, 0, content.Length);
            }
        }
    }
Ejemplo n.º 20
0
    /// <summary>
    /// Sends the given file within response.
    /// </summary>
    /// <param name="file">File to send</param>
    protected void SendFile(CMSOutputResource file)
    {
        // Clear response.
        CookieHelper.ClearResponseCookies();
        Response.Clear();

        Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches);

        // Send the file
        if ((file != null) && (file.Data != null))
        {
            // Prepare response
            Response.ContentType = "text/css";

            // Client caching - only on the live site
            if (useClientCache && AllowCache && CacheHelper.CacheImageEnabled(CurrentSiteName) && ETagsMatch(file.Etag, file.LastModified))
            {
                RespondNotModified(file.Etag);
                return;
            }

            if (useClientCache && AllowCache && CacheHelper.CacheImageEnabled(CurrentSiteName))
            {
                SetTimeStamps(file.LastModified);

                Response.Cache.SetETag(file.Etag);
            }

            // Add the file data
            Response.Write(file.Data);
        }

        CompleteRequest();
    }
Ejemplo n.º 21
0
    /// <summary>
    /// Combines the given list of resources into a single resource
    /// </summary>
    /// <param name="resources">Resources to combine</param>
    private static CMSOutputResource CombineResources(List<CMSOutputResource> resources)
    {
        StringBuilder data = new StringBuilder();
        StringBuilder etag = new StringBuilder();

        DateTime lastModified = DateTimeHelper.ZERO_TIME;

        // Build single resource
        foreach (CMSOutputResource resource in resources)
        {
            if (resource != null)
            {
                string newData = resource.Data;

                // Join the data into a single string
                if ((data.Length > 0) && !String.IsNullOrEmpty(newData))
                {
                    // Trim the charset
                    newData = CSSHelper.TrimCharset(newData);
                    if (String.IsNullOrEmpty(newData))
                    {
                        continue;
                    }

                    data.AppendLine();
                    data.AppendLine();
                }

                data.Append(newData);

                // Join e-tags
                if (etag.Length > 0)
                {
                    etag.Append('|');
                }
                etag.Append(resource.Etag);

                // Remember the largest last modified
                if (resource.LastModified > lastModified)
                {
                    lastModified = resource.LastModified;
                }
            }
        }

        // Build the result
        CMSOutputResource result = new CMSOutputResource()
        {
            Data = data.ToString(),
            Etag = etag.ToString(),
            LastModified = lastModified
        };

        return result;
    }
    /// <summary>
    /// Retrieves the stylesheet from file
    /// </summary>
    /// <param name="item">File item</param>
    /// <param name="extension">File extension</param>
    /// <param name="resolveCSSUrls">If true, the CSS URLs are resolved in the output</param>
    /// <param name="binary">If true, the file is a binary file</param>
    /// <returns>The stylesheet data (plain version only)</returns>    
    private static CMSOutputResource GetFile(CMSItem item, string extension, bool resolveCSSUrls, bool binary)
    {
        string url = item.Name;
        string path = URLHelper.GetPhysicalPath(URLHelper.GetVirtualPath(url));

        // Get the file content
        string fileContent = null;
        byte[] binaryData = null;

        if (binary)
        {
            // Binary file
            binaryData = ReadBinaryFile(path, extension);
        }
        else
        {
            // Text file
            fileContent = ReadFile(path, extension);
            if (resolveCSSUrls)
            {
                fileContent = HTMLHelper.ResolveCSSClientUrls(fileContent, URLHelper.GetAbsoluteUrl(url));
            }
        }

        var lastModified = File.GetLastWriteTime(path);

        // Build the result
        var resource = new CMSOutputResource()
        {
            Data = fileContent,
            BinaryData = binaryData,
            Name = path,
            Etag = "file|" + lastModified.ToString(),
            LastModified = lastModified,
            ContentType = MimeTypeHelper.GetMimetype(extension),
            FileName = Path.GetFileName(path),
            Extension = extension
        };

        return resource;
    }
    /// <summary>
    /// Returns the data which will be served to client depending on minification and compression settings.
    /// </summary>
    /// <param name="context">An HTTPContext object that provides references to the intrinsic server objects used to service HTTP requests</param>
    /// <param name="resource">Data container with the data to serve</param>
    /// <param name="minificationEnabled">True, if the data should be minified, otherwise false</param>
    /// <param name="contentCoding">The content coding to use when sending a response</param>
    /// <returns>Data to serve in a form of a byte block</returns>
    private static byte[] GetOutputData(HttpContext context, CMSOutputResource resource, bool minificationEnabled, out string contentCoding)
    {
        // minification must be allowed by the server and minified data must be available
        bool minified = minificationEnabled && resource.ContainsMinifiedData;

        // compression must be allowed by server, supported by client and compressed data must be available
        bool allowCompression = false;
        if (CMSAppBase.ConnectionAvailable)
        {
            allowCompression = RequestHelper.AllowResourceCompression;
        }

        bool compressed = allowCompression && RequestHelper.IsGZipSupported() && resource.ContainsCompressedData;

        // Set default content encoding
        contentCoding = ContentCodingEnum.IDENTITY;

        // Get the proper version of resource to serve based on the settings
        if (!minified && !compressed)
        {
            return Encoding.UTF8.GetBytes(resource.Data);
        }
        else if (minificationEnabled && !compressed)
        {
            return Encoding.UTF8.GetBytes(resource.MinifiedData);
        }
        else if (!minified && compressed)
        {
            contentCoding = ContentCodingEnum.DEFLATE;
            return resource.CompressedData;
        }
        else if (minified && compressed)
        {
            contentCoding = ContentCodingEnum.DEFLATE;
            return resource.MinifiedCompressedData;
        }
        else
        {
            return new byte[0];
        }
    }
    /// <summary>
    /// Checks if this is a revalidation request for a physical file that did not change since the last time.
    /// </summary>
    /// <param name="context">An HTTPContext object that provides references to the intrinsic server objects used to service HTTP requests</param>
    /// <param name="path">Full physical path to the file</param>
    private static void CheckRevalidation(HttpContext context, string path)
    {
        var lastModified = File.GetLastWriteTime(path);

        // Virtual resource, used only to check if revalidation can be short-circuited
        CMSOutputResource fileResource = new CMSOutputResource()
        {
            Etag = lastModified.ToString(),
            LastModified = lastModified
        };

        if (IsResourceUnchanged(context, fileResource))
        {
            SendNotModifiedResponse(context, fileResource.LastModified, fileResource.Etag, PhysicalFilesCacheMinutes, true);
        }
    }
    /// <summary>
    /// Retrieves the stylesheets of the web part container from the database.
    /// </summary>
    /// <param name="item">Container item</param>
    /// <returns>The stylesheet data (plain version only)</returns>
    private static CMSOutputResource GetContainer(CMSItem item)
    {
        WebPartContainerInfo containerInfo = null;
        if (item.Name != null)
        {
            containerInfo = WebPartContainerInfoProvider.GetWebPartContainerInfo(item.Name);
        }
        else
        {
            containerInfo = WebPartContainerInfoProvider.GetWebPartContainerInfo(item.ID);
        }
        if (containerInfo == null)
        {
            return null;
        }

        DateTime lastModified = containerInfo.ContainerLastModified;

        // Build the result
        var resource = new CMSOutputResource()
        {
            Data = HTMLHelper.ResolveCSSUrls(containerInfo.ContainerCSS, URLHelper.ApplicationPath),
            LastModified = lastModified,
            Etag = "webpartcontainer|" + lastModified.ToString(),
            FileName = ValidationHelper.GetSafeFileName(containerInfo.ContainerName),
            Extension = ".css"
        };

        return resource;
    }
Ejemplo n.º 26
0
    /// <summary>
    /// Wraps a piece of text in a data container.
    /// </summary>
    /// <param name="resource">Text to wrap</param>
    /// <param name="name">Identifier for the file</param>
    /// <param name="etag">Etag to use for versioning</param>
    /// <param name="lastModified">Timestamp of the last modification of data</param>
    /// <param name="minifier">Minifier to use when creating minified version of the data</param>
    /// <param name="minificationEnabled">True, if the data should be minified, otherwise false</param>
    /// <returns>Data container containing the piece of text</returns>
    private static CMSOutputResource WrapObject(string resource, string name, string etag, DateTime lastModified, IResourceMinifier minifier, bool minificationEnabled)
    {
        if (resource == null)
        {
            return null;
        }

        // Prepare new output resource object
        CMSOutputResource wrapper = new CMSOutputResource()
        {
            Name = name,
            Etag = etag,
            LastModified = lastModified,
            Data = resource,
        };

        // Set up the settings
        if (minificationEnabled)
        {
            wrapper.MinifiedData = minifier.Minify(wrapper.Data);
        }
        if (RequestHelper.AllowResourceCompression)
        {
            wrapper.CompressedData = Compress(resource);
        }
        if (minificationEnabled && RequestHelper.AllowResourceCompression)
        {
            wrapper.MinifiedCompressedData = Compress(wrapper.MinifiedData);
        }

        return wrapper;
    }
Ejemplo n.º 27
0
    /// <summary>
    /// Retrieves the specified resources and wraps them in an data container.
    /// </summary>
    /// <param name="settings">CSS settings</param>
    /// <param name="name">Resource name</param>
    /// <param name="cached">If true, the result will be cached</param>
    /// <returns>The data container with the resulting stylesheet data</returns>
    private static CMSOutputResource GetResource(CMSCssSettings settings, string name, bool cached)
    {
        List <CMSOutputResource> resources = new List <CMSOutputResource>();

        // Add files
        if (settings.Files != null)
        {
            foreach (string item in settings.Files)
            {
                // Get the resource
                CMSOutputResource resource = GetFile(item, CSS_FILE_EXTENSION);
                resources.Add(resource);
            }
        }

        // Add stylesheets
        if (settings.Stylesheets != null)
        {
            foreach (string item in settings.Stylesheets)
            {
                // Get the resource
                CMSOutputResource resource = GetStylesheet(item);
                resources.Add(resource);
            }
        }

        // Add web part containers
        if (settings.Containers != null)
        {
            foreach (string item in settings.Containers)
            {
                // Get the resource
                CMSOutputResource resource = GetContainer(item);
                resources.Add(resource);
            }
        }

        // Add web parts
        if (settings.WebParts != null)
        {
            foreach (string item in settings.WebParts)
            {
                // Get the resource
                CMSOutputResource resource = GetWebPart(item);
                resources.Add(resource);
            }
        }

        // Add templates
        if (settings.Templates != null)
        {
            foreach (string item in settings.Templates)
            {
                // Get the resource
                CMSOutputResource resource = GetTemplate(item);
                resources.Add(resource);
            }
        }

        // Add layouts
        if (settings.Layouts != null)
        {
            foreach (string item in settings.Layouts)
            {
                // Get the resource
                CMSOutputResource resource = GetLayout(item);
                resources.Add(resource);
            }
        }

        // Add transformation containers
        if (settings.Transformations != null)
        {
            foreach (string item in settings.Transformations)
            {
                // Get the resource
                CMSOutputResource resource = GetTransformation(item);
                resources.Add(resource);
            }
        }

        // Add web part layouts
        if (settings.WebPartLayouts != null)
        {
            foreach (string item in settings.WebPartLayouts)
            {
                // Get the resource
                CMSOutputResource resource = GetWebPartLayout(item);
                resources.Add(resource);
            }
        }

        // Combine to a single output
        CMSOutputResource result = CombineResources(resources);

        // Resolve the macros
        if (CSSHelper.ResolveMacrosInCSS)
        {
            MacroContext context = new MacroContext()
            {
                TrackCacheDependencies = cached
            };

            if (cached)
            {
                // Add the default dependencies
                context.AddCacheDependencies(settings.GetCacheDependencies());
                context.AddFileCacheDependencies(settings.GetFileCacheDependencies());
            }

            result.Data = CMSContext.ResolveMacros(result.Data, context);

            if (cached)
            {
                // Add cache dependency
                result.CacheDependency = CacheHelper.GetCacheDependency(context.FileCacheDependencies, context.CacheDependencies);
            }
        }
        else if (cached)
        {
            // Only the cache dependency from settings
            result.CacheDependency = settings.GetCacheDependency();
        }

        // Minify
        MinifyResource(result, mCssMinifier, CSSHelper.StylesheetMinificationEnabled && settings.EnableMinification, settings.EnableMinification);

        return(result);
    }
Ejemplo n.º 28
0
    /// <summary>
    /// Retrieves the stylesheet from file
    /// </summary>
    /// <param name="url">File URL</param>
    /// <param name="extension">File extension</param>
    /// <returns>The stylesheet data (plain version only)</returns>    
    private static CMSOutputResource GetFile(string url, string extension)
    {
        string path = URLHelper.GetPhysicalPath(URLHelper.GetVirtualPath(url));

        // Get the file content
        string fileContent = ReadFile(path, extension);
        fileContent = HTMLHelper.ResolveCSSClientUrls(fileContent, URLHelper.GetAbsoluteUrl(url));

        // Build the result
        CMSOutputResource resource = new CMSOutputResource()
        {
            Data = fileContent,
            Name = path,
            Etag = GetFileEtag(path),
            LastModified = File.GetLastWriteTime(path)
        };

        return resource;
    }
Ejemplo n.º 29
0
    /// <summary>
    /// Minify supplied source according to settings.
    /// </summary>
    /// <param name="resource">Resource to minifz</param>
    /// <param name="minifier">Minifier to use when creating minified version of the data</param>
    /// <param name="minificationEnabled">True, if the data should be minified, otherwise false</param>
    /// <param name="compressionEnabled">True, if data should be compressed, otherwise false</param>
    private static void MinifyResource(CMSOutputResource resource, IResourceMinifier minifier, bool minificationEnabled, bool compressionEnabled)
    {
        if (resource == null)
        {
            return;
        }

        // Set up the settings
        if (minificationEnabled && (minifier != null))
        {
            resource.MinifiedData = minifier.Minify(resource.Data);
        }

        // Compress
        if (RequestHelper.AllowResourceCompression && compressionEnabled)
        {
            resource.CompressedData = Compress(resource.Data);
        }

        // Compress and minify
        if (minificationEnabled && RequestHelper.AllowResourceCompression && compressionEnabled)
        {
            resource.MinifiedCompressedData = Compress(resource.MinifiedData);
        }
    }
Ejemplo n.º 30
0
    /// <summary>
    /// Retrieve the stylesheet either from the database or file if checked out.
    /// </summary>
    /// <param name="stylesheetName">Stylesheet's unique name</param>
    /// <returns>The stylesheet data (plain version only)</returns>    
    private static CMSOutputResource GetStylesheet(string stylesheetName)
    {
        // Get the stylesheet
        CssStylesheetInfo stylesheetInfo = CssStylesheetInfoProvider.GetCssStylesheetInfo(stylesheetName);
        if (stylesheetInfo == null)
        {
            return null;
        }

        // Determine if the stylesheet is checked out or not
        string checkedOutFile = URLHelper.GetPhysicalPath(stylesheetInfo.StylesheetCheckedOutFilename);
        string stylesheet;
        DateTime lastModified;

        if ((stylesheetInfo.StylesheetCheckedOutByUserID > 0) &&
            (string.Equals(stylesheetInfo.StylesheetCheckedOutMachineName, HTTPHelper.MachineName, StringComparison.OrdinalIgnoreCase)) &&
            (File.Exists(checkedOutFile)))
        {
            // Read the stylesheet and timestamp from the checked out file
            using (StreamReader reader = StreamReader.New(checkedOutFile))
            {
                stylesheet = reader.ReadToEnd();
            }
            lastModified = File.GetLastWriteTime(checkedOutFile);
        }
        else
        {
            // Read the stylesheet and timestamp from database
            stylesheet = stylesheetInfo.StylesheetText;
            lastModified = stylesheetInfo.StylesheetLastModified;
        }

        // Build the output
        CMSOutputResource resource = new CMSOutputResource()
        {
            Data = HTMLHelper.ResolveCSSUrls(stylesheet, URLHelper.ApplicationPath),
            Name = stylesheetInfo.StylesheetName,
            LastModified = lastModified,
            Etag = stylesheetName,
        };

        return resource;
    }
Ejemplo n.º 31
0
    /// <summary>
    /// Retrieves the stylesheets of the page template from the database.
    /// </summary>
    /// <param name="templateName">Template name</param>
    /// <returns>The stylesheet data (plain version only)</returns>
    private static CMSOutputResource GetTemplate(string templateName)
    {
        // Try to get global one
        PageTemplateInfo templateInfo = PageTemplateInfoProvider.GetPageTemplateInfo(templateName);

        // Try to get site one (ad-hoc) if not found
        if (templateInfo == null)
        {
            templateInfo = PageTemplateInfoProvider.GetPageTemplateInfo(templateName, CMSContext.CurrentSiteID);
        }

        if (templateInfo == null)
        {
            return null;
        }

        // Build the result
        CMSOutputResource resource = new CMSOutputResource()
        {
            Data = HTMLHelper.ResolveCSSUrls(templateInfo.PageTemplateCSS, URLHelper.ApplicationPath),
            LastModified = templateInfo.PageTemplateLastModified,
            Etag = templateInfo.PageTemplateVersionGUID
        };

        return resource;
    }
Ejemplo n.º 32
0
    /// <summary>
    /// Retrieves the stylesheets of the web part layout from the database.
    /// </summary>
    /// <param name="layoutFullName">Layout full name</param>
    /// <returns>The stylesheet data (plain version only)</returns>
    private static CMSOutputResource GetTransformation(string transformationFullName)
    {
        TransformationInfo transformationInfo = TransformationInfoProvider.GetTransformation(transformationFullName);
        if (transformationInfo == null)
        {
            return null;
        }

        // Build the result
        CMSOutputResource resource = new CMSOutputResource()
        {
            Data = HTMLHelper.ResolveCSSUrls(transformationInfo.TransformationCSS, URLHelper.ApplicationPath),
            LastModified = transformationInfo.TransformationLastModified,
            Etag = transformationInfo.TransformationVersionGUID
        };

        return resource;
    }
    /// <summary>
    /// Minify supplied source according to settings.
    /// </summary>
    /// <param name="resource">Resource to minifz</param>
    /// <param name="minifier">Minifier to use when creating minified version of the data</param>
    /// <param name="minificationEnabled">True, if the data should be minified, otherwise false</param>
    /// <param name="compressionEnabled">True, if data should be compressed, otherwise false</param>
    private static void MinifyResource(CMSOutputResource resource, IResourceMinifier minifier, bool minificationEnabled, bool compressionEnabled)
    {
        if (resource == null)
        {
            return;
        }

        // Set up the settings
        if (minificationEnabled && (minifier != null))
        {
            resource.MinifiedData = minifier.Minify(resource.Data);
        }

        // Check whether the compression is enabled
        if (compressionEnabled && CMSAppBase.ConnectionAvailable)
        {
            compressionEnabled &= RequestHelper.AllowResourceCompression;
        }

        // Compress
        if (compressionEnabled)
        {
            resource.CompressedData = Compress(resource.Data);
        }

        // Compress and minify
        if (minificationEnabled && compressionEnabled)
        {
            resource.MinifiedCompressedData = Compress(resource.MinifiedData);
        }
    }
Ejemplo n.º 34
0
    /// <summary>
    /// Retrieves the stylesheets of the web part container from the database.
    /// </summary>
    /// <param name="containerName">Container name</param>
    /// <returns>The stylesheet data (plain version only)</returns>
    private static CMSOutputResource GetContainer(string containerName)
    {
        WebPartContainerInfo containerInfo = WebPartContainerInfoProvider.GetWebPartContainerInfo(containerName);
        if (containerInfo == null)
        {
            return null;
        }

        // Build the result
        CMSOutputResource resource = new CMSOutputResource()
        {
            Data = HTMLHelper.ResolveCSSUrls(containerInfo.ContainerCSS, URLHelper.ApplicationPath),
            LastModified = containerInfo.ContainerLastModified,
            Etag = containerInfo.ContainerName
        };

        return resource;
    }
    /// <summary>
    /// Sends a response containing the requested data.
    /// </summary>
    /// <param name="context">An HTTPContext object that provides references to the intrinsic server objects used to service HTTP requests</param>
    /// <param name="resource">Container with the data to serve</param>
    /// <param name="allowCache">True, if client caching is enabled, otherwise false</param>
    /// <param name="minificationEnabled">True, if the data can be served minified, otherwise false</param>
    /// <param name="clientCacheMinutes">Number of minutes after which the content in the client cache expires</param>
    /// <param name="staticContent">If true, the content is static</param>
    private static void SendResponse(HttpContext context, CMSOutputResource resource, bool allowCache, bool minificationEnabled, int clientCacheMinutes, bool staticContent)
    {
        // Set client cache revalidation
        SetRevalidation(context, staticContent);

        // Let client use data cached in browser if versions match and there was no change in data
        if (allowCache && IsResourceUnchanged(context, resource))
        {
            SendNotModifiedResponse(context, resource.LastModified, resource.Etag, clientCacheMinutes, true);
            return;
        }
        else
        {
            byte[] content = null;

            if (resource.Data == null)
            {
                // Binary content
                content = resource.BinaryData;
            }
            else
            {
                // Text content
                string contentCoding = null;
                content = GetOutputData(context, resource, minificationEnabled, out contentCoding);

                if (contentCoding != ContentCodingEnum.IDENTITY)
                {
                    context.Response.AppendHeader("Content-Encoding", contentCoding);
                    context.Response.AppendHeader("Vary", "Content-Encoding");
                }
            }

            if (content == null)
            {
                // 404 if no content found
                RequestHelper.Respond404();
            }

            // Set client caching
            if (allowCache)
            {
                SetClientCaching(context, allowCache, resource.LastModified, resource.Etag, clientCacheMinutes);
            }

            context.Response.ContentType = resource.ContentType;

            // Set the file name and extension if defined
            if (!String.IsNullOrEmpty(resource.FileName) && !String.IsNullOrEmpty(resource.Extension))
            {
                HTTPHelper.SetFileDisposition(resource.FileName, resource.Extension);
            }

            // Do not send output if there's none
            if ((content != null) && (content.Length > 0))
            {
                context.Response.OutputStream.Write(content, 0, content.Length);
            }
        }
    }
Ejemplo n.º 36
0
    /// <summary>
    /// Sends the given file within response.
    /// </summary>
    /// <param name="file">File to send</param>
    protected void SendFile(CMSOutputResource file)
    {
        // Clear response.
        CookieHelper.ClearResponseCookies();
        Response.Clear();

        Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches);

        // Send the file
        if ((file != null) && (file.Data != null))
        {
            // Client caching - only on the live site
            if (useClientCache && (CMSContext.ViewMode == ViewModeEnum.LiveSite) && (CacheHelper.CacheImageEnabled(CurrentSiteName)) && ETagsMatch(file.Etag, file.LastModified))
            {
                RespondNotModified(file.Etag, true);
                return;
            }

            // Prepare response
            Response.ContentType = "text/css";

            if (useClientCache && (CMSContext.ViewMode == ViewModeEnum.LiveSite) && (CacheHelper.CacheImageEnabled(CurrentSiteName)))
            {
                DateTime expires = DateTime.Now;

                // Send last modified header to allow client caching
                Response.Cache.SetLastModified(file.LastModified);
                Response.Cache.SetCacheability(HttpCacheability.Public);
                if (DocumentBase.AllowClientCache() && DocumentBase.UseFullClientCache)
                {
                    expires = DateTime.Now.AddMinutes(CacheHelper.CacheImageMinutes(CurrentSiteName));
                }

                Response.Cache.SetExpires(expires);
                Response.Cache.SetETag(file.Etag);
            }

            // Add the file data
            Response.Write(file.Data);
        }

        CompleteRequest();
    }
    /// <summary>
    /// Combines the given list of resources into a single resource
    /// </summary>
    /// <param name="resources">Resources to combine</param>
    private static CMSOutputResource CombineResources(IEnumerable<CMSOutputResource> resources)
    {
        StringBuilder data = new StringBuilder();
        StringBuilder etag = new StringBuilder();

        DateTime lastModified = DateTimeHelper.ZERO_TIME;
        List<string> files = new List<string>();

        int count = 0;

        string fileName = null;

        // Build single resource
        foreach (CMSOutputResource resource in resources)
        {
            if (resource != null)
            {
                string newData = resource.Data;

                // Join the data into a single string
                if ((data.Length > 0) && !String.IsNullOrEmpty(newData))
                {
                    // Trim the charset
                    newData = CSSHelper.TrimCharset(newData);
                    if (String.IsNullOrEmpty(newData))
                    {
                        continue;
                    }

                    data.AppendLine();
                    data.AppendLine();
                }

                data.Append(newData);

                // Join e-tags
                if (etag.Length > 0)
                {
                    etag.Append('|');
                }
                etag.Append(resource.Etag);

                // Remember the largest last modified
                if (resource.LastModified > lastModified)
                {
                    lastModified = resource.LastModified;
                }

                files.AddRange(resource.ComponentFiles);

                fileName = resource.Name;
            }

            count++;
        }

        // Build the result
        CMSOutputResource result = new CMSOutputResource()
        {
            Data = data.ToString(),
            Etag = etag.ToString(),
            LastModified = lastModified,
            ComponentFiles = files,
            Extension = ".css"
        };

        // Set the file name
        if (count == 1)
        {
            result.FileName = ValidationHelper.GetSafeFileName(fileName) + ".css";
        }
        else
        {
            result.FileName = "components.css";
        }

        return result;
    }
    /// <summary>
    /// Retrieve the stylesheet either from the database or file if checked out.
    /// </summary>
    /// <param name="item">Stylesheet item</param>
    /// <returns>The stylesheet data (plain version only)</returns>    
    private static CMSOutputResource GetStylesheet(CMSItem item)
    {
        // Get the stylesheet
        CssStylesheetInfo stylesheetInfo = null;
        if (item.Name != null)
        {
            stylesheetInfo = CssStylesheetInfoProvider.GetCssStylesheetInfo(item.Name);
        }
        else
        {
            stylesheetInfo = CssStylesheetInfoProvider.GetCssStylesheetInfo(item.ID);
        }
        if (stylesheetInfo == null)
        {
            return null;
        }

        // Get last modified date with dependency on external storage
        DateTime lastModified = stylesheetInfo.StylesheetLastModified;
        FileInfo fi = stylesheetInfo.GetFileInfo(CssStylesheetInfo.EXTERNAL_COLUMN_CSS);
        if (fi != null)
        {
            lastModified = fi.LastWriteTime.ToUniversalTime();
        }

        string stylesheetName = stylesheetInfo.StylesheetName;

        // Build the output
        var resource = new CMSOutputResource()
        {
            Data = HTMLHelper.ResolveCSSUrls(stylesheetInfo.StylesheetText, URLHelper.ApplicationPath),
            Name = stylesheetName,
            LastModified = lastModified,
            Etag = "cssstylesheet|" + stylesheetInfo.StylesheetVersionGUID.ToString(),
            FileName = stylesheetName + ".css",
            Extension = ".css"
        };

        // Add file dependency on component css file
        if (fi != null)
        {
            resource.ComponentFiles.Add(stylesheetInfo.GetVirtualFileRelativePath(CssStylesheetInfo.EXTERNAL_COLUMN_CSS));
        }

        return resource;
    }
    /// <summary>
    /// Retrieves the stylesheets of the device layout from the database.
    /// </summary>
    /// <param name="item">Device layout item</param>
    /// <returns>The stylesheet data (plain version only)</returns>
    private static CMSOutputResource GetDeviceLayout(CMSItem item)
    {
        PageTemplateDeviceLayoutInfo layoutInfo = null;
        if (item.Name != null)
        {
            // Not supported, device layout doesn't contain name
        }
        else
        {
            layoutInfo = PageTemplateDeviceLayoutInfoProvider.GetTemplateDeviceLayoutInfo(item.ID);
        }

        if (layoutInfo == null)
        {
            return null;
        }

        // Get last modified date with dependency on external storage
        DateTime lastModified = layoutInfo.LayoutLastModified;
        FileInfo fi = layoutInfo.GetFileInfo(PageTemplateDeviceLayoutInfo.EXTERNAL_COLUMN_CSS);
        if (fi != null)
        {
            lastModified = fi.LastWriteTime.ToUniversalTime();
        }

        // Build the result
        var resource = new CMSOutputResource()
        {
            Data = HTMLHelper.ResolveCSSUrls(layoutInfo.LayoutCSS, URLHelper.ApplicationPath),
            LastModified = lastModified,
            Etag = "layout|" + layoutInfo.LayoutVersionGUID,
            FileName = Convert.ToString(layoutInfo.LayoutID),
            Extension = ".css"
        };

        // Add file dependency on component css file
        if (fi != null)
        {
            resource.ComponentFiles.Add(layoutInfo.GetVirtualFileRelativePath(PageTemplateDeviceLayoutInfo.EXTERNAL_COLUMN_CSS));
        }

        return resource;
    }
    /// <summary>
    /// Retrieves the stylesheets of the page template from the database.
    /// </summary>
    /// <param name="item">Template item</param>
    /// <returns>The stylesheet data (plain version only)</returns>
    private static CMSOutputResource GetTemplate(CMSItem item)
    {
        // Try to get global one
        PageTemplateInfo templateInfo = null;
        if (item.Name != null)
        {
            string templateName = item.Name;

            templateInfo = PageTemplateInfoProvider.GetPageTemplateInfo(templateName);

            // Try to get site one (ad-hoc) if not found
            if (templateInfo == null)
            {
                templateInfo = PageTemplateInfoProvider.GetPageTemplateInfo(templateName, CMSContext.CurrentSiteID);
            }
        }
        else
        {
            templateInfo = PageTemplateInfoProvider.GetPageTemplateInfo(item.ID);
        }
        if (templateInfo == null)
        {
            return null;
        }

        // Get last modified date with dependency on external storage
        DateTime lastModified = templateInfo.PageTemplateLastModified;
        FileInfo fi = templateInfo.GetFileInfo(PageTemplateInfo.EXTERNAL_COLUMN_CSS);
        if (fi != null)
        {
            lastModified = fi.LastWriteTime.ToUniversalTime();
        }

        // Build the result
        var resource = new CMSOutputResource()
        {
            Data = HTMLHelper.ResolveCSSUrls(templateInfo.PageTemplateCSS, URLHelper.ApplicationPath),
            LastModified = lastModified,
            Etag = "template|" + templateInfo.PageTemplateVersionGUID,
            FileName = ValidationHelper.GetSafeFileName(templateInfo.CodeName),
            Extension = ".css"
        };

        // Add file dependency on component css file
        if (fi != null)
        {
            resource.ComponentFiles.Add(templateInfo.GetVirtualFileRelativePath(PageTemplateInfo.EXTERNAL_COLUMN_CSS));
        }

        return resource;
    }
    /// <summary>
    /// Retrieves the stylesheets of the layout from the database.
    /// </summary>
    /// <param name="item">Layout item</param>
    /// <returns>The stylesheet data (plain version only)</returns>
    private static CMSOutputResource GetLayout(CMSItem item)
    {
        LayoutInfo layoutInfo = null;
        if (item.Name != null)
        {
            layoutInfo = LayoutInfoProvider.GetLayoutInfo(item.Name);
        }
        else
        {
            layoutInfo = LayoutInfoProvider.GetLayoutInfo(item.ID);
        }
        if (layoutInfo == null)
        {
            return null;
        }

        // Get last modified date with dependency on external storage
        DateTime lastModified = layoutInfo.LayoutLastModified;
        FileInfo fi = layoutInfo.GetFileInfo(LayoutInfo.EXTERNAL_COLUMN_CSS);
        if (fi != null)
        {
            lastModified = fi.LastWriteTime.ToUniversalTime();
        }

        // Build the result
        var resource = new CMSOutputResource()
        {
            Data = HTMLHelper.ResolveCSSUrls(layoutInfo.LayoutCSS, URLHelper.ApplicationPath),
            LastModified = lastModified,
            Etag = "layout|" + layoutInfo.LayoutVersionGUID,
            FileName = ValidationHelper.GetSafeFileName(layoutInfo.LayoutCodeName),
            Extension = ".css"
        };

        // Add file dependency on component css file
        if (fi != null)
        {
            resource.ComponentFiles.Add(layoutInfo.GetVirtualFileRelativePath(LayoutInfo.EXTERNAL_COLUMN_CSS));
        }

        return resource;
    }
    /// <summary>
    /// Retrieves the stylesheets of the web part layout from the database.
    /// </summary>
    /// <param name="item">Layout item</param>
    /// <returns>The stylesheet data (plain version only)</returns>
    private static CMSOutputResource GetTransformation(CMSItem item)
    {
        TransformationInfo transformationInfo = null;
        if (item.Name != null)
        {
            transformationInfo = TransformationInfoProvider.GetTransformation(item.Name);
        }
        else
        {
            transformationInfo = TransformationInfoProvider.GetTransformation(item.ID);
        }
        if (transformationInfo == null)
        {
            return null;
        }

        // Get last modified date with dependency on external storage
        DateTime lastModified = transformationInfo.TransformationLastModified;
        FileInfo fi = transformationInfo.GetFileInfo(TransformationInfo.EXTERNAL_COLUMN_CSS);
        if (fi != null)
        {
            lastModified = fi.LastWriteTime.ToUniversalTime();
        }

        // Build the result
        var resource = new CMSOutputResource()
        {
            Data = HTMLHelper.ResolveCSSUrls(transformationInfo.TransformationCSS, URLHelper.ApplicationPath),
            LastModified = lastModified,
            Etag = "transformation|" + transformationInfo.TransformationVersionGUID,
            FileName = ValidationHelper.GetSafeFileName(transformationInfo.TransformationFullName) + ".css",
            Extension = ".css"
        };

        // Add file dependency on component css file
        if (fi != null)
        {
            resource.ComponentFiles.Add(transformationInfo.GetVirtualFileRelativePath(TransformationInfo.EXTERNAL_COLUMN_CSS));
        }

        return resource;
    }
    /// <summary>
    /// Generates the QR code
    /// </summary>
    /// <param name="code">Code to generate by the QR code</param>
    /// <param name="size">Image size, image is rendered with recommended resolution for the QR code</param>
    /// <param name="encoding">Encoding, possible options (B - Byte, AN - Alphanumeric, N - Numeric)</param>
    /// <param name="version">QR code version (by default supported 1 to 10), additional data templates may be put into ~/App_Data/CMS_Modules/QRCode/Resources.zip</param>
    /// <param name="correction">Correction type, possible options (L, M, Q, H)</param>
    /// <param name="maxSideSize">Maximum size of the code in pixels, the code will be resized if larger than this size</param>
    /// <param name="fgColor">Foreground color</param>
    /// <param name="bgColor">Background color</param>
    private static CMSOutputResource GetQRCode(string code, string encoding, int size, int version, string correction, int maxSideSize, Color fgColor, Color bgColor)
    {
        QRCodeEncoder qrCodeEncoder = new QRCodeEncoder();

        try
        {
            // Set encoding
            switch (encoding.ToLowerCSafe())
            {
                case "an":
                    qrCodeEncoder.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.ALPHA_NUMERIC;
                    break;

                case "n":
                    qrCodeEncoder.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.NUMERIC;
                    break;

                default:
                    qrCodeEncoder.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.BYTE;
                    break;
            }

            // Set scale
            try
            {
                qrCodeEncoder.QRCodeScale = size;
            }
            catch
            {
                qrCodeEncoder.QRCodeScale = 4;
            }

            // Set error correction
            switch (correction.ToLowerCSafe())
            {
                case "l":
                    qrCodeEncoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.L;
                    break;

                case "q":
                    qrCodeEncoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.Q;
                    break;

                case "h":
                    qrCodeEncoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.H;
                    break;

                default:
                    qrCodeEncoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.M;
                    break;
            }

            // Set colors
            qrCodeEncoder.QRCodeForegroundColor = fgColor;
            qrCodeEncoder.QRCodeBackgroundColor = bgColor;

            Image image = null;

            // Attempt to process all versions
            while (version <= 40)
            {
                if (!QRVersionSupported(version))
                {
                    // Move to higher version
                    version++;

                    if (version > 40)
                    {
                        throw new Exception("Version higher than 40 is not supported.");
                    }
                    continue;
                }

                try
                {
                    // Try to get requested version
                    qrCodeEncoder.QRCodeVersion = version;

                    image = qrCodeEncoder.Encode(code);

                    break;
                }
                catch (IndexOutOfRangeException ex)
                {
                    // Try next version to fit the data
                    version++;

                    if (version > 40)
                    {
                        throw ex;
                    }
                }
            }

            byte[] bytes = ImageHelper.GetBytes(image, ImageFormat.Png);

            // Resize to a proper size
            if (maxSideSize > 0)
            {
                // Resize the image by image helper to a proper size
                ImageHelper ih = new ImageHelper(bytes);
                image = ih.GetResizedImage(maxSideSize);

                bytes = ImageHelper.GetBytes(image, ImageFormat.Png);
            }

            // Build the result
            var resource = new CMSOutputResource()
            {
                BinaryData = bytes,
                Name = code,
                Etag = "QRCode",
                LastModified = new DateTime(2012, 1, 1),
                ContentType = MimeTypeHelper.GetMimetype(".png"),
                FileName = "QRCode.png",
                Extension = ".png"
            };

            return resource;
        }
        catch (Exception ex)
        {
            // Report too long text
            string message = "[GetResource.GetQRCode]: Failed to generate QR code with text '" + code + "', this may be caused by the text being too long. Original message: " + ex.Message;

            var newEx = new Exception(message, ex);

            EventLogProvider.LogException("GetResource", "QRCODE", newEx);

            throw newEx;
        }
    }
    /// <summary>
    /// Retrieves the stylesheet of the web part from the database.
    /// </summary>
    /// <param name="item">Web part item</param>
    /// <returns>The stylesheet data (plain version only)</returns>
    private static CMSOutputResource GetWebPart(CMSItem item)
    {
        WebPartInfo webPartInfo = null;
        if (item.Name != null)
        {
            webPartInfo = WebPartInfoProvider.GetWebPartInfo(item.Name);
        }
        else
        {
            webPartInfo = WebPartInfoProvider.GetWebPartInfo(item.ID);
        }
        if (webPartInfo == null)
        {
            return null;
        }

        // Build the result
        var resource = new CMSOutputResource()
        {
            Data = HTMLHelper.ResolveCSSUrls(webPartInfo.WebPartCSS, URLHelper.ApplicationPath),
            LastModified = webPartInfo.WebPartLastModified,
            Etag = "webpart|" + webPartInfo.WebPartName,
            FileName = ValidationHelper.GetSafeFileName(webPartInfo.WebPartName) + ".css",
            Extension = ".css"
        };

        return resource;
    }
Ejemplo n.º 45
0
 /// <summary>
 /// Processes the stylesheet.
 /// </summary>
 protected void ProcessStylesheet()
 {
     // Newsletter template stylesheet
     if (!string.IsNullOrEmpty(newsletterTemplateName))
     {
         // Get the template
         et = EmailTemplateInfoProvider.GetEmailTemplateInfo(newsletterTemplateName, SiteContext.CurrentSiteID);
         if (et != null)
         {
             // Create the output file
             outputFile = new CMSOutputResource
             {
                 Name = RequestContext.URL.ToString(),
                 Data = HTMLHelper.ResolveCSSUrls(et.TemplateStylesheetText, SystemContext.ApplicationPath),
                 Etag = et.TemplateName
             };
         }
     }
 }
    /// <summary>
    /// Checks if resource in the client cache matches the server version.
    /// </summary>
    /// <param name="context">An HTTPContext object that provides references to the intrinsic server objects used to service HTTP requests</param>
    /// <param name="resource">Resource to check</param>
    /// <returns>true, if resource is unchanged, otherwise false</returns>
    private static bool IsResourceUnchanged(HttpContext context, CMSOutputResource resource)
    {
        // Determine the last modified date and etag sent from the browser
        string currentETag = RequestHelper.GetHeader("If-None-Match", string.Empty);
        string ifModified = RequestHelper.GetHeader("If-Modified-Since", string.Empty);

        // If resources match, compare last modification timestamps
        if ((ifModified != string.Empty) && (currentETag == resource.Etag))
        {
            // Get first part of header (colons can delimit additional data)
            DateTime modifiedStamp;
            if (DateTime.TryParse(ifModified.Split(";".ToCharArray())[0], out modifiedStamp))
            {
                return (resource.LastModified.ToUniversalTime() <= modifiedStamp.ToUniversalTime().AddSeconds(1));
            }
        }

        return false;
    }
Ejemplo n.º 47
0
    /// <summary>
    /// Sends a response containing the requested data.
    /// </summary>
    /// <param name="context">An HTTPContext object that provides references to the intrinsic server objects used to service HTTP requests</param>
    /// <param name="resource">Container with the data to serve</param>
    /// <param name="contentType">Content type to use when sending a response</param>
    /// <param name="allowCache">True, if client caching is enabled, otherwise false</param>
    /// <param name="minificationEnabled">True, if the data can be served minified, otherwise false</param>
    /// <param name="clientCacheMinutes">Number of minutes after which the content in the client cache expires</param>
    private static void SendResponse(HttpContext context, CMSOutputResource resource, string contentType, bool allowCache, bool minificationEnabled, int clientCacheMinutes)
    {
        // Set client cache revalidation
        SetRevalidation(context);

        // Let client use data cached in browser if versions match and there was no change in data
        if (allowCache && IsResourceUnchanged(context, resource))
        {
            SendNotModifiedResponse(context, resource.LastModified, resource.Etag, clientCacheMinutes, true);
            return;
        }
        else
        {
            // Otherwise get content to send
            string contentCoding;
            byte[] content = GetOutputData(context, resource, minificationEnabled, out contentCoding);

            // Set client caching
            if (allowCache)
            {
                SetClientCaching(context, allowCache, resource.LastModified, resource.Etag, clientCacheMinutes);
            }

            if (contentCoding != ContentCodingEnum.IDENTITY)
            {
                context.Response.AppendHeader("Content-Encoding", contentCoding);
                context.Response.AppendHeader("Vary", "Content-Encoding");
            }

            context.Response.ContentType = contentType;

            // Do not send output if there's none
            if (content.Length > 0)
            {
                context.Response.OutputStream.Write(content, 0, content.Length);
            }
        }
    }
Ejemplo n.º 48
0
    /// <summary>
    /// Retrieves the stylesheets of the web part layout from the database.
    /// </summary>
    /// <param name="layoutFullName">Layout full name</param>
    /// <returns>The stylesheet data (plain version only)</returns>
    private static CMSOutputResource GetWebPartLayout(string layoutFullName)
    {
        WebPartLayoutInfo layoutInfo = WebPartLayoutInfoProvider.GetWebPartLayoutInfo(layoutFullName);
        if (layoutInfo == null)
        {
            return null;
        }

        // Build the result
        CMSOutputResource resource = new CMSOutputResource()
        {
            Data = HTMLHelper.ResolveCSSUrls(layoutInfo.WebPartLayoutCSS, URLHelper.ApplicationPath),
            LastModified = layoutInfo.WebPartLayoutLastModified,
            Etag = layoutInfo.WebPartLayoutFullName
        };

        return resource;
    }