Ejemplo n.º 1
0
        private XRpcStruct MetaWeblogNewMediaObject(
            string userName,
            string password,
            XRpcStruct file,
            UrlHelper url) {

            var user = _membershipService.ValidateUser(userName, password);
            if (!_authorizationService.TryCheckAccess(Permissions.ManageMediaContent, user, null)) {
                throw new OrchardCoreException(T("Access denied"));
            }

            var name = file.Optional<string>("name");
            var bits = file.Optional<byte[]>("bits");

            string directoryName = Path.GetDirectoryName(name);
            if (string.IsNullOrWhiteSpace(directoryName)) { // Some clients only pass in a name path that does not contain a directory component.
                directoryName = "media";
            }

            try {
                // delete the file if it already exists, e.g. an updated image in a blog post
                // it's safe to delete the file as each content item gets a specific folder
                _mediaLibraryService.DeleteFile(directoryName, Path.GetFileName(name));
            }
            catch {
                // current way to delete a file if it exists
            }

            string publicUrl = _mediaLibraryService.UploadMediaFile(directoryName, Path.GetFileName(name), bits);
            _mediaLibraryService.ImportMedia(directoryName, Path.GetFileName(name));
            return new XRpcStruct() // Some clients require all optional attributes to be declared Wordpress responds in this way as well.
                .Set("file", publicUrl)
                .Set("url", url.MakeAbsolute(publicUrl))
                .Set("type", file.Optional<string>("type"));
        }
Ejemplo n.º 2
0
        public void Populate(FeedContext context)
        {
            foreach (var feedItem in context.Response.Items.OfType<FeedItem<ContentItem>>()) {

                var inspector = new ItemInspector(
                    feedItem.Item,
                    _contentManager.GetItemMetadata(feedItem.Item),
                    _htmlFilters);

                // author is intentionally left empty as it could result in unwanted spam

                // add to known formats
                if (context.Format == "rss") {
                    var link = new XElement("link");
                    var guid = new XElement("guid", new XAttribute("isPermaLink", "true"));

                    context.Response.Contextualize(requestContext => {
                                                        var urlHelper = new UrlHelper(requestContext, _routes);
                                                        var uriBuilder = new UriBuilder(urlHelper.MakeAbsolute("/")) { Path = urlHelper.RouteUrl(inspector.Link) };
                                                        link.Add(uriBuilder.Uri.OriginalString);
                                                        guid.Add(uriBuilder.Uri.OriginalString);
                                                   });

                    feedItem.Element.SetElementValue("title", inspector.Title);
                    feedItem.Element.Add(link);
                    feedItem.Element.SetElementValue("description", inspector.Description);

                    if ( inspector.PublishedUtc != null ) {
                        // RFC833
                        // The "R" or "r" standard format specifier represents a custom date and time format string that is defined by
                        // the DateTimeFormatInfo.RFC1123Pattern property. The pattern reflects a defined standard, and the property
                        // is read-only. Therefore, it is always the same, regardless of the culture used or the format provider supplied.
                        // The custom format string is "ddd, dd MMM yyyy HH':'mm':'ss 'GMT'". When this standard format specifier is used,
                        // the formatting or parsing operation always uses the invariant culture.
                        feedItem.Element.SetElementValue("pubDate", inspector.PublishedUtc.Value.ToString("r"));
                    }

                    feedItem.Element.Add(guid);
                }
                else {
                    var feedItem1 = feedItem;
                    context.Response.Contextualize(requestContext => {
                                                       var urlHelper = new UrlHelper(requestContext, _routes);
                                                       context.Builder.AddProperty(context, feedItem1, "link", urlHelper.RouteUrl(inspector.Link));
                                                   });
                    context.Builder.AddProperty(context, feedItem, "title", inspector.Title);
                    context.Builder.AddProperty(context, feedItem, "description", inspector.Description);

                    if (inspector.PublishedUtc != null)
                        context.Builder.AddProperty(context, feedItem, "published-date", Convert.ToString(inspector.PublishedUtc)); // format? cvt to generic T?
                }
            }
        }
