-
Notifications
You must be signed in to change notification settings - Fork 20
/
Form.ascx.cs
646 lines (588 loc) · 28.9 KB
/
Form.ascx.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Threading;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Xml;
using DotNetNuke.Entities.Icons;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Entities.Modules.Actions;
using DotNetNuke.Modules.UserDefinedTable.Components;
using DotNetNuke.Modules.UserDefinedTable.Interfaces;
using DotNetNuke.Security;
using DotNetNuke.Services.Exceptions;
using DotNetNuke.Services.Localization;
using DotNetNuke.UI.Skins.Controls;
using DotNetNuke.UI.Utilities;
using DotNetNuke.UI.WebControls;
using Globals = DotNetNuke.Common.Globals;
using DotNetNuke.Web.Client.ClientResourceManagement;
using System.Text;
using System.Globalization;
namespace DotNetNuke.Modules.UserDefinedTable
{
public partial class EditForm : PortalModuleBase, IActionable, IFormEvents
{
EditControls _editControls;
int _userDefinedRowId;
CaptchaControl _ctlCaptcha;
bool _hasUpdatePermission;
bool _hasDeletePermission;
readonly IDictionary<Label, Control> _labelcontrols = new Dictionary<Label, Control>();
readonly IDictionary<PropertyLabelControl, Control> _propertylabelcontrols = new Dictionary<PropertyLabelControl, Control>();
UserDefinedTableController _udtController;
UserDefinedTableController UdtController => _udtController ?? (_udtController = new UserDefinedTableController(ModuleContext));
public string JsUiDatePattern => Thread.CurrentThread.CurrentCulture.DateTimeFormat.ShortDatePattern
.ToLower()
.Replace("yyyy", "yy");
DataSet _data;
DataSet Data
{
get
{
if (_data == null)
{
if (!int.TryParse(Request.QueryString[DataTableColumn.RowId], out _userDefinedRowId))
{
_userDefinedRowId = Convert.ToInt32(-1);
}
_data = UdtController.GetRow(_userDefinedRowId);
}
return _data;
}
}
DataRow CurrentRow
{
get
{
if (Data.Tables[DataSetTableName.Data].Rows.Count == 0)
{
var r = Data.Tables[DataSetTableName.Data].NewRow();
r[DataTableColumn.RowId] = _userDefinedRowId;
Data.Tables[DataSetTableName.Data].Rows.Add(r);
}
return Data.Tables[DataSetTableName.Data].Rows[0];
}
}
Components.Settings _settings;
new Components.Settings Settings => _settings ?? (_settings = new Components.Settings(ModuleContext.Settings));
bool IsNewRow => _userDefinedRowId == -1;
#region Private Methods
void BuildTemplateForm(IEnumerable<FormColumnInfo> editForm, string template)
{
var tr = new TokenReplaceForForms();
var controlstring = tr.GetControlTemplate(template);
var control = Page.ParseControl(controlstring);
foreach (var currentField in editForm)
{
var controlId = currentField.Title.SafeId();
var editcontrolPlaceholder = FindControlRecursive(control, $"editor_for_{ controlId}");
if (editcontrolPlaceholder != null && currentField.EditControl != null) editcontrolPlaceholder.Controls.Add(currentField.EditControl);
var labelPlaceholder = FindControlRecursive(control, $"label_for_{controlId}");
if (labelPlaceholder != null) labelPlaceholder.Controls.Add(GetLabel(currentField.Title, currentField.Help, currentField.EditControl));
}
EditFormPlaceholder.Visible = true;
EditFormPlaceholder.Controls.Add(control);
}
private Control FindControlRecursive(Control rootControl, string controlID)
{
if (rootControl.ID == controlID)
return rootControl;
foreach (Control controlToSearch in rootControl.Controls)
{
Control controlToReturn = FindControlRecursive(controlToSearch, controlID);
if (controlToReturn != null)
return controlToReturn;
}
return null;
}
void BuildCssForm(IEnumerable<FormColumnInfo> editForm)
{
EditFormPlaceholder.Visible = true;
Control currentContainer = EditFormPlaceholder;
foreach (var currentField in editForm)
{
if (currentField.IsCollapsible)
{
EditFormPlaceholder.Controls.Add(GetSeparatorFormPattern(currentField.Title, true));
var fieldset = new HtmlGenericControl("fieldset");
currentContainer = fieldset;
fieldset.Visible = currentField.Visible;
EditFormPlaceholder.Controls.Add(currentContainer);
}
else if (currentField.IsSeparator && currentField.Visible)
{
EditFormPlaceholder.Controls.Add(GetSeparatorFormPattern(currentField.Title));
currentContainer = EditFormPlaceholder;
}
else
{
var divFormItem = new HtmlGenericControl("div");
divFormItem.Attributes.Add("class", string.Format("dnnFormItem"));
divFormItem.Controls.Add(GetLabel(currentField.Title, currentField.Help, currentField.EditControl));
if (currentField.EditControl != null)
{
divFormItem.Controls.Add(currentField.EditControl);
}
divFormItem.Visible = currentField.Visible;
if (!currentField.IsUserDefinedField) currentContainer = EditFormPlaceholder;
currentContainer.Controls.Add(divFormItem);
}
}
}
Control GetLabel(string title, string help, Control editcontrol)
{
if (help == string.Empty)
{
var l = new Label
{
Text = string.Format("<span>{0}</span>", title),
AssociatedControlID = editcontrol.ID
};
var d = new HtmlGenericControl("div");
d.Attributes.Add("class", "dnnFormLabelWithoutHelp");
d.Controls.Add(l);
_labelcontrols.Add(l, editcontrol);
return d;
}
var label = new PropertyLabelControl
{
ID = string.Format("{0}_label", XmlConvert.EncodeName(title)),
Caption = title,
HelpText = help,
EditControl = editcontrol,
};
_propertylabelcontrols.Add(label, editcontrol);
return label;
}
static Control GetSeparatorFormPattern(string title, bool expendable = false)
{
return title == string.Empty
? new LiteralControl("<h2 class=\"dnnFormSectionHead\"/>")
: (expendable
? new LiteralControl(string.Format("<h2 class=\"dnnFormSectionHead\"><a>{0}</a></h2>", title))
: new LiteralControl(string.Format("<h2 class=\"dnnFormSectionHead\">{0}</h2>", title)));
}
void CheckPermission(bool isUsersOwnItem = true)
{
var security = new ModuleSecurity(ModuleContext);
if (
!((!IsNewRow && security.IsAllowedToEditRow(isUsersOwnItem)) ||
(IsNewRow && security.IsAllowedToAddRow() && (security.IsAllowedToAdministrateModule() || HasAddPermissonByQuota()))))
{
if (IsNested())
{
cmdUpdate.Enabled = false;
divForm.Visible = true;
}
else
{
Response.Redirect(Globals.NavigateURL(ModuleContext.TabId), true);
}
}
else
{
_hasUpdatePermission = true;
}
_hasDeletePermission = Convert.ToBoolean(security.IsAllowedToDeleteRow(isUsersOwnItem) && !IsNewRow);
cmdDelete.Visible = _hasDeletePermission;
}
bool IsNested()
{
return (Parent.Parent) is PortalModuleBase;
}
bool HasAddPermissonByQuota()
{
var userquota = Settings.UserRecordQuota;
if (userquota > 0 && Request.IsAuthenticated)
{
var ds = UdtController.GetDataSet(false);
return ModuleSecurity.HasAddPermissonByQuota(ds.Tables[DataSetTableName.Fields],
ds.Tables[DataSetTableName.Data], userquota,
UserInfo.GetSafeUsername());
}
return true;
}
void CheckPermission(string createdBy)
{
CheckPermission(ModuleContext.PortalSettings.UserInfo.Username == createdBy &&
createdBy != Definition.NameOfAnonymousUser);
}
bool CaptchaNeeded()
{
return ModuleContext.PortalSettings.UserId == - 1 && Settings.ForceCaptchaForAnonymous && !Settings.PreferReCaptcha ;
}
void ShowUponSubmit()
{
var message = new HtmlGenericControl("div")
{ InnerHtml = Settings.SubmissionText };
message.Attributes["class"] = "dnnFormMessage dnnFormSuccess";
MessagePlaceholder.Controls.Add(message);
}
void BuildEditForm()
{
var fieldSettingsTable = FieldSettingsController.GetFieldSettingsTable(ModuleId);
var editForm = new List<FormColumnInfo>();
FormColumnInfo currentField;
var security = new ModuleSecurity(ModuleContext);
_editControls = new EditControls(ModuleContext);
foreach (DataRow dr in Data.Tables[DataSetTableName.Fields].Rows)
{
var fieldTitle = dr[FieldsTableColumn.Title].AsString();
var dataTypeName = dr[FieldsTableColumn.Type].AsString();
var dataType = DataType.ByName(dataTypeName);
var isColumnEditable =
Convert.ToBoolean((!dataType.SupportsHideOnEdit ||
Convert.ToBoolean(dr[FieldsTableColumn.ShowOnEdit])) &&
(!Convert.ToBoolean(dr[FieldsTableColumn.IsPrivate]) ||
security.IsAllowedToEditAllColumns()));
//If Column is hidden, the Fieldtype falls back to "String" as the related EditControl works perfect even if it is not visibile
//EditControls of other user defined datatypes may use core controls (e.g. UrlControl or RTE) which are not rock solid regarding viewstate.
if (!isColumnEditable && dataType.IsUserDefinedField)
{
dataTypeName = "String";
}
currentField = new FormColumnInfo { IsUserDefinedField = dataType.IsUserDefinedField };
if (dataType.IsSeparator)
{
var fieldId = (int)dr[FieldsTableColumn.Id];
currentField.IsCollapsible = Data.Tables[DataSetTableName.FieldSettings].GetFieldSetting("IsCollapsible", fieldId).AsBoolean();
currentField.IsSeparator = true;
if (dr[FieldsTableColumn.Visible].AsBoolean())
{
currentField.Title = fieldTitle;
}
currentField.Visible = isColumnEditable;
}
else
{
currentField.Help = dr[FieldsTableColumn.HelpText].AsString();
currentField.Title = dr[FieldsTableColumn.Title].AsString();
currentField.Required =
Convert.ToBoolean(dr[FieldsTableColumn.Required].AsBoolean() &&
dataType.IsUserDefinedField);
//advanced Settings: Dynamic control
currentField.EditControl = _editControls.Add(dr[FieldsTableColumn.Title].AsString(),
dataTypeName, Convert.ToInt32(dr[FieldsTableColumn.Id]),
dr[FieldsTableColumn.HelpText].AsString(),
dr[FieldsTableColumn.Default].AsString(),
dr[FieldsTableColumn.Required].AsBoolean(),
dr[FieldsTableColumn.ValidationRule].AsString(),
dr[FieldsTableColumn.ValidationMessage].AsString(),
dr[FieldsTableColumn.EditStyle].AsString(),
dr[FieldsTableColumn.InputSettings].AsString(),
dr[FieldsTableColumn.OutputSettings].AsString(),
dr[FieldsTableColumn.NormalizeFlag].AsBoolean(),
dr[FieldsTableColumn.MultipleValues].AsBoolean(),
fieldSettingsTable,
this);
currentField.Visible = isColumnEditable;
}
editForm.Add(currentField);
}
if (CaptchaNeeded())
{
if (!Settings.PreferReCaptcha)
{
// use DnnCaptcha
_ctlCaptcha = new CaptchaControl
{
ID = "Captcha",
CaptchaWidth = Unit.Pixel(130),
CaptchaHeight = Unit.Pixel(40),
ToolTip = Localization.GetString("CaptchaToolTip", LocalResourceFile),
ErrorMessage = Localization.GetString("CaptchaError", LocalResourceFile)
};
currentField = new FormColumnInfo
{
Title = Localization.GetString("Captcha", LocalResourceFile),
EditControl = _ctlCaptcha,
Visible = true,
IsUserDefinedField = false
};
editForm.Add(currentField);
}
}
var enableFormTemplate = Settings.EnableFormTemplate;
var formTemplate = Settings.FormTemplate;
if (enableFormTemplate && !string.IsNullOrEmpty(formTemplate))
BuildTemplateForm(editForm, formTemplate);
else
BuildCssForm(editForm);
//Change captions of buttons in Form mode
if (IsNewRow && Settings.ListOrForm.Contains("Form"))
{
cmdUpdate.Attributes["resourcekey"] = "cmdSend.Text";
}
}
#endregion
#region Event Handlers
protected override void OnInit(EventArgs e)
{
Page.RegisterRequiresViewStateEncryption();
BuildEditForm();
cmdCancel.Click += cmdCancel_Click;
cmdDelete.Click += cmdDelete_Click;
cmdUpdate.Click += cmdUpdate_Click;
Load += Page_Load;
PreRender += EditForm_PreRender;
}
void EditForm_PreRender(object sender, EventArgs e)
{
foreach (var labelcontrol in _labelcontrols)
{
var label = labelcontrol.Key;
var control = (EditControl)labelcontrol.Value;
if (control.ValueControl != null) label.AssociatedControlID = control.ValueControl.ID;
}
foreach (var labelcontrol in _propertylabelcontrols)
{
var label = labelcontrol.Key;
var control = labelcontrol.Value as EditControl;
if (control != null && control.ValueControl != null) label.EditControl = control.ValueControl;
}
}
void Page_Load(object sender, EventArgs e)
{
try
{
if (ModuleContext.PortalSettings.UserId == -1 && Settings.ForceCaptchaForAnonymous && Settings.PreferReCaptcha)
{
cmdUpdate.Attributes["disabled"] = "disabled";
cmdUpdate.CssClass += " disabled";
DotNetNuke.Framework.CDefault page = (DotNetNuke.Framework.CDefault)this.Page;
StringBuilder sb = new StringBuilder();
sb.AppendLine(@"<script type=""text/javascript"">");
sb.AppendLine("var onSubmit = function(token) {");
sb.AppendLine("$('#" + cmdUpdate.ClientID + "').removeAttr('disabled');");
sb.AppendLine("$('#" + cmdUpdate.ClientID + "').removeClass('disabled');");
sb.AppendLine("};");
sb.AppendLine("var onloadCallback = function() {");
sb.AppendLine("grecaptcha.render('" + gRecaptcha.ClientID + "', {");
sb.AppendLine("'sitekey' : '" + Settings.ReCaptchaSiteKey + "',");
sb.AppendLine("'callback' : onSubmit");
sb.AppendLine("});");
sb.AppendLine("};");
sb.AppendLine("</script>");
page.Header.Controls.Add(new LiteralControl(sb.ToString()));
string languageCode = CultureInfo.CurrentUICulture.TwoLetterISOLanguageName;
page.Header.Controls.Add(new LiteralControl(@"<script src=""https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit&hl=" + languageCode + @""" async defer ></script>"));
}
if (Page.IsPostBack == false)
{
EnsureActionButton();
ClientAPI.AddButtonConfirm(cmdDelete, Localization.GetString("DeleteItem", LocalResourceFile));
}
if (!IsNewRow)
{
if (!Page.IsPostBack)
{
//Clear all default values
foreach (var edit in _editControls.Values)
{
edit.Value = "";
}
}
foreach (DataRow field in Data.Tables[DataSetTableName.Fields].Rows)
{
var dataTypeName = field[FieldsTableColumn.Type].AsString();
var dataType = DataType.ByName(dataTypeName);
var value = CurrentRow[field[FieldsTableColumn.Title].ToString()].ToString();
if (!dataType.IsSeparator)
{
if (!Page.IsPostBack)
{
_editControls[field[FieldsTableColumn.Title].ToString()].Value = value;
}
if (field[FieldsTableColumn.Type].ToString() == "CreatedBy")
{
CheckPermission(value);
}
}
}
}
else //New Entry
{
//Default Values already have been set in BuildEditForms
cmdDelete.Visible = false;
CheckPermission();
if (!Page.IsPostBack && Request.QueryString["OnSubmit"].AsInt() == ModuleContext.ModuleId)
{
ShowUponSubmit();
}
}
}
catch (Exception exc) //Module failed to load
{
Exceptions.ProcessModuleLoadException(this, exc);
CheckPermission(false);
}
}
void cmdCancel_Click(object sender, EventArgs e)
{
try
{
if (Settings.ListOrForm.Contains("Form") && IsNewRow)
{
Response.Redirect(Request.RawUrl);
}
else
{
Response.Redirect(Globals.NavigateURL(ModuleContext.TabId), true);
}
}
catch (Exception exc) //Module failed to load
{
Exceptions.ProcessModuleLoadException(this, exc);
}
}
void cmdUpdate_Click(object sender, EventArgs e)
{
if (_hasUpdatePermission)
{
try
{
//warning message of validation has failed
var warningMessage = string.Empty;
warningMessage = _editControls.Values.Where(edit => !edit.IsValid())
.Aggregate(warningMessage,
(current, edit) => current + string.Format(
"<li><b>{0}</b><br />{1}</li>",
edit.FieldTitle,
edit.ValidationMessage));
if (CaptchaNeeded() && !_ctlCaptcha.IsValid)
{
warningMessage += string.Format("<li><b>{0}</b><br />{1}</li>",
Localization.GetString("Captcha.Text", LocalResourceFile),
Localization.GetString("CaptchaError.Text", LocalResourceFile));
}
if (ModuleContext.PortalSettings.UserId == -1 && Settings.ForceCaptchaForAnonymous && Settings.PreferReCaptcha)
{
string encodedResponse = Request.Form["g-recaptcha-response"];
if (!ReCaptcha.Validate(encodedResponse, Settings.ReCaptchaSecretKey))
{
warningMessage += string.Format("<li><b>{0}</b><br />{1}</li>",
Localization.GetString("ReCaptcha.Text", LocalResourceFile), Localization.GetString("ReCaptchaError.Text", LocalResourceFile));
}
}
if (warningMessage == string.Empty)
{
//'Save values for every field separately
foreach (var edit in _editControls.Values)
{
var value = edit.Value;
CurrentRow[edit.FieldTitle] = value;
}
UdtController.UpdateRow(Data);
RecordUpdated();
switch (Settings.ListOrForm)
{
case "List":
Response.Redirect(Globals.NavigateURL(ModuleContext.TabId), true);
break;
case "FormAndList":
case "ListAndForm":
var url = IsNewRow
? Request.RawUrl
: Globals.NavigateURL(ModuleContext.TabId);
Response.Redirect(url,
true);
break;
case "Form":
switch (Settings.UponSubmitAction)
{
case "Text":
divForm.Visible = false;
ShowUponSubmit();
break;
case "Form":
Response.Redirect(
Globals.NavigateURL(ModuleContext.TabId, "",
string.Format("OnSubmit={0}", ModuleId)), true);
break;
default:
var strRedirectUrl = Settings.UponSubmitRedirect ?? Globals.NavigateURL(ModuleContext.TabId);
Response.Redirect(Globals.LinkClick(strRedirectUrl, ModuleContext.TabId,
ModuleContext.ModuleId));
break;
}
break;
}
}
else
{
var moduleControl = (PortalModuleBase)(((Parent.Parent) is PortalModuleBase) ? Parent.Parent : this);
UI.Skins.Skin.AddModuleMessage(moduleControl, string.Format("<ul style=\"padding-left:1.6em;padding-bottom:0;\">{0}</ul>", warningMessage),
ModuleMessage.ModuleMessageType.RedError);
}
}
catch (Exception exc) //Module failed to load
{
Exceptions.ProcessModuleLoadException(this, exc);
}
}
}
void cmdDelete_Click(object sender, EventArgs e)
{
if (_hasDeletePermission)
{
try
{
UdtController.DeleteRow(_userDefinedRowId);
RecordDeleted();
Response.Redirect(Globals.NavigateURL(ModuleContext.TabId), true);
}
catch (Exception exc) //Module failed to load
{
Exceptions.ProcessModuleLoadException(this, exc);
}
}
}
#endregion
#region Optional Interfaces
public void EnsureActionButton()
{
var useButtons = Settings.UseButtonsInForm;
var sec = new ModuleSecurity(ModuleId, TabId, Settings);
if (sec.IsAllowedToViewList() && Settings.OnlyFormIsShown)
{
var url = Globals.NavigateURL(TabId, "", "show=records");
var title = Localization.GetString("List.Action", LocalResourceFile);
cmdShowRecords.NavigateUrl = url;
cmdShowRecords.Text = title;
cmdShowRecords.Visible = useButtons;
}
}
/// -----------------------------------------------------------------------------
/// <summary>
/// Add the "ManageUDT" link to the current action list.
/// </summary>
/// <returns>ModuleActionCollection</returns>
/// -----------------------------------------------------------------------------
public ModuleActionCollection ModuleActions
{
get
{
var useButtons = Settings.UseButtonsInForm;
var cmdName = useButtons ? "" : ModuleActionType.AddContent;
var actions = new ModuleActionCollection();
var sec = new ModuleSecurity(ModuleId, TabId, Settings);
if (sec.IsAllowedToViewList() && Settings.OnlyFormIsShown)
{
var url = Globals.NavigateURL(TabId, "", "show=records");
var title = Localization.GetString("List.Action", LocalResourceFile);
actions.Add(ModuleContext.GetNextActionID(),
title, cmdName,
"", Utilities.IconURL("View"), url, false, SecurityAccessLevel.View, true, false);
}
return actions;
}
}
public event Action RecordUpdated = delegate { };
public event Action RecordDeleted = delegate { };
#endregion
}
}