protected override void Initialize(System.Web.Routing.RequestContext requestContext)
        {
            base.Initialize(requestContext);
            string sitePath = CmsRoute.GetSitePath();

            _Authman = AuthenticationManager.Get(sitePath);
        }
        public static void RedirectToControllerAction(CmsPage page, string[] parameters)
        {
            if (!page.IsAvailable)
            {
                PageHasExpired();
                return;
            }

            var type           = GetControllerType(page);
            var controller     = (Controller)Activator.CreateInstance(type);
            var controllerName = StripEnd(type.Name.ToLowerInvariant(), "controller");
            var httpContext    = new HttpContextWrapper(HttpContext.Current);
            var route          = new CmsRoute(page.PageUrl.ToString().TrimStart('/') + "{action}", new MvcRouteHandler());
            var routeData      = route.GetRouteData(httpContext);

            if (routeData == null)
            {
                var message = string.Format("Not an action /{0}/{1}/", controllerName, string.Join("/", parameters));
                throw new Exception(message);
            }

            routeData.Values["controller"]  = controllerName;
            routeData.Values["currentPage"] = ((IPageController)controller).GetTypedPage(page);

            HttpContext.Current.Response.Clear();
            var requestContext = new RequestContext(new HttpContextWrapper(HttpContext.Current), routeData);

            ((IController)controller).Execute(requestContext);
            HttpContext.Current.ApplicationInstance.CompleteRequest();
        }
        protected override void Initialize(System.Web.Routing.RequestContext requestContext)
        {
            base.Initialize(requestContext);

            string sitePath = CmsRoute.GetSitePath();

            isPreviewRequest  = requestContext.HttpContext.Request.QueryString["_previewAsset_"] == "true";
            isPreviewRequest |= Reference.Reference.IsDesignTime(sitePath);

            if (isPreviewRequest)
            {
                HttpApplicationStateBase application = requestContext.HttpContext.Application;
                _GetContentStore(requestContext, application);
            }

            //check if the asset followed with querystring "previewAsset"
            AssetBasePath = (isPreviewRequest) ?
                            ConfigurationManager.AppSettings["DesignTimeAssetsLocation"] :
                            sitePath;

            if (string.IsNullOrEmpty(AssetBasePath))
            {
                AssetBasePath = sitePath;
            }

            Authman = AuthenticationManager.Get(sitePath);
        }
示例#4
0
        private void InjectMvcRoute()
        {
            var route = new CmsRoute("{cmsPageUrl}/{action}", new MvcRouteHandler())
            {
                Constraints = new RouteValueDictionary {
                    { "cmsPageUrl", new CmsRouteConstraint() }
                },
                Defaults = new RouteValueDictionary {
                    { "action", "Index" }
                }
            };

            RouteTable.Routes.Insert(0, route);
        }
示例#5
0
        protected override void Initialize(System.Web.Routing.RequestContext requestContext)
        {
            base.Initialize(requestContext);

            SitePath          = CmsRoute.GetSitePath();
            isPreviewRequest  = requestContext.HttpContext.Request.QueryString["_previewAsset_"] == "true";
            isPreviewRequest |= Reference.Reference.IsDesignTime(SitePath);

            if (isPreviewRequest)
            {
                HttpApplicationStateBase application = requestContext.HttpContext.Application;
                _GetContentStore(requestContext, application);
            }
        }
