Example #1
0
        /*
         * This Key generated used to be in the PolicyPartDriver. It is reproduced here because
         * its logic was replicating what is already done here. However it was adding some potentially
         * useful bits to the cachekey, so those are moved here.
         *
         * public void KeyGenerated(StringBuilder key) {
         *  var part = _currentContentAccessor.CurrentContentItem.As<PolicyPart>();
         *  if (part == null) return;
         *
         *  if (_policyServices.HasPendingPolicies(part.ContentItem) ?? false) {
         *      _additionalCacheKey = "policy-not-accepted;";
         *      _additionalCacheKey += "pendingitempolicies=" + String.Join("_", _policyServices.PendingPolicies(part.ContentItem).Select(s => s.Id)) + ";";
         *  }
         *  else {
         *      _additionalCacheKey = "policy-accepted;";
         *  }
         *
         *  key.Append(_additionalCacheKey);
         * }
         */

        private void SetPendingPolicies()
        {
            if (pendingPolicies != null)
            {
                return;
            }

            IContent content = CurrentContent();

            //_maxLevel = maxLevel;
            if (content != null)
            {
                // content would be null if rather than on a content item we are trying
                // to go to a controller aciton. Those should manage their own permissions
                // and caching so they would not have to be handled here
                var policy = content.As <Models.PolicyPart>();
                if (policy != null && (_policyServices.HasPendingPolicies(content.ContentItem) ?? false))   // Se l'oggetto ha delle pending policies allora devo scrivere la lista delle pending policies
                {
                    pendingPolicies = _policyServices.PendingPolicies(content.ContentItem);
                }
                else
                {
                    pendingPolicies = new List <IContent>();
                }
            }
        }
        private void SetPendingPolicies()
        {
            if (pendingPolicies != null)
            {
                return;
            }
            var      routeData      = HttpContext.Current.Request.RequestContext.RouteData;
            string   areaName       = (routeData.Values["area"] ?? string.Empty).ToString();
            string   controllerName = (routeData.Values["controller"] ?? string.Empty).ToString();
            string   actionName     = (routeData.Values["action"] ?? string.Empty).ToString();
            string   alias;
            IContent content;

            if (areaName.Equals("Laser.Orchard.WebServices", StringComparison.InvariantCultureIgnoreCase) &&
                controllerName.Equals("WebApi", StringComparison.InvariantCultureIgnoreCase) &&
                actionName.Equals("display", StringComparison.InvariantCultureIgnoreCase))
            {
                // For our webapi, we determine the content through its alias
                alias   = (HttpContext.Current.Request.Params["alias"] ?? string.Empty).ToString();
                content = _commonServices.GetContentByAlias(alias);
            }
            else if (areaName.Equals("Laser.Orchard.Policy", StringComparison.InvariantCultureIgnoreCase) &&
                     controllerName.Equals("Policies", StringComparison.InvariantCultureIgnoreCase) &&
                     actionName.Equals("Index", StringComparison.InvariantCultureIgnoreCase))
            {
                // since we also cache the page where we ask to accept the policies,
                // and that's on a specific controller, we do need to figure out the content item
                // we are preventing the used to see
                alias   = (HttpContext.Current.Request.Params["alias"] ?? string.Empty).ToString();
                content = _commonServices.GetContentByAlias(alias);
            }
            else
            {
                // this is the "normal" case, in which we are accessing a contentitem
                // directly on its display view
                content = _currenContent.CurrentContentItem;
            }
            //_maxLevel = maxLevel;
            if (content != null)
            {
                // content would be null if rather than on a content item we are trying
                // to go to a controller aciton. Those should manage their own permissions
                // and caching so they would not have to be handled here
                var policy = content.As <Models.PolicyPart>();
                if (policy != null && (_policyServices.HasPendingPolicies(content.ContentItem) ?? false))   // Se l'oggetto ha delle pending policies allora devo scrivere la lista delle pending policies
                {
                    pendingPolicies = _policyServices.PendingPolicies(content.ContentItem);
                }
                else
                {
                    pendingPolicies = new List <IContent>();
                }
            }
        }
        /// <summary>
        /// Called by OutputCache after the default cache key has been defined.
        /// </summary>
        /// <param name="key">Default cache key such as defined in Orchard.OutputCache.</param>
        public void KeyGenerated(StringBuilder key)
        {
            var part = _currentContentAccessor.CurrentContentItem.As <PolicyPart>();

            if (part == null)
            {
                return;
            }

            if (_policyServices.HasPendingPolicies(part.ContentItem) ?? false)
            {
                _additionalCacheKey  = "policy-not-accepted;";
                _additionalCacheKey += "pendingitempolicies=" + String.Join("_", _policyServices.PendingPolicies(part.ContentItem).Select(s => s.Id)) + ";";
            }
            else
            {
                _additionalCacheKey = "policy-accepted;";
            }

            key.Append(_additionalCacheKey);
        }
        private ActionResult GetContent(IContent content, SourceTypes sourceType = SourceTypes.ContentItem, ResultTarget resultTarget = ResultTarget.Contents, string fieldspartsFilter = "", int page = 1, int pageSize = 10, bool tinyResponse = true, bool minified = false, bool realformat = false, int deeplevel = 10, string[] complexBehaviour = null)
        {
            var result = new ContentResult {
                ContentType = "application/json"
            };
            var jsonString = "{}";

            var      _filterContentFieldsParts = fieldspartsFilter.ToLower().Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
            XElement dump;
            XElement projectionDump = null;
            // il dump dell'oggetto principale non filtra per field
            ObjectDumper    dumper = new ObjectDumper(deeplevel, null, false, tinyResponse, complexBehaviour);
            dynamic         shape; //, specificShape;
            var             sb          = new StringBuilder();
            List <XElement> listContent = new List <XElement>();

            // verifico se l'oggetto è soggetto all'accettazione delle policies
            var policy = content.As <Policy.Models.PolicyPart>();

            //if (policy != null) {
            //    if ((String.IsNullOrWhiteSpace(_orchardServices.WorkContext.HttpContext.Request.QueryString["v"]))) {// E' soggetto a privacy, quindi faccio sempre il redirect se manca il parametro in querystring v=
            //        if (policy.HasPendingPolicies ?? false) { // se ha delle pending policies deve restituire le policy text, legate al contenuto, qui ndi non deve mai servire cache
            //            var redirectUrl = String.Format("{0}{1}v={2}", _orchardServices.WorkContext.HttpContext.Request.RawUrl, (_orchardServices.WorkContext.HttpContext.Request.RawUrl.Contains("?") ? "&" : "?"), Guid.NewGuid());
            //            _orchardServices.WorkContext.HttpContext.Response.Redirect(redirectUrl, true);
            //        } else {// se NON ha delle pending policies deve restituire un url non cacheato (quindi aggiungo v=),
            //            var redirectUrl = String.Format("{0}{1}v={2}", _orchardServices.WorkContext.HttpContext.Request.RawUrl, (_orchardServices.WorkContext.HttpContext.Request.RawUrl.Contains("?") ? "&" : "?"), "cached-content");
            //            _orchardServices.WorkContext.HttpContext.Response.Redirect(redirectUrl, true);
            //            //_orchardServices.WorkContext.HttpContext.Response.Redirect(redirectUrl, true);
            //        }
            //        return null; // in entrambi i casi ritorno null come risultato della current request
            //    }
            //}
            if (policy != null && (_policyServices.HasPendingPolicies(content.ContentItem) ?? false))   // Se l'oggetto ha delle pending policies allora devo serivre la lista delle pending policies
            //policy.PendingPolicies
            {
                sb.Insert(0, "{");
                sb.AppendFormat("\"n\": \"{0}\"", "Model");
                sb.AppendFormat(", \"v\": \"{0}\"", "VirtualContent");
                sb.Append(", \"m\": [{");
                sb.AppendFormat("\"n\": \"{0}\"", "VirtualId"); // Unused property for mobile mapper needs
                sb.AppendFormat(", \"v\": \"{0}\"", "0");
                sb.Append("}]");

                sb.Append(", \"l\":[");

                int i = 0;
                sb.Append("{");
                sb.AppendFormat("\"n\": \"{0}\"", "PendingPolicies");
                sb.AppendFormat(", \"v\": \"{0}\"", "ContentItem[]");
                sb.Append(", \"m\": [");

                foreach (var item in _policyServices.PendingPolicies(content.ContentItem))
                {
                    if (i > 0)
                    {
                        sb.Append(",");
                    }
                    sb.Append("{");
                    dumper         = new ObjectDumper(deeplevel, _filterContentFieldsParts, false, tinyResponse, complexBehaviour);
                    projectionDump = dumper.Dump(item, String.Format("[{0}]", i));
                    JsonConverter.ConvertToJSon(projectionDump, sb, minified, realformat);
                    sb.Append("}");
                    i++;
                }
                sb.Append("]");
                sb.Append("}");

                sb.Append("]"); // l : [
                sb.Append("}");
            }
            else     // Se l'oggetto NON ha delle pending policies allora posso servire l'oggetto stesso
            {
                shape = _orchardServices.ContentManager.BuildDisplay(content);
                if (sourceType == SourceTypes.ContentItem)
                {
                    dump = dumper.Dump(content, "Model");
                }
                else
                {
                    dump = dumper.Dump(shape, "Model");
                }
                //dump.XPathSelectElements("");
                //var filteredDump = dump.Descendants();
                //ConvertToJSon(dump, sb);
                JsonConverter.ConvertToJSon(dump, sb, minified, realformat);
                sb.Insert(0, "{");
                sb.Append(", \"l\":[");
                // Dopo avere convertito il contentItem in JSON aggiungo i Json delle eventuali liste
                dynamic part                 = null;
                var     firstList            = true;
                var     listDumpedContentIds = new List <int>();

                #region [ProjectionPart ]

                try {
                    part = shape.ContentItem.ProjectionPart;
                } catch {
                    part = null;
                }
                if (part != null)
                {
                    if (!firstList)
                    {
                        sb.Append(",");
                    }
                    firstList = false;
                    var queryId    = part.Record.QueryPartRecord.Id;
                    var queryItems = _projectionManager.GetContentItems(queryId, (page - 1) * pageSize, pageSize);
                    int i          = 0;
                    sb.Append("{");
                    sb.AppendFormat("\"n\": \"{0}\"", "ProjectionList");
                    sb.AppendFormat(", \"v\": \"{0}\"", "ContentItem[]");
                    sb.Append(", \"m\": [");

                    foreach (var item in queryItems)
                    {
                        if (i > 0)
                        {
                            sb.Append(",");
                        }
                        sb.Append("{");
                        dumper         = new ObjectDumper(deeplevel, _filterContentFieldsParts, false, tinyResponse, complexBehaviour);
                        projectionDump = dumper.Dump(item, String.Format("[{0}]", i));
                        JsonConverter.ConvertToJSon(projectionDump, sb, minified, realformat);
                        sb.Append("}");
                        i++;
                    }
                    sb.Append("]");
                    sb.Append("}");
                }
                part = null;

                #endregion [ProjectionPart ]

                #region [CalendarPart ]

                try {
                    part = shape.ContentItem.CalendarPart;
                } catch {
                    part = null;
                }
                if (part != null)
                {
                    if (!firstList)
                    {
                        sb.Append(",");
                    }
                    firstList = false;
                    if (_orchardServices.WorkContext.TryResolve <IEventsService>(out _eventsService))  // non sempre questo modulo è attivo quindi se non riesce a risolvere il servizio, bypassa la chiamata
                    {
                        var queryItems = _eventsService.GetAggregatedList(part, page, pageSize);
                        int i          = 0;
                        sb.Append("{");
                        sb.AppendFormat("\"n\": \"{0}\"", "EventList");
                        sb.AppendFormat(", \"v\": \"{0}\"", "ContentItem[]");
                        sb.Append(", \"m\": [");

                        foreach (var item in queryItems)
                        {
                            if (i > 0)
                            {
                                sb.Append(",");
                            }
                            sb.Append("{");
                            dumper         = new ObjectDumper(deeplevel, _filterContentFieldsParts, false, tinyResponse, complexBehaviour);
                            projectionDump = dumper.Dump(item, String.Format("[{0}]", i));
                            JsonConverter.ConvertToJSon(projectionDump, sb);
                            sb.Append("}");
                            i++;
                        }
                        sb.Append("]");
                        sb.Append("}");
                    }
                }
                part = null;

                #endregion [CalendarPart ]

                #region [ExernalField]

                var ExtertalFields = (dynamic)
                                     (from parte in ((ContentItem)shape.ContentItem).Parts
                                      from field in parte.Fields
                                      where (field.GetType().Name == "FieldExternal" && ((dynamic)field).Setting.GenerateL)
                                      select field).FirstOrDefault();
                if (ExtertalFields != null)
                {
                    if (!firstList)
                    {
                        sb.Append(",");
                    }
                    firstList = false;
                    //sb.Append("{");
                    //sb.AppendFormat("\"n\": \"{0}\"", "ExternalContent");
                    //sb.AppendFormat(", \"v\": \"{0}\"", "ExternalContent");
                    //sb.Append(", \"m\": [");

                    sb.Append("{");
                    dumper = new ObjectDumper(deeplevel, _filterContentFieldsParts, false, tinyResponse, complexBehaviour);
                    //nameDynamicJsonArray = "List<generic>";
                    if (ExtertalFields.ContentObject != null)
                    {
                        if (ExtertalFields.ContentObject.GetType() == typeof(ExternalFieldRemoteException))
                        {
                            throw new ExternalFieldRemoteException();
                        }
                        projectionDump = dumper.Dump(cleanobj(ExtertalFields.ContentObject), ExtertalFields.Name, "List<generic>");
                        JsonConverter.ConvertToJSon(projectionDump, sb, minified, realformat);
                    }
                    //    sb.Append("}]}");
                    sb.Append("}");
                }

                #endregion [ExernalField]

                #region [ WidgetsContainerPart ]

                try {
                    part = shape.ContentItem.WidgetsContainerPart;
                } catch {
                    part = null;
                }
                if (part != null)
                {
                    //var queryId = part.Record.QueryPartRecord.Id;
                    if (_orchardServices.WorkContext.TryResolve <IWidgetManager>(out _widgetManager))  // non semepre questo modulo è attivo quindi se non riesce a risolvere il servizio, bypassa la chiamata
                    {
                        if (!firstList)
                        {
                            sb.Append(",");
                        }
                        firstList = false;
                        var queryItems = _widgetManager.GetWidgets(part.Id);
                        int i          = 0;
                        sb.Append("{");
                        sb.AppendFormat("\"n\": \"{0}\"", "WidgetList");
                        sb.AppendFormat(", \"v\": \"{0}\"", "ContentItem[]");
                        sb.Append(", \"m\": [");

                        foreach (var item in queryItems)
                        {
                            if (i > 0)
                            {
                                sb.Append(",");
                            }
                            sb.Append("{");
                            dumper         = new ObjectDumper(deeplevel, _filterContentFieldsParts, false, tinyResponse, complexBehaviour);
                            projectionDump = dumper.Dump(item, String.Format("[{0}]", i));
                            JsonConverter.ConvertToJSon(projectionDump, sb, minified, realformat);
                            sb.Append("}");
                            i++;
                        }
                        sb.Append("]");
                        sb.Append("}");
                    }
                }

                #endregion [ WidgetsContainerPart ]

                #region [ Taxonomy/TermsPart ]

                part = null;
                try {
                    if (shape.ContentItem.ContentType.EndsWith("Term") || !String.IsNullOrWhiteSpace(shape.ContentItem.TypeDefinition.Settings["Taxonomy"]))
                    {
                        part = shape.ContentItem.TermPart;
                    }
                } catch {
                    part = null;
                }
                if (part != null)
                {
                    if (!firstList)
                    {
                        sb.Append(",");
                    }
                    firstList = false;
                    dynamic termContentItems;
                    if (resultTarget == ResultTarget.Terms)
                    {
                        termContentItems = _taxonomyService.GetChildren(part, true);
                    }
                    else if (resultTarget == ResultTarget.SubTerms)
                    {
                        termContentItems = _taxonomyService.GetChildren(part, false);
                    }
                    else
                    {
                        termContentItems = _taxonomyService.GetContentItems(part, (page - 1) * pageSize, pageSize);
                    }

                    int i = 0;
                    sb.Append("{");
                    if (resultTarget == ResultTarget.Contents)
                    {
                        sb.AppendFormat("\"n\": \"{0}\"", "TaxonomyTermList");
                        sb.AppendFormat(", \"v\": \"{0}\"", "ContentItem[]");
                    }
                    else
                    {
                        sb.AppendFormat("\"n\": \"{0}\"", "TermPartList");
                        sb.AppendFormat(", \"v\": \"{0}\"", "TermPart[]");
                    }
                    sb.Append(", \"m\": [");

                    foreach (var item in termContentItems)
                    {
                        if (i > 0)
                        {
                            sb.Append(",");
                        }
                        sb.Append("{");
                        dumper = new ObjectDumper(deeplevel, _filterContentFieldsParts, false, tinyResponse, complexBehaviour);
                        if (resultTarget == ResultTarget.Contents)
                        {
                            projectionDump = dumper.Dump(item.ContentItem, String.Format("[{0}]", i));
                            JsonConverter.ConvertToJSon(projectionDump, sb, minified, realformat);
                        }
                        else
                        {
                            var dumperForPart = new ObjectDumper(deeplevel, _filterContentFieldsParts, true, tinyResponse, complexBehaviour);
                            projectionDump = dumperForPart.Dump(item, "TermPart");
                            JsonConverter.ConvertToJSon(projectionDump, sb, minified, realformat);
                        }
                        sb.Append("}");
                        i++;
                    }
                    sb.Append("]");
                    sb.Append("}");
                }
                part = null;

                #endregion [ Taxonomy/TermsPart ]

                sb.Append("]"); // l : [
                sb.Append("}");
            }
            jsonString     = sb.ToString().Replace("\t", " ");
            result.Content = jsonString;
            return(result);
        }
