public void btnSubmit_Click(object sender, EventArgs e) { PermissionsManager mgr = new PermissionsManager(); GroupPolicyLevel lvl; Enum.TryParse<GroupPolicyLevel>(ddlPermissionLevel.SelectedValue, out lvl); var result = mgr.CreateGroup(txtGroupName.Text, Context.User.Identity.Name, txtGroupDescription.Text, lvl); switch (result) { case PermissionErrorCode.AlreadyExists: lblErrorMessage.Text = "Group Already Exists"; break; case PermissionErrorCode.NotAuthorized: break; case PermissionErrorCode.DoesNotExist: break; case PermissionErrorCode.OutOfRange: break; case PermissionErrorCode.AlreadyIncluded: break; case PermissionErrorCode.NotIncluded: break; case PermissionErrorCode.Ok: BindGroups(); break; default: break; } mgr.Dispose(); }
public void btnAddUser_Click(object sender, EventArgs args) { PermissionsManager mgr = new PermissionsManager(); ModelPermissionLevel lvl; Enum.TryParse<ModelPermissionLevel>(ddlUserPermission.SelectedValue, out lvl); var result = mgr.SetModelToUserLevel(Context.User.Identity.Name, txtAddUser.Text, PID, lvl); BindUsers(mgr); }
public void btnAddUser_Click(object sender, EventArgs args) { PermissionsManager mgr = new PermissionsManager(); ModelPermissionLevel lvl; Enum.TryParse<ModelPermissionLevel>(ddlPermission2.Text, out lvl); var result = mgr.SetModelToGroupLevel(Context.User.Identity.Name, PID,txtGroupName.Text, lvl); BindGroups(mgr); }
private void BindGroups(PermissionsManager mgr) { if (PID != null) { usersWithPermissionToModel.DataSource = mgr.GetGroupsByPid(PID); usersWithPermissionToModel.DataBind(); } }
private void BindUsers(PermissionsManager mgr) { if (PID != null) { usersWithPermissionToModel.DataSource = mgr.GetUsersWithModelPermission(PID); usersWithPermissionToModel.DataBind(); } }
protected void Page_Load(object sender, EventArgs e) { PermissionsManager mgr = new PermissionsManager(); var pid = Request.QueryString["ContentObjectID"]; this.PID = pid; //ddlPermission2.Items.Clear(); if (!IsPostBack) { foreach (var item in Enum.GetNames(typeof(vwarDAL.ModelPermissionLevel))) { if (item.ToString() != "Invisible" && item.ToString() != "NotSet") ddlPermission2.Items.Add(item); } } if(!String.IsNullOrEmpty(PID)) BindGroups(mgr); }
protected void Page_Load(object sender, EventArgs e) { PermissionsManager mgr = new PermissionsManager(); var pid = Request.QueryString["ContentObjectID"]; this.PID = pid; if (!IsPostBack) { foreach (var item in Enum.GetNames(typeof(vwarDAL.ModelPermissionLevel))) { if (item.ToString() != "Invisible" && item.ToString() != "NotSet") ddlUserPermission.Items.Add(item); } } if(!String.IsNullOrEmpty(this.PID)) BindUsers(mgr); usersWithPermissionToModel.RowDeleting += new GridViewDeleteEventHandler(usersWithPermissionToModel_RowDeleting); }
public static string GrantOrDenyRequest(string username,string mode, string pid) { if (Membership.GetUser() == null || !Membership.GetUser().IsApproved) return "You must be logged in! How did you even get here?"; MessageManager messageMgr = new MessageManager(); PermissionsManager permMgr = new PermissionsManager(); ModelPermissionLevel permission = permMgr.GetPermissionLevel(Membership.GetUser().UserName, pid); ModelPermissionLevel userpermission = permMgr.GetPermissionLevel(username, pid); if (userpermission >= ModelPermissionLevel.Fetchable) { permMgr.Dispose(); messageMgr.Dispose(); return username + " already has access permission for this model."; } string result = ""; if (permission >= ModelPermissionLevel.Editable) { if (mode == "Grant") { permMgr.SetModelToUserLevel(Membership.GetUser().UserName, pid, username, ModelPermissionLevel.Fetchable); messageMgr.SendMessage(Membership.GetUser().UserName, username, "Request approved for model " + pid, "The owner of model <a href='/public/model.aspx?ContentObjectID=" + pid + "'>" + pid + "</a> has granted your request for access. You may now download the model.", Membership.GetUser().UserName); result = "You have granted "+ username +" permission to this model. A message will be sent notifying the user of your response."; } if (mode == "Deny") { messageMgr.SendMessage(Membership.GetUser().UserName, username, "Request denied for model " + pid, "The owner of model <a href='/public/model.aspx?ContentObjectID=" + pid + "'>" + pid + "</a> has denied your request for access.", Membership.GetUser().UserName); result = "You have denied " + username + " permission to this model. A message will be sent notifying the user of your response."; } } else { result = "You do not have permission to grant or deny this request."; } permMgr.Dispose(); messageMgr.Dispose(); return result; }
public bool TryDoCommand(Players.Player player, string chat, List <string> split) { if (!chat.StartsWith("/archive", StringComparison.OrdinalIgnoreCase)) { return(false); } if (player == null || player.ID == NetworkID.Server || !PermissionsManager.CheckAndWarnPermission(player, new PermissionsManager.Permission(GameLoader.NAMESPACE + ".Permissions.Archive"))) { return(true); } foreach (var c in ServerManager.ColonyTracker.ColoniesByID.Values) { ColonyArchive.SaveOffline(c); } return(true); }
//Misc checks to call a command public static bool CheckCommand(Players.Player player) { //Player exists if (null == player || NetworkID.Server == player.ID) { return(false); } //Player has permission if (!PermissionsManager.CheckAndWarnPermission(player, "khanx.wand")) { return(false); } AdvancedWand wand = AdvancedWand.GetAdvancedWand(player); //Wand is OFF if (!wand.active) { Chatting.Chat.Send(player, "<color=orange>Wand is OFF, use //wand to activate</color>"); return(false); } //Pos1 initialized if (!wand.area.IsPos1Initialized()) { Chatting.Chat.Send(player, "<color=orange>Pos 1 not initialized</color>"); return(false); } //Pos2 initialized if (!wand.area.IsPos2Initialized()) { Chatting.Chat.Send(player, "<color=orange>Pos 2 not initialized</color>"); return(false); } return(true); }
public bool TryDoCommand(Players.Player player, string chat, List <string> splits) { if (!chat.Trim().ToLower().Equals("/empire_setrank")) { return(false); } if (!PermissionsManager.CheckAndWarnPermission(player, "khanx.imperium")) { return(true); } if (Empire.GetEmpire(player) == null) { Chatting.Chat.Send(player, "<color=orange>You do not belong to any empire.</color>"); return(true); } EmpireMenu.SendMenuSetRank(player); return(true); }
public bool TryDoCommand(Players.Player causedBy, string chattext) { try { if (PermissionsManager.CheckAndWarnPermission(causedBy, KingdomsModEntries.MOD_PREFIX + $"kill{KingdomType}")) { NpcKingdom closestFarm; if (chattext.Equals($"/kill{KingdomType} all")) { KingdomsTracker.GetAllByType(KingdomType).ForEach(kingdom => kingdom.Kill()); KingdomsTracker.SendKingdomNotification($"killed all {KingdomType}"); } else if (KingdomsTracker.TryGetClosest(KingdomType, causedBy.VoxelPosition, out closestFarm)) { closestFarm.Kill(); KingdomsTracker.SendKingdomNotification($"Killed {KingdomType} at {closestFarm.Origin}"); } } } catch (Exception exception) { Log.WriteError($"Exception while parsing command; {exception.Message} - {exception.StackTrace}"); } return(true); }
public bool AddUserToGroup(string username, string groupname) { PermissionsManager permissionsManager = new PermissionsManager(); if (Context.User.Identity.IsAuthenticated) { if (Website.Common.IsValidUser(username)) { if (permissionsManager.GetGroupsByOwner(Context.User.Identity.Name).Contains(groupname)) { PermissionErrorCode ret = permissionsManager.AddUserToGroup(Context.User.Identity.Name, groupname, username); if (ret == PermissionErrorCode.Ok) { permissionsManager.Dispose(); return true; } } } } permissionsManager.Dispose(); return false; }
protected void Page_Load(object sender, EventArgs e) { PermissionsManager mgr = new PermissionsManager(); var pid = Request.QueryString["ContentObjectID"]; this.PID = pid; if (!IsPostBack) { foreach (var item in Enum.GetNames(typeof(vwarDAL.ModelPermissionLevel))) { if (item.ToString() != "Invisible" && item.ToString() != "NotSet") { ddlUserPermission.Items.Add(item); } } } if (!String.IsNullOrEmpty(this.PID)) { BindUsers(mgr); } usersWithPermissionToModel.RowDeleting += new GridViewDeleteEventHandler(usersWithPermissionToModel_RowDeleting); }
public bool AddUserToGroup(string username, string groupname) { PermissionsManager permissionsManager = new PermissionsManager(); if (Context.User.Identity.IsAuthenticated) { if (Website.Common.IsValidUser(username)) { if (permissionsManager.GetGroupsByOwner(Context.User.Identity.Name).Contains(groupname)) { PermissionErrorCode ret = permissionsManager.AddUserToGroup(Context.User.Identity.Name, groupname, username); if (ret == PermissionErrorCode.Ok) { permissionsManager.Dispose(); return(true); } } } } permissionsManager.Dispose(); return(false); }
public void EnableCommand(Players.Player causedBy, string param) { if (!PermissionsManager.CheckAndWarnPermission(causedBy, AntiGrief.MOD_PREFIX + "announcements.enable")) { return; } if (param.Length > 0) { int Index; if (!TryGetIndex(causedBy, param, ENABLE_PREFIX, out Index)) { return; } Announcements.EnableAnnouncement(Index); Chat.Send(causedBy, $"Enabled announcement {Index}"); } else { Announcements.EnableAllAnnouncements(); Chat.Send(causedBy, "Enabled all announcements"); } }
protected override bool RunCommand(Players.Player ply, string[] args, NetworkID target) { if (PermissionsManager.CheckAndWarnPermission(ply, "chunk.info") && ColonyAPI.Managers.ConfigManager.getConfigBoolean("ColonyPlusPlus-Utilities", "chunks.enabled")) { Vector3Int pos = ColonyAPI.Managers.WorldManager.positionToVector3Int(ply.Position).ToChunk(); string chunkName = ColonyAPI.Managers.WorldManager.XZPositionToString(pos); if (Managers.WorldManager.ChunkDataList.ContainsKey(chunkName)) { Data.ChunkData c = Managers.WorldManager.ChunkDataList[chunkName]; ColonyAPI.Helpers.Chat.sendSilent(ply, String.Format("Chunk data for chunk: {0}", chunkName), ColonyAPI.Helpers.Chat.ChatColour.lime, ColonyAPI.Helpers.Chat.ChatStyle.bold); ColonyAPI.Helpers.Chat.sendSilent(ply, String.Format("Currently owned: {0}", c.hasOwner()), ColonyAPI.Helpers.Chat.ChatColour.lime, ColonyAPI.Helpers.Chat.ChatStyle.bold); if (c.hasOwner()) { ColonyAPI.Helpers.Chat.sendSilent(ply, String.Format("Currently owned by: {0}", Players.GetPlayer(c.getOwner()).Name), ColonyAPI.Helpers.Chat.ChatColour.lime, ColonyAPI.Helpers.Chat.ChatStyle.bold); } string prevOwners = ""; foreach (NetworkID n in c.ownerHistory) { prevOwners += Players.GetPlayer(n).Name + ", "; } ColonyAPI.Helpers.Chat.sendSilent(ply, String.Format("Previous Owners ({0}): {1}", c.ownerHistory.Count, prevOwners), ColonyAPI.Helpers.Chat.ChatColour.lime, ColonyAPI.Helpers.Chat.ChatStyle.bold); } else { ColonyAPI.Helpers.Chat.sendSilent(ply, "No chunk data", ColonyAPI.Helpers.Chat.ChatColour.red, ColonyAPI.Helpers.Chat.ChatStyle.bold); } } else { ColonyAPI.Helpers.Chat.sendSilent(ply, "You cannot check chunk info", ColonyAPI.Helpers.Chat.ChatColour.red, ColonyAPI.Helpers.Chat.ChatStyle.bold); } return(true); }
public bool TryDoCommand(Players.Player causedBy, string chattext, List <string> splits) { if (!splits[0].Equals("/unmute")) { return(false); } if (!PermissionsManager.CheckAndWarnPermission(causedBy, AntiGrief.MOD_PREFIX + "mute")) { return(true); } var m = Regex.Match(chattext, @"/unmute (?<targetplayername>['].+[']|[^ ]+)"); if (!m.Success) { Chat.Send(causedBy, "Syntax: /unmute [targetplayername]"); return(true); } var targetPlayerName = m.Groups["targetplayername"].Value; Players.Player targetPlayer; string error; if (!PlayerHelper.TryGetPlayer(targetPlayerName, out targetPlayer, out error)) { Chat.Send(causedBy, $"Could not find target player '{targetPlayerName}': {error}"); return(true); } if (MuteList.MutedMinutes.ContainsKey(targetPlayer)) { MuteList.MutedMinutes.Remove(targetPlayer); Log.Write($"Unmuted {targetPlayer.Name}"); } else { Chat.Send(causedBy, $"{targetPlayer.Name} was not muted"); } return(true); }
/// <summary> /// /// </summary> /// <param name="c"></param> protected void BindViewData(Control c) { PermissionsManager permManager = new PermissionsManager(); string username = HttpContext.Current.User.Identity.Name; //You gotta love how FindControl isn't recursive... DataList list = (DataList)c.FindControl("RotatorLayoutTable") .FindControl("RotatorListViewRow") .FindControl("RotatorListViewColumn") .FindControl("RotatorListView"); ISearchProxy permissionsHonoringProxy = new DataAccessFactory().CreateSearchProxy(HttpContext.Current.User.Identity.Name); switch (c.ID) { case "HighestRatedRotator": list.DataSource = permissionsHonoringProxy.GetByRating(4); break; case "MostPopularRotator": list.DataSource = permissionsHonoringProxy.GetByViews(4); break; case "RecentlyUpdatedRotator": list.DataSource = permissionsHonoringProxy.GetByLastUpdated(4); break; case "RandomRotator": list.DataSource = permissionsHonoringProxy.GetByRandom(4); break; default: throw new Exception("No control '" + c.ID + "' could be found to bind data to."); } list.DataBind(); permissionsHonoringProxy.Dispose(); permManager.Dispose(); }
public void btnSubmit_Click(object sender, EventArgs e) { PermissionsManager mgr = new PermissionsManager(); GroupPolicyLevel lvl; Enum.TryParse <GroupPolicyLevel>(ddlPermissionLevel.SelectedValue, out lvl); var result = mgr.CreateGroup(txtGroupName.Text, Context.User.Identity.Name, txtGroupDescription.Text, lvl); switch (result) { case PermissionErrorCode.AlreadyExists: lblErrorMessage.Text = "Group Already Exists"; break; case PermissionErrorCode.NotAuthorized: break; case PermissionErrorCode.DoesNotExist: break; case PermissionErrorCode.OutOfRange: break; case PermissionErrorCode.AlreadyIncluded: break; case PermissionErrorCode.NotIncluded: break; case PermissionErrorCode.Ok: BindGroups(); break; default: break; } mgr.Dispose(); }
public static GetSupportingFilesResponse GetSupportingFiles(string pid) { APIWrapper api = null; if (Membership.GetUser() != null && Membership.GetUser().IsApproved) { api = new APIWrapper(Membership.GetUser().UserName, null); } else { api = new APIWrapper(vwarDAL.DefaultUsers.Anonymous[0], null); } vwar.service.host.Metadata md = api.GetMetadata(pid, "00-00-00"); if (md == null) { return(new GetSupportingFilesResponse(false)); } PermissionsManager prm = new PermissionsManager(); MembershipUser user = Membership.GetUser(); ModelPermissionLevel Permission = prm.GetPermissionLevel(user != null ? user.UserName:vwarDAL.DefaultUsers.Anonymous[0], pid); prm.Dispose(); GetSupportingFilesResponse response = new GetSupportingFilesResponse(true); response.DownloadAllowed = Permission >= ModelPermissionLevel.Fetchable; response.EditAllowed = Permission >= ModelPermissionLevel.Editable; response.files = new vwarDAL.SupportingFile[md.SupportingFiles.Count]; for (int i = 0; i < md.SupportingFiles.Count; i++) { response.files[i] = new vwarDAL.SupportingFile(md.SupportingFiles[i].Filename, md.SupportingFiles[i].Description, ""); } return(response); }
public bool TryDoCommand(Players.Player causedBy, string chattext) { if (causedBy == null) { return(true); } else if (!PermissionsManager.CheckAndWarnPermission(causedBy, CapsulesModEntries.CAPSULE_PERMISSION)) { return(true); } int amount = 1; var matched = Regex.Match(chattext, @"/capsule (?<name>.+) (?<amount>\d+)"); if (!matched.Success) { matched = Regex.Match(chattext, @"/capsule (?<name>.+)"); if (!matched.Success) { Chat.Send(causedBy, "Command didn't match, use /capsule name amount"); return(true); } } else { amount = Int32.Parse(matched.Groups["amount"].Value); } string blueprintName = matched.Groups["name"].Value; string blueprintFullname = ManagerBlueprints.BLUEPRINTS_PREFIX + blueprintName; if (!ManagerBlueprints.blueprints.ContainsKey(blueprintFullname)) { Chat.Send(causedBy, string.Format("Blueprint '{0}' not known", blueprintName)); return(true); } Stockpile.GetStockPile(causedBy).Add(ItemTypes.IndexLookup.GetIndex(blueprintFullname + CapsulesModEntries.CAPSULE_SUFFIX), amount); Chat.Send(causedBy, string.Format("Added {0} emperor capsule '{1}' to your stockpile", amount, blueprintName)); return(true); }
public bool TryDoCommand(Players.Player causedBy, string chattext, List <string> splits) { if (!splits[0].Equals("/eventstart")) { return(false); } if (!PermissionsManager.CheckAndWarnPermission(causedBy, AntiGrief.MOD_PREFIX + "events")) { return(true); } if (Events.currentLocation != Vector3Int.invalidPos) { Chat.Send(causedBy, "There is already an ongoing event"); return(true); } Events.currentLocation = causedBy.VoxelPosition; Events.originPositions.Clear(); if (Events.msgAllStarted.Length > 0) { Chat.SendToConnected(Events.msgAllStarted.Replace("{startername}", causedBy.Name)); } return(true); }
public bool TryDoCommand(Players.Player player, string chat, List <string> splits) { if (!chat.Trim().ToLower().StartsWith("//wand")) { return(false); } //Player exists if (null == player || NetworkID.Server == player.ID) { return(true); } //Check permissions if (!PermissionsManager.CheckAndWarnPermission(player, "khanx.wand")) { return(true); } AdvancedWand wand = AdvancedWand.GetAdvancedWand(player); //Change the status of the wand wand.active = !wand.active; if (wand.active) { Chat.Send(player, "<color=lime>Wand ON</color>"); } else { Chat.Send(player, "<color=lime>Wand OFF</color>"); AdvancedWand.RemoveAdvancedWand(player); } return(true); }
public bool TryDoCommand(Players.Player causedBy, string chattext, List <string> splits) { if (!splits[0].Equals("/warpspawn")) { return(false); } if (!PermissionsManager.CheckAndWarnPermission(causedBy, AntiGrief.MOD_PREFIX + "warp.spawn.self")) { return(true); } var m = Regex.Match(chattext, @"/warpspawn ?(?<playername>.+)?"); if (!m.Success) { Chat.Send(causedBy, "use /warpspawn or /warpspawn <playername>"); return(true); } var TeleportPlayer = causedBy; var TeleportPlayerName = m.Groups ["playername"].Value; if (TeleportPlayerName.Length > 0) { if (!PermissionsManager.CheckAndWarnPermission(causedBy, AntiGrief.MOD_PREFIX + "warp.spawn")) { return(true); } string Error; if (!PlayerHelper.TryGetPlayer(TeleportPlayerName, out TeleportPlayer, out Error)) { Chat.Send(causedBy, $"Could not find teleport player '{TeleportPlayerName}'; {Error}"); return(true); } } Teleport.TeleportTo(TeleportPlayer, ServerManager.TerrainGenerator.GetDefaultSpawnLocation().Vector); return(true); }
public bool TryDoCommand(Players.Player causedBy, string chattext, List <string> splits) { if (!splits[0].Equals("/setjail")) { return(false); } if (!PermissionsManager.CheckAndWarnPermission(causedBy, AntiGrief.MOD_PREFIX + "setjailposition")) { return(true); } if (chattext.Equals("/setjail visitor")) { JailManager.setJailVisitorPosition(causedBy.Position); Chat.Send(causedBy, "Jail visiting position set"); return(true); } var m = Regex.Match(chattext, @"/setjail (?<range>[0-9]+)"); if (m.Success) { uint range = 0; if (!uint.TryParse(m.Groups["range"].Value, out range)) { Chat.Send(causedBy, "Could not parse range value"); } JailManager.setJailPosition(causedBy, range); Chat.Send(causedBy, $"Jail set to your current position with range {range}"); } else { JailManager.setJailPosition(causedBy); Chat.Send(causedBy, $"Jail set to your current position and default range {JailManager.DEFAULT_RANGE}"); } return(true); }
public void IntervalCommand(Players.Player causedBy, string param) { if (!PermissionsManager.CheckAndWarnPermission(causedBy, AntiGrief.MOD_PREFIX + "announcements.interval")) { return; } var m = Regex.Match(param, @"(?<intervalSeconds>\d+)"); if (!m.Success) { Chat.Send(causedBy, $"Params didn't match, use {INTERVAL_PREFIX} [intervalSeconds]"); return; } int Interval; string StrInterval = m.Groups ["intervalSeconds"].Value; if (!int.TryParse(StrInterval, out Interval)) { Chat.Send(causedBy, $"Could not parse given parameter '{StrInterval}' as index number"); return; } Announcements.SetIntervalSeconds(Interval); Chat.Send(causedBy, $"Set announcement interval to {Interval} seconds"); }
public void GetObjectForUserIncludedInGroupTest() { using (var c = new DataObjectCleaner()) { var user = GetUniqueUserForTesting(); c.Insert(user); var group = new TblGroups { Name = "test group with user" }; c.Insert(group); ServerModel.DB.Link(user, group); var course = new TblCourses { Name = "test_course", Description = "test description" }; c.Insert(course); PermissionsManager.Grand(course, FxCourseOperations.Use, null, group.ID, DateTimeInterval.Full); Assert.AreEqual(0, PermissionsManager.GetObjectsForGroup(SECURED_OBJECT_TYPE.COURSE, group.ID, FxCourseOperations.Modify.ID, null).Count); var ids1 = PermissionsManager.GetObjectsForGroup(SECURED_OBJECT_TYPE.COURSE, group.ID, FxCourseOperations.Use.ID, null); Assert.AreEqual(1, ids1.Count); Assert.AreEqual(course.ID, ids1[0]); var ids2 = PermissionsManager.GetObjectsForUser(SECURED_OBJECT_TYPE.COURSE, user.ID, null, null); Assert.AreEqual(1, ids2.Count); Assert.AreEqual(course.ID, ids2[0]); var ids3 = PermissionsManager.GetObjectsForUser(SECURED_OBJECT_TYPE.COURSE, user.ID, FxCourseOperations.Use.ID, null); Assert.AreEqual(1, ids3.Count); Assert.AreEqual(course.ID, ids3[0]); } }
public void SafeDeleteAndPermissionManagerTest_GetObjectsForUser() { using (var c = new DataObjectCleaner()) { var u = GetUniqueUserForTesting(); c.Insert(u); var g = new TblGroups { Name = "g1" }; ServerModel.DB.Insert(g); PermissionsManager.Grand(g, FxGroupOperations.View, u.ID, null, DateTimeInterval.Full); var res1 = PermissionsManager.GetObjectsForUser(SECURED_OBJECT_TYPE.GROUP, u.ID, null, null); Assert.AreEqual(1, res1.Count); Assert.AreEqual(g.ID, res1[0]); ServerModel.DB.Delete <TblGroups>(g.ID); var res2 = PermissionsManager.GetObjectsForUser(SECURED_OBJECT_TYPE.GROUP, u.ID, null, null); Assert.AreEqual(0, res2.Count); } }
internal static async Task InfiniteStatsTick() { if (!IsPlayerDead(PlayerId())) // Allows respawning after killing yourself { if (PermissionsManager.IsAllowed(Permission.PMGodMode) && UserDefaults.PlayerGodMode) { Function.Call((Hash)0xC6258F41D86676E0, PlayerPedId(), 0, 100.0f); } if (PermissionsManager.IsAllowed(Permission.PMInfiniteStamina) && UserDefaults.PlayerInfiniteStamina) { RestorePlayerStamina(PlayerId(), 100.0f); Function.Call((Hash)0xC6258F41D86676E0, PlayerPedId(), 1, 100.0f); } if (PermissionsManager.IsAllowed(Permission.PMInfiniteDeadEye) && UserDefaults.PlayerInfiniteDeadEye) { Function.Call((Hash)0xC6258F41D86676E0, PlayerPedId(), 2, 100.0f); } } await Delay(1000); await Task.FromResult(0); }
public bool TryDoCommand(Players.Player causedBy, string chattext, List <string> splits) { if (!splits[0].Equals("/areashow")) { return(false); } if (!PermissionsManager.CheckAndWarnPermission(causedBy, AntiGrief.MOD_PREFIX + "areashow")) { return(true); } // if parameter action given toggle all areas shown Match m = Regex.Match(chattext, @"/areashow ?(?<action>.+)?"); string action = m.Groups["action"].Value; if (action.Equals("add")) { if (AreaShowManager.Add(causedBy)) { Chat.Send(causedBy, "You now see area jobs of all players"); } return(true); } else if (action.Equals("remove")) { if (AreaShowManager.Remove(causedBy)) { Chat.Send(causedBy, "You no longer see area jobs of all players"); } return(true); } // without action parameter just trigger a data send AreaJobTracker.SendData(causedBy); return(true); }
/// <summary> /// /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void CreateUserWizardStep1_CreatedUser(object sender, EventArgs e) { // Create an empty Profile for the newly created user //ProfileCommon p = (ProfileCommon)ProfileCommon.Create(CreateUserWizard1.UserName, true); // Populate some Profile properties off of the create user wizard //p.FirstName = ((TextBox)CreateUserWizard1.CreateUserStep.Controls[0].FindControl("FirstName")).Text; //p.LastName = ((TextBox)CreateUserWizard1.CreateUserStep.Controls[0].FindControl("LastName")).Text; //load new membership user and set 'Comment' property to {FirstName}|{LastName} MembershipUser mu = String.IsNullOrEmpty(CreateUserWizard1.UserName) ? Membership.GetUser(CreateOpenIDWizard.UserName) : Membership.GetUser(CreateUserWizard1.UserName.Trim()); //approved = false by default if (mu != null) { //set approved mu.IsApproved = Website.Config.MembershipUserApprovedByDefault; string targetRole = "Users"; if (!Roles.IsUserInRole(mu.UserName, targetRole)) { Roles.AddUserToRole(mu.UserName, targetRole); } //create user profile UserProfile p = null; string memGUID = mu.ProviderUserKey.ToString().Trim(); string fName = ((TextBox)CreateUserWizard1.CreateUserStep.Controls[0].FindControl("FirstName")).Text; string lName = ((TextBox)CreateUserWizard1.CreateUserStep.Controls[0].FindControl("LastName")).Text; string email = ((TextBox)CreateUserWizard1.CreateUserStep.Controls[0].FindControl("Email")).Text; try { p = UserProfileDB.InsertUserProfile(memGUID, fName, lName, email, email, email); mu.Comment = p.FirstName.Trim() + "|" + p.LastName.Trim(); Membership.UpdateUser(mu); Database.ConnString = Website.Config.PostgreSQLConnectionString; Database.DBType = "MySQL"; Database.DBPrefix = "DMG"; email = Functions.RepairString(email); string password = Functions.Encrypt(Functions.RepairString(CreateUserWizard1.Password)); PermissionsManager mgr = new PermissionsManager(); mgr.AddUserToGroup(System.Configuration.ConfigurationManager.AppSettings["DefaultAdminName"], vwarDAL.DefaultGroups.AllUsers, mu.UserName); if (Website.Config.SendEmailForNewRegistrations) { Website.Mail.SendNewRegistrationNotificationEmail(mu); } mgr.Dispose(); //Database.Write("INSERT INTO " + Database.DBPrefix + "_MEMBERS (MEMBER_USERNAME, MEMBER_PASSWORD, MEMBER_LEVEL, MEMBER_EMAIL, MEMBER_LOCATION, MEMBER_HOMEPAGE, MEMBER_SIGNATURE, MEMBER_SIGNATURE_SHOW, MEMBER_IM_AOL, MEMBER_IM_ICQ, MEMBER_IM_MSN, MEMBER_IM_YAHOO, MEMBER_POSTS, MEMBER_DATE_JOINED, MEMBER_DATE_LASTVISIT, MEMBER_TITLE, MEMBER_TITLE_ALLOWCUSTOM, MEMBER_TITLE_USECUSTOM, MEMBER_EMAIL_SHOW, MEMBER_IP_LAST, MEMBER_IP_ORIGINAL, MEMBER_REALNAME, MEMBER_OCCUPATION, MEMBER_SEX, MEMBER_AGE, MEMBER_BIRTHDAY, MEMBER_NOTES, MEMBER_FAVORITESITE, MEMBER_PHOTO, MEMBER_AVATAR, MEMBER_AVATAR_SHOW, MEMBER_AVATAR_ALLOWCUSTOM, MEMBER_AVATAR_USECUSTOM, MEMBER_AVATAR_CUSTOMLOADED, MEMBER_AVATAR_CUSTOMTYPE, MEMBER_VALIDATED, MEMBER_VALIDATION_STRING, MEMBER_RANKING) VALUES ('" + email + "','" + password + "', " + 1 + ", '" + email + "', ' ', ' ', ' ', 0, '', '', '', '', 0, " + Database.GetTimeStamp() + ", " + Database.GetTimeStamp() + ", '', 0, 0, 0, '', '', '', '', '', '', '', '', '', '', 1, 0 , 0, 0, 0, 'jpg', 1, '', 0)"); } catch { } } // Save profile - must be done since we explicitly created it // p.Save(); if (Website.Config.MembershipUserApprovedByDefault == false) { //not approved FormsAuthentication.SignOut(); MultiView1.SetActiveView(ConfirmationView); } else { //approved FormsAuthentication.RedirectFromLoginPage(CreateUserWizard1.UserName, false); Website.Mail.SendRegistrationApprovalEmail(mu.Email); } }
private void ProcessWatchers(List<IssueDto> issues, DateTime lastChecked) { var lastCheckedLocal = lastChecked.ToLocal(_issueManager.UserContext.User.TimeZone); Dictionary<int, WatcherData> targets = new Dictionary<int, WatcherData>(); Dictionary<string, WatcherData> emailTargets = new Dictionary<string, WatcherData>(); var userManager = new UserManager(_issueManager); List<int> projectsMissingFollowerTemplate = new List<int>(); int emailWatchers = -3; // Build array of users that are watching issues foreach (var issue in issues) { //Safety check if (issue.Watchers.Count == 0) continue; if (issue.Revised == issue.Created) continue; if (issue.Revised.ToUtc(_issueManager.UserContext.User.TimeZone) <= lastChecked) continue; var history = _issueManager.GetHistory(issue); issue.History = new List<IssueAuditDto>(history); history.RemoveAll(h => h.Entity.Created <= lastCheckedLocal); foreach (var watcher in issue.Watchers) { if (watcher.Entity.UserId != null) { if (targets.ContainsKey(watcher.Entity.UserId.Value)) { WatcherData data = targets[watcher.Entity.UserId.Value]; var permissionManager = new PermissionsManager(data.User, _types, _permissionSets, _organizations, _issueManager.UserContext.Config.HelpDeskModeGroup, false); if (!permissionManager.CanSeeItem(issue.Project, issue)) continue; if (!data.User.Entity.EmailMeMyChanges && IsUserOnlyChange(history, data.User.Entity.Id)) continue; data.IssueId.Add(issue.Entity.Id); } else { WatcherData data = new WatcherData(); data.User = userManager.Get(watcher.Entity.UserId.Value); if (data.User.Entity.Active) { var permissionManager = new PermissionsManager(data.User, _types, _permissionSets, _organizations, _issueManager.UserContext.Config.HelpDeskModeGroup, false); if (!permissionManager.CanSeeItem(issue.Project, issue)) continue; if (!data.User.Entity.EmailMeMyChanges && IsUserOnlyChange(history, data.User.Entity.Id)) continue; data.IssueId.Add(issue.Entity.Id); targets.Add(watcher.Entity.UserId.Value, data); } } } else { if (emailTargets.ContainsKey(watcher.Entity.Email.ToLower())) { WatcherData data = emailTargets[watcher.Entity.Email.ToLower()]; data = targets[data.User.Entity.Id]; data.IssueId.Add(issue.Entity.Id); } else { WatcherData data = new WatcherData(); data.User = new UserDto(new User()); data.User.Entity.Id = emailWatchers--; data.User.Entity.Email = watcher.Entity.Email; data.User.Entity.EmailMe = true; data.User.Entity.EmailMeMyChanges = true; data.User.Entity.ProjectGroups.Add(new ProjectGroupMembership() { ProjectGroupId = Constants.GlobalGroupEveryone, UserId = data.User.Entity.Id }); UserSettings settings = new UserSettings(); settings.IndividualFollowerAlerts = true; data.User.Entity.Settings = settings.ToJson(); var group = new ProjectGroup() { Id = Constants.GlobalGroupEveryone, Members = new List<ProjectGroupMembership>() }; group.Members2.Add(new ProjectGroupMembership() { UserId = data.User.Entity.Id, ProjectGroupId = Constants.GlobalGroupEveryone }); data.User.ProjectGroups.Add(group); data.IssueId.Add(issue.Entity.Id); emailTargets.Add(watcher.Entity.Email.ToLower(), data); targets.Add(data.User.Entity.Id, data); } } } } AlertsTemplateHelper alerts = new AlertsTemplateHelper(_templates, GetUrl(_issueManager)); // Now loop through users sending them watcher summary email Dictionary<int, List<IssueCommentDto>> originalComments = new Dictionary<int, List<IssueCommentDto>>(); List<int> processedProjects; foreach (var target in targets) { processedProjects = new List<int>(); if (originalComments.Count > 0) { foreach (var kv in originalComments) { IssueDto issue = issues.Find(i => i.Entity.Id == kv.Key); // Safety check if (issue == null || issue.Entity.IsNew) continue; issue.Comments = kv.Value; } originalComments = new Dictionary<int, List<IssueCommentDto>>(); } var recipient = target.Value; // Safety check if (!recipient.User.Entity.EmailMe || recipient.User.Entity.Email.IsEmpty()) continue; AlertTypeWatchersTemplateModel model = new AlertTypeWatchersTemplateModel(); model.TheRecipient = recipient.User; model.Version = GeminiVersion.Version; model.GeminiUrl = alerts.GeminiUrl; foreach (int issueId in recipient.IssueId) { IssueDto issue = issues.Find(i => i.Entity.Id == issueId); // Safety check if (issue == null || issue.Entity.IsNew) continue; issue.ChangeLog = _issueManager.GetChangeLog(issue, _issueManager.UserContext.User, recipient.User, lastCheckedLocal); var permissionManager = new PermissionsManager(recipient.User, _types, _permissionSets, _organizations, _issueManager.UserContext.Config.HelpDeskModeGroup, false); foreach (var comment in issue.Comments) { if (!permissionManager.CanSeeComment(issue, comment)) { originalComments.Add(issueId, issue.Comments); List<IssueCommentDto> comments = new List<IssueCommentDto>(issue.Comments); comments.RemoveAll(c => !permissionManager.CanSeeComment(issue, c)); issue.Comments = comments; break; } } if (issue.ChangeLog.Count == 0) continue; if (recipient.User.GetSettings().IndividualFollowerAlerts) { var template = alerts.FindTemplateForProject(AlertTemplateType.Updated, issue.Entity.ProjectId); if (template == null) { LogDebugMessage("No update notification template found"); continue; } var indModel = new AlertTypeIndividualTemplateModel(); indModel.GeminiUrl = model.GeminiUrl; indModel.LinkViewItem = NavigationHelper.GetIssueUrl(_issueManager.UserContext, issue.Entity.ProjectId, issue.EscapedProjectCode, issue.Entity.Id); indModel.TheItem = issue; indModel.TheRecipient = recipient.User; indModel.Version = GeminiVersion.Version; indModel.IsNewItem = false; string html = alerts.GenerateHtml(template, indModel); if (GeminiApp.GeminiLicense.IsFree) html = alerts.AddSignature(html); string log; string subject = template.Options.Subject.HasValue() ? alerts.GenerateHtml(template, indModel, true) : string.Format("[{0}] {1} {2} ({3})", issue.IssueKey, issue.Type, "Updated", issue.Title, issue.IsClosed ? "Closed" : string.Empty); EmailHelper.Send(_issueManager.UserContext.Config, subject, html, recipient.User.Entity.Email, recipient.User.Fullname, true, out log); } else { model.TheItemsUpdated.Add(issue); } } if (recipient.User.GetSettings().IndividualFollowerAlerts) continue; // Safety check! if (model.ChangeCount > 0) { var watcherAlertTemplates = alerts.Templates.FindAll(s => s.AlertType == AlertTemplateType.Watchers); if (watcherAlertTemplates.Count == 0) { LogDebugMessage("No follower notification template found"); continue; } if (!watcherAlertTemplates.Any(p => p.GetAssociatedProjectValue().IsEmpty())) { List<Project> allItemProjects = model.TheItemsUpdated.Select(s => s.Project).ToList(); allItemProjects = allItemProjects.Where(s => !watcherAlertTemplates.Any(a => a.GetAssociatedProjects().Contains(s.Id))).ToList(); if (projectsMissingFollowerTemplate.Count > 0) { allItemProjects = allItemProjects.Where(s => !projectsMissingFollowerTemplate.Contains(s.Id)).ToList(); } if (allItemProjects.Count > 0) { LogDebugMessage(string.Concat("No follower notification template found for project ", string.Join(", ", allItemProjects.Select(s => s.Name).Distinct()))); projectsMissingFollowerTemplate.AddRange(allItemProjects.Select(s => s.Id).Distinct()); } } watcherAlertTemplates.Sort((x, y) => y.GetAssociatedProjectValue().CompareTo(x.GetAssociatedProjectValue())); foreach(var watcherTemplate in watcherAlertTemplates) { var allTemplateProjects = watcherTemplate.GetAssociatedProjects(); var issuesTemplate = allTemplateProjects.Count == 0 ? model.TheItemsUpdated : model.TheItemsUpdated.FindAll(s => allTemplateProjects.Contains(s.Entity.ProjectId)); if (issuesTemplate.Count == 0) continue; var projectIds = issuesTemplate.Select(s => s.Entity.ProjectId).Distinct(); if (processedProjects.Count > 0) { projectIds = projectIds.Where(s => !processedProjects.Contains(s)); issuesTemplate = issuesTemplate.Where(s => !processedProjects.Contains(s.Entity.ProjectId)).ToList(); } if (processedProjects.Contains(0) || projectIds.Count() == 0 || issuesTemplate.Count == 0) continue; AlertTypeWatchersTemplateModel projectTemplateModel = new AlertTypeWatchersTemplateModel(); projectTemplateModel.TheItemsUpdated.AddRange(issuesTemplate); projectTemplateModel.TheRecipient = model.TheRecipient; projectTemplateModel.Version = model.Version; projectTemplateModel.GeminiUrl = model.GeminiUrl; AlertTemplate template = alerts.FindTemplateForProject(AlertTemplateType.Watchers, issuesTemplate.First().Entity.ProjectId); if (template.Id == 0) { continue; } // Generate email template string html = alerts.GenerateHtml(template, projectTemplateModel); if (GeminiApp.GeminiLicense.IsFree) html = alerts.AddSignature(html); string subject = template.Options.Subject.HasValue() ? alerts.GenerateHtml(template, projectTemplateModel, true) : string.Format("{0} {1}", projectTemplateModel.ChangeCount, "Gemini Updates"); // Send email string log; EmailHelper.Send(_issueManager.UserContext.Config, subject, html, recipient.User.Entity.Email, recipient.User.Entity.Fullname, true, out log); if (allTemplateProjects.Count == 0) { processedProjects.Add(0); } else { processedProjects.AddRange(projectIds); } } } } }
private void ProcessAppNavCardAlerts() { var navigationCardsManager = new NavigationCardsManager(_issueManager); List<NavigationCard> cards = navigationCardsManager.GetPendingAlertCards(); LogDebugMessage("Email templates loaded: " + _templates.Count); LogDebugMessage("Pending card alerts: " + cards.Count); // ? We need to store user id and issue id for every email we send out -- avoids dupes? List<string> issuesEmailedToUsers = new List<string>(50); List<string> individualIssuesEmailedToUsers = new List<string>(50); AlertsTemplateHelper alerts = new AlertsTemplateHelper(_templates, GetUrl(_issueManager)); UserManager userManager = new UserManager(_issueManager); bool refreshCache = false; var allOptOuts = navigationCardsManager.GetOptOuts(); foreach (NavigationCard card in cards) { List<IssueDto> individualIssues = new List<IssueDto>(); // Safety checks if (!card.UserId.HasValue) continue; if (card.CardData.Alerts.Count == 0) continue; UserDto recepient = userManager.Get(card.UserId.Value); // Safety check if (!recepient.Entity.EmailMe || recepient.Entity.Email.IsEmpty()) continue; DateTime lastChecked = card.CardData.AlertsLastSent.HasValue ? card.CardData.AlertsLastSent.Value : card.Created; DateTime lastCheckedLocal = lastChecked.ToLocal(_issueManager.UserContext.User.TimeZone); AlertTypeAppNavAlertsTemplateModel model = new AlertTypeAppNavAlertsTemplateModel(); model.TheRecipient = recepient; model.Version = GeminiVersion.Version; model.GeminiUrl = alerts.GeminiUrl; List<int> issuesToAlert = new List<int>(card.CardData.Alerts); foreach (int issueId in issuesToAlert) { IssueDto issue = _issueManager.Get(issueId); // Safety check if (issue == null || issue.Entity.IsNew) continue; // Dupe check string dupeKey = string.Format("{0}-{1}-{2}", recepient.Entity.Id, issueId, card.Id); if (issuesEmailedToUsers.Contains(dupeKey)) continue; var permissionManager = new PermissionsManager(recepient, _types, _permissionSets, _organizations, _issueManager.UserContext.Config.HelpDeskModeGroup, false); if (!permissionManager.CanSeeItem(issue.Project, issue)) continue; foreach (var comment in issue.Comments) { if (!permissionManager.CanSeeComment(issue, comment)) { issue.Comments.RemoveAll(c => !permissionManager.CanSeeComment(issue, c)); break; } } issue.ChangeLog = _issueManager.GetChangeLog(issue, _issueManager.UserContext.User, recepient, lastCheckedLocal); // Populate model for email template if (card.CardData.Subscription.IndividualAlert) individualIssues.Add(issue); if (card.CardData.Subscription.Created && issue.Created.ToUtc(_issueManager.UserContext.User.TimeZone) >= lastChecked) { model.TheItemsCreated.Add(issue); } else { List<IssueAuditDto> allChanges = issue.History.FindAll(h => h.Entity.Created.ToUtc(_issueManager.UserContext.User.TimeZone) >= lastChecked); List<IssueAuditDto> commentChanges = allChanges.FindAll(a => !a.Entity.IsCustom && a.Entity.AttributeChanged == ItemAttributeVisibility.AssociatedComments); List<IssueAuditDto> nonCommentChanges = allChanges.FindAll(a => a.Entity.IsCustom || a.Entity.AttributeChanged != ItemAttributeVisibility.AssociatedComments); // Add comments and updates if (card.CardData.Subscription.Updated && nonCommentChanges.Count > 0 || card.CardData.Subscription.Commented && commentChanges.Count > 0 && issue.Comments.Count > 0) { model.TheItemsUpdated.Add(issue); } if (card.CardData.Subscription.Commented && commentChanges.Count > 0 && issue.Comments.Count > 0) { model.TheItemsCommented.Add(issue); } } // Record the fact that we have processed this issue for this recepient (to prevent dupes) issuesEmailedToUsers.Add(dupeKey); } model.CardTitle = string.Format("{0} {1}", card.Key, card.Title); model.CardKey = card.Key; model.CardDescription = card.Title; model.CardComment = card.CardData.Comment; model.CardUrl = string.Concat(model.GeminiUrl, "workspace/", card.Id, '/', card.Url); // Safety check! if (model.ChangeCount > 0) { List<UserDto> subscribers = GetCardSubscribers(card, navigationCardsManager, userManager, recepient); //if (!subscribers.Contains(recepient) && subscribers.Find(u => u.Entity.Id == recepient.Entity.Id) == null) subscribers.Insert(0, recepient); if (card.CardData.Subscription.IndividualAlert) { foreach (var user in subscribers) { if (allOptOuts.Any(s => s.UserId == user.Entity.Id && s.CardId == card.Id && s.OptOutType == OptOutEmails.OptOutTypes.Alert)) continue; foreach (var issue in individualIssues) { string individualDupeKey = string.Format("{0}-{1}", user.Entity.Id, issue.Entity.Id); if (individualIssuesEmailedToUsers.Contains(individualDupeKey)) continue; if (user != recepient) { var permissionManager = new PermissionsManager(user, _types, _permissionSets, _organizations, _issueManager.UserContext.Config.HelpDeskModeGroup, false); if (!permissionManager.CanSeeItem(issue.Project, issue)) continue; issue.ChangeLog = _issueManager.GetChangeLog(issue, _issueManager.UserContext.User, user, lastCheckedLocal); } var indModel = new AlertTypeIndividualTemplateModel(); indModel.GeminiUrl = model.GeminiUrl; indModel.LinkViewItem = NavigationHelper.GetIssueUrl(_issueManager.UserContext, issue.Entity.ProjectId, issue.EscapedProjectCode, issue.Entity.Id); indModel.TheItem = issue; indModel.TheRecipient = user; indModel.Version = GeminiVersion.Version; indModel.IsNewItem = model.TheItemsCreated.Contains(issue); indModel.CardKey = model.CardKey; indModel.CardDescription = model.CardDescription; indModel.CardComment = model.CardComment; indModel.CardUrl = model.CardUrl; if (!indModel.IsNewItem && issue.ChangeLog.Count == 0) continue; var template = alerts.FindTemplateForProject(indModel.IsNewItem ? AlertTemplateType.Created : AlertTemplateType.Updated, issue.Entity.ProjectId); string html = alerts.GenerateHtml(template, indModel); if (GeminiApp.GeminiLicense.IsFree) html = alerts.AddSignature(html); // Send email string log; string subject = template.Options.Subject.HasValue() ? alerts.GenerateHtml(template, indModel, true) : string.Format("[{0}] {1} {2} ({3})", issue.IssueKey, issue.Type, model.TheItemsCreated.Contains(issue) ? "Created" : "Updated", issue.Title, issue.IsClosed ? "Closed" : string.Empty); EmailHelper.Send(_issueManager.UserContext.Config, subject, html, user.Entity.Email, user.Fullname, true, out log); individualIssuesEmailedToUsers.Add(individualDupeKey); } } } else { var cloneCreated = new List<IssueDto>(model.TheItemsCreated); var cloneUpdated = new List<IssueDto>(model.TheItemsUpdated); var cloneCommented = new List<IssueDto>(model.TheItemsCommented); // Find email template to use (for this project or fall back to default template) AlertTemplate template = alerts.FindTemplateForProject(AlertTemplateType.AppNavAlerts, 0); foreach (var user in subscribers) { if (allOptOuts.Any(s => s.UserId == user.Entity.Id && s.CardId == card.Id && s.OptOutType == OptOutEmails.OptOutTypes.Alert)) continue; model.TheItemsCreated = new List<IssueDto>(cloneCreated); model.TheItemsUpdated = new List<IssueDto>(cloneUpdated); model.TheItemsCommented = new List<IssueDto>(cloneCommented); if (user != recepient) { var permissionManager = new PermissionsManager(user, _types, _permissionSets, _organizations, _issueManager.UserContext.Config.HelpDeskModeGroup, false); model.TheItemsCreated.RemoveAll(i => !permissionManager.CanSeeItem(i.Project, i)); model.TheItemsUpdated.RemoveAll(i => !permissionManager.CanSeeItem(i.Project, i)); model.TheItemsCommented.RemoveAll(i => !permissionManager.CanSeeItem(i.Project, i)); foreach (var issue in model.TheItemsCreated.Concat(model.TheItemsUpdated).Concat(model.TheItemsCommented)) { issue.ChangeLog = _issueManager.GetChangeLog(issue, _issueManager.UserContext.User, user, lastCheckedLocal); } } //model.TheItemsCreated.RemoveAll(i => i.ChangeLog.Count == 0); model.TheItemsUpdated.RemoveAll(i => i.ChangeLog.Count == 0); model.TheItemsCommented.RemoveAll(i => i.ChangeLog.Count == 0); if (model.ChangeCount == 0) continue; // Generate email template string html = alerts.GenerateHtml(template, model); if (GeminiApp.GeminiLicense.IsFree) html = alerts.AddSignature(html); string subject = template.Options.Subject.HasValue() ? alerts.GenerateHtml(template, model, true) : string.Format("{0} {1}", card.Key, card.Title); // Send email string log; EmailHelper.Send(_issueManager.UserContext.Config, subject, html, user.Entity.Email, user.Fullname, true, out log); } } } // Remove the alert notifications and update the database lock (card.CardData.Alerts) { card.CardData.Alerts.RemoveAll(a => issuesToAlert.Contains(a)); } card.CardData.AlertsLastSent = DateTime.UtcNow; refreshCache = true; navigationCardsManager.Update(card, false, false); } if (refreshCache) { navigationCardsManager.Cache.NavigationCards.Invalidate(); var webNodes = GeminiApp.Container.Resolve<IWebNodes>(); webNodes.AddDataOnAllNodesButMe(new WebNodeData() { NodeGuid = GeminiApp.GUID, Key = "cache", Value = navigationCardsManager.Cache.NavigationCards.CacheKey }); } }
protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { _permissionsManager = new PermissionsManager(); _type = BindDataList(); } }
public static bool IsValidUser(string identity) { if (HttpContext.Current.User.Identity.IsAuthenticated) { IList<string> users = new List<string>(); //TODO: global cache instead of per-session cache if (HttpContext.Current.Session["UserList"] != null) users = (IList<string>)HttpContext.Current.Session["UserList"]; else { PermissionsManager pman = new PermissionsManager(); users = pman.GetGroupsUsers(pman.GetUserGroup(DefaultGroups.AllUsers)); pman.Dispose(); } bool val = users.Where(x => String.Equals(x, identity, StringComparison.InvariantCultureIgnoreCase)) .Count() > 0; return val; } else return false; }
public static GetSupportingFilesResponse GetSupportingFiles(string pid) { APIWrapper api = null; if (Membership.GetUser() != null && Membership.GetUser().IsApproved) api = new APIWrapper(Membership.GetUser().UserName, null); else api = new APIWrapper(vwarDAL.DefaultUsers.Anonymous[0], null); vwar.service.host.Metadata md = api.GetMetadata(pid, "00-00-00"); if (md == null) { return new GetSupportingFilesResponse(false); } PermissionsManager prm = new PermissionsManager(); MembershipUser user = Membership.GetUser(); ModelPermissionLevel Permission = prm.GetPermissionLevel(user != null ? user.UserName:vwarDAL.DefaultUsers.Anonymous[0], pid); prm.Dispose(); GetSupportingFilesResponse response = new GetSupportingFilesResponse(true); response.DownloadAllowed = Permission >= ModelPermissionLevel.Fetchable; response.EditAllowed = Permission >= ModelPermissionLevel.Editable; response.files = new vwarDAL.SupportingFile[md.SupportingFiles.Count]; for(int i=0; i<md.SupportingFiles.Count; i++) { response.files[i] = new vwarDAL.SupportingFile(md.SupportingFiles[i].Filename, md.SupportingFiles[i].Description, ""); } return response; }
public bool TryDoCommand(Players.Player causedBy, string chattext, List <string> splits) { if (!splits[0].Equals("/antigrief")) { return(false); } var matched = Regex.Match(chattext, @"/antigrief (?<accesslevel>[^ ]+) ((?<playername>['].+[']|[^ ]+)|((?<rangex>\d+) (?<rangez>\d+))|((?<rangexn>\d+) (?<rangexp>\d+) (?<rangezn>\d+) (?<rangezp>\d+)))$"); if (!matched.Success) { Chat.Send(causedBy, "Command didn't match, use /antigrief [spawn|nospawn|banner|deny] [playername] or /antigrief area [rangex rangez|rangexn rangexp rangezn rangezp]"); return(true); } var accesslevel = matched.Groups ["accesslevel"].Value; var targetPlayerName = matched.Groups ["playername"].Value; if (accesslevel.Equals("area")) { if (causedBy == null || causedBy.ID == NetworkID.Server) { Log.WriteError("You can't define custom protection areas as server (missing center)"); return(true); } else if (!PermissionsManager.CheckAndWarnPermission(causedBy, AntiGrief.PERMISSION_SUPER)) { return(true); } var rangex = matched.Groups ["rangex"].Value; var rangez = matched.Groups ["rangez"].Value; int rx, rz; var rangexn = matched.Groups ["rangexn"].Value; var rangexp = matched.Groups ["rangexp"].Value; var rangezn = matched.Groups ["rangezn"].Value; var rangezp = matched.Groups ["rangezp"].Value; int rxn, rxp, rzn, rzp; if (rangex.Length > 0 && int.TryParse(rangex, out rx) && rangez.Length > 0 && int.TryParse(rangez, out rz)) { AntiGrief.AddCustomArea(new CustomProtectionArea(causedBy.VoxelPosition, rx, rz)); Chat.Send(causedBy, $"Added anti grief area at {causedBy.VoxelPosition} with x-range {rx} and z-range {rz}"); } else if (rangexn.Length > 0 && int.TryParse(rangexn, out rxn) && rangexp.Length > 0 && int.TryParse(rangexp, out rxp) && rangezn.Length > 0 && int.TryParse(rangezn, out rzn) && rangezp.Length > 0 && int.TryParse(rangezp, out rzp)) { AntiGrief.AddCustomArea(new CustomProtectionArea(causedBy.VoxelPosition, rxn, rxp, rzn, rzp)); Chat.Send(causedBy, $"Added anti grief area at {causedBy.VoxelPosition} from x- {rxn} to x+ {rxp} and from z- {rzn} to z+ {rzp}"); } else { Chat.Send(causedBy, $"Could not parse protection area ranges {rangex} {rangez} {rangexn} {rangexp} {rangezn} {rangezp}"); } } else { Players.Player targetPlayer; string error; if (!PlayerHelper.TryGetPlayer(targetPlayerName, out targetPlayer, out error, true)) { Chat.Send(causedBy, $"Could not find target player '{targetPlayerName}'; {error}"); return(true); } if (accesslevel.Equals("spawn")) { if (PermissionsManager.CheckAndWarnPermission(causedBy, AntiGrief.PERMISSION_SUPER)) { PermissionsManager.AddPermissionToUser(causedBy, targetPlayer, AntiGrief.PERMISSION_SPAWN_CHANGE); Chat.Send(causedBy, $"You granted [{targetPlayer.Name}] permission to change the spawn area"); Chat.Send(targetPlayer, "You got permission to change the spawn area"); } } else if (accesslevel.Equals("nospawn")) { if (PermissionsManager.HasPermission(causedBy, AntiGrief.PERMISSION_SUPER)) { PermissionsManager.RemovePermissionOfUser(causedBy, targetPlayer, AntiGrief.PERMISSION_SPAWN_CHANGE); Chat.Send(causedBy, $"You revoked permission for [{targetPlayer.Name}] to change the spawn area"); Chat.Send(targetPlayer, "You lost permission to change the spawn area"); } } else if (accesslevel.Equals("banner")) { if (causedBy.Equals(targetPlayer)) { Chat.Send(causedBy, "You already have this permission"); return(true); } PermissionsManager.AddPermissionToUser(causedBy, targetPlayer, AntiGrief.PERMISSION_BANNER_PREFIX + causedBy.ID.steamID); Chat.Send(causedBy, $"You granted [{targetPlayer.Name}] permission to change your banner area"); Chat.Send(targetPlayer, $"You got permission to change banner area of [{causedBy.Name}]"); } else if (accesslevel.Equals("deny")) { if (causedBy.Equals(targetPlayer)) { Chat.Send(causedBy, "You can't revoke the permission for yourself"); return(true); } PermissionsManager.RemovePermissionOfUser(causedBy, targetPlayer, AntiGrief.PERMISSION_BANNER_PREFIX + causedBy.ID.steamID); Chat.Send(causedBy, $"You revoked permission for [{targetPlayer.Name}] to change your banner area"); Chat.Send(targetPlayer, $"You lost permission to change banner area of [{causedBy.Name}]"); } else { Chat.Send(causedBy, "Unknown access level, use /antigrief [spawn|nospawn|banner|deny] steamid"); } } return(true); }
public static string SubmitUpload(string DeveloperName, string ArtistName, string DeveloperUrl, string SponsorName, string LicenseType, bool RequireResubmit) { HttpServerUtility server = HttpContext.Current.Server; ContentObject tempCO = (ContentObject)HttpContext.Current.Session["contentObject"]; try { FileStatus status = (FileStatus)HttpContext.Current.Session["fileStatus"]; var factory = new DataAccessFactory(); IDataRepository dal = factory.CreateDataRepositorProxy(); dal.InsertContentObject(tempCO); tempCO.DeveloperName = server.HtmlEncode(DeveloperName); tempCO.ArtistName = server.HtmlEncode(ArtistName); tempCO.MoreInformationURL = server.HtmlEncode(DeveloperUrl); tempCO.RequireResubmit = RequireResubmit; tempCO.SponsorName = server.HtmlEncode(SponsorName); vwarDAL.PermissionsManager perMgr = new PermissionsManager(); var groupSetReturnCode = perMgr.SetModelToGroupLevel(HttpContext.Current.User.Identity.Name, tempCO.PID, vwarDAL.DefaultGroups.AllUsers, ModelPermissionLevel.Fetchable); groupSetReturnCode = perMgr.SetModelToGroupLevel(HttpContext.Current.User.Identity.Name, tempCO.PID, vwarDAL.DefaultGroups.AnonymousUsers, ModelPermissionLevel.Searchable); string pid = tempCO.PID; //tempCO.SponsorURL = SponsorUrl; !missing SponsorUrl metadata in ContentObject if (LicenseType == "publicdomain") { tempCO.CreativeCommonsLicenseURL = "http://creativecommons.org/publicdomain/mark/1.0/"; } else { tempCO.CreativeCommonsLicenseURL = String.Format(ConfigurationManager.AppSettings["CCBaseUrl"], LicenseType); } //Upload the thumbnail and logos string filename = status.hashname; string basehash = filename.Substring(0, filename.LastIndexOf(".") - 1); foreach (FileInfo f in new DirectoryInfo(HttpContext.Current.Server.MapPath("~/App_Data/imageTemp")).GetFiles("*" + basehash + "*")) { using (FileStream fstream = f.OpenRead()) { string type = f.Name.Substring(0, f.Name.IndexOf('_')); switch (type) { case ImagePrefix.DEVELOPER_LOGO: tempCO.DeveloperLogoImageFileName = "developer_logo" + f.Extension; tempCO.DeveloperLogoImageFileNameId = dal.SetContentFile(fstream, tempCO.PID, tempCO.DeveloperLogoImageFileName); break; case ImagePrefix.SPONSOR_LOGO: tempCO.SponsorLogoImageFileName = "sponsor_logo" + f.Extension; tempCO.SponsorLogoImageFileNameId = dal.SetContentFile(fstream, tempCO.PID, tempCO.SponsorLogoImageFileName); break; case ImagePrefix.SCREENSHOT: tempCO.ScreenShot = "screenshot" + f.Extension; tempCO.ScreenShotId = dal.SetContentFile(fstream, tempCO.PID, tempCO.ScreenShot); System.Drawing.Imaging.ImageFormat fmt = System.Drawing.Imaging.ImageFormat.Png; if (f.Extension == ".png") fmt = System.Drawing.Imaging.ImageFormat.Png; else if (f.Extension == ".jpg") fmt = System.Drawing.Imaging.ImageFormat.Jpeg; else if (f.Extension == ".gif") fmt = System.Drawing.Imaging.ImageFormat.Gif; else throw new Exception("Invalid screenshot format"); tempCO.ThumbnailId = Website.Common.GetFileSHA1AndSalt(fstream) + f.Extension; using (FileStream outFile = new FileStream(HttpContext.Current.Server.MapPath("~/thumbnails/" + tempCO.ThumbnailId), FileMode.Create)) Website.Common.GenerateThumbnail(fstream, outFile, fmt); break; default: break; } } } string dataPath = HttpContext.Current.Server.MapPath("~/App_Data/"); if (status.type == FormatType.VIEWABLE) { //Upload the original file using (FileStream s = new FileStream(dataPath + status.hashname, FileMode.Open)) { tempCO.OriginalFileId = dal.SetContentFile(s, pid, "original_" + status.filename); tempCO.OriginalFileName = "original_" + status.filename; } using (FileStream s = new FileStream(Path.Combine(dataPath, "converterTemp/" + status.hashname.ToLower().Replace("skp", "zip")),FileMode.Open,FileAccess.Read)) { tempCO.DisplayFileId = dal.SetContentFile(s, pid, status.filename.ToLower().Replace("skp", "zip")); } using (FileStream s = new FileStream(Path.Combine(dataPath, "viewerTemp/" + status.hashname.ToLower().Replace("skp", "o3d").Replace("zip", "o3d")), FileMode.Open)) { dal.SetContentFile(s, pid, status.filename.ToLower().Replace("skp", "o3d").Replace("zip", "o3d")); } } else if (status.type == FormatType.RECOGNIZED) { using (FileStream s = new FileStream(dataPath + status.hashname, FileMode.Open)) { tempCO.OriginalFileName = "original_" + status.filename; tempCO.OriginalFileId = dal.SetContentFile(s, pid, tempCO.OriginalFileName); } } tempCO.Enabled = true; tempCO.UploadedDate = DateTime.Now; ///////////////////////////////////////// //TO DO: Real Cert Time tempCO.Date_Certification = DateTime.Now; tempCO.Date_Copyright = DateTime.Now; tempCO.Date_Modification = DateTime.Now; ///////////////////////////////////////// //TO DO: Real data tempCO.CommunityURL = ""; tempCO.ContributorsURL = ""; tempCO.CertificationURL = ""; tempCO.Copyright = ""; tempCO.RightsHolder = ""; Dictionary<String, Object> metadataroot = HttpContext.Current.Session["metadata"] as Dictionary<String, Object>; tempCO.JSONMetadata = metadataroot; if (metadataroot != null) { Dictionary<String, Object> metadata = null; if(metadataroot.ContainsKey("ImmersiveEducationInitiative")) metadata = metadataroot["ImmersiveEducationInitiative"] as Dictionary<String, Object>; if (metadata != null) { if (metadata.ContainsKey("COMMUNITY")) tempCO.CommunityURL = metadata["COMMUNITY"].ToString(); if (metadata.ContainsKey("CONTRIBUTORS")) tempCO.ContributorsURL = metadata["CONTRIBUTORS"].ToString(); if (metadata.ContainsKey("CERTIFICATION")) tempCO.CertificationURL = metadata["CERTIFICATION"].ToString(); if (metadata.ContainsKey("COPYRIGHT")) tempCO.Copyright = metadata["COPYRIGHT"].ToString(); if (metadata.ContainsKey("RIGHTSHOLDER")) tempCO.RightsHolder = metadata["RIGHTSHOLDER"].ToString(); if (metadata.ContainsKey("TITLE")) tempCO.Title = metadata["TITLE"].ToString(); if (metadata.ContainsKey("DESCRIPTION")) tempCO.Description = metadata["DESCRIPTION"].ToString(); DateTime tempdate; if (metadata.ContainsKey("DATE_COPYRIGHT")) { DateTime.TryParse(metadata["DATE_COPYRIGHT"].ToString(), out tempdate); tempCO.Date_Copyright = tempdate; } if (metadata.ContainsKey("DATE_CERTIFICATION")) { DateTime.TryParse(metadata["DATE_CERTIFICATION"].ToString(), out tempdate); tempCO.Date_Certification = tempdate; } if (metadata.ContainsKey("DATE_MODIFICATION")) { DateTime.TryParse(metadata["DATE_MODIFICATION"].ToString(), out tempdate); tempCO.Date_Modification = tempdate; } if (metadata.ContainsKey("ARTIST")) { tempCO.ArtistName = ArrayOrStringToString(metadata["ARTIST"]); } if (metadata.ContainsKey("CREATOR")) { tempCO.DeveloperName = ArrayOrStringToString(metadata["CREATOR"]); } if (metadata.ContainsKey("KEYWORDS")) { string[] Keywords = metadata["KEYWORDS"].ToString().Split(new char[] {','}); for (int i = 0; i < Keywords.Length; i++) Keywords[i] = Keywords[i].Trim(); tempCO.Keywords = String.Join(",", Keywords); } if (metadata.ContainsKey("LICENSE")) { tempCO.CreativeCommonsLicenseURL = metadata["LICENSE"].ToString(); } } } dal.UpdateContentObject(tempCO); UploadReset(status.hashname); List<string> textureReferences = HttpContext.Current.Session["contentTextures"] as List<string>; List<string> textureReferenceMissing = HttpContext.Current.Session["contentMissingTextures"] as List<string>; if (textureReferences != null) { foreach (string tex in textureReferences) { tempCO.SetParentRepo(dal); tempCO.AddTextureReference(tex, "unknown", 0); } } if (textureReferenceMissing != null) { foreach (string tex in textureReferenceMissing) { tempCO.SetParentRepo(dal); tempCO.AddMissingTexture(tex, "unknown", 0); } } if (LR_3DR_Bridge.LR_Integration_Enabled()) LR_3DR_Bridge.ModelUploaded(tempCO); Website.Mail.SendModelUploaded(tempCO); dal.Dispose(); perMgr.Dispose(); return tempCO.PID; } catch (Exception e) { #if DEBUG return String.Format("fedoraError|" + e.Message + "<br /><br />" + e.StackTrace); #else return "fedoraError|" + ConfigurationManager.AppSettings["UploadPage_FedoraError"]; #endif } }
private void BindModelDetails() { if (String.IsNullOrEmpty(ContentObjectID)) { Response.Redirect("~/Default.aspx"); } PermissionsManager prm = new PermissionsManager(); ModelPermissionLevel Permission = prm.GetPermissionLevel(Context.User.Identity.Name, ContentObjectID); prm.Dispose(); prm = null; if (Permission < ModelPermissionLevel.Searchable) { Response.StatusCode = (int)HttpStatusCode.Unauthorized; } var uri = Request.Url; //string proxyTemplate = "Model.ashx?pid={0}&file={1}&fileid={2}"; vwarDAL.IDataRepository vd = (new vwarDAL.DataAccessFactory()).CreateDataRepositorProxy(); vwarDAL.ContentObject co = vd.GetContentObjectById(ContentObjectID, !IsPostBack, true); vd.Dispose(); vd = null; //model screenshot if (co != null) { if (LR_3DR_Bridge.LR_Integration_Enabled()) LR_3DR_Bridge.ModelViewed(co); Community_URL.Text = co.CommunityURL.Substring(0, min(50, co.CommunityURL.Length)) + "..."; Community_URL.NavigateUrl = co.CommunityURL; Certification_URL.Text = co.CertificationURL.Substring(0, min(50, co.CertificationURL.Length)) + "..."; Certification_URL.NavigateUrl = co.CertificationURL; Contributor_URL.Text = co.ContributorsURL.Substring(0, min(50, co.ContributorsURL.Length)) + "..."; Contributor_URL.NavigateUrl = co.ContributorsURL; Copyright.Text = co.Copyright; Rights_Holder.Text = co.RightsHolder; Certification_Date.Text = co.Date_Certification.ToString(); Copyright_Date.Text = co.Date_Copyright.ToString(); Modification_Date.Text = co.Date_Modification.ToString(); HashCode.Text = co.JSONMetadata["SHA1Hash"].ToString(); DownloadButton.Enabled = Permission >= ModelPermissionLevel.Fetchable; DownloadButton.Visible = Permission >= ModelPermissionLevel.Fetchable; if ("Model".Equals(co.AssetType, StringComparison.InvariantCultureIgnoreCase) || true) { //if the content object file is null, dont' try to display if (co.DisplayFile != string.Empty && co.Location != string.Empty && Permission > ModelPermissionLevel.Searchable) { Page.ClientScript.RegisterClientScriptBlock(GetType(), "vload", string.Format("vLoader = new ViewerLoader('{0}', '{1}', '{2}', '{3}', {4});", Page.ResolveClientUrl("~/Public/Serve.ashx?mode=PreviewModel"), (co.UpAxis != null) ? co.UpAxis : "", (co.UnitScale != null) ? co.UnitScale : "", co.NumPolygons, "\"" + co.PID.Replace(':','_') + "\""), true); BodyTag.Attributes["onunload"] += "vLoader.DestroyViewer();"; } if (String.IsNullOrWhiteSpace(co.ScreenShot) && String.IsNullOrWhiteSpace(co.ScreenShotId)) { ScreenshotImage.ImageUrl = Page.ResolveUrl("~/styles/images/nopreview_icon.png"); } else { ScreenshotImage.ImageUrl = String.Format("Serve.ashx?pid={0}&mode=GetScreenshot", co.PID); } AddHeaderTag("link", "og:image", ScreenshotImage.ImageUrl); } else if ("Texture".Equals(co.AssetType, StringComparison.InvariantCultureIgnoreCase)) { ScreenshotImage.ImageUrl = String.Format("Serve.ashx?pid={0}&mode=GetScreenshot", co.PID, co.Location); } IDLabel.Text = co.PID; TitleLabel.Text = co.Title; AddHeaderTag("meta", "og:title", co.Title); //show hide edit link if (Permission >= ModelPermissionLevel.Fetchable) { if (Website.Security.IsAdministrator() || Permission >= ModelPermissionLevel.Editable) { editLink.Visible = true; PermissionsLink.Visible = true; DeleteLink.Visible = true; editLink.NavigateUrl = "~/Users/Edit.aspx?ContentObjectID=" + co.PID; } //show and hide requires resubmit checkbox if (co.RequireResubmit) { RequiresResubmitCheckbox.Visible = true; RequiresResubmitCheckbox.Enabled = true; RequiresResubmitLabel.Visible = true; } submitRating.Visible = true; } else { LoginToDlLabel.Visible = true; submitRating.Visible = false; } //rating int rating = Website.Common.CalculateAverageRating(co.Reviews); ir.CurrentRating = rating; this.NotRatedLabel.Visible = (rating == 0); //description DescriptionLabel.Text = String.IsNullOrEmpty(co.Description) ? "No description available." : co.Description; AddHeaderTag("meta", "og:description", co.Description); upAxis.Value = co.UpAxis; unitScale.Value = co.UnitScale; //keywords var keywordsList = string.IsNullOrEmpty(co.Keywords) ? new String[0] : co.Keywords.Split(new char[] { ',' }); foreach (var keyword in keywordsList) { HyperLink link = new HyperLink() { Text = keyword, NavigateUrl = "~/Public/Results.aspx?ContentObjectID=" + ContentObjectID + "&Keywords=" + Server.UrlEncode(keyword.Trim()), CssClass = "Hyperlink" }; keywords.Controls.Add(link); keywords.Controls.Add(new LiteralControl(" ")); } this.keywordLabel.Visible = !string.IsNullOrEmpty(co.Keywords); //more details this.MoreDetailsHyperLink.NavigateUrl = co.MoreInformationURL; this.MoreDetailsHyperLink.Text = co.MoreInformationURL; this.MoreDetailsRow.Visible = !string.IsNullOrEmpty(co.MoreInformationURL); string submitterFullName = Website.Common.GetFullUserName(co.SubmitterEmail); if (co.UploadedDate != null) { UploadedDateLabel.Text = "Uploaded by: " + submitterFullName + " on " + co.UploadedDate.ToString(); } if (!String.IsNullOrEmpty(co.SponsorName) || !String.IsNullOrEmpty(co.SponsorLogoImageFileName) || !String.IsNullOrEmpty(co.SponsorLogoImageFileNameId)) { //sponsor logo if (!string.IsNullOrEmpty(co.SponsorLogoImageFileName)) { this.SponsorLogoImage.ImageUrl = String.Format("Serve.ashx?pid={0}&mode=GetSponsorLogo", co.PID); } this.SponsorLogoRow.Visible = !string.IsNullOrEmpty(co.SponsorLogoImageFileName); this.SponsorNameLabel.Text = co.SponsorName; this.SponsorNameRow.Visible = !string.IsNullOrEmpty(co.SponsorName); } else { this.SponsorInfoSection.Visible = false; } if (!String.IsNullOrEmpty(co.DeveloperName) || !String.IsNullOrEmpty(co.ArtistName) || !String.IsNullOrEmpty(co.DeveloperLogoImageFileName) || !String.IsNullOrEmpty(co.DeveloperLogoImageFileNameId)) { //developr logo if (!string.IsNullOrEmpty(co.DeveloperLogoImageFileName)) { this.DeveloperLogoImage.ImageUrl = String.Format("Serve.ashx?pid={0}&mode=GetDeveloperLogo", co.PID); } this.DeveloperLogoRow.Visible = !string.IsNullOrEmpty(co.DeveloperLogoImageFileName); //developer name this.DeveloperNameHyperLink.NavigateUrl = "~/Public/Results.aspx?ContentObjectID=" + ContentObjectID + "&DeveloperName=" + Server.UrlEncode(co.DeveloperName); this.DeveloperNameHyperLink.Text = co.DeveloperName; if (String.IsNullOrEmpty(co.ArtistName)) { this.ArtistRow.Visible = false; } else { this.ArtistNameHyperLink.NavigateUrl = "~/Public/Results.aspx?ContentObjectID=" + ContentObjectID + "&ArtistName=" + Server.UrlEncode(co.ArtistName); this.ArtistNameHyperLink.Text = co.ArtistName; } this.DeveloperRow.Visible = !string.IsNullOrEmpty(co.DeveloperName); } else { this.DeveloperInfoSection.Visible = false; } this.FormatLabel.Text = "Native format: " + ((string.IsNullOrEmpty(co.Format)) ? "Unknown" : co.Format); //num polygons this.NumPolygonsLabel.Text = co.NumPolygons.ToString(); this.NumPolygonsRow.Visible = !string.IsNullOrEmpty(co.NumPolygons.ToString()); //num textures this.NumTexturesLabel.Text = co.NumTextures.ToString(); this.NumTexturesRow.Visible = !string.IsNullOrEmpty(co.NumTextures.ToString()); //cclrow this.CCLHyperLink.Visible = !string.IsNullOrEmpty(co.CreativeCommonsLicenseURL); this.CCLHyperLink.NavigateUrl = co.CreativeCommonsLicenseURL; if (!string.IsNullOrEmpty(co.CreativeCommonsLicenseURL)) { switch (co.CreativeCommonsLicenseURL.ToLower().Trim()) { case "http://ImmersiveEducation.org/@/RocketWorld/license": case "http://creativecommons.org/licenses/by-nc-sa/3.0/legalcode": this.CCLHyperLink.ImageUrl = "http://i.creativecommons.org/l/by-nc-sa/3.0/88x31.png"; this.CCLHyperLink.ToolTip = "by-nc-sa"; break; case "http://creativecommons.org/licenses/by-nc-nd/3.0/legalcode": this.CCLHyperLink.ImageUrl = "http://i.creativecommons.org/l/by-nc-nd/3.0/88x31.png"; this.CCLHyperLink.ToolTip = "by-nc-nd"; break; case "http://creativecommons.org/licenses/by-nc/3.0/legalcode": this.CCLHyperLink.ImageUrl = "http://i.creativecommons.org/l/by-nc/3.0/88x31.png"; this.CCLHyperLink.ToolTip = "by-nc"; break; case "http://creativecommons.org/licenses/by-nd/3.0/legalcode": this.CCLHyperLink.ImageUrl = "http://i.creativecommons.org/l/by-nd/3.0/88x31.png"; this.CCLHyperLink.ToolTip = "by-nd"; break; case "http://creativecommons.org/licenses/by-sa/3.0/legalcode": this.CCLHyperLink.ImageUrl = "http://i.creativecommons.org/l/by-sa/3.0/88x31.png"; this.CCLHyperLink.ToolTip = "by-sa"; break; case "http://creativecommons.org/publicdomain/mark/1.0/": this.CCLHyperLink.ImageUrl = "http://i.creativecommons.org/l/publicdomain/88x31.png"; this.CCLHyperLink.ToolTip = "Public Domain"; break; case "http://creativecommons.org/licenses/by/3.0/legalcode": this.CCLHyperLink.ImageUrl = "http://i.creativecommons.org/l/by/3.0/88x31.png"; this.CCLHyperLink.ToolTip = "by"; break; } } //downloads DownloadsLabel.Text = co.Downloads.ToString(); this.DownloadsRow.Visible = !string.IsNullOrEmpty(co.Downloads.ToString()); //views ViewsLabel.Text = co.Views.ToString(); this.ViewsRow.Visible = !string.IsNullOrEmpty(co.Views.ToString()); //download buton //this.DownloadButton.Visible = Context.User.Identity.IsAuthenticated; this.CommentsGridView.DataSource = co.Reviews; this.CommentsGridView.DataBind(); } }
private int Validate_SiteInfo(out string errorMessage) { try { var isHq = TranslateUtils.ToBool(RblIsRoot.SelectedValue); // 是否主站 var parentSiteId = 0; var siteDir = string.Empty; if (isHq == false) { if (DirectoryUtils.IsSystemDirectory(TbSiteDir.Text)) { errorMessage = "文件夹名称不能为系统文件夹名称!"; return(0); } parentSiteId = TranslateUtils.ToInt(DdlParentId.SelectedValue); siteDir = TbSiteDir.Text; var list = DataProvider.SiteDao.GetLowerSiteDirList(parentSiteId); if (list.IndexOf(siteDir.ToLower()) != -1) { errorMessage = "已存在相同的发布路径!"; return(0); } if (!DirectoryUtils.IsDirectoryNameCompliant(siteDir)) { errorMessage = "文件夹名称不符合系统要求!"; return(0); } } var nodeInfo = new ChannelInfo(); nodeInfo.ChannelName = nodeInfo.IndexName = "首页"; nodeInfo.ParentId = 0; nodeInfo.ContentModelPluginId = string.Empty; var psInfo = new SiteInfo { SiteName = PageUtils.FilterXss(TbSiteName.Text), SiteDir = siteDir, TableName = DdlTableName.SelectedValue, ParentId = parentSiteId, IsRoot = isHq }; psInfo.Additional.IsCheckContentLevel = TranslateUtils.ToBool(RblIsCheckContentUseLevel.SelectedValue); if (psInfo.Additional.IsCheckContentLevel) { psInfo.Additional.CheckContentLevel = TranslateUtils.ToInt(DdlCheckContentLevel.SelectedValue); } psInfo.Additional.Charset = DdlCharset.SelectedValue; var theSiteId = DataProvider.ChannelDao.InsertSiteInfo(nodeInfo, psInfo, Body.AdminName); var permissions = PermissionsManager.GetPermissions(Body.AdminName); if (permissions.IsSystemAdministrator && !permissions.IsConsoleAdministrator) { var siteIdList = ProductPermissionsManager.Current.SiteIdList ?? new List <int>(); siteIdList.Add(theSiteId); DataProvider.AdministratorDao.UpdateSiteIdCollection(Body.AdminName, TranslateUtils.ObjectCollectionToString(siteIdList)); } Body.AddAdminLog("创建新站点", $"站点名称:{PageUtils.FilterXss(TbSiteName.Text)}"); errorMessage = string.Empty; return(theSiteId); } catch (Exception e) { errorMessage = e.Message; return(0); } }
public void Page_Load(object sender, EventArgs e) { if (IsForbidden) { return; } PageUtils.CheckRequestParameter("PublishmentSystemId"); _isMultiple = TranslateUtils.ToBool(Request.QueryString["isMultiple"]); _jsMethod = Request.QueryString["jsMethod"]; _itemIndex = TranslateUtils.ToInt(Request.QueryString["itemIndex"]); _isKeywordAdd = TranslateUtils.ToBool(Request.QueryString["isKeywordAdd"]); _keywordId = TranslateUtils.ToInt(Request.QueryString["keywordID"]); if (!string.IsNullOrEmpty(Request.QueryString["NodeID"])) { _nodeId = int.Parse(Request.QueryString["NodeID"]); } else { _nodeId = PublishmentSystemId; } _nodeInfo = NodeManager.GetNodeInfo(PublishmentSystemId, _nodeId); _tableStyle = NodeManager.GetTableStyle(PublishmentSystemInfo, _nodeInfo); var tableName = NodeManager.GetTableName(PublishmentSystemInfo, _nodeInfo); _attributesOfDisplay = TranslateUtils.StringCollectionToStringCollection(NodeManager.GetContentAttributesOfDisplay(PublishmentSystemId, _nodeId)); _relatedIdentities = RelatedIdentities.GetChannelRelatedIdentities(PublishmentSystemId, _nodeId); _tableStyleInfoList = TableStyleManager.GetTableStyleInfoList(_tableStyle, tableName, _relatedIdentities); SpContents.ControlToPaginate = RptContents; if (string.IsNullOrEmpty(Request.QueryString["NodeID"])) { var pm = PermissionsManager.GetPermissions(Body.AdministratorName); var stateType = ETriStateUtils.GetEnumType(State.SelectedValue); SpContents.SelectCommand = DataProvider.ContentDao.GetSelectCommend(_tableStyle, tableName, PublishmentSystemId, _nodeId, pm.IsSystemAdministrator, ProductPermissionsManager.Current.OwningNodeIdList, SearchType.SelectedValue, Keyword.Text, DateFrom.Text, DateTo.Text, true, stateType, !IsDuplicate.Checked, false); } else { var pm = PermissionsManager.GetPermissions(Body.AdministratorName); var stateType = ETriStateUtils.GetEnumType(Request.QueryString["State"]); SpContents.SelectCommand = DataProvider.ContentDao.GetSelectCommend(_tableStyle, tableName, PublishmentSystemId, _nodeId, pm.IsSystemAdministrator, ProductPermissionsManager.Current.OwningNodeIdList, Request.QueryString["SearchType"], Request.QueryString["Keyword"], Request.QueryString["DateFrom"], Request.QueryString["DateTo"], true, stateType, !TranslateUtils.ToBool(Request.QueryString["IsDuplicate"]), false); } SpContents.ItemsPerPage = PublishmentSystemInfo.Additional.PageSize; SpContents.SortField = ContentAttribute.Id; SpContents.SortMode = SortMode.DESC; SpContents.OrderByString = ETaxisTypeUtils.GetOrderByString(_tableStyle, ETaxisType.OrderByIdDesc); RptContents.ItemDataBound += rptContents_ItemDataBound; if (!IsPostBack) { NodeManager.AddListItems(NodeIdDropDownList.Items, PublishmentSystemInfo, true, true, Body.AdministratorName); if (_tableStyleInfoList != null) { foreach (var styleInfo in _tableStyleInfoList) { if (styleInfo.IsVisible) { var listitem = new ListItem(styleInfo.DisplayName, styleInfo.AttributeName); SearchType.Items.Add(listitem); } } } ETriStateUtils.AddListItems(State, "全部", "已审核", "待审核"); //添加隐藏属性 SearchType.Items.Add(new ListItem("内容ID", ContentAttribute.Id)); SearchType.Items.Add(new ListItem("添加者", ContentAttribute.AddUserName)); SearchType.Items.Add(new ListItem("最后修改者", ContentAttribute.LastEditUserName)); if (!string.IsNullOrEmpty(Request.QueryString["NodeID"])) { if (PublishmentSystemId != _nodeId) { ControlUtils.SelectListItems(NodeIdDropDownList, _nodeId.ToString()); } ControlUtils.SelectListItems(State, Request.QueryString["State"]); IsDuplicate.Checked = TranslateUtils.ToBool(Request.QueryString["IsDuplicate"]); ControlUtils.SelectListItems(SearchType, Request.QueryString["SearchType"]); Keyword.Text = Request.QueryString["Keyword"]; DateFrom.Text = Request.QueryString["DateFrom"]; DateTo.Text = Request.QueryString["DateTo"]; } SpContents.DataBind(); } }
public void Page_Load(object sender, EventArgs e) { if (IsForbidden) { return; } PageUtils.CheckRequestParameter("siteId"); _channelId = Body.IsQueryExists("ChannelId") ? Body.GetQueryInt("ChannelId") : SiteId; var permissions = PermissionsManager.GetPermissions(Body.AdminName); _relatedIdentities = RelatedIdentities.GetChannelRelatedIdentities(SiteId, _channelId); _nodeInfo = ChannelManager.GetChannelInfo(SiteId, _channelId); _tableName = ChannelManager.GetTableName(SiteInfo, _nodeInfo); _styleInfoList = TableStyleManager.GetTableStyleInfoList(_tableName, _relatedIdentities); _attributesOfDisplay = TranslateUtils.StringCollectionToStringCollection(ChannelManager.GetContentAttributesOfDisplay(SiteId, _channelId)); _attributesOfDisplayStyleInfoList = ContentUtility.GetColumnTableStyleInfoList(SiteInfo, _styleInfoList); _pluginLinks = PluginContentManager.GetContentLinks(_nodeInfo); _isEdit = TextUtility.IsEdit(SiteInfo, _channelId, Body.AdminName); if (IsPostBack) { return; } var checkedLevel = 5; var isChecked = true; foreach (var owningChannelId in ProductPermissionsManager.Current.OwningChannelIdList) { int checkedLevelByChannelId; var isCheckedByChannelId = CheckManager.GetUserCheckLevel(Body.AdminName, SiteInfo, owningChannelId, out checkedLevelByChannelId); if (checkedLevel > checkedLevelByChannelId) { checkedLevel = checkedLevelByChannelId; } if (!isCheckedByChannelId) { isChecked = false; } } ChannelManager.AddListItems(DdlChannelId.Items, SiteInfo, true, true, Body.AdminName); CheckManager.LoadContentLevelToList(DdlState, SiteInfo, SiteId, isChecked, checkedLevel); var checkLevelList = new List <int>(); if (!string.IsNullOrEmpty(Body.GetQueryString("channelId"))) { ControlUtils.SelectSingleItem(DdlChannelId, Body.GetQueryString("channelId")); } if (!string.IsNullOrEmpty(Body.GetQueryString("state"))) { ControlUtils.SelectSingleItem(DdlState, Body.GetQueryString("state")); checkLevelList.Add(Body.GetQueryInt("state")); } else { checkLevelList = CheckManager.LevelInt.GetCheckLevelList(SiteInfo, isChecked, checkedLevel); } SpContents.ControlToPaginate = RptContents; SpContents.ItemsPerPage = SiteInfo.Additional.PageSize; var nodeInfo = ChannelManager.GetChannelInfo(SiteId, _channelId); var tableName = ChannelManager.GetTableName(SiteInfo, nodeInfo); var channelIdList = DataProvider.ChannelDao.GetIdListByScopeType(nodeInfo.Id, nodeInfo.ChildrenCount, EScopeType.All, string.Empty, string.Empty, nodeInfo.ContentModelPluginId); var list = new List <int>(); if (permissions.IsSystemAdministrator) { list = channelIdList; } else { var owningChannelIdList = new List <int>(); foreach (var owningChannelId in ProductPermissionsManager.Current.OwningChannelIdList) { if (AdminUtility.HasChannelPermissions(Body.AdminName, SiteId, owningChannelId, ConfigManager.Permissions.Channel.ContentCheck)) { owningChannelIdList.Add(owningChannelId); } } foreach (var theChannelId in channelIdList) { if (owningChannelIdList.Contains(theChannelId)) { list.Add(theChannelId); } } } SpContents.SelectCommand = DataProvider.ContentDao.GetSelectedCommendByCheck(tableName, SiteId, list, checkLevelList); SpContents.SortField = ContentAttribute.LastEditDate; SpContents.SortMode = SortMode.DESC; RptContents.ItemDataBound += RptContents_ItemDataBound; SpContents.DataBind(); var showPopWinString = ModalContentCheck.GetOpenWindowStringForMultiChannels(SiteId, PageUrl); BtnCheck.Attributes.Add("onclick", showPopWinString); LtlColumnsHead.Text = TextUtility.GetColumnsHeadHtml(_styleInfoList, _attributesOfDisplay, SiteInfo); if (!HasChannelPermissions(SiteId, ConfigManager.Permissions.Channel.ContentDelete)) { BtnDelete.Visible = false; } else { BtnDelete.Attributes.Add("onclick", PageContentDelete.GetRedirectClickStringForMultiChannels(SiteId, false, PageUrl)); } }
public static string SubmitUpload(string DeveloperName, string ArtistName, string DeveloperUrl, string SponsorName, string LicenseType, bool RequireResubmit) { HttpServerUtility server = HttpContext.Current.Server; ContentObject tempCO = (ContentObject)HttpContext.Current.Session["contentObject"]; try { FileStatus status = (FileStatus)HttpContext.Current.Session["fileStatus"]; var factory = new DataAccessFactory(); IDataRepository dal = factory.CreateDataRepositorProxy(); dal.InsertContentObject(tempCO); tempCO.DeveloperName = server.HtmlEncode(DeveloperName); tempCO.ArtistName = server.HtmlEncode(ArtistName); tempCO.MoreInformationURL = server.HtmlEncode(DeveloperUrl); tempCO.RequireResubmit = RequireResubmit; tempCO.SponsorName = server.HtmlEncode(SponsorName); vwarDAL.PermissionsManager perMgr = new PermissionsManager(); var groupSetReturnCode = perMgr.SetModelToGroupLevel(HttpContext.Current.User.Identity.Name, tempCO.PID, vwarDAL.DefaultGroups.AllUsers, ModelPermissionLevel.Fetchable); groupSetReturnCode = perMgr.SetModelToGroupLevel(HttpContext.Current.User.Identity.Name, tempCO.PID, vwarDAL.DefaultGroups.AnonymousUsers, ModelPermissionLevel.Searchable); string pid = tempCO.PID; //tempCO.SponsorURL = SponsorUrl; !missing SponsorUrl metadata in ContentObject if (LicenseType == "publicdomain") { tempCO.CreativeCommonsLicenseURL = "http://creativecommons.org/publicdomain/mark/1.0/"; } else { tempCO.CreativeCommonsLicenseURL = String.Format(ConfigurationManager.AppSettings["CCBaseUrl"], LicenseType); } //Upload the thumbnail and logos string filename = status.hashname; string basehash = filename.Substring(0, filename.LastIndexOf(".") - 1); foreach (FileInfo f in new DirectoryInfo(HttpContext.Current.Server.MapPath("~/App_Data/imageTemp")).GetFiles("*" + basehash + "*")) { using (FileStream fstream = f.OpenRead()) { string type = f.Name.Substring(0, f.Name.IndexOf('_')); switch (type) { case ImagePrefix.DEVELOPER_LOGO: tempCO.DeveloperLogoImageFileName = "developer_logo" + f.Extension; tempCO.DeveloperLogoImageFileNameId = dal.SetContentFile(fstream, tempCO.PID, tempCO.DeveloperLogoImageFileName); break; case ImagePrefix.SPONSOR_LOGO: tempCO.SponsorLogoImageFileName = "sponsor_logo" + f.Extension; tempCO.SponsorLogoImageFileNameId = dal.SetContentFile(fstream, tempCO.PID, tempCO.SponsorLogoImageFileName); break; case ImagePrefix.SCREENSHOT: tempCO.ScreenShot = "screenshot" + f.Extension; tempCO.ScreenShotId = dal.SetContentFile(fstream, tempCO.PID, tempCO.ScreenShot); System.Drawing.Imaging.ImageFormat fmt = System.Drawing.Imaging.ImageFormat.Png; if (f.Extension == ".png") fmt = System.Drawing.Imaging.ImageFormat.Png; else if (f.Extension == ".jpg") fmt = System.Drawing.Imaging.ImageFormat.Jpeg; else if (f.Extension == ".gif") fmt = System.Drawing.Imaging.ImageFormat.Gif; else throw new Exception("Invalid screenshot format"); tempCO.ThumbnailId = Website.Common.GetFileSHA1AndSalt(fstream) + f.Extension; using (FileStream outFile = new FileStream(HttpContext.Current.Server.MapPath("~/thumbnails/" + tempCO.ThumbnailId), FileMode.Create)) Website.Common.GenerateThumbnail(fstream, outFile, fmt); break; default: break; } } } string dataPath = HttpContext.Current.Server.MapPath("~/App_Data/"); if (status.type == FormatType.VIEWABLE) { //Upload the original file using (FileStream s = new FileStream(dataPath + status.hashname, FileMode.Open)) { tempCO.OriginalFileId = dal.SetContentFile(s, pid, "original_" + status.filename); tempCO.OriginalFileName = "original_" + status.filename; } using (FileStream s = new FileStream(Path.Combine(dataPath, "converterTemp/" + status.hashname.ToLower().Replace("skp", "zip")),FileMode.Open,FileAccess.Read)) { tempCO.DisplayFileId = dal.SetContentFile(s, pid, status.filename.ToLower().Replace("skp", "zip")); } using (FileStream s = new FileStream(Path.Combine(dataPath, "viewerTemp/" + status.hashname.ToLower().Replace("skp", "o3d").Replace("zip", "o3d")), FileMode.Open)) { dal.SetContentFile(s, pid, status.filename.ToLower().Replace("skp", "o3d").Replace("zip", "o3d")); } } else if (status.type == FormatType.RECOGNIZED) { using (FileStream s = new FileStream(dataPath + status.hashname, FileMode.Open)) { tempCO.OriginalFileName = "original_" + status.filename; tempCO.OriginalFileId = dal.SetContentFile(s, pid, tempCO.OriginalFileName); } } tempCO.Enabled = true; tempCO.UploadedDate = DateTime.Now; dal.UpdateContentObject(tempCO); UploadReset(status.hashname); List<string> textureReferences = HttpContext.Current.Session["contentTextures"] as List<string>; List<string> textureReferenceMissing = HttpContext.Current.Session["contentMissingTextures"] as List<string>; if (textureReferences != null) { foreach (string tex in textureReferences) { tempCO.SetParentRepo(dal); tempCO.AddTextureReference(tex, "unknown", 0); } } if (textureReferenceMissing != null) { foreach (string tex in textureReferenceMissing) { tempCO.SetParentRepo(dal); tempCO.AddMissingTexture(tex, "unknown", 0); } } if (LR_3DR_Bridge.LR_Integration_Enabled()) LR_3DR_Bridge.ModelUploaded(tempCO); Website.Mail.SendModelUploaded(tempCO); dal.Dispose(); perMgr.Dispose(); return tempCO.PID; } catch (Exception e) { #if DEBUG return String.Format("fedoraError|" + e.Message + "<br /><br />" + e.StackTrace); #else return "fedoraError|" + ConfigurationManager.AppSettings["UploadPage_FedoraError"]; #endif } }
private void BindModelDetails() { if (String.IsNullOrEmpty(ContentObjectID)) { Response.Redirect("~/Default.aspx"); } PermissionsManager prm = new PermissionsManager(); ModelPermissionLevel Permission = prm.GetPermissionLevel(Context.User.Identity.Name, ContentObjectID); prm.Dispose(); prm = null; if (Permission < ModelPermissionLevel.Searchable) { Response.StatusCode = (int)HttpStatusCode.Unauthorized; return; } APILink.NavigateUrl = ConfigurationManager.AppSettings["LR_Integration_APIBaseURL"] + "/" + ContentObjectID + "/Metadata/json?id=00-00-00"; var uri = Request.Url; //string proxyTemplate = "Model.ashx?pid={0}&file={1}&fileid={2}"; vwarDAL.IDataRepository vd = (new vwarDAL.DataAccessFactory()).CreateDataRepositorProxy(); vwarDAL.ContentObject co = vd.GetContentObjectById(ContentObjectID, !IsPostBack, true); vd.Dispose(); vd = null; //model screenshot if (co != null) { if (LR_3DR_Bridge.LR_Integration_Enabled()) LR_3DR_Bridge.ModelViewed(co); DownloadButton.Enabled = Permission >= ModelPermissionLevel.Fetchable; DownloadButton.Visible = Permission >= ModelPermissionLevel.Fetchable; if ("Model".Equals(co.AssetType, StringComparison.InvariantCultureIgnoreCase) || true) { //if the content object file is null, dont' try to display if (co.DisplayFile != string.Empty && co.Location != string.Empty && Permission > ModelPermissionLevel.Searchable) { Page.ClientScript.RegisterClientScriptBlock(GetType(), "vload", string.Format("vLoader = new ViewerLoader('{0}', '{1}', '{2}', '{3}', {4});", Page.ResolveClientUrl("~/Public/Serve.ashx?mode=PreviewModel"), (co.UpAxis != null) ? co.UpAxis : "", (co.UnitScale != null) ? co.UnitScale : "", co.NumPolygons, "\"" + co.PID.Replace(':','_') + "\""), true); BodyTag.Attributes["onunload"] += "vLoader.DestroyViewer();"; } if (String.IsNullOrWhiteSpace(co.ScreenShot) && String.IsNullOrWhiteSpace(co.ScreenShotId)) { ScreenshotImage.ImageUrl = Page.ResolveUrl("~/styles/images/nopreview_icon.png"); } else { ScreenshotImage.ImageUrl = String.Format("Serve.ashx?pid={0}&mode=GetScreenshot", co.PID); } AddHeaderTag("link", "og:image", ScreenshotImage.ImageUrl); } else if ("Texture".Equals(co.AssetType, StringComparison.InvariantCultureIgnoreCase)) { ScreenshotImage.ImageUrl = String.Format("Serve.ashx?pid={0}&mode=GetScreenshot", co.PID, co.Location); } IDLabel.Text = co.PID; TitleLabel.Text = co.Title; AddHeaderTag("meta", "og:title", co.Title); //show hide edit link if (Permission >= ModelPermissionLevel.Editable) { editLink.Visible = true; PermissionsLink.Visible = true; DeleteLink.Visible = true; //editLink.NavigateUrl = "~/Users/Edit.aspx?ContentObjectID=" + co.PID; } else { EditorButtons.Visible = false; } if (Permission >= ModelPermissionLevel.Fetchable) { //show and hide requires resubmit checkbox if (co.RequireResubmit) { RequiresResubmitCheckbox.Visible = true; RequiresResubmitCheckbox.Enabled = true; RequiresResubmitLabel.Visible = true; } submitRating.Visible = true; } else { string returnUrlParam = "?ReturnUrl=" + Page.ResolveUrl("~/Public/Model.aspx?ContentObjectID=" + co.PID); LoginLink.NavigateUrl += returnUrlParam; ReveiwLoginHyperLink.NavigateUrl += returnUrlParam; if (User.Identity.IsAuthenticated) { RequestAccessLabel.Visible = true; } else { LoginToDlLabel.Visible = true; } submitRating.Visible = false; } //rating int rating = Website.Common.CalculateAverageRating(co.Reviews); ir.CurrentRating = rating; this.NotRatedLabel.Visible = (rating == 0); //description DescriptionLabel.Text = String.IsNullOrEmpty(co.Description) ? "No description available." : co.Description; AddHeaderTag("meta", "og:description", co.Description); upAxis.Value = co.UpAxis; unitScale.Value = co.UnitScale; //keywords var keywordsList = string.IsNullOrEmpty(co.Keywords) ? new String[0] : co.Keywords.Split(new char[] { ',' }); foreach (var keyword in keywordsList) { HyperLink link = new HyperLink() { Text = keyword, NavigateUrl = "~/Public/Results.aspx?ContentObjectID=" + ContentObjectID + "&Keywords=" + Server.UrlEncode(keyword.Trim()), CssClass = "Hyperlink" }; keywords.Controls.Add(link); keywords.Controls.Add(new LiteralControl(" ")); } //more details this.MoreDetailsHyperLink.NavigateUrl = co.MoreInformationURL; this.MoreDetailsHyperLink.Text = co.MoreInformationURL; string submitterFullName = Website.Common.GetFullUserName(co.SubmitterEmail); if (co.UploadedDate != null) { UploadedDateLabel.Text = "Uploaded by: " + submitterFullName + " on " + co.UploadedDate.ToString(); } //sponsor logo if (!string.IsNullOrEmpty(co.SponsorLogoImageFileName)) { this.SponsorLogoImage.ImageUrl = String.Format("Serve.ashx?pid={0}&mode=GetSponsorLogo", co.PID); } this.SponsorNameLabel.Text = co.SponsorName; //developr logo if (!string.IsNullOrEmpty(co.DeveloperLogoImageFileName)) { this.DeveloperLogoImage.ImageUrl = String.Format("Serve.ashx?pid={0}&mode=GetDeveloperLogo", co.PID); } //this.DeveloperLogoRow.Visible = !string.IsNullOrEmpty(co.DeveloperLogoImageFileName); //developer name this.DeveloperNameHyperLink.NavigateUrl = "~/Public/Results.aspx?ContentObjectID=" + ContentObjectID + "&DeveloperName=" + Server.UrlEncode(co.DeveloperName); this.DeveloperNameHyperLink.Text = co.DeveloperName; if (String.IsNullOrEmpty(co.ArtistName)) { } else { this.ArtistNameHyperLink.NavigateUrl = "~/Public/Results.aspx?ContentObjectID=" + ContentObjectID + "&ArtistName=" + Server.UrlEncode(co.ArtistName); this.ArtistNameHyperLink.Text = co.ArtistName; } //this.DeveloperRow.Visible = !string.IsNullOrEmpty(co.DeveloperName); this.FormatLabel.Text = ((string.IsNullOrEmpty(co.Format)) ? "Unknown" : co.Format); //num polygons this.NumPolygonsLabel.Text = co.NumPolygons.ToString(); //num textures this.NumTexturesLabel.Text = co.NumTextures.ToString(); //cclrow this.CCLHyperLink.NavigateUrl = co.CreativeCommonsLicenseURL; if (!string.IsNullOrEmpty(co.CreativeCommonsLicenseURL)) { switch (co.CreativeCommonsLicenseURL.ToLower().Trim()) { case "http://creativecommons.org/licenses/by-nc-sa/3.0/legalcode": this.CCLHyperLink.ImageUrl = "../styles/images/by-nc-sa.png"; this.CCLHyperLink.ToolTip = "by-nc-sa"; break; case "http://creativecommons.org/licenses/by-nc-nd/3.0/legalcode": this.CCLHyperLink.ImageUrl = "../styles/images/by-nc-nd.png"; this.CCLHyperLink.ToolTip = "by-nc-nd"; break; case "http://creativecommons.org/licenses/by-nc/3.0/legalcode": this.CCLHyperLink.ImageUrl = "../styles/images/by-nc.png"; this.CCLHyperLink.ToolTip = "by-nc"; break; case "http://creativecommons.org/licenses/by-nd/3.0/legalcode": this.CCLHyperLink.ImageUrl = "../styles/images/by-nd.png"; this.CCLHyperLink.ToolTip = "by-nd"; break; case "http://creativecommons.org/licenses/by-sa/3.0/legalcode": this.CCLHyperLink.ImageUrl = "../styles/images/by-sa.png"; this.CCLHyperLink.ToolTip = "by-sa"; break; case "http://creativecommons.org/publicdomain/mark/1.0/": this.CCLHyperLink.ImageUrl = "../styles/images/publicdomain.png"; this.CCLHyperLink.ToolTip = "Public Domain"; break; case "http://creativecommons.org/licenses/by/3.0/legalcode": this.CCLHyperLink.ImageUrl = "../styles/images/by.png"; this.CCLHyperLink.ToolTip = "by"; break; } } //downloads DownloadsLabel.Text = co.Downloads.ToString(); this.DownloadsRow.Visible = !string.IsNullOrEmpty(co.Downloads.ToString()); //views ViewsLabel.Text = co.Views.ToString(); this.ViewsRow.Visible = !string.IsNullOrEmpty(co.Views.ToString()); //download buton //this.DownloadButton.Visible = Context.User.Identity.IsAuthenticated; this.CommentsGridView.DataSource = co.Reviews; this.CommentsGridView.DataBind(); //SupportingFileGrid.DataSource = co.SupportingFiles; //if(Permission < ModelPermissionLevel.Fetchable) // ((ButtonField)SupportingFileGrid.Columns[2]).ImageUrl = "../styles/images/icons/expand_disabled.jpg"; //SupportingFileGrid.DataBind(); //SupportingFileGrid.Enabled = Permission >= ModelPermissionLevel.Fetchable; EditKeywords.Text = co.Keywords; EditDistributionDeterminationDate.Text = co.Distribution_Determination_Date.ToString(); EditDistributionOffice.Text = co.Distribution_Contolling_Office; EditDistributionReasonLabel.Text = co.Distribution_Reason; EditDistributionRegulation.Text = co.Distribution_Regulation; DistributionLabel.Text = Enum.GetName(typeof(DistributionGrade), co.Distribution_Grade); DistributionStatementText.InnerText = GetDistributionText(co); } }
public PluginManager() { enabledPlugins = new Dictionary <string, Plugin>(); disabledPlugins = new Dictionary <string, Plugin>(); permissionsManager = new PermissionsManager(); }
public void usersWithPermissionToModel_RowDeleting(object sender, GridViewDeleteEventArgs e) { PermissionsManager mgr = new PermissionsManager(); mgr.RemoveUserPermission(Context.User.Identity.Name, PID, e.Values[0] as String); BindUsers(mgr); }
protected void Step1NextButton_Click(object sender, EventArgs e) { //update if (IsModelUpload) { vwarDAL.IDataRepository dal = (new vwarDAL.DataAccessFactory()).CreateDataRepositorProxy(); ; if (this.IsNew) { //create new & add to session ContentObject co = new ContentObject(dal); co.Title = this.TitleTextBox.Text.Trim(); co.UploadedDate = DateTime.Now; co.LastModified = DateTime.Now; co.Views = 0; co.SubmitterEmail = Context.User.Identity.Name.Trim(); dal.InsertContentObject(co); FedoraContentObject = co; this.ContentObjectID = co.PID; } else { FedoraContentObject.Title = TitleTextBox.Text.Trim(); } if (this.FedoraContentObject != null) { //asset type this.FedoraContentObject.AssetType = "Model"; string newFileName = TitleTextBox.Text.ToLower().Replace(' ', '_') + Path.GetExtension(this.ContentFileUpload.PostedFile.FileName); //model upload Utility_3D.ConvertedModel model = null; if (this.ContentFileUpload.HasFile) { string newOriginalFileName = "original_" + newFileName; if (IsNew) { using (MemoryStream stream = new MemoryStream()) { stream.Write(this.ContentFileUpload.FileBytes, 0, this.ContentFileUpload.FileBytes.Length); FedoraContentObject.OriginalFileId = dal.SetContentFile(stream, FedoraContentObject.PID, newOriginalFileName); } } else { //Update the original file dal.UpdateFile(this.ContentFileUpload.FileBytes, FedoraContentObject.PID, FedoraContentObject.OriginalFileName, newOriginalFileName); } FedoraContentObject.OriginalFileName = newOriginalFileName; Utility_3D.Model_Packager pack = new Utility_3D.Model_Packager(); Utility_3D _3d = new Utility_3D(); Utility_3D.ConverterOptions cOptions = new Utility_3D.ConverterOptions(); cOptions.EnableTextureConversion(Utility_3D.ConverterOptions.PNG); cOptions.EnableScaleTextures(Website.Config.MaxTextureDimension); _3d.Initialize(Website.Config.ConversionLibarayLocation); string UploadedFilename = newFileName; if (Path.GetExtension(UploadedFilename) != ".zip") UploadedFilename = Path.ChangeExtension(newFileName, ".zip"); try { model = pack.Convert(this.ContentFileUpload.PostedFile.InputStream, this.ContentFileUpload.PostedFile.FileName, cOptions); } catch { Response.Redirect(Page.ResolveClientUrl("~/Public/Model.aspx?ContentObjectID=" + this.ContentObjectID)); } var displayFilePath = ""; string convertedFileName = newFileName.Replace(Path.GetExtension(newFileName).ToLower(), ".zip"); if (this.ContentFileUpload.HasFile) { using (Stream stream = new MemoryStream()) { stream.Write(model.data, 0, model.data.Length); stream.Seek(0, SeekOrigin.Begin); FedoraContentObject.Location = UploadedFilename; //FedoraContentObject.DisplayFileId = dal.SetContentFile(stream, FedoraContentObject, UploadedFilename); } } else { using (MemoryStream stream = new MemoryStream()) { stream.Write(model.data, 0, model.data.Length); stream.Seek(0, SeekOrigin.Begin); dal.SetContentFile(stream, FedoraContentObject, UploadedFilename); FedoraContentObject.Location = UploadedFilename; } } FedoraContentObject.Location = convertedFileName; if (model.type != "UNKNOWN") { string optionalPath = (newFileName.LastIndexOf("o3d", StringComparison.CurrentCultureIgnoreCase) != -1) ? "viewerTemp/" : "converterTemp/"; string pathToTempFile = "~/App_Data/" + optionalPath; string destPath = Path.Combine(Context.Server.MapPath(pathToTempFile), newFileName); System.IO.FileStream savefile = new FileStream(destPath, FileMode.OpenOrCreate); byte[] filedata = new Byte[model.data.Length]; model.data.CopyTo(filedata, 0); savefile.Write(model.data, 0, (int)model.data.Length); savefile.Close(); string outfilename = Context.Server.MapPath("~/App_Data/viewerTemp/") + newFileName.Replace(".zip", ".o3d"); string convertedtempfile = ConvertFileToO3D(destPath,outfilename); displayFilePath = FedoraContentObject.DisplayFile; string o3dFileName = newFileName.Replace(Path.GetExtension(newFileName).ToLower(), ".o3d"); if (this.ContentFileUpload.HasFile) { using (FileStream stream = new FileStream(convertedtempfile, FileMode.Open)) { FedoraContentObject.DisplayFileId = dal.SetContentFile(stream, FedoraContentObject, o3dFileName); } } else { using (MemoryStream stream = new MemoryStream()) { stream.Write(filedata, 0, filedata.Length); stream.Seek(0, SeekOrigin.Begin); dal.SetContentFile(stream, FedoraContentObject, UploadedFilename); FedoraContentObject.DisplayFile = Path.GetFileName(FedoraContentObject.DisplayFile); } } FedoraContentObject.DisplayFile = o3dFileName; } else { FedoraContentObject.DisplayFile = string.Empty; } FedoraContentObject.UnitScale = model._ModelData.TransformProperties.UnitMeters.ToString(); FedoraContentObject.UpAxis = model._ModelData.TransformProperties.UpAxis; FedoraContentObject.NumPolygons = model._ModelData.VertexCount.Polys; FedoraContentObject.NumTextures = model._ModelData.ReferencedTextures.Length; PopulateValidationViewMetadata(FedoraContentObject); } //upload thumbnail if (this.ThumbnailFileUpload.HasFile) { int length = (int)this.ThumbnailFileUpload.PostedFile.InputStream.Length; if (IsNew || FedoraContentObject.ScreenShot == "")// order counts here have to set screenshot id after the update so we can find the correct dsid this.FedoraContentObject.ScreenShot = "screenshot.png"; FedoraContentObject.ScreenShotId = dal.SetContentFile(this.ThumbnailFileUpload.PostedFile.InputStream, this.FedoraContentObject, FedoraContentObject.ScreenShot); string ext = new FileInfo(ThumbnailFileUpload.PostedFile.FileName).Extension.ToLower(); System.Drawing.Imaging.ImageFormat format; if (ext == ".png") format = System.Drawing.Imaging.ImageFormat.Png; else if (ext == ".jpg") format = System.Drawing.Imaging.ImageFormat.Jpeg; else if (ext == ".gif") format = System.Drawing.Imaging.ImageFormat.Gif; else { ScreenshotValidator.Visible = true; ScreenshotValidator.Text = "Nice job generating a POST request without the interface. Don't you feel special?"; return; } //Avoid wasting space by removing old thumbnails if (!String.IsNullOrEmpty(FedoraContentObject.ThumbnailId)) File.Delete("~/thumbnails/" + FedoraContentObject.ThumbnailId); //Use the original file bytes to remain consistent with the new file upload ID creation for thumbnails FedoraContentObject.ThumbnailId = Website.Common.GetFileSHA1AndSalt(ThumbnailFileUpload.PostedFile.InputStream) + ext; using (FileStream outFile = new FileStream(HttpContext.Current.Server.MapPath("~/thumbnails/" + FedoraContentObject.ThumbnailId), FileMode.Create)) Website.Common.GenerateThumbnail(ThumbnailFileUpload.PostedFile.InputStream, outFile, format); } //creative commons license url if (this.CCLicenseDropDownList.SelectedItem != null && this.CCLicenseDropDownList.SelectedValue != "None") { this.FedoraContentObject.CreativeCommonsLicenseURL = this.CCLicenseDropDownList.SelectedValue.Trim(); } //Require Resubmit Checkbox FedoraContentObject.RequireResubmit = this.RequireResubmitCheckbox.Checked; //developer logo this.UploadDeveloperLogo(dal, this.FedoraContentObject); //developer name if (!string.IsNullOrEmpty(this.DeveloperNameTextBox.Text)) { this.FedoraContentObject.DeveloperName = this.DeveloperNameTextBox.Text.Trim(); } //sponsor logo this.UploadSponsorLogo(dal, this.FedoraContentObject); //sponsor name if (!string.IsNullOrEmpty(this.SponsorNameTextBox.Text)) { this.FedoraContentObject.SponsorName = this.SponsorNameTextBox.Text.Trim(); } //artist name if (!string.IsNullOrEmpty(this.ArtistNameTextBox.Text)) { this.FedoraContentObject.ArtistName = this.ArtistNameTextBox.Text.Trim(); } //format if (!string.IsNullOrEmpty(this.FormatTextBox.Text)) { this.FedoraContentObject.Format = this.FormatTextBox.Text.Trim(); } //description if (!string.IsNullOrEmpty(this.DescriptionTextBox.Text)) { this.FedoraContentObject.Description = this.DescriptionTextBox.Text.Trim(); } //more information url if (!string.IsNullOrEmpty(this.MoreInformationURLTextBox.Text)) { this.FedoraContentObject.MoreInformationURL = this.MoreInformationURLTextBox.Text.Trim(); } //keywords string cleanTags = ""; foreach (string s in KeywordsTextBox.Text.Split(',')) { cleanTags += s.Trim() + ","; } cleanTags = HttpContext.Current.Server.HtmlEncode(cleanTags.Trim(',')); this.FedoraContentObject.Keywords = cleanTags; } dal.UpdateContentObject(FedoraContentObject); if (IsNew) { PermissionsManager perm = new PermissionsManager(); perm.SetModelToGroupLevel(System.Configuration.ConfigurationManager.AppSettings["DefaultAdminName"], FedoraContentObject.PID, vwarDAL.DefaultGroups.AllUsers, ModelPermissionLevel.Fetchable); perm.SetModelToGroupLevel(System.Configuration.ConfigurationManager.AppSettings["DefaultAdminName"], FedoraContentObject.PID, vwarDAL.DefaultGroups.AnonymousUsers, ModelPermissionLevel.Searchable); perm.Dispose(); } SetModelDisplay(); this.PopulateValidationViewMetadata(FedoraContentObject); this.MultiView1.SetActiveView(this.ValidationView); var admins = UserProfileDB.GetAllAdministrativeUsers(); foreach (DataRow row in admins.Rows) { var url = Request.Url.OriginalString.Replace(Request.Url.PathAndQuery, this.ResolveUrl(Website.Pages.Types.FormatModel(this.ContentObjectID))); Website.Mail.SendModelUploaded(FedoraContentObject); } dal.Dispose(); } }
public bool DeleteGroup(string groupname) { PermissionsManager permissionsManager = new PermissionsManager(); if (Context.User.Identity.IsAuthenticated) { if (permissionsManager.GetGroupsByOwner(Context.User.Identity.Name).Contains(groupname)) { PermissionErrorCode ret = permissionsManager.DeleteGroup(Context.User.Identity.Name, groupname); if (ret == PermissionErrorCode.Ok) { permissionsManager.Dispose(); return true; } } } permissionsManager.Dispose(); return false; }
public void Page_Load(object sender, EventArgs e) { if (IsForbidden) { return; } var permissions = PermissionsManager.GetPermissions(Body.AdministratorName); _jsMethod = Body.GetQueryString("jsMethod"); PageUtils.CheckRequestParameter("PublishmentSystemID"); var nodeId = Body.GetQueryInt("NodeID"); if (nodeId == 0) { nodeId = PublishmentSystemId; } _nodeInfo = NodeManager.GetNodeInfo(PublishmentSystemId, nodeId); _tableStyle = NodeManager.GetTableStyle(PublishmentSystemInfo, _nodeInfo); _tableName = NodeManager.GetTableName(PublishmentSystemInfo, _nodeInfo); _relatedIdentities = RelatedIdentities.GetChannelRelatedIdentities(PublishmentSystemId, _nodeInfo.NodeId); _tableStyleInfoList = TableStyleManager.GetTableStyleInfoList(_tableStyle, _tableName, _relatedIdentities); spContents.ControlToPaginate = rptContents; if (string.IsNullOrEmpty(Body.GetQueryString("NodeID"))) { spContents.SelectCommand = DataProvider.ContentDao.GetSelectCommend(_tableStyle, _tableName, PublishmentSystemId, _nodeInfo.NodeId, permissions.IsSystemAdministrator, ProductPermissionsManager.Current.OwningNodeIdList, SearchType.SelectedValue, Keyword.Text, DateFrom.Text, DateTo.Text, true, ETriState.True, !IsDuplicate.Checked, false); } else { spContents.SelectCommand = DataProvider.ContentDao.GetSelectCommend(_tableStyle, _tableName, PublishmentSystemId, _nodeInfo.NodeId, permissions.IsSystemAdministrator, ProductPermissionsManager.Current.OwningNodeIdList, Body.GetQueryString("SearchType"), Body.GetQueryString("Keyword"), Body.GetQueryString("DateFrom"), Body.GetQueryString("DateTo"), true, ETriState.True, !Body.GetQueryBool("IsDuplicate"), true); } spContents.ItemsPerPage = PublishmentSystemInfo.Additional.PageSize; spContents.SortField = ContentAttribute.Id; spContents.SortMode = SortMode.DESC; spContents.OrderByString = ETaxisTypeUtils.GetOrderByString(_tableStyle, ETaxisType.OrderByIdDesc); rptContents.ItemDataBound += rptContents_ItemDataBound; if (!IsPostBack) { NodeManager.AddListItems(NodeIDDropDownList.Items, PublishmentSystemInfo, false, true, true, EContentModelType.Content, Body.AdministratorName); if (_tableStyleInfoList != null) { foreach (var styleInfo in _tableStyleInfoList) { if (styleInfo.IsVisible) { var listitem = new ListItem(styleInfo.DisplayName, styleInfo.AttributeName); SearchType.Items.Add(listitem); } } } //添加隐藏属性 SearchType.Items.Add(new ListItem("内容ID", ContentAttribute.Id)); SearchType.Items.Add(new ListItem("添加者", ContentAttribute.AddUserName)); SearchType.Items.Add(new ListItem("最后修改者", ContentAttribute.LastEditUserName)); if (Body.IsQueryExists("NodeID")) { if (PublishmentSystemId != _nodeInfo.NodeId) { ControlUtils.SelectListItems(NodeIDDropDownList, _nodeInfo.NodeId.ToString()); } IsDuplicate.Checked = Body.GetQueryBool("IsDuplicate"); ControlUtils.SelectListItems(SearchType, Body.GetQueryString("SearchType")); Keyword.Text = Body.GetQueryString("Keyword"); DateFrom.Text = Body.GetQueryString("DateFrom"); DateTo.Text = Body.GetQueryString("DateTo"); } spContents.DataBind(); } }
public List<UserGroup> GetAllGroups() { PermissionsManager permissionsManager = new PermissionsManager(); if (Context.User.Identity.IsAuthenticated) { } permissionsManager.Dispose(); return new List<UserGroup>(); }
public static string SubmitUpload(string DeveloperName, string ArtistName, string DeveloperUrl, string SponsorName, string LicenseType, bool RequireResubmit) { HttpServerUtility server = HttpContext.Current.Server; ContentObject tempCO = (ContentObject)HttpContext.Current.Session["contentObject"]; try { FileStatus status = (FileStatus)HttpContext.Current.Session["fileStatus"]; var factory = new DataAccessFactory(); IDataRepository dal = factory.CreateDataRepositorProxy(); dal.InsertContentObject(tempCO); tempCO.DeveloperName = server.HtmlEncode(DeveloperName); tempCO.ArtistName = server.HtmlEncode(ArtistName); tempCO.MoreInformationURL = server.HtmlEncode(DeveloperUrl); tempCO.RequireResubmit = RequireResubmit; tempCO.SponsorName = server.HtmlEncode(SponsorName); vwarDAL.PermissionsManager perMgr = new PermissionsManager(); var groupSetReturnCode = perMgr.SetModelToGroupLevel(HttpContext.Current.User.Identity.Name, tempCO.PID, vwarDAL.DefaultGroups.AllUsers, ModelPermissionLevel.Fetchable); groupSetReturnCode = perMgr.SetModelToGroupLevel(HttpContext.Current.User.Identity.Name, tempCO.PID, vwarDAL.DefaultGroups.AnonymousUsers, ModelPermissionLevel.Searchable); string pid = tempCO.PID; //tempCO.SponsorURL = SponsorUrl; !missing SponsorUrl metadata in ContentObject if (LicenseType == "publicdomain") { tempCO.CreativeCommonsLicenseURL = "http://creativecommons.org/publicdomain/mark/1.0/"; } else { tempCO.CreativeCommonsLicenseURL = String.Format(ConfigurationManager.AppSettings["CCBaseUrl"], LicenseType); } //Upload the thumbnail and logos string filename = status.hashname; string basehash = filename.Substring(0, filename.LastIndexOf(".") - 1); foreach (FileInfo f in new DirectoryInfo(HttpContext.Current.Server.MapPath("~/App_Data/imageTemp")).GetFiles("*" + basehash + "*")) { using (FileStream fstream = f.OpenRead()) { string type = f.Name.Substring(0, f.Name.IndexOf('_')); switch (type) { case ImagePrefix.DEVELOPER_LOGO: tempCO.DeveloperLogoImageFileName = "developer_logo" + f.Extension; tempCO.DeveloperLogoImageFileNameId = dal.SetContentFile(fstream, tempCO.PID, tempCO.DeveloperLogoImageFileName); break; case ImagePrefix.SPONSOR_LOGO: tempCO.SponsorLogoImageFileName = "sponsor_logo" + f.Extension; tempCO.SponsorLogoImageFileNameId = dal.SetContentFile(fstream, tempCO.PID, tempCO.SponsorLogoImageFileName); break; case ImagePrefix.SCREENSHOT: tempCO.ScreenShot = "screenshot" + f.Extension; tempCO.ScreenShotId = dal.SetContentFile(fstream, tempCO.PID, tempCO.ScreenShot); System.Drawing.Imaging.ImageFormat fmt = System.Drawing.Imaging.ImageFormat.Png; if (f.Extension == ".png") { fmt = System.Drawing.Imaging.ImageFormat.Png; } else if (f.Extension == ".jpg") { fmt = System.Drawing.Imaging.ImageFormat.Jpeg; } else if (f.Extension == ".gif") { fmt = System.Drawing.Imaging.ImageFormat.Gif; } else { throw new Exception("Invalid screenshot format"); } tempCO.ThumbnailId = Website.Common.GetFileSHA1AndSalt(fstream) + f.Extension; using (FileStream outFile = new FileStream(HttpContext.Current.Server.MapPath("~/thumbnails/" + tempCO.ThumbnailId), FileMode.Create)) Website.Common.GenerateThumbnail(fstream, outFile, fmt); break; default: break; } } } string dataPath = HttpContext.Current.Server.MapPath("~/App_Data/"); if (status.type == FormatType.VIEWABLE) { //Upload the original file using (FileStream s = new FileStream(dataPath + status.hashname, FileMode.Open)) { tempCO.OriginalFileId = dal.SetContentFile(s, pid, "original_" + status.filename); tempCO.OriginalFileName = "original_" + status.filename; } using (FileStream s = new FileStream(Path.Combine(dataPath, "converterTemp/" + status.hashname.ToLower().Replace("skp", "zip")), FileMode.Open, FileAccess.Read)) { tempCO.DisplayFileId = dal.SetContentFile(s, pid, status.filename.ToLower().Replace("skp", "zip")); } using (FileStream s = new FileStream(Path.Combine(dataPath, "viewerTemp/" + status.hashname.ToLower().Replace("skp", "o3d").Replace("zip", "o3d")), FileMode.Open)) { dal.SetContentFile(s, pid, status.filename.ToLower().Replace("skp", "o3d").Replace("zip", "o3d")); } } else if (status.type == FormatType.RECOGNIZED) { using (FileStream s = new FileStream(dataPath + status.hashname, FileMode.Open)) { tempCO.OriginalFileName = "original_" + status.filename; tempCO.OriginalFileId = dal.SetContentFile(s, pid, tempCO.OriginalFileName); } } tempCO.Enabled = true; tempCO.UploadedDate = DateTime.Now; dal.UpdateContentObject(tempCO); UploadReset(status.hashname); List <string> textureReferences = HttpContext.Current.Session["contentTextures"] as List <string>; List <string> textureReferenceMissing = HttpContext.Current.Session["contentMissingTextures"] as List <string>; if (textureReferences != null) { foreach (string tex in textureReferences) { tempCO.SetParentRepo(dal); tempCO.AddTextureReference(tex, "unknown", 0); } } if (textureReferenceMissing != null) { foreach (string tex in textureReferenceMissing) { tempCO.SetParentRepo(dal); tempCO.AddMissingTexture(tex, "unknown", 0); } } if (LR_3DR_Bridge.LR_Integration_Enabled()) { LR_3DR_Bridge.ModelUploaded(tempCO); } Website.Mail.SendModelUploaded(tempCO); dal.Dispose(); perMgr.Dispose(); return(tempCO.PID); } catch (Exception e) { #if DEBUG return(String.Format("fedoraError|" + e.Message + "<br /><br />" + e.StackTrace)); #else return("fedoraError|" + ConfigurationManager.AppSettings["UploadPage_FedoraError"]); #endif } }
public bool RemoveUserPermission(string pid, string username, bool temp) { PermissionsManager permissionsManager = new PermissionsManager(); pid = HttpContext.Current.Server.UrlDecode(pid); if (Context.User.Identity.IsAuthenticated) { if (Website.Common.IsValidUser(username)) { PermissionErrorCode error = PermissionErrorCode.Ok; if (temp) _tempUserPermissions.Remove(username); else error = permissionsManager.RemoveUserPermission(HttpContext.Current.User.Identity.Name, pid, username); switch (error) { case PermissionErrorCode.Ok: HttpContext.Current.Response.StatusCode = 200; break; case PermissionErrorCode.NotAuthorized: HttpContext.Current.Response.StatusCode = 401; break; default: HttpContext.Current.Response.StatusCode = 400; break; } permissionsManager.Dispose(); return true; } else { HttpContext.Current.Response.StatusCode = 400; permissionsManager.Dispose(); return false; } } else { HttpContext.Current.Response.StatusCode = 401; permissionsManager.Dispose(); return false; } }
public void Page_Load(object sender, EventArgs e) { if (IsForbidden) { return; } _publishmentSystemType = EPublishmentSystemTypeUtils.GetEnumType(Body.GetQueryString("publishmentSystemType")); _sortedlist = SiteTemplateManager.Instance.GetSiteTemplateSortedList(); _permissions = PermissionsManager.GetPermissions(Body.AdministratorName); if (!IsPostBack) { BaiRongDataProvider.TableCollectionDao.CreateAllAuxiliaryTableIfNotExists(); SiteTemplateDir.Value = Body.GetQueryString("siteTemplate"); string pageTitle = $"创建{EPublishmentSystemTypeUtils.GetText(_publishmentSystemType)}"; ltlPageTitle.Text = pageTitle; BreadCrumbSys(AppManager.Sys.LeftMenu.Site, pageTitle, AppManager.Sys.Permission.SysSite); var hqSiteId = DataProvider.PublishmentSystemDao.GetPublishmentSystemIdByIsHeadquarters(); if (hqSiteId == 0) { IsHeadquarters.SelectedValue = "True"; phNotIsHeadquarters.Visible = false; } else { IsHeadquarters.Enabled = false; } ltlPublishmentSystemType.Text = EPublishmentSystemTypeUtils.GetHtml(_publishmentSystemType); phWCMTables.Visible = _publishmentSystemType == EPublishmentSystemType.WCM; ParentPublishmentSystemID.Items.Add(new ListItem("<无上级站点>", "0")); var publishmentSystemIdArrayList = PublishmentSystemManager.GetPublishmentSystemIdList(); var mySystemInfoArrayList = new ArrayList(); var parentWithChildren = new Hashtable(); foreach (int publishmentSystemId in publishmentSystemIdArrayList) { var publishmentSystemInfo = PublishmentSystemManager.GetPublishmentSystemInfo(publishmentSystemId); if (publishmentSystemInfo.IsHeadquarters == false) { if (publishmentSystemInfo.ParentPublishmentSystemId == 0) { mySystemInfoArrayList.Add(publishmentSystemInfo); } else { var children = new ArrayList(); if (parentWithChildren.Contains(publishmentSystemInfo.ParentPublishmentSystemId)) { children = (ArrayList)parentWithChildren[publishmentSystemInfo.ParentPublishmentSystemId]; } children.Add(publishmentSystemInfo); parentWithChildren[publishmentSystemInfo.ParentPublishmentSystemId] = children; } } } foreach (PublishmentSystemInfo publishmentSystemInfo in mySystemInfoArrayList) { AddSite(ParentPublishmentSystemID, publishmentSystemInfo, parentWithChildren, 0); } ControlUtils.SelectListItems(ParentPublishmentSystemID, "0"); phNodeRelated.Visible = EPublishmentSystemTypeUtils.IsNodeRelated(_publishmentSystemType); ECharsetUtils.AddListItems(Charset); ControlUtils.SelectListItems(Charset, ECharsetUtils.GetValue(ECharset.utf_8)); var tableList = BaiRongDataProvider.TableCollectionDao.GetAuxiliaryTableListCreatedInDbByAuxiliaryTableType(EAuxiliaryTableType.BackgroundContent); foreach (var tableInfo in tableList) { var li = new ListItem($"{tableInfo.TableCnName}({tableInfo.TableEnName})", tableInfo.TableEnName); AuxiliaryTableForContent.Items.Add(li); } tableList = BaiRongDataProvider.TableCollectionDao.GetAuxiliaryTableListCreatedInDbByAuxiliaryTableType(EAuxiliaryTableType.GovPublicContent); foreach (var tableInfo in tableList) { var li = new ListItem($"{tableInfo.TableCnName}({tableInfo.TableEnName})", tableInfo.TableEnName); AuxiliaryTableForGovPublic.Items.Add(li); } tableList = BaiRongDataProvider.TableCollectionDao.GetAuxiliaryTableListCreatedInDbByAuxiliaryTableType(EAuxiliaryTableType.GovInteractContent); foreach (var tableInfo in tableList) { var li = new ListItem($"{tableInfo.TableCnName}({tableInfo.TableEnName})", tableInfo.TableEnName); AuxiliaryTableForGovInteract.Items.Add(li); } tableList = BaiRongDataProvider.TableCollectionDao.GetAuxiliaryTableListCreatedInDbByAuxiliaryTableType(EAuxiliaryTableType.VoteContent); foreach (var tableInfo in tableList) { var li = new ListItem($"{tableInfo.TableCnName}({tableInfo.TableEnName})", tableInfo.TableEnName); AuxiliaryTableForVote.Items.Add(li); } tableList = BaiRongDataProvider.TableCollectionDao.GetAuxiliaryTableListCreatedInDbByAuxiliaryTableType(EAuxiliaryTableType.JobContent); foreach (var tableInfo in tableList) { var li = new ListItem($"{tableInfo.TableCnName}({tableInfo.TableEnName})", tableInfo.TableEnName); AuxiliaryTableForJob.Items.Add(li); } IsCheckContentUseLevel.Items.Add(new ListItem("默认审核机制", false.ToString())); IsCheckContentUseLevel.Items.Add(new ListItem("多级审核机制", true.ToString())); ControlUtils.SelectListItems(IsCheckContentUseLevel, false.ToString()); UseSiteTemplate.Attributes.Add("onclick", "displaySiteTemplateDiv(this)"); BindGrid(); if (_sortedlist.Count > 0) { SetActivePlaceHolder(WizardPlaceHolder.ChooseSiteTemplate, ChooseSiteTemplate); } else { ChooseSiteTemplate.Visible = false; UseSiteTemplate.Checked = false; SetActivePlaceHolder(WizardPlaceHolder.CreateSiteParameters, CreateSiteParameters); RowSiteTemplateName.Visible = RowIsImportContents.Visible = RowIsImportTableStyles.Visible = RowIsUserSiteTemplateAuxiliaryTables.Visible = false; phAuxiliaryTable.Visible = true; } } }
public string SavePermissions(string type, string pid, List<string> targets, List<string> permissions, bool temp) { PermissionsManager permissionsManager = new PermissionsManager(); HttpContext context = HttpContext.Current; string identity = context.User.Identity.Name; pid = context.Server.UrlDecode(pid); if (targets.Count == permissions.Count && (type == "user" || type == "group")) { for (int i = 0; i < targets.Count; i++) { ModelPermissionLevel perm = (ModelPermissionLevel)(Int32.Parse(permissions[i])); if (type == "group") { //Transform any end-user-view groupnames into codebehind groupnames if (targets[i] == PermissionsManager.ALL_USERS_LABEL) targets[i] = DefaultGroups.AllUsers; else if (targets[i] == PermissionsManager.ANONYMOUS_USERS_LABEL) targets[i] = DefaultGroups.AnonymousUsers; } PermissionErrorCode errorCode = PermissionErrorCode.Ok; if (type == "user" && !Website.Common.IsValidUser(targets[i])) errorCode = PermissionErrorCode.DoesNotExist; else { if (temp) { if (type == "group") _tempGroupPermissions[targets[i]] = perm; else _tempUserPermissions[targets[i]] = perm; } else { errorCode = (type == "group") ? permissionsManager.SetModelToGroupLevel(identity, pid, targets[i], perm) : permissionsManager.SetModelToUserLevel(identity, pid, targets[i], perm); } } switch (errorCode) { case PermissionErrorCode.Ok: context.Response.StatusCode = 200; break; case PermissionErrorCode.NotAuthorized: context.Response.StatusCode = 401; break; default: context.Response.StatusCode = 400; break; } if (errorCode != PermissionErrorCode.Ok) break; } } else context.Response.StatusCode = 400; permissionsManager.Dispose(); //TODO: Add more specific error messages return (context.Response.StatusCode == 200) ? "success" : "failure"; }