示例#6
0
        public PageModel GetPage(string pageUrl = "/")
        {
            //System.Diagnostics.Debugger.Launch();
            if (!pageUrl.StartsWith("/") && !pageUrl.IsXId())
            {
                pageUrl = $"/{pageUrl}";
            }
            string          sitePath    = CmsRoute.GetSitePath();
            var             context     = new HttpContextWrapper(HttpContext.Current);
            HttpRequestBase _request    = context.Request;
            CMSPageFactory  pageFactory = new CMSPageFactory(sitePath);
            ICMSPage        page;

            if (!pageUrl.IsXId())
            {
                page = pageFactory.GetPageByPath(_request, pageUrl) as ICMSPage;
            }
            else
            {
                page = pageFactory.GetPage(_request, pageUrl) as ICMSPage;
            }

            if (page == null)
            {
                throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.NotFound, "this item does not exist"));
            }

            Request.Properties[IGXWebApiCacheAttribute.NAVS_CACHED_PROP_NAME] = (page as CMSPageRequest).NavigationUsingCacheContent;

            var eleExceptions  = new ElementModel().ElementExceptionList;
            var attrExceptions = new ElementModel().AttributeExceptionList;

            var pageModel = new PageModel()
            {
                Attributes = page
                             .Attributes()
                             .Where(pageAttrs => !attrExceptions.Contains(pageAttrs.AttributeName))
                             .ToDictionary(pageAttrs => pageAttrs.AttributeName, pageAttrs => pageAttrs.Value),
                Elements = page
                           .Elements()
                           .Select(e => new ElementModel(e)).Where(e => !eleExceptions.Contains(e.Name))
            };

            pageModel.Attributes.Add("TestTime", System.DateTime.Now.ToString());

            return(pageModel);
        }
示例#7
0
        public ActionResult AssetMetaData(string assetIdNum, string isCheckedIn)
        {
            string   assetId = assetIdNum.StartsWith("a/") ? assetIdNum : "a/" + assetIdNum;
            DateTime now     = DateTime.Now;
            XElement ele;

            if (isPreviewRequest)
            {
                using (IUserSession session = _ContentStore.OpenReadSession(_CurrentUser))
                {
                    var map   = Assets.DocumentPreviewAssetFactory.Get(session);
                    var asset = map.GetAssetByID(assetId);

                    if (asset == null)
                    {
                        throw new HttpException(404, string.Format("Asset {0} not found.", assetId));
                    }
                    if (!asset.Valid())
                    {
                        throw new HttpException(404, string.Format("Asset {0} is invalid.", asset.FilePath));
                    }

                    ele = asset.Metadata.Serialize();
                }
            }
            else
            {
                SitePath = CmsRoute.GetSitePath();
                var map   = Assets.AssetFactory.Get(SitePath);
                var asset = map.GetAssetByID(assetId);

                if (asset == null)
                {
                    throw new HttpException(404, string.Format("Asset {0} not found.", assetId));
                }
                if (!asset.Valid())
                {
                    throw new HttpException(404, string.Format("Asset {0} is invalid.", asset.FilePath));
                }

                ele = asset.Metadata.Serialize();
            }

            return(new XmlResult(ele));
        }