Example #5
0
        private ActionResult GetContent(
            IContent content,
            SourceTypes sourceType    = SourceTypes.ContentItem,
            ResultTarget resultTarget = ResultTarget.Contents,
            string fieldspartsFilter  = "",
            int page                  = 1,
            int pageSize              = 10,
            bool tinyResponse         = true,
            bool minified             = false,
            bool realformat           = false,
            int deeplevel             = 10,
            string[] complexBehaviour = null)
        {
            var result = new ContentResult {
                ContentType = "application/json"
            };
            var jsonString = "{}";

            var      _filterContentFieldsParts = fieldspartsFilter.ToLower().Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
            XElement dump;
            XElement projectionDump = null;
            // il dump dell'oggetto principale non filtra per field
            ObjectDumper dumper = new ObjectDumper(deeplevel, null, false, tinyResponse, complexBehaviour);
            var          sb     = new StringBuilder();

            // verifico se l'oggetto è soggetto all'accettazione delle policies
            var policy = content.As <Policy.Models.PolicyPart>();

            if (policy != null)
            {
                if ((String.IsNullOrWhiteSpace(_orchardServices.WorkContext.HttpContext.Request.QueryString["v"]))) // E' soggetto a privacy, quindi faccio sempre il redirect se manca il parametro in querystring v=
                {
                    if (_policyServices.HasPendingPolicies(content.ContentItem) ?? false)                           // se ha delle pending policies deve restituire le policy text, legate al contenuto, quindi non deve mai servire cache
                    {
                        var redirectUrl = String.Format("{0}{1}v={2}", _orchardServices.WorkContext.HttpContext.Request.RawUrl, (_orchardServices.WorkContext.HttpContext.Request.RawUrl.Contains("?") ? "&" : "?"), Guid.NewGuid());
                        _orchardServices.WorkContext.HttpContext.Response.Redirect(redirectUrl, true);
                    }
                    else    // se NON ha delle pending policies deve restituire un url non cacheato (quindi aggiungo v=),
                    {
                        var redirectUrl = String.Format("{0}{1}v={2}", _orchardServices.WorkContext.HttpContext.Request.RawUrl, (_orchardServices.WorkContext.HttpContext.Request.RawUrl.Contains("?") ? "&" : "?"), "cached-content");
                        _orchardServices.WorkContext.HttpContext.Response.Redirect(redirectUrl, true);
                        //_orchardServices.WorkContext.HttpContext.Response.Redirect(redirectUrl, true);
                    }
                    return(null); // in entrambi i casi ritorno null come risultato della current request
                }
            }
            if (policy != null && (_policyServices.HasPendingPolicies(content.ContentItem) ?? false))   // Se l'oggetto ha delle pending policies allora devo serivre la lista delle pending policies
            //policy.PendingPolicies
            {
                sb.Insert(0, "{");
                sb.AppendFormat("\"n\": \"{0}\"", "Model");
                sb.AppendFormat(", \"v\": \"{0}\"", "VirtualContent");
                sb.Append(", \"m\": [{");
                sb.AppendFormat("\"n\": \"{0}\"", "VirtualId"); // Unused property for mobile mapper needs
                sb.AppendFormat(", \"v\": \"{0}\"", "0");
                sb.Append("}]");

                sb.Append(", \"l\":[");

                int i = 0;
                sb.Append("{");
                sb.AppendFormat("\"n\": \"{0}\"", "PendingPolicies");
                sb.AppendFormat(", \"v\": \"{0}\"", "ContentItem[]");
                sb.Append(", \"m\": [");

                foreach (var item in _policyServices.PendingPolicies(content.ContentItem))
                {
                    if (i > 0)
                    {
                        sb.Append(",");
                    }
                    sb.Append("{");
                    dumper         = new ObjectDumper(deeplevel, _filterContentFieldsParts, false, tinyResponse, complexBehaviour);
                    projectionDump = dumper.Dump(item, String.Format("[{0}]", i));
                    JsonConverter.ConvertToJSon(projectionDump, sb, minified, realformat);
                    sb.Append("}");
                    i++;
                }
                sb.Append("]");
                sb.Append("}");

                sb.Append("]"); // l : [
                sb.Append("}");
            }
            else     // Se l'oggetto NON ha delle pending policies allora posso servire l'oggetto stesso
            // Doing a IContentManager.Get here should ensure that the handlers that populate lazyfields
            // are executed, and all data in ContentParts and ContentField is initialized as it should.
            {
                content = _orchardServices.ContentManager.Get(content.Id, VersionOptions.Published);

                dump = dumper.Dump(content, "Model");

                JsonConverter.ConvertToJSon(dump, sb, minified, realformat);
                sb.Insert(0, "{");
                sb.Append(", \"l\":[");
                // Dopo avere convertito il contentItem in JSON aggiungo i Json delle eventuali liste

                var dumperContext = new DumperServiceContext(
                    content,
                    () =>
                    new ObjectDumper(deeplevel, _filterContentFieldsParts, false, tinyResponse, complexBehaviour),
                    (_xElement, _stringBuilder) =>
                    JsonConverter.ConvertToJSon(_xElement, _stringBuilder, minified, realformat),
                    resultTarget,
                    page, pageSize);
                foreach (var dumperService in _dumperServices)
                {
                    dumperService.DumpList(dumperContext);
                }
                sb.Append(string.Join(",", dumperContext.ContentLists));

                sb.Append("]"); // l : [
                sb.Append("}");
            }
            jsonString     = sb.ToString().Replace("\t", " ");
            result.Content = jsonString;
            return(result);
        }