Beispiel #1
0
        public void Create()
        {
            var projectList = _contentManager.Create(ContentTypes.ProjectListContentType, VersionOptions.Draft);
            var menuPart    = projectList.As <MenuPart>();

            if (!String.IsNullOrWhiteSpace(MenuText))
            {
                var menu = _menuService.GetMenu(MenuName);

                if (menu != null)
                {
                    var menuItem = _contentManager.Create <ContentMenuItemPart>("ContentMenuItem");
                    menuItem.Content = projectList;
                    menuItem.As <MenuPart>().MenuPosition = Position.GetNext(_navigationManager.BuildMenu(menu));
                    menuItem.As <MenuPart>().MenuText     = MenuText;
                    menuItem.As <MenuPart>().Menu         = menu;
                }
            }

            _contentManager.Publish(projectList);
        }
Beispiel #2
0
        public ActionResult Index()
        {
            var contentItem = _contentManager.New("Foo");

            contentItem.As <TestContentPartA>().Line = "Orchard VNext Rocks";
            _contentManager.Create(contentItem);

            var retrieveContentItem = _contentManager.Get(contentItem.Id);
            var lineToSay           = retrieveContentItem.As <TestContentPartA>().Line;

            return(View("Index", _testDependency.SayHi(lineToSay)));
        }
        public void AddProfilingData()
        {
            var admin = _membershipService.GetUser("admin");

            for (var index = 0; index != 5; ++index)
            {
                var pageName = "page" + index;
                var page     = _contentManager.Create("Page", VersionOptions.Draft);
                page.As <ICommonPart>().Owner     = admin;
                page.As <TitlePart>().Title       = pageName;
                page.As <BodyPart>().Text         = pageName;
                page.As <MenuPart>().OnMainMenu   = true;
                page.As <MenuPart>().MenuPosition = "5." + index;
                page.As <MenuPart>().MenuText     = pageName;
                _contentManager.Publish(page);

                var blogName = "blog" + index;
                var blog     = _contentManager.New("Blog");
                blog.As <ICommonPart>().Owner     = admin;
                blog.As <TitlePart>().Title       = blogName;
                blog.As <MenuPart>().OnMainMenu   = true;
                blog.As <MenuPart>().MenuPosition = "6." + index;
                blog.As <MenuPart>().MenuText     = blogName;
                _contentManager.Create(blog);

                // "BlogPost" content type can't be created w/out http context at the moment
                //for (var index2 = 0; index2 != 5; ++index2) {
                //    var postName = "post" + index;
                //    var post = _contentManager.New("BlogPost");
                //    post.As<ICommonPart>().Owner = admin;
                //    post.As<ICommonPart>().Container = blog;
                //    post.As<RoutableAspect>().Slug = postName;
                //    post.As<RoutableAspect>().Title = postName;
                //    post.As<BodyPart>().Text = postName;
                //    _contentManager.Create(post);
                //}
            }

            Context.Output.WriteLine(T("Finished adding profiling data"));
        }