示例#8
0
        protected override void Initialize(System.Web.Routing.RequestContext requestContext)
        {
            base.Initialize(requestContext);

            _SitePath = CmsRoute.GetSitePath();

            _DTSitePath = ConfigurationManager.AppSettings["DesignTimeAssetsLocation"]
                          .ToNullOrEmptyHelper()
                          .Return(_SitePath);
            _AllowTfrm = ConfigurationManager.AppSettings["EnableTFRMParameter"].ToNullHelper().Branch(
                str => str.Trim().ToLowerInvariant() == "true",
                () => true);
            _LegacyTransformation = ConfigurationManager.AppSettings["LegacyRendering"].ToNullHelper()
                                    .Branch(
                str => str.Trim().ToLowerInvariant() != "false",
                () => true);

            _UseTempStylesheetsLocation = ConfigurationManager.AppSettings["UseTempStylesheetsLocation"].ToNullHelper().Branch(str => str.Trim().ToLowerInvariant() != "false", () => true);

            _IsDesignTime = Reference.Reference.IsDesignTime(_SitePath);

            try
            {
                //page factory is a cheap object to construct, since both surl map and ssmap are cached most time
                _PageFactory = CMSPageFactoryHelper.GetPageFactory(_IsDesignTime, _SitePath, requestContext, _LegacyTransformation, out _IsDTAuthenticated) as CMSPageFactory;
            }
            catch (Ingeniux.CMS.Exceptions.LicensingException e)
            {
                if (e.Expired)
                {
                    _InvalidPageResult = new XmlResult(
                        new XElement("TrialLicenseExpired",
                                     new XAttribute("ExpirationDateUTC", e.ExpirationDate.ToIso8601DateString(true)),
                                     new XElement("IngeniuxSupport",
                                                  new XAttribute("Phone", "1.877.299.8900"),
                                                  new XAttribute("Email", "*****@*****.**"),
                                                  new XAttribute("Portal", "http://support.ingeniux.com/"))));
                }
                else
                {
                    _InvalidPageResult = new XmlResult(
                        new XElement("InvalidCMSLicense",
                                     new XElement("IngeniuxSupport",
                                                  new XAttribute("Phone", "1.877.299.8900"),
                                                  new XAttribute("Email", "*****@*****.**"),
                                                  new XAttribute("Portal", "http://support.ingeniux.com/"))));
                }
            }

            if (_InvalidPageResult == null)
            {
                if (_PageFactory.CacheSiteControls)
                {
                    // only set site control schemas when list is not empty
                    string[] siteControlSchemas = ConfigurationManager.AppSettings["SiteControlSchemas"].ToNullHelper().Branch <string[]>(
                        str => str.Split(';').Select(
                            s => s.Trim()).Where(
                            s => s != "").ToArray(),
                        () => new string[] { });

                    if (siteControlSchemas.Length > 0)
                    {
                        _PageFactory.SiteControlSchemas = siteControlSchemas;
                    }
                }

                _PageFactory.LocalExportsIncludeLinks = ConfigurationManager.AppSettings["LocalExportsIncludeLinks"].ToNullHelper().Branch <bool>(
                    str => str.Trim().ToLowerInvariant() == "true",
                    () => true);

                //move page getting to here so it can be used to OnActionExecuting
                try
                {
                    _CMSPageRoutingRequest = _PageFactory.GetPage(Request, false);
                }
                catch (DesignTimeInvalidPageIDException exp)
                {
                    //this message is exclusive to design time and need to present a special page
                    _InvalidPageResult = new XmlResult(new XElement("DynamicPreviewError", exp.Message));
                }
            }

            if (_CMSPageRoutingRequest != null && string.IsNullOrWhiteSpace(_CMSPageRoutingRequest.RemaingPath))
            {
                HttpContext.Items["PageRequest"] = _CMSPageRoutingRequest;
            }
        }
