public void ImportModule(int moduleId, string content, string version, int userId) { var module = OpenContentModuleConfig.Create(moduleId, Null.NullInteger, PortalSettings.Current); var dataSource = new OpenContentDataSource(); var dsContext = OpenContentUtils.CreateDataContext(module, userId); XmlNode xml = Globals.GetContent(content, "opencontent"); var items = xml.SelectNodes("item"); if (items != null) { foreach (XmlNode item in items) { XmlNode json = item.SelectSingleNode("json"); XmlNode collection = item.SelectSingleNode("collection"); XmlNode key = item.SelectSingleNode("key"); try { JToken data = JToken.Parse(json.InnerText); dsContext.Collection = collection?.InnerText ?? ""; dataSource.Add(dsContext, data); App.Services.CacheAdapter.SyncronizeCache(module); } catch (Exception e) { App.Services.Logger.Error($"Failed to parse imported json. Item key: {key}. Collection: {collection}. Error: {e.Message}. Stacktrace: {e.StackTrace}"); throw; } } } }
public static DataSourceContext CreateDataContext(OpenContentModuleConfig module, int userId = -1, bool single = false, JObject options = null) { var template = module.Settings.Template; if (template == null) { App.Services.Logger.Error($"Template [{(module.Settings.TemplateAvailable ? module.Settings.TemplateKey.ToString() : "???")}] not found"); // are you importing and forgot to install the files? } var dsContext = new DataSourceContext { PortalId = module.ViewModule.PortalId, ActiveModuleId = module.ViewModule.ModuleId, TabId = module.ViewModule.TabId, TabModuleId = module.ViewModule.TabModuleId, ModuleId = module.DataModule.ModuleId, TemplateFolder = module.Settings.TemplateDir.FolderPath, UserId = userId, Config = module.Settings.Manifest.DataSourceConfig, Index = template?.Manifest?.Index ?? false, Options = options, Single = single, Collection = template?.Collection ?? "" }; if (PortalSettings.Current != null) { //PortalSettings is null if called from scheduler (eg UrlRewriter, Search, ...) dsContext.CurrentCultureCode = DnnLanguageUtils.GetCurrentCultureCode(); } return(dsContext); }
public HttpResponseMessage UpdateData(JObject json) { try { var module = OpenContentModuleConfig.Create(ActiveModule, PortalSettings); string key = json["key"].ToString(); var dataManifest = module.Settings.Template.Manifest.GetAdditionalData(key); IDataSource ds = DataSourceManager.GetDataSource(module.Settings.Manifest.DataSource); var dsContext = OpenContentUtils.CreateDataContext(module, UserInfo.UserID); var dsItem = ds.GetData(dsContext, dataManifest.ScopeType, dataManifest.StorageKey ?? key); if (dsItem == null) { ds.AddData(dsContext, dataManifest.ScopeType, dataManifest.StorageKey ?? key, json["form"]); } else { ds.UpdateData(dsContext, dsItem, json["form"]); } return(Request.CreateResponse(HttpStatusCode.OK, new { isValid = true })); } catch (Exception exc) { App.Services.Logger.Error(exc); return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc)); } }
public static IEnumerable <OpenContentModuleConfig> GetDnnOpenContentModules(int portalId) { ModuleController mc = new ModuleController(); ArrayList modules = mc.GetModulesByDefinition(portalId, App.Config.Opencontent); return(modules.OfType <ModuleInfo>().Select(module => OpenContentModuleConfig.Create(module, PortalSettings.Current))); }
public HttpResponseMessage ReOrder(List <string> ids) { try { var module = OpenContentModuleConfig.Create(ActiveModule, PortalSettings); IDataSource ds = DataSourceManager.GetDataSource(module.Settings.Manifest.DataSource); var dsContext = OpenContentUtils.CreateDataContext(module, UserInfo.UserID); IDataItem dsItem = null; if (module.IsListMode()) { if (ids != null) { int i = 1; foreach (var id in ids) { dsItem = ds.Get(dsContext, id); var json = dsItem.Data; json["SortIndex"] = i; ds.Update(dsContext, dsItem, json); i++; } } } return(Request.CreateResponse(HttpStatusCode.OK, new { isValid = true })); } catch (Exception exc) { App.Services.Logger.Error(exc); return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc)); } }
public HttpResponseMessage EditData(string key) { try { var module = OpenContentModuleConfig.Create(ActiveModule, PortalSettings); var dataManifest = module.Settings.Manifest.GetAdditionalData(key); IDataSource ds = DataSourceManager.GetDataSource(module.Settings.Manifest.DataSource); var dsContext = OpenContentUtils.CreateDataContext(module, UserInfo.UserID); var dsItem = ds.GetData(dsContext, dataManifest.ScopeType, dataManifest.StorageKey ?? key); var json = ds.GetDataAlpaca(dsContext, true, true, true, key); if (dsItem != null) { json["data"] = dsItem.Data; var versions = ds.GetDataVersions(dsContext, dsItem); if (versions != null) { json["versions"] = versions; } } return(Request.CreateResponse(HttpStatusCode.OK, json)); } catch (Exception exc) { App.Services.Logger.Error(exc); return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc)); } }
/// <summary> /// Checks the OpenContent settings. /// </summary> public static bool CheckOpenContentTemplateFiles(OpenContentModuleConfig module) { bool result = true; var settings = module.Settings; if (settings?.TemplateKey?.TemplateDir != null && !settings.TemplateKey.TemplateDir.FolderExists) { var url = DnnUrlUtils.NavigateUrl(module.ViewModule.TabId); App.Services.Logger.Error($"Error loading OpenContent Template on page [{module.ViewModule.PortalId}-{module.ViewModule.TabId}-{url}] module [{module.ViewModule.ModuleId}-{module.ViewModule.ModuleTitle}]. Reason: Template not found [{settings.TemplateKey}]"); result = false; } return(result); }
public HttpResponseMessage ImagesLookupExt(string q, string folder, string itemKey = "") { try { var module = OpenContentModuleConfig.Create(ActiveModule, PortalSettings); var folderManager = FolderManager.Instance; string imageFolder = "OpenContent/Files/" + ActiveModule.ModuleID; if (module.Settings.Manifest.DeleteFiles) { if (!string.IsNullOrEmpty(itemKey)) { imageFolder += "/" + itemKey; } } if (!string.IsNullOrEmpty(folder)) { imageFolder = folder; } var dnnFolder = folderManager.GetFolder(PortalSettings.PortalId, imageFolder); if (dnnFolder == null) { dnnFolder = folderManager.AddFolder(PortalSettings.PortalId, imageFolder); } var files = folderManager.GetFiles(dnnFolder, true); files = files.Where(f => f.IsImageFile()); if (q != "*" && !string.IsNullOrEmpty(q)) { files = files.Where(f => f.FileName.ToLower().Contains(q.ToLower())); } int folderLength = imageFolder.Length; var res = files.Select(f => new { id = f.FileId.ToString(), thumbUrl = ImageHelper.GetImageUrl(f, new Ratio(40, 40)), //todo for install in application folder is dat niet voldoende ??? url = FileManager.Instance.GetUrl(f).RemoveCachebuster(), text = f.Folder.Substring(folderLength).TrimStart('/') + f.FileName, filename = f.FileName, width = f.Width, height = f.Height }).Take(1000); return(Request.CreateResponse(HttpStatusCode.OK, res)); } catch (Exception exc) { Logger.Error(exc); return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc)); } }
public HttpResponseMessage Submit() { SubmitDTO req = JsonConvert.DeserializeObject <SubmitDTO>(HttpContextSource.Current.Request.Form["data"].ToString()); var form = req.form; var statuses = new List <FilesStatus>(); try { //todo can we eliminate the HttpContext here UploadWholeFile(HttpContextSource.Current, statuses); var files = new JArray(); form["Files"] = files; int i = 1; foreach (var item in statuses) { var file = new JObject(); file["id"] = item.id; file["name"] = item.name; file["url"] = FormUtils.ToAbsoluteUrl(item.url); files.Add(file); //form["File"+i] = OpenFormUtils.ToAbsoluteUrl(item.url); i++; } } catch (Exception exc) { Log.Logger.Error(exc); } try { var data = new JObject(); data["form"] = req.form; string jsonSettings = ActiveModule.ModuleSettings["formsettings"] as string; if (!string.IsNullOrEmpty(jsonSettings)) { data["formSettings"] = JObject.Parse(jsonSettings); } var module = OpenContentModuleConfig.Create(ActiveModule, PortalSettings); IDataSource ds = DataSourceManager.GetDataSource(module.Settings.Manifest.DataSource); var dsContext = OpenContentUtils.CreateDataContext(module, UserInfo.UserID); var dsItem = ds.Get(dsContext, req.id); var res = ds.Action(dsContext, string.IsNullOrEmpty(req.action) ? "FormSubmit" : req.action, dsItem, data); return(Request.CreateResponse(HttpStatusCode.OK, res)); } catch (Exception exc) { App.Services.Logger.Error(exc); return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc)); } }
public HttpResponseMessage Delete(JObject json) { try { var module = OpenContentModuleConfig.Create(ActiveModule, PortalSettings); string editRole = module.Settings.Template.Manifest.GetEditRole(); int createdByUserid = -1; IDataSource ds = DataSourceManager.GetDataSource(module.Settings.Manifest.DataSource); var dsContext = OpenContentUtils.CreateDataContext(module, UserInfo.UserID); IDataItem content = null; if (module.IsListMode()) { content = ds.Get(dsContext, json["id"].ToString()); if (content != null) { createdByUserid = content.CreatedByUserId; } } else { dsContext.Single = true; content = ds.Get(dsContext, null); if (content != null) { createdByUserid = content.CreatedByUserId; } } //todo: can't we do some of these checks at the beginning of this method to fail faster? if (!DnnPermissionsUtils.HasEditPermissions(module, editRole, createdByUserid)) { return(Request.CreateResponse(HttpStatusCode.Unauthorized)); } AddNotifyInfo(dsContext); if (content != null) { ds.Delete(dsContext, content); } App.Services.CacheAdapter.SyncronizeCache(module); return(Request.CreateResponse(HttpStatusCode.OK, "")); } catch (Exception exc) { App.Services.Logger.Error(exc); return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc)); } }
public void SyncronizeCache(OpenContentModuleConfig ocModuleConfig) { int dataModuleId = ocModuleConfig.DataModule.ModuleId; var dataModuleHasCrossPortalData = Json.JsonExtensions.GetValue(ocModuleConfig.DataModule.ModuleInfo.OpenContentSettings().Manifest.Permissions, "AllowCrossPortalData", false); if (dataModuleHasCrossPortalData) { foreach (PortalInfo portal in PortalController.Instance.GetPortals()) { SyncronizeLinkedModules(portal.PortalID, dataModuleId); } } else { SyncronizeLinkedModules(PortalSettings.Current.PortalId, dataModuleId); } }
public HttpResponseMessage LookupCollection(LookupCollectionRequestDTO req) { var module = OpenContentModuleConfig.Create(ActiveModule, PortalSettings); var res = new List <LookupResultDTO>(); try { IDataSource ds = DataSourceManager.GetDataSource(module.Settings.Manifest.DataSource); var dsContext = OpenContentUtils.CreateDataContext(module, UserInfo.UserID); dsContext.Collection = req.collection; if (module.IsListMode()) { var items = ds.GetAll(dsContext, null).Items; if (items != null) { foreach (var item in items) { var json = item.Data as JObject; json = json.DeepClone() as JObject; JsonUtils.SimplifyJson(json, DnnLanguageUtils.GetCurrentCultureCode()); if (json?[req.textField] != null) { res.Add(new LookupResultDTO() { value = item.Id, text = json[req.textField].ToString() }); } } } } return(Request.CreateResponse(HttpStatusCode.OK, res)); } catch (Exception exc) { App.Services.Logger.Error(exc); return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc)); } }
public HttpResponseMessage LookupData(LookupDataRequestDTO req) { List <LookupResultDTO> res = new List <LookupResultDTO>(); try { var module = OpenContentModuleConfig.Create(ActiveModule, PortalSettings); string key = req.dataKey; var additionalDataManifest = module.Settings.Template.Manifest.GetAdditionalData(key); IDataSource ds = DataSourceManager.GetDataSource(module.Settings.Manifest.DataSource); var dsContext = OpenContentUtils.CreateDataContext(module, UserInfo.UserID); var dataItems = ds.GetData(dsContext, additionalDataManifest.ScopeType, additionalDataManifest.StorageKey ?? key); if (dataItems != null) { JToken json = dataItems.Data; if (!string.IsNullOrEmpty(req.dataMember)) { json = json[req.dataMember]; } if (json is JArray) { json = json.DeepClone(); JsonUtils.SimplifyJson(json, DnnLanguageUtils.GetCurrentCultureCode()); AddLookupItems(req.valueField, req.textField, req.childrenField, res, json as JArray); } } return(Request.CreateResponse(HttpStatusCode.OK, res)); } catch (Exception exc) { App.Services.Logger.Error(exc); return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc)); } }
public HttpResponseMessage Version(string id, string ticks) { var module = OpenContentModuleConfig.Create(ActiveModule, PortalSettings); JToken json = new JObject(); try { int createdByUserid = -1; IDataSource ds = DataSourceManager.GetDataSource(module.Settings.Manifest.DataSource); var dsContext = OpenContentUtils.CreateDataContext(module, UserInfo.UserID); var dsItem = ds.Get(dsContext, id); if (dsItem != null) { var version = ds.GetVersion(dsContext, dsItem, new DateTime(long.Parse(ticks))); if (version != null) { json = version; createdByUserid = dsItem.CreatedByUserId; } } string editRole = module.Settings.Template.Manifest.GetEditRole(); //todo: can't we do some of these checks at the beginning of this method to fail faster? if (!DnnPermissionsUtils.HasEditPermissions(module, editRole, createdByUserid)) { return(Request.CreateResponse(HttpStatusCode.Unauthorized)); } return(Request.CreateResponse(HttpStatusCode.OK, json)); } catch (Exception exc) { App.Services.Logger.Error(exc); return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc)); } }
public HttpResponseMessage Add(UpdateRequest req) { try { var module = OpenContentModuleConfig.Create(req.ModuleId, req.TabId, PortalSettings); string editRole = module.Settings.Template.Manifest.GetEditRole(); var dataSource = new OpenContentDataSource(); if (module.IsListMode()) { if (!DnnPermissionsUtils.HasEditPermissions(module, editRole, -1)) { App.Services.Logger.Warn($"Failed the HasEditPermissions() check"); return(Request.CreateResponse(HttpStatusCode.Unauthorized, "Failed the HasEditPermissions() check")); } var dsContext = OpenContentUtils.CreateDataContext(module, UserInfo.UserID); dsContext.Collection = req.Collection; JToken data = req.json; data["Title"] = ActiveModule.ModuleTitle; dataSource.Add(dsContext, data); App.Services.CacheAdapter.SyncronizeCache(module); return(Request.CreateResponse(HttpStatusCode.OK, "")); } else { return(Request.CreateResponse(HttpStatusCode.BadRequest, "It's not a list mode module")); } } catch (Exception exc) { App.Services.Logger.Error(exc); return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc)); } }
public HttpResponseMessage Submit(SubmitDTO req) { try { var data = new JObject(); data["form"] = req.form; string jsonSettings = ActiveModule.ModuleSettings["formsettings"] as string; if (!string.IsNullOrEmpty(jsonSettings)) { data["formSettings"] = JObject.Parse(jsonSettings); } var module = OpenContentModuleConfig.Create(ActiveModule, PortalSettings); IDataSource ds = DataSourceManager.GetDataSource(module.Settings.Manifest.DataSource); var dsContext = OpenContentUtils.CreateDataContext(module, UserInfo.UserID); var dsItem = ds.Get(dsContext, req.id); var res = ds.Action(dsContext, string.IsNullOrEmpty(req.action) ? "FormSubmit" : req.action, dsItem, data); return(Request.CreateResponse(HttpStatusCode.OK, res)); } catch (Exception exc) { App.Services.Logger.Error(exc); return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc)); } }
public ModuleStateDto SaveTemplate(SaveDto input) { ModuleController mc = new ModuleController(); if (!input.otherModule) // this module { mc.DeleteModuleSetting(ActiveModule.ModuleID, "tabid"); mc.DeleteModuleSetting(ActiveModule.ModuleID, "moduleid"); } else // other module { var dsModule = (new ModuleController()).GetTabModule(input.tabModuleId); mc.UpdateModuleSetting(ActiveModule.ModuleID, "tabid", dsModule.TabID.ToString()); mc.UpdateModuleSetting(ActiveModule.ModuleID, "moduleid", dsModule.ModuleID.ToString()); } if (!input.newTemplate) // existing { mc.UpdateModuleSetting(ActiveModule.ModuleID, "template", input.template); ActiveModule.ModuleSettings["template"] = input.template; } else // new { try { if (!input.fromWeb) // site { string oldFolder = HostingEnvironment.MapPath(input.template); var template = OpenContentUtils.CopyTemplate(ActiveModule.PortalID, oldFolder, input.templateName); mc.UpdateModuleSetting(ActiveModule.ModuleID, "template", template); ActiveModule.ModuleSettings["template"] = template; } else // web { //string fileName = ddlTemplate.SelectedValue; //string template = OpenContentUtils.ImportFromWeb(ModuleContext.PortalId, fileName, tbTemplateName.Text); //mc.UpdateModuleSetting(ModuleContext.ModuleId, "template", template); //ModuleContext.Settings["template"] = template; //string fileName = ddlTemplate.SelectedValue; var template = GithubTemplateUtils.ImportFromGithub(ActiveModule.PortalID, input.template, input.template, input.templateName); mc.UpdateModuleSetting(ActiveModule.ModuleID, "template", template); ActiveModule.ModuleSettings["template"] = template; } } catch (Exception ex) { return(new ModuleStateDto() { Error = ex.Message }); } } //mc.UpdateModuleSetting(ActiveModule.ModuleID, "detailtabid", ddlDetailPage.SelectedValue); //don't reset settings. Sure they might be invalid, but maybe not. And you can't ever revert. //mc.DeleteModuleSetting(ModuleContext.ModuleId, "data"); var settings = ActiveModule.OpenContentSettings(); var templateManifest = settings.Template; if (templateManifest.SettingsNeeded()) { var settingsFilename = templateManifest.MainTemplateUri().PhysicalFullDirectory + "\\" + templateManifest.Key.ShortKey + "-data.json"; if (File.Exists(settingsFilename)) { var settingContent = File.ReadAllText(settingsFilename); mc.UpdateModuleSetting(ActiveModule.ModuleID, "data", settingContent); ActiveModule.ModuleSettings["data"] = settingContent; settings = ActiveModule.OpenContentSettings(); } } bool defaultData = false; if (templateManifest.DataNeeded()) { var dataFilename = templateManifest.MainTemplateUri().PhysicalFullDirectory + "\\data.json"; if (File.Exists(dataFilename)) { var module = OpenContentModuleConfig.Create(ActiveModule, PortalSettings); IDataSource ds = DataSourceManager.GetDataSource(settings.Manifest.DataSource); var dsContext = OpenContentUtils.CreateDataContext(module, UserInfo.UserID); ds.Add(dsContext, JObject.Parse(File.ReadAllText(dataFilename))); defaultData = true; } } return(new ModuleStateDto() { SettingsNeeded = templateManifest.SettingsNeeded(), SettingsDefined = !string.IsNullOrEmpty(settings.Data), DataNeeded = settings.Template.DataNeeded() && !defaultData, Template = settings.TemplateKey.ToString(), Error = "" }); }
public HttpResponseMessage Action(SubmitDTO req) { try { var module = OpenContentModuleConfig.Create(ActiveModule, PortalSettings); string editRole = module.Settings.Template.Manifest.GetEditRole(); int createdByUserid = -1; IDataSource ds = DataSourceManager.GetDataSource(module.Settings.Manifest.DataSource); var dsContext = OpenContentUtils.CreateDataContext(module, UserInfo.UserID); IDataItem dsItem = null; if (module.IsListMode()) { if (req.id != null) { var itemId = req.id; dsItem = ds.Get(dsContext, itemId); if (dsItem != null) { createdByUserid = dsItem.CreatedByUserId; } } } else { dsContext.Single = true; dsItem = ds.Get(dsContext, null); if (dsItem != null) { createdByUserid = dsItem.CreatedByUserId; } } //todo: can't we do some of these checks at the beginning of this method to fail faster? if (!DnnPermissionsUtils.HasEditPermissions(module, editRole, createdByUserid)) { return(Request.CreateResponse(HttpStatusCode.Unauthorized)); } try { var res = ds.Action(dsContext, req.action, dsItem, req.form); return(Request.CreateResponse(HttpStatusCode.OK, new { isValid = true, result = res })); } catch (DataNotValidException ex) { return(Request.CreateResponse(HttpStatusCode.OK, new { isValid = false, validMessage = ex.Message })); } } catch (Exception exc) { App.Services.Logger.Error(exc); return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc)); } }
// Upload entire file private void UploadWholeFile(HttpContextBase context, ICollection <FilesStatus> statuses) { for (var i = 0; i < context.Request.Files.Count; i++) { var file = context.Request.Files[i]; if (file == null) { continue; } var fileName = CleanUpFileName(Path.GetFileName(file.FileName)); if (IsAllowedExtension(fileName)) { bool?overwrite = null; var module = OpenContentModuleConfig.Create(ActiveModule, PortalSettings); if (!string.IsNullOrEmpty(context.Request.Form["overwrite"])) { overwrite = context.Request.Form["overwrite"] == "true"; } string uploadfolder = "OpenContent/Files/" + ActiveModule.ModuleID; if (module.Settings.Manifest.DeleteFiles) { if (!string.IsNullOrEmpty(context.Request.Form["itemKey"])) { uploadfolder += "/" + context.Request.Form["itemKey"]; } } if (!string.IsNullOrEmpty(context.Request.Form["uploadfolder"])) { uploadfolder = context.Request.Form["uploadfolder"]; } var userFolder = _folderManager.GetFolder(PortalSettings.PortalId, uploadfolder); if (userFolder == null) { userFolder = _folderManager.AddFolder(PortalSettings.PortalId, uploadfolder); } int suffix = 0; string baseFileName = Path.GetFileNameWithoutExtension(fileName); string extension = Path.GetExtension(fileName); var fileInfo = _fileManager.GetFile(userFolder, fileName); if (fileInfo != null && overwrite.HasValue && overwrite.Value) { //fileInfo = _fileManager.UpdateFile(fileInfo, file.InputStream); fileInfo = _fileManager.AddFile(userFolder, fileName, file.InputStream, true); } else if (fileInfo != null && overwrite.HasValue && !overwrite.Value) { statuses.Add(new FilesStatus { success = false, name = fileName, message = "File exist already." }); return; } else { while (fileInfo != null) { suffix++; fileName = baseFileName + "-" + suffix + extension; fileInfo = _fileManager.GetFile(userFolder, fileName); } fileInfo = _fileManager.AddFile(userFolder, fileName, file.InputStream, true); } var fileIcon = IconController.IconURL("Ext" + fileInfo.Extension, "32x32"); if (!File.Exists(context.Server.MapPath(fileIcon))) { fileIcon = IconController.IconURL("File", "32x32"); } statuses.Add(new FilesStatus { success = true, name = fileName, extension = fileInfo.Extension, type = fileInfo.ContentType, size = file.ContentLength, progress = "1.0", url = fileInfo.ToUrl().RemoveCachebuster(), thumbnail_url = fileIcon, message = "success", id = fileInfo.FileId, }); } else { statuses.Add(new FilesStatus { success = false, name = fileName, message = "File type not allowed." }); } } }
public HttpResponseMessage Update(JObject json) { try { var module = OpenContentModuleConfig.Create(ActiveModule, PortalSettings); string editRole = module.Settings.Template.Manifest.GetEditRole(); int createdByUserid = -1; IDataSource ds = DataSourceManager.GetDataSource(module.Settings.Manifest.DataSource); var dsContext = OpenContentUtils.CreateDataContext(module, UserInfo.UserID); IDataItem dsItem = null; if (module.IsListMode()) { if (json["id"] != null) { var itemId = json["id"].ToString(); dsItem = ds.Get(dsContext, itemId); if (dsItem != null) { createdByUserid = dsItem.CreatedByUserId; } } } else { dsContext.Single = true; dsItem = ds.Get(dsContext, null); if (dsItem != null) { createdByUserid = dsItem.CreatedByUserId; } } //todo: can't we do some of these checks at the beginning of this method to fail faster? if (!DnnPermissionsUtils.HasEditPermissions(module, editRole, createdByUserid)) { return(Request.CreateResponse(HttpStatusCode.Unauthorized)); } AddNotifyInfo(dsContext); try { if (dsItem == null) { ds.Add(dsContext, json["form"] as JObject); } else { ds.Update(dsContext, dsItem, json["form"] as JObject); } App.Services.CacheAdapter.SyncronizeCache(module); } catch (DataNotValidException ex) { return(Request.CreateResponse(HttpStatusCode.OK, new { isValid = false, validMessage = ex.Message })); } if (json["form"]["ModuleTitle"] != null && json["form"]["ModuleTitle"].Type == JTokenType.String) { string moduleTitle = json["form"]["ModuleTitle"].ToString(); ActiveModule.UpdateModuleTitle(moduleTitle); } else if (json["form"]["ModuleTitle"] != null && json["form"]["ModuleTitle"].Type == JTokenType.Object) { if (json["form"]["ModuleTitle"][DnnLanguageUtils.GetCurrentCultureCode()] != null) { string moduleTitle = json["form"]["ModuleTitle"][DnnLanguageUtils.GetCurrentCultureCode()].ToString(); ActiveModule.UpdateModuleTitle(moduleTitle); } } return(Request.CreateResponse(HttpStatusCode.OK, new { isValid = true })); } catch (Exception exc) { App.Services.Logger.Error(exc); return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc)); } }
public HttpResponseMessage ReOrder(List <string> ids) { try { var module = OpenContentModuleConfig.Create(ActiveModule, PortalSettings); IDataSource ds = DataSourceManager.GetDataSource(module.Settings.Manifest.DataSource); var dsContext = OpenContentUtils.CreateDataContext(module, UserInfo.UserID); var alpaca = ds.GetAlpaca(dsContext, false, true, false); var opt = alpaca["options"]?["fields"]?["SortIndex"]?["type"]?.ToString(); var ml = opt == "mlnumber"; if (!module.IsListMode()) { return(Request.CreateResponse(HttpStatusCode.OK, new { isValid = true })); } if (ids == null) { return(Request.CreateResponse(HttpStatusCode.OK, new { isValid = true })); } int i = 1; string errorOccured = ""; foreach (var id in ids) { if (id == "-1") { continue; // ignore items explicitly marked with id -1; } var dsItem = ds.Get(dsContext, id); if (dsItem == null) { Utils.DebuggerBreak(); // item not found. investigate! errorOccured = $"Reorder failed. Unknown item {id}. Reindex module and try again."; App.Services.Logger.Error(errorOccured); continue; } var json = dsItem.Data; if (ml) // multi language { #region Normalize irregulatities with SortIndex field // if old data-format (single-language) detected. Migrate to ML version. if (json["SortIndex"] == null || json["SortIndex"].Type != JTokenType.Object) { json["SortIndex"] = new JObject(); } // if not all site languages initialized, then give them a default value. var langList = DnnLanguageUtils.GetPortalLocales(this.PortalSettings.PortalId); if (json["SortIndex"].Count() != langList.Count) { foreach (var locale in langList) { json["SortIndex"][locale.Key] = i; } } #endregion // Set the new SortIndex value for this item. json["SortIndex"][DnnLanguageUtils.GetCurrentCultureCode()] = i; } else { json["SortIndex"] = i; } ds.Update(dsContext, dsItem, json); i++; } return(Request.CreateResponse(HttpStatusCode.OK, new { isValid = string.IsNullOrEmpty(errorOccured), errorMsg = errorOccured })); } catch (Exception exc) { App.Services.Logger.Error(exc); return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc)); } }
public HttpResponseMessage Edit(string id) { try { var module = OpenContentModuleConfig.Create(ActiveModule, PortalSettings); IDataSource ds = DataSourceManager.GetDataSource(module.Settings.Manifest.DataSource); var dsContext = OpenContentUtils.CreateDataContext(module); IDataItem dsItem = null; if (module.IsListMode()) { if (!string.IsNullOrEmpty(id)) // not a new item { dsItem = ds.Get(dsContext, id); } } else { dsContext.Single = true; dsItem = ds.Get(dsContext, null); } int createdByUserid = -1; var json = ds.GetAlpaca(dsContext, true, true, true); if (ds is IDataActions) { var actions = ((IDataActions)ds).GetActions(dsContext, dsItem); if (json["options"] == null) { json["options"] = new JObject(); } if (json["options"]["form"] == null) { json["options"]["form"] = new JObject(); } if (json["options"]["form"]["buttons"] == null) { json["options"]["form"]["buttons"] = new JObject(); } var buttons = json["options"]["form"]["buttons"] as JObject; var newButtons = new JObject(); foreach (var act in actions) { var but = buttons[act.Name]; if (but == null) { but = new JObject(); } but["after"] = act.AfterExecute; newButtons[act.Name] = but; } json["options"]["form"]["buttons"] = newButtons; } if (dsItem != null) { json["data"] = dsItem.Data; if (json["schema"]["properties"]["ModuleTitle"] is JObject) { if (json["data"]["ModuleTitle"] != null && json["data"]["ModuleTitle"].Type == JTokenType.String) { json["data"]["ModuleTitle"] = ActiveModule.ModuleTitle; } else if (json["data"]["ModuleTitle"] != null && json["data"]["ModuleTitle"].Type == JTokenType.Object) { json["data"]["ModuleTitle"][DnnLanguageUtils.GetCurrentCultureCode()] = ActiveModule.ModuleTitle; } } var versions = ds.GetVersions(dsContext, dsItem); if (versions != null) { json["versions"] = versions; } createdByUserid = dsItem.CreatedByUserId; } var context = new JObject(); var currentLocale = DnnLanguageUtils.GetCurrentLocale(PortalSettings.PortalId); context["culture"] = currentLocale.Code; //todo why not use DnnLanguageUtils.GetCurrentCultureCode() ??? context["defaultCulture"] = LocaleController.Instance.GetDefaultLocale(PortalSettings.PortalId).Code; context["numberDecimalSeparator"] = currentLocale.Culture.NumberFormat.NumberDecimalSeparator; context["rootUrl"] = System.Web.VirtualPathUtility.ToAbsolute(string.Concat(System.Web.HttpRuntime.AppDomainAppVirtualPath, "/")); context["alpacaCulture"] = AlpacaEngine.AlpacaCulture(currentLocale.Code); context["bootstrap"] = App.Services.CreateGlobalSettingsRepository(PortalSettings.PortalId).GetEditLayout() != AlpacaLayoutEnum.DNN; context["horizontal"] = App.Services.CreateGlobalSettingsRepository(PortalSettings.PortalId).GetEditLayout() == AlpacaLayoutEnum.BootstrapHorizontal; json["context"] = context; //todo: can't we do some of these checks at the beginning of this method to fail faster? if (!DnnPermissionsUtils.HasEditPermissions(module, module.Settings.Manifest.GetEditRole(), createdByUserid)) { return(Request.CreateResponse(HttpStatusCode.Unauthorized)); } return(Request.CreateResponse(HttpStatusCode.OK, json)); } catch (Exception exc) { App.Services.Logger.Error(exc); return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc)); } }
public static DataSourceContext CreateDataContext(OpenContentModuleInfo moduleinfo, int userId = -1, bool single = false, JObject options = null) { var module = OpenContentModuleConfig.Create(moduleinfo.ModuleId, moduleinfo.TabId, PortalSettings.Current); return(CreateDataContext(module, userId, single, options)); }
public HttpResponseMessage Lookup(LookupRequestDTO req) { int moduleid = req.moduleid > 0 ? req.moduleid : ActiveModule.ModuleID; int tabid = req.tabid > 0 ? req.tabid : ActiveModule.TabID; var module = OpenContentModuleConfig.Create(moduleid, tabid, PortalSettings); if (module == null) { throw new Exception($"Can not find ModuleInfo (tabid:{req.tabid}, moduleid:{req.moduleid})"); } List <LookupResultDTO> res = new List <LookupResultDTO>(); try { IDataSource ds = DataSourceManager.GetDataSource(module.Settings.Manifest.DataSource); var dsContext = OpenContentUtils.CreateDataContext(module, UserInfo.UserID); if (module.IsListMode()) { var items = ds.GetAll(dsContext, null).Items; if (items != null) { foreach (var item in items) { var json = item.Data; if (!string.IsNullOrEmpty(req.dataMember) && json[req.dataMember] != null) { json = json[req.dataMember]; } json = json.DeepClone(); JsonUtils.SimplifyJson(json, DnnLanguageUtils.GetCurrentCultureCode()); var array = json as JArray; if (array != null) { res.AddRange(array.Select(childItem => new LookupResultDTO { value = string.IsNullOrEmpty(req.valueField) || childItem[req.valueField] == null ? "" : childItem[req.valueField].ToString(), text = string.IsNullOrEmpty(req.textField) || childItem[req.textField] == null ? "" : childItem[req.textField].ToString() } ) ); } else { res.Add(new LookupResultDTO { value = string.IsNullOrEmpty(req.valueField) || json[req.valueField] == null ? item.Id : json[req.valueField].ToString(), text = string.IsNullOrEmpty(req.textField) || json[req.textField] == null ? item.Title : json[req.textField].ToString() }); } } } } else { dsContext.Single = true; var struc = ds.Get(dsContext, null); if (struc != null) { JToken json = struc.Data; if (!string.IsNullOrEmpty(req.dataMember)) { json = json[req.dataMember]; json = json.DeepClone(); JsonUtils.SimplifyJson(json, DnnLanguageUtils.GetCurrentCultureCode()); if (json is JArray) { foreach (JToken item in (JArray)json) { res.Add(new LookupResultDTO() { value = item[req.valueField] == null ? "" : item[req.valueField].ToString(), text = item[req.textField] == null ? "" : item[req.textField].ToString() }); } } } } } return(Request.CreateResponse(HttpStatusCode.OK, res)); } catch (Exception exc) { App.Services.Logger.Error(exc); return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc)); } }
public static OpenContentModuleConfig GetDnnOpenContentModule(int portalId, int dataModuleId) { ModuleController mc = new ModuleController(); ArrayList modules = mc.GetModulesByDefinition(portalId, App.Config.Opencontent); return(modules.OfType <ModuleInfo>().Where(module => module.ModuleID == dataModuleId).Select(module => OpenContentModuleConfig.Create(module, PortalSettings.Current)).FirstOrDefault()); }
public override IList <SearchDocument> GetModifiedSearchDocuments(ModuleInfo modInfo, DateTime beginDateUtc) { App.Services.Logger.Trace($"Indexing content Module {modInfo.ModuleID} - Tab {modInfo.TabID} - Culture {modInfo.CultureCode}- indexing from {beginDateUtc}"); var searchDocuments = new List <SearchDocument>(); //If module is marked as "don't index" then return no results if (modInfo.ModuleSettings.GetValue("AllowIndex", "True") == "False") { App.Services.Logger.Trace($"Indexing content {modInfo.ModuleID}|{modInfo.CultureCode} - NOT - MODULE Indexing disabled"); return(searchDocuments); } //If tab of the module is marked as "don't index" then return no results if (modInfo.ParentTab.TabSettings.GetValue("AllowIndex", "True") == "False") { App.Services.Logger.Trace($"Indexing content {modInfo.ModuleID}|{modInfo.CultureCode} - NOT - TAB Indexing disabled"); return(searchDocuments); } //If tab is marked as "inactive" then return no results if (modInfo.ParentTab.DisableLink) { App.Services.Logger.Trace($"Indexing content {modInfo.ModuleID}|{modInfo.CultureCode} - NOT - TAB is inactive"); return(searchDocuments); } var module = OpenContentModuleConfig.Create(modInfo, PortalSettings.Current); if (module.Settings.Template?.Main == null || !module.Settings.Template.Main.DnnSearch) { return(searchDocuments); } if (module.Settings.IsOtherModule) { return(searchDocuments); } IDataSource ds = DataSourceManager.GetDataSource(module.Settings.Manifest.DataSource); var dsContext = OpenContentUtils.CreateDataContext(module); IDataItems contentList = ds.GetAll(dsContext, null); if (!contentList.Items.Any()) { App.Services.Logger.Trace($"Indexing content {modInfo.ModuleID}|{modInfo.CultureCode} - NOT - No content found"); } foreach (IDataItem content in contentList.Items) { if (content == null) { App.Services.Logger.Trace($"Indexing content {modInfo.ModuleID}|{modInfo.CultureCode} - NOT - Content is Null"); } else if (content.LastModifiedOnDate.ToUniversalTime() > beginDateUtc && content.LastModifiedOnDate.ToUniversalTime() < DateTime.UtcNow) { SearchDocument searchDoc; if (DnnLanguageUtils.IsMultiLingualPortal(modInfo.PortalID)) { // first process the default language module var culture = modInfo.CultureCode; var localizedData = GetLocalizedContent(content.Data, culture); searchDoc = CreateSearchDocument(modInfo, module.Settings, localizedData, content.Id, culture, content.Title, content.LastModifiedOnDate.ToUniversalTime()); searchDocuments.Add(searchDoc); App.Services.Logger.Trace($"Indexing content {modInfo.ModuleID}|{culture} - OK! {searchDoc.Title} ({modInfo.TabID}) of {content.LastModifiedOnDate.ToUniversalTime()}"); // now do the same with any linked localized instances of this module if (modInfo.LocalizedModules != null) { foreach (var localizedModule in modInfo.LocalizedModules) { culture = localizedModule.Value.CultureCode; localizedData = GetLocalizedContent(content.Data, culture); searchDoc = CreateSearchDocument(modInfo, module.Settings, localizedData, content.Id, culture, content.Title, content.LastModifiedOnDate.ToUniversalTime()); searchDocuments.Add(searchDoc); App.Services.Logger.Trace($"Indexing content {modInfo.ModuleID}|{culture} - OK! {searchDoc.Title} ({modInfo.TabID}) of {content.LastModifiedOnDate.ToUniversalTime()}"); } } } else { searchDoc = CreateSearchDocument(modInfo, module.Settings, content.Data, content.Id, "", content.Title, content.LastModifiedOnDate.ToUniversalTime()); searchDocuments.Add(searchDoc); App.Services.Logger.Trace($"Indexing content {modInfo.ModuleID}|{modInfo.CultureCode} - OK! {searchDoc.Title} ({modInfo.TabID}) of {content.LastModifiedOnDate.ToUniversalTime()}"); } } else { App.Services.Logger.Trace($"Indexing content {modInfo.ModuleID}|{modInfo.CultureCode} - NOT - No need to index: lastmod {content.LastModifiedOnDate.ToUniversalTime()} "); } } return(searchDocuments); }