Ejemplo n.º 3
0
        public void Execute(FeedContext context)
        {
            var containerIdValue = context.ValueProvider.GetValue("containerid");
            if (containerIdValue == null)
                return;

            var limitValue = context.ValueProvider.GetValue("limit");
            var limit = 20;
            if (limitValue != null) {
                Int32.TryParse(Convert.ToString(limitValue), out limit);
            }

            limit = Math.Min(limit, 100);

            var containerId = (int)containerIdValue.ConvertTo(typeof(int));
            var container = _contentManager.Get(containerId);

            if (container == null) {
                return;
            }

            var inspector = new ItemInspector(container, _contentManager.GetItemMetadata(container), _htmlFilters);
            if (context.Format == "rss") {
                var link = new XElement("link");
                context.Response.Element.SetElementValue("title", inspector.Title);
                context.Response.Element.Add(link);
                context.Response.Element.SetElementValue("description", inspector.Description);

                context.Response.Contextualize(requestContext => {
                    var urlHelper = new UrlHelper(requestContext);
                    var uriBuilder = new UriBuilder(urlHelper.MakeAbsolute("/")) { Path = urlHelper.RouteUrl(inspector.Link) };
                    link.Add(uriBuilder.Uri.OriginalString);
                });
            }
            else {
                context.Builder.AddProperty(context, null, "title", inspector.Title);
                context.Builder.AddProperty(context, null, "description", inspector.Description);
                context.Response.Contextualize(requestContext => {
                    var urlHelper = new UrlHelper(requestContext);
                    context.Builder.AddProperty(context, null, "link",urlHelper.MakeAbsolute(urlHelper.RouteUrl(inspector.Link)));
                });
            }

            var items = _contentManager.Query()
                .Where<CommonPartRecord>(x => x.Container == container.Record)
                .OrderByDescending(x => x.CreatedUtc)
                .Slice(0, limit);

            foreach (var item in items) {
                context.Builder.AddItem(context, item);
            }
        }
        public void Execute(FeedContext context)
        {
            var calendarId = context.ValueProvider.GetValue("calendar");
            if (calendarId == null)
                return;

            var containerId = (int)calendarId.ConvertTo(typeof(int));
            var container = _contentManager.Get<CalendarPart>(containerId);

            if (container == null)
            {
                return;
            }

            var inspector = new ItemInspector(container, _contentManager.GetItemMetadata(container));
            if (context.Format == "rss")
            {
                var link = new XElement("link");
                context.Response.Element.SetElementValue("title", inspector.Title);
                context.Response.Element.Add(link);
                context.Response.Element.SetElementValue("description", inspector.Description);

                context.Response.Contextualize(requestContext =>
                {
                    var urlHelper = new UrlHelper(requestContext);
                    var uriBuilder = new UriBuilder(urlHelper.MakeAbsolute("/"))
                    {
                        Path = urlHelper.RouteUrl(inspector.Link) ?? "/"
                    };
                    link.Add(uriBuilder.Uri.OriginalString);
                });
            }
            else
            {
                context.Builder.AddProperty(context, null, "title", inspector.Title);
                context.Builder.AddProperty(context, null, "description", inspector.Description);
                context.Response.Contextualize(requestContext =>
                {
                    var urlHelper = new UrlHelper(requestContext);
                    context.Builder.AddProperty(context, null, "link", urlHelper.RouteUrl(inspector.Link));
                });
            }

            var items = _calendarService.GetEvents(container.As<IdentityPart>().Identifier);

            foreach (var item in items)
            {
                // call item.ContentItem to force a cast to ContentItem, and 
                // thus use CorePartsFeedItemBuilder
                context.Builder.AddItem(context, item.ContentItem);
            }
        }