示例#9
0
        public ActionResult Asset(string assetIdNum, string isCheckedIn)
        {
            string   assetId = "a/" + assetIdNum;
            DateTime now     = DateTime.Now;

            if (isPreviewRequest)
            {
                using (IUserSession session = _ContentStore.OpenReadSession(_CurrentUser))
                {
                    IAsset asset = session.Site.Asset(assetId);

                    if (asset.IsExternal)
                    {
                        Response.Redirect(asset.ExternalUrl, true);
                    }

                    if (asset == null || asset.StartDate > now)
                    {
                        throw new HttpException(404, string.Format("Asset {0} not found.", assetId));
                    }
                    if (asset.EndDate < now)
                    {
                        throw new HttpException(404, string.Format("Asset {0} has expired.", assetId));
                    }

                    FileInfo file     = asset.File();
                    string   mimeType = MimeMapping.GetMimeMapping(file.FullName);
                    return(new RangeFilePathResult(mimeType, file.FullName, file.LastWriteTimeUtc, file.Length));
                    //return base.File(file.FullName, mimeType);
                }
            }
            else
            {
                SitePath = CmsRoute.GetSitePath();
                Assets.AssetFactory map = Assets.AssetFactory.Get(SitePath);
                var assetMapEntry       = map.GetAssetByID(assetId);

                Assets.AssetTree tree = Assets.AssetTree.Get(CmsRoute.GetSitePath());
                var assetTreeEntry    = tree.GetNode(assetId);
                if (assetTreeEntry != null && !assetTreeEntry.Valid())
                {
                    if (assetMapEntry != null)
                    {
                        throw new HttpException(404, string.Format("Asset {0} is invalid.", assetMapEntry.Url));
                    }
                    else
                    {
                        throw new HttpException(404, string.Format("Asset {0} is invalid.", assetId));
                    }
                }

                if (assetMapEntry != null && assetMapEntry.IsExternal)
                {
                    Response.Redirect(assetMapEntry.FilePath, true);
                }

                if (assetMapEntry == null)
                {
                    throw new HttpException(404, string.Format("Asset {0} not found.", assetId));
                }
                if (!assetMapEntry.Valid())
                {
                    throw new HttpException(404, string.Format("Asset {0} is invalid.", assetMapEntry.FilePath));
                }

                string   filePath = Uri.UnescapeDataString(assetMapEntry.FilePath);
                FileInfo file     = new FileInfo(filePath);
                string   mimeType = MimeMapping.GetMimeMapping(file.FullName);

                if (file.Length == 0)
                {
                    return(File(file.FullName, mimeType));
                }

                return(new RangeFilePathResult(mimeType, file.FullName, file.LastWriteTimeUtc, file.Length));
                //return base.File(file.FullName, mimeType);
            }
        }
        public async Task <ActionResult> Get()
        {
            string path = HttpUtility.UrlDecode(Request.GetRelativePath())
                          .ToLowerInvariant();

            if (path.StartsWith("http:/"))
            {
                path = "http://" + path.SubstringAfter("http:/");
                Response.Redirect(path, true);
            }
            else if (path.StartsWith("https:/"))
            {
                path = "https://" + path.SubstringAfter("https:/");
                Response.Redirect(path, true);
            }
            else if (path.StartsWith("ftp:/"))
            {
                path = "ftp://" + path.SubstringAfter("ftp:/");
                Response.Redirect(path, true);
            }

            //if it is going to ICE images, use a different system, get image content from resource
            if (path.ToLowerInvariant().EndsWith("images/_ice_/play.png"))
            {
                string ext = Path.GetExtension(path);
                //string mimeType = MIMEAssisant.GetMIMEType("png");
                string mimeType = MIMEAssistant.GetMIMEType("png");

                var image = Properties.Resources.play;

                MemoryStream ms = new MemoryStream();
                image.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
                ms.Position = 0;

                return(File(ms, mimeType));
            }
            else
            {
                path = path.ToLowerInvariant().TrimStart('/');
                Regex trimRE = new Regex(@"^((images|documents|media)\/)?assets\/");
                if (trimRE.IsMatch(path))
                {
                    path = path.SubstringAfter("assets/");
                }

                if (isPreviewRequest)
                {
                    // Pull the "assets" off the from of the path for preview. Publish puts it in 'assets'
                    path = (path.StartsWith("assets/") ? path.SubstringAfter("assets/") : path.TrimStart('/'));
                    using (var session = _ContentStore.OpenReadSession(_CurrentUser))
                    {
                        IAsset   asset = session.Site.AssetByPath(path);
                        FileInfo file;
                        if (asset != null)
                        {
                            file = asset.File();
                        }
                        else
                        {
                            IUnmanagedAsset unmanaged = session.UnmanagedAssetManager.UnmanagedAsset(path);
                            if (unmanaged != null)
                            {
                                file = unmanaged.FileInfo;
                            }
                            else
                            {
                                throw new HttpException(404, string.Format("Asset for Preview {0} is missing.", path));
                            }
                        }

                        string mime = MimeMapping.GetMimeMapping(file.FullName);
                        return(new RangeFilePathResult(mime, file.FullName, file.LastWriteTimeUtc, file.Length));
                        //return base.File(file.FullName, mime);
                    }
                }

                //else
                //{
                //	path = "assets/" + (path.StartsWith("assets/") ? path.SubstringAfter("assets/") : path.TrimStart('/'));
                //}

                string assetPath = Path.Combine(AssetBasePath, path.TrimStart('/').Replace("/", @"\"));
                assetPath = Uri.UnescapeDataString(assetPath);
                //if (!path.ToLowerInvariant().StartsWith("assets/") && !System.IO.File.Exists(assetPath))
                //{
                //	path = "assets\\" + path.TrimStart('/').Replace("/", @"\");
                //	assetPath = Path.Combine(AssetBasePath, path);
                //}

                Assets.AssetFactory map           = Assets.AssetFactory.Get(CmsRoute.GetSitePath());
                Assets.IAsset       assetMapEntry = map.GetAssetByPath(path);
                if (assetMapEntry != null)
                {
                    var assetId           = assetMapEntry.AssetId;
                    Assets.AssetTree tree = Assets.AssetTree.Get(CmsRoute.GetSitePath());
                    var assetTreeEntry    = tree.GetNode(assetId);
                    if (assetTreeEntry != null && !assetTreeEntry.Valid())
                    {
                        throw new HttpException(404, string.Format("Asset {0} is invalid.", assetPath));
                    }

                    assetPath = assetMapEntry.FilePath;

                    if (assetMapEntry.IsExternal)
                    {
                        Response.Redirect(assetPath);
                    }
                }
                else
                {
                    throw new HttpException(404, string.Format("Asset {0} is invalid.", assetPath));
                }

                //block any access in settings folder
                string settingsFolder = Path.Combine(AssetBasePath, "settings").ToLowerInvariant() + @"\";
                if (assetPath.ToLowerInvariant().StartsWith(settingsFolder))
                {
                    throw new HttpException((int)AssetRequestState.Forbidden, Ingeniux.Runtime.Properties.Resources.AccessToDynamicSiteServerMetaDataIsForbidd);
                }

                if (!System.IO.File.Exists(assetPath))
                {
                    path = path.Replace("\\", "/");
                    if (path.StartsWith("assets/"))
                    {
                        path = "/" + path.SubstringAfter("assets/");
                    }
                    var urlmap      = Runtime.StructureUrlMap.Get(CmsRoute.GetSitePath());
                    var urlmapEntry = urlmap.GetPageDataByPath(path);
                    if (urlmapEntry != null)
                    {
                        CMSPageDefaultController pageController = initPageController();
                        return(pageController.Index());
                    }
                    else
                    {
                        throw new HttpException(404, Ingeniux.Runtime.Properties.Resources.AssetDoesnTExist);
                    }
                }

                DateTime lastWriteTime = System.IO.File.GetLastWriteTime(assetPath);

                if (!changed(lastWriteTime))
                {
                    return(new HttpStatusCodeResult(304));
                }

                string ext = Path.GetExtension(assetPath).TrimStart('.');

                string mimeType = MIMEAssistant.GetMIMEType(ext);

                bool isAttachment = path.StartsWith("documents/") || mimeType == MIMEAssistant.DEFAULT_MIME_TYPE;

                //if (isAttachment)
                //	Response.AddHeader("Content-Disposition", "attachment");

                string thisUrl = Request.Url.AbsoluteUri;

                if (!isPreviewRequest)
                {
                    //if (Authman.IsForbiddenAsset(path) || Authman.IsProtectedAsset(path) || isAttachment)
                    //{
                    //	setNoCache();
                    //}
                    //else
                    //{
                    //	Response.Cache.SetCacheability(HttpCacheability.ServerAndPrivate);
                    //	//Response.Cache.SetExpires(DateTime.MaxValue);
                    //	Response.CacheControl = "private";
                    //	Response.Cache.SetLastModified(System.IO.File.GetLastWriteTime(assetPath));
                    //}

                    //when runtime request, check protected and forbidden folder
                    AssetRequestState stateCheck = Authman.CheckAssetAccessiblility(path, Request);
                    if (stateCheck == AssetRequestState.Forbidden)
                    {
                        string forbiddenResponsePagePath = AuthenticationManager.Settings.ForbiddenFoldersResponsePage;

                        //path is blocked, go to forbidden response page
                        if (!string.IsNullOrWhiteSpace(forbiddenResponsePagePath))
                        {
                            if (!forbiddenResponsePagePath.EndsWith(".xml") || !forbiddenResponsePagePath.SubstringBefore(".", false, true).IsXId())
                            {
                                string fullRedirPath = forbiddenResponsePagePath.ToAbsoluteUrl();
                                fullRedirPath += fullRedirPath.Contains("?") ? "&" : "?";
                                fullRedirPath += "blockedPath=" + HttpUtility.UrlEncode(HttpUtility.UrlEncode(thisUrl));

                                return(Redirect(fullRedirPath));
                            }
                            else
                            {
                                //if the setting is standar xid.xml, then use more friendly path rewrite
                                return(rewriteToCmsPath(
                                           forbiddenResponsePagePath.SubstringBefore(".", false, true),
                                           new Dictionary <string, string> {
                                    { "blockedPath", thisUrl }
                                }));
                            }
                        }
                        else
                        {
                            throw new HttpException((int)stateCheck, Ingeniux.Runtime.Properties.Resources.AccessToAssetIsForbidden);
                        }
                    }

                    if (stateCheck == AssetRequestState.Unauthorized)
                    {
                        string loginPagePath = Authman.LoginPath;
                        if (!string.IsNullOrWhiteSpace(loginPagePath))
                        {
                            string loginPathUrl = loginPagePath.ToAbsoluteUrl();
                            loginPathUrl += loginPathUrl.Contains("?") ? "&" : "?";
                            loginPathUrl += AuthenticationManager.Settings.RedirectionQueryStringName + "=" + Uri.EscapeDataString(Uri.EscapeDataString(thisUrl));
                            return(RedirectPermanent(loginPathUrl));
                        }
                        else
                        {
                            throw new HttpException((int)stateCheck, Ingeniux.Runtime.Properties.Resources.AccessToAssetIsNotAuthorized);
                        }
                    }

                    //use download manager if is protected asset, this way we can use the download page
                    if (!string.IsNullOrWhiteSpace(AuthenticationManager.Settings.BinaryDownloadPage) && Authman.IsProtectedAsset(path))
                    {
                        DownloadManager             downloadsMan = Authman.DownloadsManager;
                        string                      downloadPageId;
                        Dictionary <string, string> queryStrings = new Dictionary <string, string>();
                        bool presentDownloadPage = downloadsMan.ProcessProtectedDownload(Request.RequestContext.HttpContext,
                                                                                         out queryStrings, out downloadPageId);

                        if (presentDownloadPage)
                        {
                            //Response.AddHeader("Content-Disposition", "attachment");

                            //return File(assetPath, mimeType);
                            return(rewriteToCmsPath(downloadPageId, queryStrings));
                        }

                        //return rewriteToCmsPath(downloadPageId, queryStrings);
                    }
                }

                setCacheResponses(ext, mimeType, path);

                var forceDownloadDocuments = ConfigurationManager.AppSettings["ForceDownloadDocuments"] != null ?
                                             ConfigurationManager.AppSettings["ForceDownloadDocuments"].ToBoolean() : true;

                var bypassDownloadDocTypes = ConfigurationManager.AppSettings["DocumentExtBypassDownload"] != null ?
                                             ConfigurationManager.AppSettings["DocumentExtBypassDownload"].Split(';') : new string[] { "" };

                if (isAttachment && (forceDownloadDocuments && !bypassDownloadDocTypes.Contains(ext)))
                {
                    Response.AddHeader("Content-Disposition", "attachment");
                }

                FileInfo assetInfo = new FileInfo(assetPath);

                if (assetInfo.Length == 0)
                {
                    return(File(assetPath, mimeType));
                }

                try
                {
                    return(new RangeFilePathResult(mimeType, assetInfo.FullName, assetInfo.LastWriteTimeUtc, assetInfo.Length));
                    //return File(assetPath, mimeType);
                }
                catch (Exception e)
                {
                    return(File(assetPath, mimeType));
                }
            }
        }