Beispiel #4
0
        public ActionResult TranslatePOST(int id, Action <ContentItem> conditionallyPublish)
        {
            var masterContentItem = _contentManager.Get(id, VersionOptions.Latest);

            if (masterContentItem == null)
            {
                return(HttpNotFound());
            }

            var masterLocalizationPart = masterContentItem.As <LocalizationPart>();

            if (masterLocalizationPart == null)
            {
                return(HttpNotFound());
            }

            var model = new EditLocalizationViewModel();

            TryUpdateModel(model, "Localization");

            var existingTranslation = _localizationService.GetLocalizedContentItem(masterContentItem, model.SelectedCulture);

            if (existingTranslation != null)
            {
                var existingTranslationMetadata = _contentManager.GetItemMetadata(existingTranslation);
                return(RedirectToAction(
                           Convert.ToString(existingTranslationMetadata.EditorRouteValues["action"]),
                           existingTranslationMetadata.EditorRouteValues));
            }

            var contentItemTranslation = _contentManager
                                         .Create <LocalizationPart>(masterContentItem.ContentType, VersionOptions.Draft, part => {
                part.MasterContentItem = masterLocalizationPart.MasterContentItem == null ? masterContentItem : masterLocalizationPart.MasterContentItem;
            });

            var content = _contentManager.UpdateEditor(contentItemTranslation, this);

            if (!ModelState.IsValid)
            {
                Services.TransactionManager.Cancel();

                return(View(content));
            }

            conditionallyPublish(contentItemTranslation.ContentItem);

            Services.Notifier.Information(T("Created content item translation."));

            var metadata = _contentManager.GetItemMetadata(contentItemTranslation);

            return(RedirectToAction(Convert.ToString(metadata.EditorRouteValues["action"]), metadata.EditorRouteValues));
        }
        public void Create()
        {
            if (String.IsNullOrEmpty(Owner))
            {
                Owner = _siteService.GetSiteSettings().SuperUser;
            }
            var owner = _membershipService.GetUser(Owner);
            var page  = _contentManager.Create("Page", VersionOptions.Draft);

            page.As <RoutePart>().Title             = Title;
            page.As <RoutePart>().Path              = Path;
            page.As <RoutePart>().Slug              = Slug;
            page.As <RoutePart>().PromoteToHomePage = Homepage;
            page.As <ICommonPart>().Owner           = owner;
            var text = String.Empty;

            if (UseWelcomeText)
            {
                text = T(
                    @"<p>You've successfully setup your Orchard Site and this is the homepage of your new site.
Here are a few things you can look at to get familiar with the application.
Once you feel confident you don't need this anymore, you can
<a href=""Admin/Contents/Edit/{0}"">remove it by going into editing mode</a>
and replacing it with whatever you want.</p>
<p>First things first - You'll probably want to <a href=""Admin/Settings"">manage your settings</a>
and configure Orchard to your liking. After that, you can head over to
<a href=""Admin/Themes"">manage themes to change or install new themes</a>
and really make it your own. Once you're happy with a look and feel, it's time for some content.
You can start creating new custom content types or start from the built-in ones by
<a href=""Admin/Contents/Create/Page"">adding a page</a>, or <a href=""Admin/Navigation"">managing your menus.</a></p>
<p>Finally, Orchard has been designed to be extended. It comes with a few built-in
modules such as pages and blogs or themes. If you're looking to add additional functionality,
you can do so by creating your own module or by installing one that somebody else built.
Modules are created by other users of Orchard just like you so if you feel up to it,
<a href=""http://orchardproject.net/contribution"">please consider participating</a>.</p>
<p>Thanks for using Orchard – The Orchard Team </p>", page.Id).Text;
            }
            else
            {
                if (!String.IsNullOrEmpty(Text))
                {
                    text = Text;
                }
            }
            page.As <BodyPart>().Text = text;
            if (Publish)
            {
                _contentManager.Publish(page);
            }

            Context.Output.WriteLine(T("Page created successfully.").Text);
        }
        private XRpcStruct MetaWeblogNewMediaObject(
            string userName,
            string password,
            XRpcStruct file,
            UrlHelper url)
        {
            var user = _membershipService.ValidateUser(userName, password);

            if (!_authorizationService.TryCheckAccess(Permissions.ManageOwnMedia, 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";
            }

            // If the user only has access to his own folder, rewrite the folder name
            if (!_authorizationService.TryCheckAccess(Permissions.ManageMediaContent, user, null))
            {
                directoryName = Path.Combine(_mediaLibraryService.GetRootedFolderPath(directoryName));
            }

            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);
            var    mediaPart = _mediaLibraryService.ImportMedia(directoryName, Path.GetFileName(name));

            try {
                _contentManager.Create(mediaPart);
            }
            catch {
            }

            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")));
        }
        public ActionResult CreatePOST()
        {
            if (!Services.Authorizer.Authorize(Permissions.ManageEvents, T("Couldn't create event")))
            {
                return(new HttpUnauthorizedResult());
            }

            var item = Services.ContentManager.New <EventPart>("Event");

            _contentManager.Create(item, VersionOptions.Draft);
            var model = _contentManager.UpdateEditor(item, this);

            if (!ModelState.IsValid)
            {
                _transactionManager.Cancel();
                return(View(model));
            }
            _contentManager.Publish(item.ContentItem);
            Services.Notifier.Information(T("Event was successfully created"));
            return(Redirect(Url.EventEdit(item.Identifier)));
            //return Redirect(Url.EventsForAdmin());
        }
Beispiel #8
0
        public bool CreateTerm(OptionItemPart termPart)
        {
            if (GetTermByName(termPart.OptionSetId, termPart.Name) == null)
            {
                _authorizationService.CheckAccess(Permissions.CreateTerm, _services.WorkContext.CurrentUser, null);

                termPart.As <ICommonPart>().Container = GetOptionSet(termPart.OptionSetId).ContentItem;
                _contentManager.Create(termPart);
                return(true);
            }
            _notifier.Warning(T("The term {0} already exists in this taxonomy", termPart.Name));
            return(false);
        }
Beispiel #9
0
        public string Create()
        {
            if (String.IsNullOrEmpty(Owner))
            {
                Owner = _siteService.GetSiteSettings().SuperUser;
            }
            var owner = _membershipService.GetUser(Owner);

            if (owner == null)
            {
                throw new OrchardException(T("Invalid username: {0}", Owner));
            }

            if (!IsSlugValid(Slug))
            {
                throw new OrchardException(T("Invalid Slug provided. Blog creation failed."));
            }

            var blog = _contentManager.New("Blog");

            blog.As <ICommonPart>().Owner           = owner;
            blog.As <RoutePart>().Slug              = Slug;
            blog.As <RoutePart>().Path              = Slug;
            blog.As <RoutePart>().Title             = Title;
            blog.As <RoutePart>().PromoteToHomePage = Homepage;
            if (!String.IsNullOrEmpty(Description))
            {
                blog.As <BlogPart>().Description = Description;
            }
            if (!String.IsNullOrWhiteSpace(MenuText))
            {
                blog.As <MenuPart>().OnMainMenu   = true;
                blog.As <MenuPart>().MenuPosition = _menuService.Get().Select(menuPart => menuPart.MenuPosition).Max() + 1 + ".0";
                blog.As <MenuPart>().MenuText     = MenuText;
            }
            _contentManager.Create(blog);

            return("Blog created successfully");
        }
Beispiel #10
0
        public static T Create <T>(this IContentManager manager, string contentType, VersionOptions options, Action <T> initialize) where T : class, IContent
        {
            var content = manager.New <T>(contentType);

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

            initialize(content);
            manager.Create(content.ContentItem, options);
            return(content);
        }
Beispiel #11
0
        public void SubmitVideo(ObjectivePart objective, TeamPart team, string videoUrl)
        {
            Argument.ThrowIfNull(objective, "objective");
            Argument.ThrowIfNull(team, "team");
            Argument.ThrowIfNullOrEmpty(videoUrl, "videoUrl");


            var newSubmit = _actionSubmitService.NewActionSubmit <VideoSubmitPart>(objective, team, "VideoSubmit");

            newSubmit.VideoUrl = videoUrl;

            _contentManager.Create(newSubmit);
        }
Beispiel #12
0
        public IContent Create(string name)
        {
            if (string.IsNullOrWhiteSpace(name))
            {
                throw new ArgumentNullException(name);
            }

            var menu = _contentManager.Create("Menu");

            menu.As <TitlePart>().Title = name;

            return(menu);
        }
Beispiel #13
0
        public JsonResult CreateTypeContents()
        {
            var temp = this.DeserializeObject <IEnumerable <NewPartVM> >();

            foreach (var item in temp)
            {
                ContentItem DevicesInfoContentItem = _contentManager.New("新闻组管理");
                DevicesInfoContentItem.Alter <NewPart>(x => x.NewDisplayName = item.NewDisplayName);
                DevicesInfoContentItem.Alter <NewPart>(x => x.NewDescription = item.NewDescription);
                DevicesInfoContentItem.Alter <NewPart>(x => x.Classify       = item.Classify);
                item.Name = "ContentType_" + item.NewDisplayName;
                if (_contentDefinitionManager.GetTypeDefinition(item.Name) == null)
                {
                    if (item.Classify == false)
                    {
                        var BodyPartSetting = new BodyPartSettings {
                        };
                        BodyPartSetting.Editor = "Wysiwyg";
                        _contentDefinitionService.AddType(item.Name, item.NewDisplayName);
                        _contentDefinitionManager.AlterTypeDefinition(item.Name, bulid => bulid
                                                                      .Draftable()
                                                                      .Creatable()
                                                                      .Listable()
                                                                      .WithPart("TitlePart")
                                                                      .WithPart("BodyPart", part => part.WithSettings(BodyPartSetting))
                                                                      );
                    }
                    else
                    {
                        var BodyPartSetting = new BodyPartSettings {
                        };
                        BodyPartSetting.Editor = "Wysiwyg";
                        _contentDefinitionManager.AlterTypeDefinition(item.Name, bulid => bulid
                                                                      .DisplayedAs(item.NewDisplayName)
                                                                      .Draftable()
                                                                      .Creatable()
                                                                      .Listable()
                                                                      .WithPart("TitlePart", part => part.WithPosition("2"))
                                                                      .WithPart("BodyPart", part => part.WithSettings(BodyPartSetting).WithPosition("3"))
                                                                      .WithPart("TypeNewClassifyPart", part => part.WithPosition("1"))
                                                                      );
                    }
                }
                DevicesInfoContentItem.Alter <TitlePart>(x => x.Title = item.NewDisplayName);
                DevicesInfoContentItem.Alter <NewPart>(x => x.Name    = item.Name);
                _contentDefinitionManager.GetTypeDefinition(item.Name);
                _contentManager.Create(DevicesInfoContentItem);
                item.NewID = DevicesInfoContentItem.ContentItemId;
            }
            return(this.Jsonp(temp));
        }
        public ContentItem CreateProjection(string contentType, string queryName, string title, string itemContentType, int maxItems)
        {
            // get query
            var query = this.GetQuery(queryName);

            if (query != null)
            {
                var contentItem = contentManager.New(contentType);
                contentManager.Create(contentItem);

                // projection
                var projection = contentItem.As <ProjectionWithDynamicSortPart>();
                projection.Record.QueryPartRecord = query.Record;
                projection.Record.MaxItems        = maxItems;

                // layout
                var layout = this.layoutRepository.Table.FirstOrDefault(c => c.QueryPartRecord.Id == query.Id && c.Category == "Html" && c.Type == "Shape");
                if (layout != null)
                {
                    projection.Record.LayoutRecord = layout;
                }

                // Title
                TitlePart titlePart = contentItem.As <TitlePart>();
                titlePart.Title = title;

                // item type
                var projectProjectionPart = contentItem.Parts.FirstOrDefault(c => c.PartDefinition.Name == ContentTypes.ProjectProjectionContentType);
                if (projectProjectionPart != null)
                {
                    var field = projectProjectionPart.Fields.FirstOrDefault(c => c.Name == FieldNames.ProjectProjectionItemTypeFieldName);
                    if (field != null)
                    {
                        ((InputField)field).Value = itemContentType;
                    }

                    var displayField = projectProjectionPart.Fields.FirstOrDefault(c => c.Name == FieldNames.ProjectProjectionItemTypeDisplayFieldName);
                    if (displayField != null)
                    {
                        var contentTypeDefinition = this.contentManager.GetContentTypeDefinitions().FirstOrDefault(c => c.Name == itemContentType);
                        ((InputField)displayField).Value = contentTypeDefinition.DisplayName;
                    }
                }

                this.contentManager.Publish(contentItem);

                return(contentItem);
            }

            return(null);
        }
Beispiel #15
0
        public ActionResult CreatePost(string returnUrl = null)
        {
            if (!Services.Authorizer.Authorize(CustomersPermissions.EditOwnCustomerAccount, T("You are not allowed to create an account.")))
            {
                return(new HttpUnauthorizedResult());
            }

            ContentItem customer;
            var         customerPart = _customersService.GetCustomer();

            if (customerPart != null)
            {
                customer = customerPart.ContentItem;
            }
            else
            {
                customer = _contentManager.New("Customer");
                _contentManager.Create(customer);
            }

            var model = _contentManager.UpdateEditor(customer, this);

            customerPart = customer.As <CustomerPart>();
            if (customerPart != null)
            {
                customerPart.User = Services.WorkContext.CurrentUser;
            }

            if (!ModelState.IsValid)
            {
                _transactionManager.Cancel();
                return(View(model));
            }

            Services.Notifier.Information(T("Your customer account was successfully created."));

            return(this.RedirectLocal(returnUrl, () => RedirectToAction("Index")));
        }
Beispiel #16
0
        public ContentTreeSettingsPart GetSettings()
        {
            var settings = _contentManager.Query <ContentTreeSettingsPart, ContentTreeSettingsRecord>("ContentTreeSettings").List().FirstOrDefault();

            if (settings == null)
            {
                settings = _contentManager.Create <ContentTreeSettingsPart>("ContentTreeSettings", item =>
                {
                    item.IncludedTypes = new string[] { "Page" };
                });
            }

            return(settings);
        }
        public CategoryPart CreateCategory(string tagName, bool isDisabled)
        {
            var result = GetEventCategoriesByName(tagName);

            if (result == null)
            {
                result = new CategoryPart
                {
                    CategoryName = tagName
                };
                _contentManager.Create(result);
            }
            return(result);
        }
Beispiel #18
0
        /// <summary>
        /// Creates a UserPart that will be tied to the active directory
        /// username to allow the user to use the core Orchard functionality.
        /// </summary>
        /// <param name="createUserParams"></param>
        private void CreateUser(CreateUserParams createUserParams)
        {
            var user = _contentManager.New <UserPart>("User");

            user.Record.UserName           = createUserParams.Username;
            user.Record.Email              = createUserParams.Email;
            user.Record.NormalizedUserName = createUserParams.Username.ToLowerInvariant();
            user.Record.HashAlgorithm      = "SHA1";
            user.Record.RegistrationStatus = UserStatus.Approved;
            user.Record.EmailStatus        = UserStatus.Approved;
            SetPasswordHashed(user.Record, createUserParams.Password);

            _contentManager.Create(user);
        }
        public void CreateTerm(TermPart termPart)
        {
            if (GetTermByName(termPart.TaxonomyId, termPart.Name) == null)
            {
                _authorizationService.CheckAccess(Permissions.CreateTerm, _services.WorkContext.CurrentUser, null);

                termPart.As <ICommonPart>().Container = GetTaxonomy(termPart.TaxonomyId).ContentItem;
                _contentManager.Create(termPart);
            }
            else
            {
                _notifier.Warning(T("The term {0} already exists in this taxonomy", termPart.Name));
            }
        }
        public GenericDashboardHandler(IContentManager contentManager)
        {
            OnPublished <GenericDashboardPart>((context, part) => {
                if (!part.CreatePortletsOnPublishing)
                {
                    return;
                }

                // set default portlets for DashboardWidget
                if (part.ContentItem.ContentType == Consts.GenericDashboardWidgetContentType && string.IsNullOrEmpty(part.PortletList))
                {
                    part.PortletList = string.Join(",", (new string[] { Consts.SmtpPortletContentType, Consts.IMAPTPortletContentType }));
                }

                // portlet list
                var portlets = string.IsNullOrEmpty(part.PortletList) ? new string[] { } : part.PortletList.Split(',');

                // current portlets
                var currentPortlets = contentManager.Query().Where <CommonPartRecord>(c => c.Container.Id == part.ContentItem.Id).List();

                // add new portlets
                int position = -1;
                foreach (var newPortlet in portlets.Where(c => !currentPortlets.Any(d => d.ContentType == c)))
                {
                    position++;
                    var newPortletContentItem       = contentManager.Create(newPortlet, VersionOptions.Draft);
                    ContainablePart containablePart = newPortletContentItem.As <ContainablePart>();
                    if (containablePart == null)
                    {
                        continue;
                    }

                    // Position
                    containablePart.Position = position;

                    // Container
                    var newPortletCommon       = newPortletContentItem.As <CommonPart>();
                    newPortletCommon.Container = part.ContentItem;

                    contentManager.Publish(newPortletContentItem);
                }

                // delete portlets
                foreach (var portlet in currentPortlets.Where(c => !portlets.Any(d => d == c.ContentType)))
                {
                    contentManager.Remove(portlet);
                }
            });
        }
Beispiel #21
0
        public void Create()
        {
            if (!String.IsNullOrWhiteSpace(MenuText))
            {
                var menu = _menuService.GetMenu(MenuName);

                if (menu != null)
                {
                    var menuItem = _contentManager.Create <TicketMenuItemPart>("TicketMenuItem");
                    menuItem.As <MenuPart>().MenuPosition = Position.GetNext(_navigationManager.BuildMenu(menu));
                    menuItem.As <MenuPart>().MenuText     = MenuText;
                    menuItem.As <MenuPart>().Menu         = menu;
                }
            }
        }
Beispiel #22
0
        public FaqEntryPart CreateFaqEntry(string question, int sectionId, string culture, string answer = "")
        {
            var section = GetFaqSectionById(sectionId);

            var faqEntryPart = _contentManager.Create <FaqEntryPart>("FaqEntry",
                                                                     fe =>
            {
                fe.Question = question;
                fe.Answer   = answer;
                fe.Section  = section;
                fe.Language = culture;
            });

            return(faqEntryPart);
        }
Beispiel #23
0
        public ObjectiveResultPart Approve(ActionSubmitPart submit, string resultDisplayName, int resultPoints)
        {
            var result = _contentManager.New <ObjectiveResultPart>("SimpleObjectiveResult");

            result.DisplayName = resultDisplayName;
            result.Points      = resultPoints;
            result.Team        = submit.Team;
            result.Objective   = submit.Objective;

            _contentManager.Create(result);

            submit.Status = SubmitStatus.Approved;

            return(result);
        }
        private ActionResult EditionSave(ref NewsletterEditionPart newsletterEdition)
        {
            _contentManager.Create(newsletterEdition, VersionOptions.Draft);
            dynamic model = _contentManager.UpdateEditor(newsletterEdition, this);

            if (!ModelState.IsValid)
            {
                _transactionManager.Cancel();
                // Casting to avoid invalid (under medium trust) reflection over the protected View method and force a static invocation.
                return(View((object)model));
            }

            Services.ContentManager.Publish(newsletterEdition.ContentItem);
            return(null);
        }
Beispiel #25
0
        public void ImportingDraftShouldUpdateExistingDraft()
        {
            // Create a draft and an export of it.
            var contentItem = _contentManager.New(ContentTypeName);

            contentItem.As <TitlePart>().Title = "Dummy";
            _contentManager.Create(contentItem, VersionOptions.Draft);
            var element = _contentManager.Export(contentItem);

            // Change the title and then import the element.
            element.Element("TitlePart").Attr("Title", "Smarty");
            Import(element);

            // Assert that we still have the one draft.
            var allContentItems = _contentManager.Query(VersionOptions.Latest).List().ToList();

            Assert.That(allContentItems.Count, Is.EqualTo(1));
            var updatedContentItem = allContentItems[0];

            Assert.That(updatedContentItem.As <IdentityPart>().Identifier, Is.EqualTo(contentItem.As <IdentityPart>().Identifier));

            // Assert that the draft has been updated with the imported change.
            Assert.That(updatedContentItem.As <TitlePart>().Title, Is.EqualTo("Smarty"));
        }
Beispiel #26
0
        private int CreateQuery(string entityType)
        {
            var queryPart   = _contentManager.New <QueryPart>("Query");
            var filterGroup = new FilterGroupRecord();

            queryPart.Record.FilterGroups.Add(filterGroup);
            var filterRecord = new FilterRecord {
                Category = "Content",
                Type     = "ContentTypes",
                Position = filterGroup.Filters.Count,
                State    = GetContentTypeFilterState(entityType)
            };

            filterGroup.Filters.Add(filterRecord);
            _contentManager.Create(queryPart);
            return(queryPart.Id);
        }
        public ActionResult Upload(string folderPath, string type)
        {
            if (!Services.Authorizer.Authorize(Permissions.ManageOwnMedia))
            {
                return(new HttpUnauthorizedResult());
            }

            // Check permission.
            var rootMediaFolder = _mediaLibraryService.GetRootMediaFolder();

            if (!Services.Authorizer.Authorize(Permissions.ManageMediaContent) && !_mediaLibraryService.CanManageMediaFolder(folderPath))
            {
                return(new HttpUnauthorizedResult());
            }

            var statuses = new List <object>();

            // Loop through each file in the request
            for (int i = 0; i < HttpContext.Request.Files.Count; i++)
            {
                // Pointer to file
                var file     = HttpContext.Request.Files[i];
                var filename = Path.GetFileName(file.FileName);

                // if the file has been pasted, provide a default name
                if (file.ContentType.Equals("image/png", StringComparison.InvariantCultureIgnoreCase) && !filename.EndsWith(".png", StringComparison.InvariantCultureIgnoreCase))
                {
                    filename = "clipboard.png";
                }

                var mediaPart = _mediaLibraryService.ImportMedia(file.InputStream, folderPath, filename, type);
                _contentManager.Create(mediaPart);

                statuses.Add(new {
                    id       = mediaPart.Id,
                    name     = mediaPart.Title,
                    type     = mediaPart.MimeType,
                    size     = file.ContentLength,
                    progress = 1.0,
                    url      = mediaPart.FileName,
                });
            }

            // Return JSON
            return(Json(statuses, JsonRequestBehavior.AllowGet));
        }
Beispiel #28
0
        public ActionResult Import(string folderPath, string type, string url)
        {
            if (!Services.Authorizer.Authorize(Permissions.ManageOwnMedia))
            {
                return(new HttpUnauthorizedResult());
            }

            // Check permission
            if (!Services.Authorizer.Authorize(Permissions.ManageMediaContent) && !_mediaLibraryService.CanManageMediaFolder(folderPath))
            {
                return(new HttpUnauthorizedResult());
            }

            var settings          = Services.WorkContext.CurrentSite.As <MediaLibrarySettingsPart>();
            var allowedExtensions = (settings.UploadAllowedFileTypeWhitelist ?? "")
                                    .Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
                                    .Where(x => x.StartsWith("."));

            try {
                var filename = Path.GetFileName(url);

                // skip file if the allowed extensions is defined and doesn't match
                if (allowedExtensions.Any())
                {
                    if (!allowedExtensions.Any(e => filename.EndsWith(e, StringComparison.OrdinalIgnoreCase)))
                    {
                        throw new Exception(T("This file type is not allowed: {0}", Path.GetExtension(filename)).Text);
                    }
                }

                var buffer = new WebClient().DownloadData(url);
                var stream = new MemoryStream(buffer);

                var mediaPart = _mediaLibraryService.ImportMedia(stream, folderPath, filename, type);
                _contentManager.Create(mediaPart);

                return(new JsonResult {
                    Data = new { folderPath, MediaPath = mediaPart.FileName }
                });
            }
            catch (Exception e) {
                return(new JsonResult {
                    Data = new { error = e.Message }
                });
            }
        }
Beispiel #29
0
        public Task ExecuteAsync(RecipeExecutionContext context)
        {
            if (!String.Equals(context.Name, "Content", StringComparison.OrdinalIgnoreCase))
            {
                return(Task.CompletedTask);
            }

            var model = context.Step.ToObject <ContentStepModel>();

            foreach (JObject token in model.Data)
            {
                var contentItem = token.ToObject <ContentItem>();
                _contentManager.Create(contentItem);
            }

            return(Task.CompletedTask);
        }
Beispiel #30
0
        public ISite GetSiteSettings()
        {
            var siteId = _cacheManager.Get("SiteId", ctx => {
                var site = _contentManager.Query("Site")
                           .List()
                           .FirstOrDefault();

                if (site == null)
                {
                    site = _contentManager.Create <SiteSettingsPart>("Site").ContentItem;
                }

                return(site.Id);
            });

            return(_contentManager.Get <ISite>(siteId, VersionOptions.Published));
        }