Ejemplo n.º 5
0
        public void Evaluate(EvaluateContext context) {
            var urlHelper = new UrlHelper(HttpContext.Current.Request.RequestContext);

            context.For<IContent>("Content")
                .Token("PostMessage", content => content.As<PostPart>().Text)
                .Chain("PostMessage", "Text", content => content.As<PostPart>().Text)

                //viagra-test-123 is used by https://akismet.com/ to flag a subsmission as spam for testing purposes 
                .Token("PostAuthor", content => content.As<CommonPart>().Owner.UserName) //content => { return "viagra-test-123"; }) 
                .Chain("PostAuthor", "Text", content => content.As<CommonPart>().Owner.UserName) //content => { return "viagra-test-123"; }) 

                .Token("PostAuthorEmail", content => content.As<CommonPart>().Owner.Email)
                .Chain("PostAuthorEmail", "Text", content => content.As<CommonPart>().Owner.Email)

                .Token("PostUserIp", content => content.As<PostPart>().IP)

                .Token("PostPermalink", content => urlHelper.MakeAbsolute(urlHelper.ItemDisplayUrl(content.As<PostPart>().ContentItem)))

                .Token("PostFrontPage", content => urlHelper.MakeAbsolute(urlHelper.ItemDisplayUrl(content.As<PostPart>().ThreadPart.ForumPart.ForumCategoryPart.ForumsHomePagePart)))

                ;
        }
Ejemplo n.º 6
0
        public void Execute(FeedContext context) {
            var projectionId = context.ValueProvider.GetValue("projection");
            if (projectionId == null || String.IsNullOrEmpty(projectionId.AttemptedValue))
                return;

            var limitValue = context.ValueProvider.GetValue("limit");
            var limit = 20;
            if (limitValue != null) {
                Int32.TryParse(Convert.ToString(limitValue), out limit);
            }

            var containerId = (int)projectionId.ConvertTo(typeof(int));
            var container = _contentManager.Get<ProjectionPart>(containerId);

            if (container == null) {
                return;
            }

            var inspector = new ItemInspector(container, _contentManager.GetItemMetadata(container), _htmlFilters);
            if (context.Format == "rss") {
                var link = new XElement("link");
                context.Response.Element.SetElementValue("title", inspector.Title);
                context.Response.Element.Add(link);
                context.Response.Element.SetElementValue("description", inspector.Description);

                context.Response.Contextualize(requestContext => {
                    var urlHelper = new UrlHelper(requestContext);
                    var uriBuilder = new UriBuilder(urlHelper.MakeAbsolute("/")) { Path = urlHelper.RouteUrl(inspector.Link) };
                    link.Add(uriBuilder.Uri.OriginalString);
                });
            }
            else {
                context.Builder.AddProperty(context, null, "title", inspector.Title);
                context.Builder.AddProperty(context, null, "description", inspector.Description);
                context.Response.Contextualize(requestContext => {
                    var urlHelper = new UrlHelper(requestContext);
                    context.Builder.AddProperty(context, null, "link", urlHelper.RouteUrl(inspector.Link));
                });
            }

            var items = _projectionManager.GetContentItems(container.Record.QueryPartRecord.Id, 0, limit).ToList();

            foreach (var item in items) {
                context.Builder.AddItem(context, item);
            }
        }
        private XRpcStruct MetaWeblogNewMediaObject(
            string userName,
            string password,
            XRpcStruct file,
            UrlHelper url) {

            var user = _membershipService.ValidateUser(userName, password);
            if (!_authorizationService.TryCheckAccess(Permissions.ManageMedia, user, null)) {
                //TEMP: return appropriate access-denied response for user
                throw new ApplicationException("Access denied");
            }

            var name = file.Optional<string>("name");
            var bits = file.Optional<byte[]>("bits");

            string publicUrl = _mediaService.UploadMediaFile(Path.GetDirectoryName(name), Path.GetFileName(name), bits, true);
            return new XRpcStruct().Set("url", url.MakeAbsolute(publicUrl));
        }
        protected virtual bool TransformRedirect(ActionExecutedContext filterContext) {

            // Removes the target of the redirection from cache after a POST.

            if (filterContext.Result == null) {
                throw new ArgumentNullException();
            }

            if (AdminFilter.IsApplied(new RequestContext(filterContext.HttpContext, new RouteData()))) {
                return false;
            }

            var redirectResult = filterContext.Result as RedirectResult;

            // status code can't be tested at this point, so test the result type instead
            if (redirectResult == null || !filterContext.HttpContext.Request.HttpMethod.Equals("POST", StringComparison.OrdinalIgnoreCase)) {
                return false;
            }

            Logger.Debug("Redirect on POST detected; removing from cache and adding refresh key.");

            var redirectUrl = redirectResult.Url;

            if (filterContext.HttpContext.Request.IsLocalUrl(redirectUrl)) {
                // Remove all cached versions of the same item.
                var helper = new UrlHelper(filterContext.HttpContext.Request.RequestContext);
                var absolutePath = new Uri(helper.MakeAbsolute(redirectUrl)).AbsolutePath;
                var invariantCacheKey = ComputeCacheKey(_shellSettings.Name, absolutePath, null);
                _cacheService.RemoveByTag(invariantCacheKey);
            }

            // Adding a refresh key so that the redirection doesn't get restored
            // from a cached version on a proxy. This can happen when using public
            // caching, we want to force the client to get a fresh copy of the
            // redirectUrl content.

            if (CacheSettings.DefaultMaxAge > 0) {
                var epIndex = redirectUrl.IndexOf('?');
                var qs = new NameValueCollection();
                if (epIndex > 0) {
                    qs = HttpUtility.ParseQueryString(redirectUrl.Substring(epIndex));
                }

                // Substract Epoch to get a smaller number.
                var refresh = _now.Ticks - _epoch;
                qs.Remove(_refreshKey);

                qs.Add(_refreshKey, refresh.ToString("x"));
                var querystring = "?" + string.Join("&", Array.ConvertAll(qs.AllKeys, k => string.Format("{0}={1}", HttpUtility.UrlEncode(k), HttpUtility.UrlEncode(qs[k]))));

                if (epIndex > 0) {
                    redirectUrl = redirectUrl.Substring(0, epIndex) + querystring;
                }
                else {
                    redirectUrl = redirectUrl + querystring;
                }
            }

            filterContext.Result = new RedirectResult(redirectUrl, redirectResult.Permanent);
            filterContext.HttpContext.Response.Cache.SetCacheability(HttpCacheability.NoCache);

            return true;
        }
