using System;
using System.Data;
using System.Collections;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CMS.CMSHelper;
using CMS.Controls;
using CMS.EventLog;
using CMS.ExtendedControls;
using CMS.FormControls;
using CMS.FormEngine;
using CMS.GlobalHelper;
using CMS.LicenseProvider;
using CMS.PortalEngine;
using CMS.SettingsProvider;
using CMS.SiteProvider;
using CMS.DocumentEngine;
using CMS.UIControls;
using CMS.URLRewritingEngine;
using CMS.WebAnalytics;
using CMS.WorkflowEngine;
using TreeNode = CMS.DocumentEngine.TreeNode;
public partial class CMSModules_Content_Controls_UserContributions_EditForm : CMSUserControl
{
#region "Variables"
private FormModeEnum formModebeforeSave = FormModeEnum.Update;
///
/// On after approve event.
///
public event EventHandler OnAfterApprove = null;
///
/// On after reject event.
///
public event EventHandler OnAfterReject = null;
///
/// On after delete event.
///
public event EventHandler OnAfterDelete = null;
///
/// Data properties variable.
///
private readonly CMSDataProperties mDataProperties = new CMSDataProperties();
///
/// Indicates if the form has been loaded.
///
private bool mFormLoaded = false;
private DataClassInfo ci = null;
#endregion
#region "Document properties"
///
/// Indicates if the control is used on a live site.
///
public override bool IsLiveSite
{
get
{
return base.IsLiveSite;
}
set
{
base.IsLiveSite = value;
docMan.IsLiveSite = value;
}
}
///
/// Document manager
///
public override ICMSDocumentManager DocumentManager
{
get
{
return docMan;
}
}
///
/// Culture code.
///
public string CultureCode
{
get
{
return ValidationHelper.GetString(ViewState["CultureCode"], mDataProperties.CultureCode);
}
set
{
ViewState["CultureCode"] = value;
menuElem.CultureCode = value;
DocumentManager.CultureCode = value;
}
}
///
/// Site name.
///
public string SiteName
{
get
{
return ValidationHelper.GetString(ViewState["SiteName"], mDataProperties.SiteName);
}
set
{
ViewState["SiteName"] = value;
DocumentManager.SiteName = value;
}
}
///
/// Indicates if check-in/check-out functionality is automatic
///
protected bool AutoCheck
{
get
{
return DocumentManager.AutoCheck;
}
}
///
/// Gets Workflow manager instance.
///
protected WorkflowManager WorkflowManager
{
get
{
return DocumentManager.WorkflowManager;
}
}
///
/// Gets Version manager instance.
///
protected VersionManager VersionManager
{
get
{
return DocumentManager.VersionManager;
}
}
///
/// Tree provider instance.
///
protected TreeProvider TreeProvider
{
get
{
return DocumentManager.Tree;
}
}
#endregion
#region "Public properties"
///
/// Returns true if new document mode.
///
public bool NewDocument
{
get
{
return (Action.ToLowerCSafe() == "new");
}
}
///
/// Returns true if new culture mode.
///
public bool NewCulture
{
get
{
return (Action.ToLowerCSafe() == "newculture");
}
}
///
/// Returns true in delete mode.
///
public bool Delete
{
get
{
return (Action.ToLowerCSafe() == "delete");
}
}
///
/// Returns true in edit mode.
///
public bool Edit
{
get
{
return (Action.ToLowerCSafe() == "edit");
}
}
///
/// Node ID.
///
public int NodeID
{
get
{
return ValidationHelper.GetInteger(ViewState["NodeID"], 0);
}
set
{
ViewState["NodeID"] = value;
menuElem.NodeID = value;
DocumentManager.NodeID = value;
}
}
///
/// Document node.
///
public TreeNode Node
{
get
{
return DocumentManager.Node;
}
}
///
/// Form Action (mode).
///
public string Action
{
get
{
return ValidationHelper.GetString(ViewState["Action"], "");
}
set
{
ViewState["Action"] = value;
if (NewDocument)
{
DocumentManager.Mode = FormModeEnum.Insert;
}
else if (NewCulture)
{
DocumentManager.Mode = FormModeEnum.InsertNewCultureVersion;
}
else
{
DocumentManager.Mode = FormModeEnum.Update;
}
}
}
///
/// Class ID.
///
public int ClassID
{
get
{
return ValidationHelper.GetInteger(ViewState["ClassID"], 0);
}
set
{
ViewState["ClassID"] = value;
DocumentManager.NewNodeClassID = value;
}
}
///
/// Alternative form name.
///
public string AlternativeFormName
{
get
{
return ValidationHelper.GetString(ViewState["AlternativeFormName"], null);
}
set
{
ViewState["AlternativeFormName"] = value;
}
}
///
/// Form validation error message.
///
public string ValidationErrorMessage
{
get
{
return ValidationHelper.GetString(ViewState["ValidationErrorMessage"], null);
}
set
{
ViewState["ValidationErrorMessage"] = value;
}
}
///
/// Template ID.
///
public int TemplateID
{
get
{
return ValidationHelper.GetInteger(ViewState["TemplateID"], 0);
}
set
{
ViewState["TemplateID"] = value;
}
}
///
/// Owner ID.
///
public int OwnerID
{
get
{
return ValidationHelper.GetInteger(ViewState["OwnerID"], 0);
}
set
{
ViewState["OwnerID"] = value;
}
}
///
/// New item page template code name.
///
public string NewItemPageTemplate
{
get
{
return ValidationHelper.GetString(ViewState["NewItemPageTemplate"], "");
}
set
{
ViewState["NewItemPageTemplate"] = value;
// Get template and set template ID
PageTemplateInfo pti = PageTemplateInfoProvider.GetPageTemplateInfo(value);
if (pti != null)
{
TemplateID = pti.PageTemplateId;
}
}
}
///
/// List of allowed child classes separated by semicolon.
///
public string AllowedChildClasses
{
get
{
return ValidationHelper.GetString(ViewState["AllowedChildClasses"], "");
}
set
{
ViewState["AllowedChildClasses"] = value;
}
}
///
/// Document ID to use for default data of new culture version.
///
public int CopyDefaultDataFromDocumentID
{
get
{
return ValidationHelper.GetInteger(ViewState["CopyDefaultDataFromDocumentID"], 0);
}
set
{
ViewState["CopyDefaultDataFromDocumentID"] = value;
DocumentManager.SourceDocumentID = value;
}
}
///
/// If true, form allows deleting the document.
///
public bool AllowDelete
{
get
{
return ValidationHelper.GetBoolean(ViewState["AllowDelete"], true);
}
set
{
ViewState["AllowDelete"] = value;
}
}
///
/// Gets or sets the value that indicates whether document permissions are checked.
///
public bool CheckPermissions
{
get
{
return ValidationHelper.GetBoolean(ViewState["CheckPermissions"], false);
}
set
{
ViewState["CheckPermissions"] = value;
menuElem.CheckPermissions = value;
}
}
///
/// Gets or sets the value that indicates whether document type permissions are required to create new document.
///
public bool CheckDocPermissionsForInsert
{
get
{
return ValidationHelper.GetBoolean(ViewState["CheckDocPermissionsForInsert"], true);
}
set
{
ViewState["CheckDocPermissionsForInsert"] = value;
}
}
///
/// Determines whether to use progress script.
///
public bool UseProgressScript
{
get
{
return ValidationHelper.GetBoolean(ViewState["UseProgressScript"], true);
}
set
{
ViewState["UseProgressScript"] = value;
}
}
///
/// Editing form.
///
public CMSForm CMSForm
{
get
{
return formElem;
}
}
///
/// Determines whether the save is allowed (form have to be loaded first).
///
public bool AllowSave
{
get
{
return menuElem.AllowSave;
}
}
///
/// Indicates whether activity logging is enabled.
///
public bool LogActivity
{
get;
set;
}
#endregion
#region "Methods"
protected override void CreateChildControls()
{
// Reload data
ReloadData(false);
}
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
DocumentManager.LocalDocumentPanel = pnlDoc;
DocumentManager.LocalMessagesPlaceHolder = formElem.MessagesPlaceHolder;
DocumentManager.OnAfterAction += DocumentManager_OnAfterAction;
DocumentManager.OnValidateData += DocumentManager_OnValidateData;
DocumentManager.OnBeforeAction += DocumentManager_OnBeforeAction;
DocumentManager.OnLoadData += DocumentManager_OnLoadData;
}
protected void Page_Load(object sender, EventArgs e)
{
// Register external data bound event handler for UniGrid
gridClass.OnExternalDataBound += gridClass_OnExternalDataBound;
}
///
/// Reloads control.
///
/// Forces nested CMSForm to reload if true
public void ReloadData(bool forceReload)
{
if (!mFormLoaded || forceReload)
{
// Check License
LicenseHelper.CheckFeatureAndRedirect(URLHelper.GetCurrentDomain(), FeatureEnum.UserContributions);
if (StopProcessing)
{
formElem.StopProcessing = true;
}
else
{
// Set document manager mode
if (NewDocument)
{
DocumentManager.Mode = FormModeEnum.Insert;
DocumentManager.ParentNodeID = NodeID;
DocumentManager.NewNodeClassID = ClassID;
DocumentManager.CultureCode = CultureCode;
DocumentManager.SiteName = SiteName;
}
else if (NewCulture)
{
DocumentManager.Mode = FormModeEnum.InsertNewCultureVersion;
DocumentManager.NodeID = NodeID;
DocumentManager.CultureCode = CultureCode;
DocumentManager.SiteName = SiteName;
DocumentManager.SourceDocumentID = CopyDefaultDataFromDocumentID;
}
else
{
DocumentManager.Mode = FormModeEnum.Update;
DocumentManager.NodeID = NodeID;
DocumentManager.SiteName = SiteName;
DocumentManager.CultureCode = CultureCode;
}
ScriptHelper.RegisterDialogScript(Page);
formElem.StopProcessing = false;
titleElem.TitleImage = String.Empty;
titleElem.TitleText = String.Empty;
pnlSelectClass.Visible = false;
pnlEdit.Visible = false;
pnlInfo.Visible = false;
pnlNewCulture.Visible = false;
pnlDelete.Visible = false;
// If node found, init the form
if (NewDocument || (Node != null))
{
// Delete action
if (Delete)
{
// Delete document
pnlDelete.Visible = true;
titleElem.TitleText = GetString("Content.DeleteTitle");
titleElem.TitleImage = GetImageUrl("CMSModules/CMS_Content/Menu/delete.png");
chkAllCultures.Text = GetString("ContentDelete.AllCultures");
chkDestroy.Text = GetString("ContentDelete.Destroy");
lblQuestion.Text = GetString("ContentDelete.Question");
btnYes.Text = GetString("general.yes");
// Prevent button double-click
btnYes.Attributes.Add("onclick", string.Format("document.getElementById('{0}').disabled=true;this.disabled=true;{1};", btnNo.ClientID, ControlsHelper.GetPostBackEventReference(btnYes, string.Empty, true, false)));
btnNo.Text = GetString("general.no");
DataSet culturesDS = CultureInfoProvider.GetSiteCultures(SiteName);
if ((DataHelper.DataSourceIsEmpty(culturesDS)) || (culturesDS.Tables[0].Rows.Count <= 1))
{
chkAllCultures.Visible = false;
chkAllCultures.Checked = true;
}
if (Node.IsLink)
{
titleElem.TitleText = GetString("Content.DeleteTitleLink") + " \"" + HTMLHelper.HTMLEncode(Node.NodeName) + "\"";
lblQuestion.Text = GetString("ContentDelete.QuestionLink");
chkAllCultures.Checked = true;
plcCheck.Visible = false;
}
else
{
titleElem.TitleText = GetString("Content.DeleteTitle") + " \"" + HTMLHelper.HTMLEncode(Node.NodeName) + "\"";
}
}
// New document or edit action
else
{
if (NewDocument)
{
titleElem.TitleImage = GetImageUrl("CMSModules/CMS_Content/Menu/new.png");
titleElem.TitleText = GetString("Content.NewTitle");
}
// Document type selection
if (NewDocument && (ClassID <= 0))
{
// Use parent node
TreeNode parentNode = DocumentManager.ParentNode;
if (parentNode != null)
{
// Select document type
pnlSelectClass.Visible = true;
// Get the allowed child classes
DataSet ds = DataClassInfoProvider.GetAllowedChildClasses(ValidationHelper.GetInteger(parentNode.GetValue("NodeClassID"), 0), ValidationHelper.GetInteger(SiteInfoProvider.GetSiteInfo(SiteName).SiteID, 0), "ClassName, ClassDisplayName, ClassID", -1);
ArrayList deleteRows = new ArrayList();
if (!DataHelper.DataSourceIsEmpty(ds))
{
// Get the unwanted classes
string allowed = AllowedChildClasses.Trim().ToLowerCSafe();
if (!string.IsNullOrEmpty(allowed))
{
allowed = String.Format(";{0};", allowed);
}
CurrentUserInfo userInfo = CMSContext.CurrentUser;
string className = null;
// Check if the user has 'Create' permission per Content
bool isAuthorizedToCreateInContent = userInfo.IsAuthorizedPerResource("CMS.Content", "Create");
bool hasNodeAllowCreate = (userInfo.IsAuthorizedPerTreeNode(parentNode, NodePermissionsEnum.Create) != AuthorizationResultEnum.Allowed);
foreach (DataRow dr in ds.Tables[0].Rows)
{
className = ValidationHelper.GetString(DataHelper.GetDataRowValue(dr, "ClassName"), String.Empty).ToLowerCSafe();
// Document type is not allowed or user hasn't got permission, remove it from the data set
if ((!string.IsNullOrEmpty(allowed) && (!allowed.Contains(";" + className + ";"))) ||
(CheckPermissions && CheckDocPermissionsForInsert && !isAuthorizedToCreateInContent && !userInfo.IsAuthorizedPerClassName(className, "Create") && (!userInfo.IsAuthorizedPerClassName(className, "CreateSpecific") || !hasNodeAllowCreate)))
{
deleteRows.Add(dr);
}
}
// Remove the rows
foreach (DataRow dr in deleteRows)
{
ds.Tables[0].Rows.Remove(dr);
}
}
// Check if some classes are available
if (!DataHelper.DataSourceIsEmpty(ds))
{
// If number of classes is more than 1 display them in grid
if (ds.Tables[0].Rows.Count > 1)
{
ds.Tables[0].DefaultView.Sort = "ClassDisplayName";
lblError.Visible = false;
lblInfo.Visible = true;
lblInfo.Text = GetString("Content.NewInfo");
DataSet sortedResult = new DataSet();
sortedResult.Tables.Add(ds.Tables[0].DefaultView.ToTable());
gridClass.DataSource = sortedResult;
gridClass.ReloadData();
}
// else show form of the only class
else
{
ClassID = ValidationHelper.GetInteger(DataHelper.GetDataRowValue(ds.Tables[0].Rows[0], "ClassID"), 0);
ReloadData(true);
return;
}
}
else
{
// Display error message
lblError.Visible = true;
lblError.Text = GetString("Content.NoAllowedChildDocuments");
lblInfo.Visible = false;
gridClass.Visible = false;
}
}
else
{
pnlInfo.Visible = true;
lblFormInfo.Text = GetString("EditForm.DocumentNotFound");
formElem.StopProcessing = true;
}
}
// Insert or update of a document
else
{
// Display the form
pnlEdit.Visible = true;
// Try to get GroupID if group context exists
int currentGroupId = ModuleCommands.CommunityGetCurrentGroupID();
btnDelete.Attributes.Add("style", "display: none;");
btnRefresh.Attributes.Add("style", "display: none;");
// CMSForm initialization
formElem.NodeID = Node.NodeID;
formElem.SiteName = SiteName;
formElem.CultureCode = CultureCode;
formElem.ValidationErrorMessage = ValidationErrorMessage;
formElem.IsLiveSite = IsLiveSite;
// Set group ID if group context exists
formElem.GroupID = currentGroupId;
// WebDAV is allowed for live site only if the permissions are checked or user is global administrator or for group context - user is group administrator
formElem.AllowWebDAV = !IsLiveSite || CheckPermissions || CMSContext.CurrentUser.IsGlobalAdministrator || CMSContext.CurrentUser.IsGroupAdministrator(currentGroupId);
// Set the form mode
if (NewDocument)
{
ci = DataClassInfoProvider.GetDataClass(ClassID);
if (ci == null)
{
throw new Exception(String.Format("[CMSAdminControls/EditForm.aspx]: Class ID '{0}' not found.", ClassID));
}
string classDisplayName = HTMLHelper.HTMLEncode(ResHelper.LocalizeString(ci.ClassDisplayName));
titleElem.TitleText = GetString("Content.NewTitle") + ": " + classDisplayName;
// Set default template ID
formElem.DefaultPageTemplateID = TemplateID > 0 ? TemplateID : ci.ClassDefaultPageTemplateID;
// Set document owner
formElem.OwnerID = OwnerID;
formElem.FormMode = FormModeEnum.Insert;
string newClassName = ci.ClassName;
string newFormName = newClassName + ".default";
if (!String.IsNullOrEmpty(AlternativeFormName))
{
// Set the alternative form full name
formElem.AlternativeFormFullName = GetAltFormFullName(ci.ClassName);
}
if (newFormName.ToLowerCSafe() != formElem.FormName.ToLowerCSafe())
{
formElem.FormName = newFormName;
}
}
else if (NewCulture)
{
formElem.FormMode = FormModeEnum.InsertNewCultureVersion;
// Default data document ID
formElem.CopyDefaultDataFromDocumentId = CopyDefaultDataFromDocumentID;
ci = DataClassInfoProvider.GetDataClass(Node.NodeClassName);
formElem.FormName = Node.NodeClassName + ".default";
if (!String.IsNullOrEmpty(AlternativeFormName))
{
// Set the alternative form full name
formElem.AlternativeFormFullName = GetAltFormFullName(ci.ClassName);
}
}
else
{
formElem.FormMode = FormModeEnum.Update;
ci = DataClassInfoProvider.GetDataClass(Node.NodeClassName);
formElem.FormName = String.Empty;
if (!String.IsNullOrEmpty(AlternativeFormName))
{
// Set the alternative form full name
formElem.AlternativeFormFullName = GetAltFormFullName(ci.ClassName);
}
// Initialize the CMSForm
formElem.LoadForm(forceReload);
}
// Display the CMSForm
formElem.Visible = true;
ReloadForm();
}
}
}
// New culture version
else
{
// Switch to new culture version mode
DocumentManager.Mode = FormModeEnum.InsertNewCultureVersion;
DocumentManager.NodeID = NodeID;
DocumentManager.CultureCode = CultureCode;
DocumentManager.SiteName = SiteName;
if (Node != null)
{
// Offer a new culture creation
pnlNewCulture.Visible = true;
titleElem.TitleText = GetString("Content.NewCultureVersionTitle") + " (" + HTMLHelper.HTMLEncode(CMSContext.CurrentUser.PreferredCultureCode) + ")";
titleElem.TitleImage = GetImageUrl("CMSModules/CMS_Content/Menu/new.png");
lblNewCultureInfo.Text = GetString("ContentNewCultureVersion.Info");
radCopy.Text = GetString("ContentNewCultureVersion.Copy");
radEmpty.Text = GetString("ContentNewCultureVersion.Empty");
radCopy.Attributes.Add("onclick", "ShowSelection();");
radEmpty.Attributes.Add("onclick", "ShowSelection()");
AddScript(
"function ShowSelection() { \n" +
" if (document.getElementById('" + radCopy.ClientID + "').checked) { document.getElementById('divCultures').style.display = 'block'; } \n" +
" else { document.getElementById('divCultures').style.display = 'none'; } \n" +
"} \n"
);
btnOk.Text = GetString("ContentNewCultureVersion.Create");
// Load culture versions
SiteInfo si = SiteInfoProvider.GetSiteInfo(Node.NodeSiteID);
if (si != null)
{
lstCultures.Items.Clear();
DataSet nodes = TreeProvider.SelectNodes(si.SiteName, Node.NodeAliasPath, TreeProvider.ALL_CULTURES, false, null, null, null, 1, false);
foreach (DataRow nodeCulture in nodes.Tables[0].Rows)
{
ListItem li = new ListItem();
li.Text = CultureInfoProvider.GetCultureInfo(nodeCulture["DocumentCulture"].ToString()).CultureName;
li.Value = nodeCulture["DocumentID"].ToString();
lstCultures.Items.Add(li);
}
if (lstCultures.Items.Count > 0)
{
lstCultures.SelectedIndex = 0;
}
}
}
else
{
pnlInfo.Visible = true;
lblFormInfo.Text = GetString("EditForm.DocumentNotFound");
formElem.StopProcessing = true;
}
}
}
// Set flag that the form is loaded
mFormLoaded = true;
}
}
///
/// Unigrid external databound.
///
protected object gridClass_OnExternalDataBound(object sender, string sourceName, object parameter)
{
switch (sourceName.ToLowerCSafe())
{
// Display link to class type
case "classdisplayname":
{
DataRowView row = (DataRowView)parameter;
LinkButton btn = new LinkButton();
btn.CssClass = "UserContributionNewClass";
btn.CommandArgument = ValidationHelper.GetString(row["ClassID"], "0");
btn.Command += btnClass_Command;
Image img = new Image();
img.ImageUrl = GetDocumentTypeIconUrl(Convert.ToString(row["ClassName"]));
Label lbl = new Label();
string classDisplayName = Convert.ToString(row["ClassDisplayName"]);
lbl.Text = HTMLHelper.HTMLEncode(ResHelper.LocalizeString(classDisplayName));
btn.Controls.Add(img);
btn.Controls.Add(lbl);
return btn;
}
}
return null;
}
private void ReloadForm()
{
// Enable the CMSForm
formElem.Enabled = true;
if ((Node != null) && !NewDocument && !NewCulture)
{
// Check the permissions
if (CheckPermissions)
{
// Check read permissions
if (CMSContext.CurrentUser.IsAuthorizedPerDocument(Node, NodePermissionsEnum.Read) == AuthorizationResultEnum.Denied)
{
RedirectToAccessDenied(String.Format(GetString("cmsdesk.notauthorizedtoreaddocument"), Node.NodeAliasPath));
}
// Check modify permissions
else if (CMSContext.CurrentUser.IsAuthorizedPerDocument(Node, NodePermissionsEnum.Modify) == AuthorizationResultEnum.Denied)
{
formElem.Enabled = false;
DocumentManager.DocumentInfo = String.Format(GetString("cmsdesk.notauthorizedtoeditdocument"), Node.NodeAliasPath);
}
}
}
// Reload edit menu
menuElem.ShowDelete = AllowDelete && Edit;
menuElem.CheckPermissions = CheckPermissions;
}
///
/// Adds the alert message to the output request window.
///
/// Message to display
private void AddAlert(string message)
{
ScriptHelper.RegisterStartupScript(this, typeof(string), message.GetHashCode().ToString(), ScriptHelper.GetAlertScript(message));
}
///
/// Adds the script to the output request window.
///
/// Script to add
private void AddScript(string script)
{
ScriptHelper.RegisterStartupScript(this, typeof(string), script.GetHashCode().ToString(), ScriptHelper.GetScript(script));
}
///
/// Save new or existing document.
///
public bool SaveDocument()
{
return DocumentManager.SaveDocument();
}
void DocumentManager_OnValidateData(object sender, DocumentManagerEventArgs e)
{
// Additional validation
if (e.IsValid)
{
e.IsValid = !IsBannedIP();
if (!e.IsValid)
{
e.ErrorMessage = GetString("General.BannedIP");
}
}
}
void DocumentManager_OnBeforeAction(object sender, DocumentManagerEventArgs e)
{
// Store old form mode (will be used to
formModebeforeSave = formElem.FormMode;
}
void DocumentManager_OnAfterAction(object sender, DocumentManagerEventArgs e)
{
switch (e.ActionName)
{
case ComponentEvents.SAVE:
// Clear cache if current document is blogpost or blog
if (ci != null)
{
if ((ci.ClassName.ToLowerCSafe() == "cms.blogpost") || (ci.ClassName.ToLowerCSafe() == "cms.blog"))
{
// Clear cache
if (CMSControlsHelper.CurrentPageManager != null)
{
CMSControlsHelper.CurrentPageManager.ClearCache();
}
}
}
// Set the edit mode
if (Node != null)
{
NodeID = Node.NodeID;
Action = "edit";
ReloadData(true);
// Log insert/update activity
switch (formModebeforeSave)
{
case FormModeEnum.Insert:
case FormModeEnum.InsertNewCultureVersion:
LogInsertActivity(Node);
break;
case FormModeEnum.Update:
LogUpdateActivity(Node);
break;
}
}
AddScript("changed=false;");
break;
case DocumentComponentEvents.APPROVE:
RaiseOnAfterApprove();
break;
case DocumentComponentEvents.REJECT:
RaiseOnAfterReject();
break;
case DocumentComponentEvents.UNDO_CHECKOUT:
formElem.LoadForm(true);
// Reload the values in the form
formElem.BasicForm.LoadControlValues();
break;
default:
break;
}
ReloadForm();
}
void DocumentManager_OnLoadData(object sender, DocumentManagerEventArgs e)
{
formElem.BasicForm.LoadControlValues();
}
///
/// Refresh button click event handler.
///
protected void btnRefresh_Click(object sender, EventArgs e)
{
if (Node != null)
{
// Check permission to modify document
if (!CheckPermissions || (CMSContext.CurrentUser.IsAuthorizedPerDocument(Node, NodePermissionsEnum.Modify) == AuthorizationResultEnum.Allowed))
{
// Ensure version for later detection whether node is published
VersionManager.EnsureVersion(Node, Node.IsPublished);
// Move to edit step
WorkflowManager.MoveToFirstStep(Node, null);
// Reload form
ReloadForm();
if (DocumentManager.SaveChanges)
{
ScriptHelper.RegisterStartupScript(this, typeof(string), "moveToEditStepChange", ScriptHelper.GetScript("Changed();"));
}
}
}
}
///
/// New class selection click event handler.
///
protected void btnClass_Command(object sender, CommandEventArgs e)
{
int newClassId = ValidationHelper.GetInteger(e.CommandArgument, 0);
if (newClassId > 0)
{
ClassID = newClassId;
ReloadData(true);
}
}
///
/// OK button click event handler.
///
protected void btnOK_Click(object sender, EventArgs e)
{
if (IsBannedIP())
{
return;
}
Action = "newculture";
CopyDefaultDataFromDocumentID = radCopy.Checked ? ValidationHelper.GetInteger(lstCultures.SelectedValue, 0) : 0;
DocumentManager.ClearNode();
ReloadData(true);
}
///
/// Yes button click event handler.
///
protected void btnYes_Click(object sender, EventArgs e)
{
if (IsBannedIP())
{
return;
}
// Prepare the where condition
string where = "NodeID = " + NodeID;
// Get the documents
DataSet ds = null;
if (chkAllCultures.Checked)
{
ds = TreeProvider.SelectNodes(SiteName, "/%", TreeProvider.ALL_CULTURES, true, null, where, null, -1, false);
}
else
{
ds = TreeProvider.SelectNodes(SiteName, "/%", CultureCode, false, null, where, null, -1, false);
}
if (!DataHelper.DataSourceIsEmpty(ds))
{
// Get node alias
string nodeAlias = ValidationHelper.GetString(DataHelper.GetDataRowValue(ds.Tables[0].Rows[0], "NodeAlias"), string.Empty);
// Get parent alias path
string parentAliasPath = TreePathUtils.GetParentPath(ValidationHelper.GetString(DataHelper.GetDataRowValue(ds.Tables[0].Rows[0], "NodeAliasPath"), string.Empty));
string aliasPath = null;
string culture = null;
string className = null;
bool hasUserDeletePermission = false;
TreeNode treeNode = null;
// Delete the documents
foreach (DataRow dr in ds.Tables[0].Rows)
{
aliasPath = ValidationHelper.GetString(dr["NodeAliasPath"], string.Empty);
culture = ValidationHelper.GetString(dr["DocumentCulture"], string.Empty);
className = ValidationHelper.GetString(dr["ClassName"], string.Empty);
// Get the node
treeNode = TreeProvider.SelectSingleNode(SiteName, aliasPath, culture, false, className, false);
if (treeNode != null)
{
// Check delete permissions
hasUserDeletePermission = !CheckPermissions || IsUserAuthorizedToDeleteDocument(treeNode, chkDestroy.Checked);
if (hasUserDeletePermission)
{
// Delete the document
try
{
LogDeleteActivity(treeNode);
DocumentHelper.DeleteDocument(treeNode, TreeProvider, chkAllCultures.Checked, chkDestroy.Checked, true);
}
catch (Exception ex)
{
EventLogProvider log = new EventLogProvider();
log.LogEvent(EventLogProvider.EVENT_TYPE_ERROR, DateTime.Now, "Content", "DELETEDOC", CMSContext.CurrentUser.UserID, CMSContext.CurrentUser.UserName, treeNode.NodeID, treeNode.GetDocumentName(), HTTPHelper.UserHostAddress, EventLogProvider.GetExceptionLogMessage(ex), CMSContext.CurrentSite.SiteID, HTTPHelper.GetAbsoluteUri());
AddAlert(GetString("ContentRequest.DeleteFailed") + ": " + ex.Message);
return;
}
}
// Access denied - not authorized to delete the document
else
{
AddAlert(String.Format(GetString("cmsdesk.notauthorizedtodeletedocument"), treeNode.NodeAliasPath));
return;
}
}
else
{
AddAlert(GetString("ContentRequest.ErrorMissingSource"));
return;
}
}
RaiseOnAfterDelete();
string rawUrl = URLRewriter.RawUrl.TrimEnd(new char[] { '/' });
if ((!string.IsNullOrEmpty(nodeAlias)) && (rawUrl.Substring(rawUrl.LastIndexOfCSafe('/')).Contains(nodeAlias)))
{
// Redirect to the parent url when current url belongs to deleted document
URLHelper.Redirect(CMSContext.GetUrl(parentAliasPath));
}
else
{
// Redirect to current url
URLHelper.Redirect(rawUrl);
}
}
else
{
AddAlert(GetString("DeleteDocument.CultureNotExists"));
return;
}
}
///
/// No button click event handler.
///
protected void btnNo_Click(object sender, EventArgs e)
{
Action = "edit";
ReloadData(true);
}
///
/// Delete button click event handler.
///
protected void btnDelete_Click(object sender, EventArgs e)
{
if (IsBannedIP())
{
return;
}
Action = "delete";
ReloadData(true);
}
protected override void OnPreRender(EventArgs e)
{
if (Visible)
{
if (pnlEdit.Visible)
{
// Register other scripts which are necessary in edit mode
if (UseProgressScript)
{
ScriptHelper.RegisterProgress(Page);
}
// Register script
StringBuilder sb = new StringBuilder();
sb.AppendLine("function Delete_" + menuElem.ClientID + "(NodeID) { " + Page.ClientScript.GetPostBackEventReference(btnDelete, null) + "; } \n");
sb.AppendLine("function " + formElem.ClientID + "_RefreshForm(){" + Page.ClientScript.GetPostBackEventReference(btnRefresh, "") + " }");
// Register the scripts
AddScript(sb.ToString());
// Disable maximize plugin on HTML editors
var htmlControls = formElem.BasicForm.FormInformation.GetFields(FormFieldControlTypeEnum.HtmlAreaControl);
if (htmlControls.Any())
{
foreach (FormFieldInfo field in htmlControls)
{
Control control = formElem.BasicForm.FieldControls[field.Name] as Control;
CMSHtmlEditor htmlEditor = ControlsHelper.GetChildControl(control, typeof(CMSHtmlEditor)) as CMSHtmlEditor;
if (htmlEditor != null)
{
htmlEditor.RemovePlugin("maximize");
}
}
}
if (!NewDocument && !NewCulture)
{
formElem.Enabled = AllowSave;
}
}
}
base.OnPreRender(e);
}
///
/// Checks whether the user is authorized to delete document.
///
/// Document node
/// Delete document history?
protected bool IsUserAuthorizedToDeleteDocument(TreeNode treeNode, bool deleteDocHistory)
{
bool isAuthorized = true;
CurrentUserInfo currentUser = CMSContext.CurrentUser;
// Check delete permission
if (currentUser.IsAuthorizedPerDocument(treeNode, new NodePermissionsEnum[] { NodePermissionsEnum.Delete, NodePermissionsEnum.Read }) == AuthorizationResultEnum.Allowed)
{
if (deleteDocHistory)
{
// Check destroy permission
if (currentUser.IsAuthorizedPerDocument(treeNode, NodePermissionsEnum.Destroy) != AuthorizationResultEnum.Allowed)
{
isAuthorized = false;
}
}
}
else
{
isAuthorized = false;
}
return isAuthorized;
}
///
/// Check if user IP is banned.
///
private bool IsBannedIP()
{
// Check banned IP
if (!BannedIPInfoProvider.IsAllowed(CMSContext.CurrentSiteName, BanControlEnum.AllNonComplete))
{
AddAlert(GetString("General.BannedIP"));
return true;
}
return false;
}
///
/// Returns alternative form name in full version - 'ClassName.AltFormCodeName'.
///
/// Class name
private string GetAltFormFullName(string className)
{
if (!string.IsNullOrEmpty(AlternativeFormName) && !string.IsNullOrEmpty(className) && !AlternativeFormName.StartsWithCSafe(className))
{
if (AlternativeFormName.Contains("."))
{
// Remove class name if it is different from class name in parameter
AlternativeFormName = AlternativeFormName.Remove(0, AlternativeFormName.LastIndexOfCSafe(".") + 1);
}
return className + "." + AlternativeFormName;
}
else
{
return AlternativeFormName;
}
}
///
/// Raises the OnAfterApprove event.
///
private void RaiseOnAfterApprove()
{
if (OnAfterApprove != null)
{
OnAfterApprove(this, null);
}
}
///
/// Raises the OnAfterReject event.
///
private void RaiseOnAfterReject()
{
if (OnAfterReject != null)
{
OnAfterReject(this, null);
}
}
///
/// Raises the OnAfterDelete event.
///
private void RaiseOnAfterDelete()
{
if (OnAfterDelete != null)
{
OnAfterDelete(this, null);
}
}
///
/// Logs "insert" activity
///
/// Node
private void LogInsertActivity(TreeNode node)
{
if ((node == null) || !LogActivity )
{
return;
}
Activity activity = new ActivityUserContributionInsert(node, node.GetDocumentName(), CMSContext.ActivityEnvironmentVariables);
activity.Log();
}
///
/// Logs "update" activity
///
/// Node to log the activity for
private void LogUpdateActivity(TreeNode node)
{
if ((node == null) || !LogActivity)
{
return;
}
Activity activity = new ActivityUserContributionUpdate(node, node.GetDocumentName(), CMSContext.ActivityEnvironmentVariables);
activity.Log();
}
///
/// Logs "delete" activity
///
/// Node to log the activity for
private void LogDeleteActivity(TreeNode node)
{
if ((node == null) || !LogActivity )
{
return;
}
Activity activity = new ActivityUserContributionDelete(node, node.GetDocumentName(), CMSContext.ActivityEnvironmentVariables);
activity.Log();
}
#endregion
}