Ejemplo n.º 9
0
        public void Execute(FeedContext context) {
            var tagIdValue = context.ValueProvider.GetValue("tag");
            if (tagIdValue == null)
                return;

            var limitValue = context.ValueProvider.GetValue("limit");
            var limit = 20;
            if (limitValue != null) { 
                Int32.TryParse(Convert.ToString(limitValue), out limit);
            }
            
            limit = Math.Min(limit, 100);

            var tagName = (string)tagIdValue.ConvertTo(typeof(string));
            var tag = _tagService.GetTagByName(tagName);

            if (tag == null) {
                return;
            }

            var displayRouteValues = new RouteValueDictionary {
                {"area", "Orchard.Tags"},
                {"controller", "Home"},
                {"action", "Search"},
                {"tagName", tag.TagName}
            };

            if (context.Format == "rss") {
                var link = new XElement("link");
                context.Response.Element.SetElementValue("title", tag.TagName);
                context.Response.Element.Add(link);
                context.Response.Element.SetElementValue("description", T("Content tagged with {0}", tag.TagName).ToString());

                context.Response.Contextualize(requestContext => {
                    var urlHelper = new UrlHelper(requestContext);
                    var uriBuilder = new UriBuilder(urlHelper.MakeAbsolute("/")) { Path = urlHelper.RouteUrl(displayRouteValues) };
                    link.Add(uriBuilder.Uri.OriginalString);
                });
            }
            else {
                context.Builder.AddProperty(context, null, "title", tag.TagName);
                context.Builder.AddProperty(context, null, "description", T("Content tagged with {0}", tag.TagName).ToString());
                context.Response.Contextualize(requestContext => {
                    var urlHelper = new UrlHelper(requestContext);
                    context.Builder.AddProperty(context, null, "link", urlHelper.MakeAbsolute(urlHelper.RouteUrl(displayRouteValues)));
                });
            }

            var items = _tagService.GetTaggedContentItems(tag.Id, 0, limit);

            foreach (var item in items) {
                context.Builder.AddItem(context, item.ContentItem);
            }
        }
        private XElement CreatePackage(PackagePart package, UrlHelper urlHelper, string baseUrl, IShapeDisplay shapeDisplay, dynamic shapeFactory) {
            var element = new XElement(atomns + "entry");

            dynamic content = package.ContentItem;
            string iconUrl = null;

            if (content.Package.Icon != null && content.Package.Icon.FirstMediaUrl != null) {
                iconUrl = (string)content.Package.Icon.FirstMediaUrl;
                iconUrl = shapeDisplay.Display(shapeFactory.ResizeMediaUrl(Path: iconUrl, Width: 64, Heigth: 64));
            }

            var screenshots = new XElement(atomns + "link",
                    new XAttribute("rel", "http://schemas.microsoft.com/ado/2007/08/dataservices/related/Screenshots"),
                    new XAttribute("type", "application/atom+xml;type=feed"),
                    new XAttribute("title", "Screenshots"),
                    new XAttribute("href", "Packages(Id='" + package.PackageId + "')/Screenshots")
                    );


            foreach (var media in (IEnumerable<dynamic>)content.Package.Screenshots.MediaParts) {

                string screenshotUrl = media.MediaUrl;
                screenshotUrl = shapeDisplay.Display(shapeFactory.ResizeMediaUrl(Path: screenshotUrl, Width: 164, Heigth: 128));

                screenshots.Add(
                    new XElement(mns + "inline",
                        new XElement(atomns + "feed",
                            new XElement(atomns + "title", "Screenshots", new XAttribute("type", "text")),
                            new XElement(atomns + "id", urlHelper.MakeAbsolute("/FeedService/Packages(Id='" + package.PackageId + "')/Screenshots", baseUrl)),
                            new XElement(atomns + "link",
                                new XAttribute("rel", "self"),
                                new XAttribute("title", "Screenshots"),
                                new XAttribute("href", "Packages(Id='" + package.PackageId + "')/Screenshots")
                                ),
                            new XElement(atomns + "entry",
                                new XElement(atomns + "id", urlHelper.MakeAbsolute("/FeedService.svc/Screenshots(" + (string)media.Id.ToString() + ")", baseUrl)),
                                new XElement(atomns + "title", media.ContentItem.TitlePart.Title, new XAttribute("type", "text")),
                                new XElement(atomns + "content", new XAttribute("type", "application/xml"),
                                    new XElement(mns + "properties",
                                        new XElement(dns + "Id", media.ContentItem.Id, new XAttribute(mns + "type", "Edm.Int32")),
                                        new XElement(dns + "PublishedPackageId", package.PackageId),
                                        new XElement(dns + "ScreenshotUri", urlHelper.MakeAbsolute(screenshotUrl, baseUrl)),
                                        new XElement(dns + "Caption", new XAttribute(mns + "null", "true"))
                                    )
                                )
                            )
                        )
                    )
                );
            }

            element.Add(
                new XElement(atomns + "id", urlHelper.MakeAbsolute(urlHelper.ItemDisplayUrl(package), baseUrl)),
                new XElement(atomns + "title", package.TitlePart.Title, new XAttribute("type", "text")),
                new XElement(atomns + "summary", package.Summary, new XAttribute("type", "text")),
                new XElement(atomns + "updated", package.LatestVersionUtc.ToString("o")),
                new XElement(atomns + "author",
                    new XElement(atomns + "name", package.CommonPart.Owner.UserName)
                    ),
                screenshots,
                // edit-media
                // edit
                //new XElement(atomns + "category",
                //    new XAttribute("term", "Gallery.Infrastructure.FeedModels.PublishedPackage"),
                //    new XAttribute("scheme", "http://schemas.microsoft.com/ado/2007/08/dataservices/scheme")
                //    ),
                new XElement(atomns + "content",
                    new XAttribute("type", "application/zip"),
                    new XAttribute("src", urlHelper.MakeAbsolute(urlHelper.Action("Download", "PackageVersion", new { id = package.PackageId, version = package.LatestVersion, area = "Orchard.Gallery" }), baseUrl))
                    ),
                new XElement(mns + "properties",
                    new XElement(dns + "Id", package.PackageId),
                    new XElement(dns + "Version", package.LatestVersion),
                    new XElement(dns + "Title", package.TitlePart.Title),
                    new XElement(dns + "Authors", package.CommonPart.Owner.UserName),
                    new XElement(dns + "PackageType", package.ExtensionType),
                    new XElement(dns + "Summary", package.Summary),
                    new XElement(dns + "Description", package.BodyPart.Text),
                    new XElement(dns + "Copyright", "", new XAttribute(mns + "null", "true")),
                    new XElement(dns + "PackageHashAlgorithm", ""),
                    new XElement(dns + "PackageHash", ""),
                    new XElement(dns + "PackageSize", new XAttribute(mns + "type", "Edm.Int64"), "0"),
                    new XElement(dns + "Price", "0", new XAttribute(mns + "type", "Edm.Decimal")),
                    new XElement(dns + "RequireLicenseAcceptance", "false", new XAttribute(mns + "type", "Edm.Boolean")),
                    new XElement(dns + "IsLatestVersion", "true", new XAttribute(mns + "type", "Edm.Boolean")),
                    new XElement(dns + "VersionRating", "5", new XAttribute(mns + "type", "Edm.Double")),
                    new XElement(dns + "VersionRatingsCount", "0", new XAttribute(mns + "type", "Edm.Int32")),
                    new XElement(dns + "VersionDownloadCount", package.DownloadCount, new XAttribute(mns + "type", "Edm.Int32")),
                    new XElement(dns + "Created", package.CommonPart.CreatedUtc.Value.ToString("o"), new XAttribute(mns + "type", "Edm.DateTime")),
                    new XElement(dns + "LastUpdated", package.LatestVersionUtc.ToString("o"), new XAttribute(mns + "type", "Edm.DateTime")),
                    new XElement(dns + "Published", package.CommonPart.PublishedUtc.Value.ToString("o"), new XAttribute(mns + "type", "Edm.DateTime")),
                    new XElement(dns + "ExternalPackageUrl", "", new XAttribute(mns + "null", "true")),
                    new XElement(dns + "ProjectUrl", package.ProjectUrl),
                    new XElement(dns + "LicenseUrl", package.LicenseUrl, new XAttribute(mns + "null", "true")),
                    new XElement(dns + "IconUrl", iconUrl),
                    new XElement(dns + "Rating", "5", new XAttribute(mns + "type", "Edm.Double")),
                    new XElement(dns + "RatingsCount", "0", new XAttribute(mns + "type", "Edm.Int32")),
                    new XElement(dns + "DownloadCount", package.DownloadCount, new XAttribute(mns + "type", "Edm.Int32")),
                    new XElement(dns + "Categories", ""),
                    new XElement(dns + "Tags", new XAttribute(XNamespace.Xml + "space", "preserve"), String.Join(" ", package.TagsPart.CurrentTags.ToArray())),
                    new XElement(dns + "Dependencies", ""),
                    new XElement(dns + "ReportAbuseUrl", ""),
                    new XElement(dns + "GalleryDetailsUrl", "")
                    )
            );

            return element;
        }
Ejemplo n.º 11
0
        public bool RequestLostPassword(string username) {
            var registrationSettings = _orchardServices.WorkContext.CurrentSite.As<RegistrationSettingsPart>();
            if ( !registrationSettings.EnableLostPassword ) {
                return false;
            }

            if(String.IsNullOrWhiteSpace(username)){
                return false;
            }

            var siteUrl = _orchardServices.WorkContext.CurrentSite.BaseUrl;
            if (String.IsNullOrWhiteSpace(siteUrl)) {
                siteUrl = HttpContext.Current.Request.ToRootUrlString();
            }
            UrlHelper url = new UrlHelper(HttpContext.Current.Request.RequestContext);
            return _user.SendLostPasswordEmail(username, nonce => url.MakeAbsolute(url.Action("LostPassword", "Account", new { Area = "Orchard.Users", nonce = nonce }), siteUrl));
        }