-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathFrontendFormsManager.module
1429 lines (1180 loc) · 60.8 KB
/
FrontendFormsManager.module
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
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
namespace ProcessWire;
use Exception;
use PDO;
/**
* A custom admin page module for the FrontendForms module
*/
class FrontendFormsManager extends Process implements Module, ConfigurableModule
{
protected WireInputData|null $filtervalues = null; // post data after the filter form has been submitted
protected int $items_per_page = 10; // default number of questions to show inside the table, if there are more questions -> pagination will be added
protected PageArray $allQuestions; // PageArray containing all questions independent of status
protected PageArray $publishedQuestions; // PageArray containing all questions with status published
protected PageArray $unpublishedQuestions; // PageArray containing all questions with status unpublished
protected PageArray $hiddenQuestions; // PageArray containing all questions with status hidden
protected PageArray $lockedQuestions; // PageArray containing all questions with status locked
protected PageArray $activeQuestions; // PageArray containing all questions that are visible and will be used in the CAPTCHA
protected PageArray $inactiveQuestions; // PageArray containing all questions that are NOT visible and will NOT be used in the CAPTCHA
protected array $chartTexts = [];
protected array $questionFields = []; // configuration array containing all question fields
protected bool $langSupport = false; // language support is enabled (true) or not (false)
protected bool $langSupportFields = false; // language support for fields on the frontend is enabled (true) or not (false)
protected array $frontendforms_config = [];
protected array $failedAttempts = []; // array containing ips as key and number of failed attempts as value
// objects
protected FrontendForms $frontendForms;
/**
* Constructor method which runs during class initialization
* @throws \ProcessWire\WireException
*/
public function __construct()
{
parent::__construct();
// include configuration file for the question fields
include('config/questionFields.php');
// grab FrontendForms module to be able to use some methods of it
$this->frontendForms = wire('modules')->get('FrontendForms');
$this->frontendforms_config = wire('modules')->getConfig('FrontendForms');
// set config values if present
if ($this->input_paginationnumber)
$this->items_per_page = $this->input_paginationnumber;
$this->langSupport = $this->wire('modules')->isInstalled('LanguageSupport');
$this->langSupportFields = $this->wire('modules')->isInstalled('LanguageSupportFields');
}
/**
* Function to run before all modules have been initialized
* @return void
* @throws \ProcessWire\WireException
*/
public function init(): void
{
// set the chart intro text
$this->chartTexts = [
'QuestionsStatusChart' => $this->_('This chart indicates how many questions belong to a certain status.'),
'QuestionsActiveChart' => $this->_('This chart shows how many questions are displayed on the frontend (active) or not (inactive).'),
];
// add the chart.js to the backend
$this->wire('config')->scripts->add(
'https://cdn.jsdelivr.net/npm/chart.js'
);
// get questions with different status
$this->allQuestions = $this->wire('pages')->find('template=ff_question,include=all');
$this->publishedQuestions = $this->activeQuestions = $this->wire('pages')->find('template=ff_question');
$this->unpublishedQuestions = $this->wire('pages')->find('template=ff_question,status=unpublished');
$this->hiddenQuestions = $this->wire('pages')->find('template=ff_question,status=hidden');
$this->lockedQuestions = $this->wire('pages')->find('template=ff_question,status=locked');
$this->inactiveQuestions = $this->wire('pages')->find('template=ff_question,status=unpublished|hidden');
$this->addHookAfter('Pages::saved, Pages::deleted', $this, 'redirectAfterQuestionEdit');
$this->addHookAfter('ProcessLanguage::processCSV', $this, 'writeDataToFields');
$this->addHookBefore('Process::headline', $this, 'changePageHeadline');
// set post values if the filter form has been submitted
if ($this->wire('input')) {
$this->filtervalues = $this->wire('input')->post;
}
// set failed attempts for the IPs
if (wire('log')->getTotalEntries('failed-attempts-frontendforms')) {
// group array by IP
$result = array();
foreach (wire('log')->getEntries('failed-attempts-frontendforms') as $element) {
$data = json_decode($element['text']);
$result[] = $data->IP;
}
$result = array_count_values($result);
arsort($result);
$this->failedAttempts = $result;
}
}
/**
* Change the headlines of the questions-overview page and the add new question page
* @param \ProcessWire\HookEvent $event
* @return void
* @throws \ProcessWire\WireException
* @throws \ProcessWire\WirePermissionException
*/
protected function changePageHeadline(HookEvent $event): void
{
$process = $event->object;
$headline = '';
if (($process == 'FrontendFormsManager') || ($process == 'ProcessPageAdd')) {
if ($process == 'FrontendFormsManager') {
$slug = null;
$pageNum = ($this->wire($this->wire('input')->pageNum)) ?? 1;
$slug = $this->wire('input')->urlSegments[$pageNum];
$headlines = [
'questions-for-the-simple-question-captcha' => $this->_('List of all questions for the simple question CAPTCHA'),
'list-of-failed-attempts' => $this->_('List of temporarily blocked IPs'),
];
if (!is_null($slug) && array_key_exists($slug, $headlines)) {
$headline = $headlines[$slug];
// Overwrite the processBrowserTitle
$this->wire('processBrowserTitle', $headline);
}
} else {
$page = $this->wire('page');
$slug = $this->wire('input')->get();
$template_id = (int)$slug->template_id;
$template_ID = $this->wire('templates')->get('ff_question')->id;
if ($template_id === $template_ID) {
$headline = $this->_('Add a new question');
}
}
$event->arguments(0, $headline);
}
}
/**
* Parse the csv file and get the translation according to a given text
* @param string $path
* @param string $defaultText
* @return string|array
*/
protected function parseLanguageCSV(string $path, string $defaultText): string|array
{
$csvArray = array_map('str_getcsv', file($path));
$key = array_search($defaultText, array_column($csvArray, 0));
return $csvArray[$key][1];
}
/**
* Add the translations to the newly created fields
* @param \ProcessWire\HookEvent $event
* @return void
* @throws \ProcessWire\WireException
* @throws \ProcessWire\WirePermissionException
*/
protected function writeDataToFields(HookEvent $event): void
{
$csvFile_path = $event->arguments(0);
// run only if the translation file of this module is processed (contains FrontendFormsManager in the path)
if (str_contains($csvFile_path, 'frontendformsmanager')) {
$template = $this->wire('templates')->get('ff_question');
$language = $event->arguments(1); // the language where the translation should be added
//get the Language translator class for this language
$translation = $this->wire('languages')->translator($language);
// save data (label, description,..) to fields in current language
$textdomain = $translation->filenameToTextdomain($this->wire('config')->paths->siteModules . 'frontendforms/config/questionFields.php');
foreach ($this->questionFields as $name => $fieldproperties) {
//grab the field object
$f = $this->wire('fields')->get($name);
// create an array of field properties that should be set and saved
$field_properties = ['label', 'description', 'notes'];
foreach ($field_properties as $property) {
if ($f->$property) {
${$property} = $translation->getTranslation($textdomain, $f->$property);
if ($language->isDefault()) {
$property_lang = $property;
} else {
$property_lang = $property . $language->id;
}
$f->set($property_lang, ${$property});
$f->save($property);
}
}
}
// set a new text domain because translatable strings for the options are inside another file
$textdomain = $translation->filenameToTextdomain($this->wire('config')->paths->siteModules . 'frontendforms/frontendformsmanager.module');
// get the FieldtypeOptions field "ff_descposition" and add the translations for the options
$f = $this->wire('fields')->get('ff_descposition');
if ($f) {
$options = $this->wire('modules')->get('FieldtypeOptions')->getOptions($f);
$database = $this->wire('database');
// get the table
$tablename = 'fieldtype_options';
// check first if this table exists
if ($database->tableExists($tablename)) {
// check if single or multi-lang site with languages installed
$multilang = ($this->languages->count() > 1);
// update the title language column
foreach ($options as $option) {
if ($multilang) {
$colTitle = 'title' . $language->id;
$colValue = 'value' . $language->id;
} else {
$colTitle = 'title';
$colValue = 'value';
}
// needs to be done this way, because translation will not be found at the first csv import
$title = $translation->getTranslation($textdomain, $option->title, '', ['getInfo' => true]);
if ($title['translated']) {
$title = $title['response']['text'];
} else {
$title = $this->parseLanguageCSV($csvFile_path, $option->title);
}
//$title = $translation->getTranslation($textdomain, $option->title);
$value = $option->value;
// create sql statement to add title and value to the entry
$sql = 'UPDATE ' . $tablename . ' SET ' . $colTitle . '=:title, ' . $colValue . '=:value WHERE fields_id=:fieldid AND option_id=:optionid';
// try to save the data to the database
try {
$query = $database->prepare($sql);
$query->bindValue(":title", $title);
$query->bindValue(":value", $value);
$query->bindValue(":fieldid", $f->id, PDO::PARAM_INT);
$query->bindValue(":optionid", $option->id, PDO::PARAM_INT);
// execute the query to save the language values to the databse
$query->execute();
} catch (Exception $e) {
// not used at the moment
}
}
}
}
// save the template context label for the title field in the given language
// will be changed from title to question
$f = $template->fieldgroup->getField('title', true);
// needs to be done this way, because translation will not be found at the first csv import
$label = $translation->getTranslation($textdomain, $f->label, '', ['getInfo' => true]);
if ($label['translated']) {
$label = $label['response']['text'];
} else {
$label = $this->parseLanguageCSV($csvFile_path, $f->label);
}
if ($language->isDefault()) {
$property = 'label';
} else {
$property = 'label' . $language->id;
}
$f->set($property, $label);
$this->wire('fields')->saveFieldgroupContext($f, $template->fieldgroup);
}
}
/**
* Method to redirect to the questions table page if there are no errors
* @param \ProcessWire\Page $page
* @return void
* @throws \ProcessWire\WireException
*/
protected function redirectQuestion(Page $page): void
{
$errors = false;
// not a page with the question template? return
if ($page->template->name != 'ff_question') return;
// page does not contain at least 1 question? return ->
// this is especially to prevent redirect on newly added page
if ($this->wire('input')) {
if ($this->wire('input')->post->ff_answers) {
if (!empty($page->ff_answers)) {
// check for errors
foreach (wire('notices') as $notice) {
if ($notice instanceof NoticeError) $errors = true;
}
// if there are no errors -> redirect to the questions' overview page
if (!$errors) {
$this->wire('session')->redirect($this->wire('urls')->admin . 'setup/frontendforms-dashboard/questions-for-the-simple-question-captcha');
}
}
}
}
}
/**
* Method to redirect to the questions table page if a question has been edited without errors
* @param \ProcessWire\HookEvent $event
* @return void
* @throws \ProcessWire\WireException
*/
public function redirectAfterQuestionEdit(HookEvent $event): void
{
$page = $event->arguments(0);
$this->redirectQuestion($page);
}
/**
* Render the chart for the questions
* @return string
* @throws \ProcessWire\WireException
* @throws \ProcessWire\WirePermissionException
*/
public function renderQuestionsChart(): string
{
$out = '<div id="questionsstatistic"></div>';
// page load
$out .= '<div id="pageload" style="width:100%;"><p>' . $this->chartTexts['QuestionsStatusChart'] . '</p><canvas id="questions"></canvas></div>';
$out .= $this->createQuestionsStatusChart();
$form = $this->modules->get('InputfieldForm');
$form->action = $this->wire('input')->url; // we submit on the same page
$form->method = 'post';
$form->attr('name+id', 'ff_question_statistic_form');
// create buttons for different views
$buttons = [
'QuestionsStatusChart' => $this->_('Status'),
'QuestionsActiveChart' => $this->_('Visibility')
];
foreach ($buttons as $id => $label) {
$button = $this->modules->get('InputfieldButton');
$button->setSmall();
$button->addClass('statistics');
$button->id = $id;
$button->value = $label;
$button->attr('data-statistic', $id);
$button->type = 'submit';
$form->add($button);
}
$out .= $form->render();
return $out;
}
/**
* Generate the script for showing the status charts
* @return string
*/
protected function createQuestionsStatusChart(): string
{
// run only if questions exist
if ($this->allQuestions->count) {
// make a data string out of the array
$data = [
$this->allQuestions->count,
$this->publishedQuestions->count,
$this->unpublishedQuestions->count,
$this->hiddenQuestions->count,
$this->lockedQuestions->count,
];
} else {
$data = [0, 0, 0, 0, 0, 0];
}
$data = implode(', ', $data);
// output the script tag
return '<script>
const ctx = document.getElementById("questions");
new Chart(ctx, {
type: "bar",
data: {
labels: ["' . $this->_('total') . '",
"' . $this->_('published') . '",
"' . $this->_('unpublished') . '",
"' . $this->_('hidden') . '",
"' . $this->_('locked') . '"],
datasets: [{
label: "' . $this->_('Number of questions') . '" ,
data: [' . $data . '],
borderWidth: 1
}]
},
options: {
scales: {
y: {
beginAtZero: true,
title: {
display: true,
text: "' . $this->_('Number of questions') . '"
},
ticks: {
stepSize: 1
}
},
x: {
title: {
display: true,
text: "' . $this->_('Status types') . '"
}
}
},
plugins: {
title: {
display: true,
text: "' . $this->_('Number of question per status and total') . '"
}
}
}
})
</script>';
}
/**
* Generate the script for the active/inactive charts
* @return string
*/
protected function createQuestionsActiveChart(): string
{
// run only if questions exist
if ($this->allQuestions->count) {
// make a data string out of the array
$data = [
$this->allQuestions->count,
$this->activeQuestions->count,
$this->inactiveQuestions->count,
];
} else {
$data = [0, 0, 0];
}
$data = implode(', ', $data);
// output the script tag
return '<script>
const ctx = document.getElementById("questions");
new Chart(ctx, {
type: "bar",
data: {
labels: ["' . $this->_('total') . '",
"' . $this->_('active') . '",
"' . $this->_('inactive') . '"],
datasets: [{
label: "' . $this->_('Number of questions') . '" ,
data: [' . $data . '],
borderWidth: 1
}]
},
options: {
scales: {
y: {
beginAtZero: true,
title: {
display: true,
text: "' . $this->_('Number of questions') . '"
},
ticks: {
stepSize: 1
}
},
x: {
title: {
display: true,
text: "' . $this->_('Visibility types') . '"
}
}
},
plugins: {
title: {
display: true,
text: "' . $this->_('Number of active and inactive question and total') . '"
}
}
}
})
</script>';
}
/**
* Method to redirect to the questions table page if a new question has been added without errors
* @param \ProcessWire\HookEvent $event
* @return void
* @throws \ProcessWire\WireException
*/
public function redirectAfterQuestionAdded(HookEvent $event): void
{
$page = $event->arguments(0);
$this->redirectQuestion($page);
}
/**
* Create the module info
* @return array
*/
public static function getModuleinfo(): array
{
return [
'title' => __('FrontendForms Manager', __FILE__),
'summary' => __('Additional administration page for the FrontendForms module.', __FILE__),
'author' => 'Jürgen Kern',
'version' => '1.1.0',
'icon' => 'area-chart',
'permanent' => false,
'autoload' => true,
'permission' => 'page-edit',
'requires' => [
'FrontendForms',
'PHP>=8.0.0',
'ProcessWire>=3.0.195'
],
'page' => [
'name' => 'frontendforms-dashboard',
'parent' => 'setup',
'title' => __('FrontendForms Manager', __FILE__),
],
];
}
/**
* Dashboard page
* @return string
* @throws \ProcessWire\WireException
* @throws \ProcessWire\WirePermissionException
*/
public function execute(): string
{
if ($this->wire('config')->ajax) {
// load JS depending on button value
$input = $this->wire('input');
$method = 'create' . $input->post('type');
$out = $this->$method();
// create the canvas for the chart
$out .= '<div style="width:100%;"><p>' . $this->chartTexts[$input->post('type')] . '</p><canvas id="questions"></canvas></div>';
return $out;
} else {
$form = $this->modules->get('InputfieldForm');
// Question part
$fieldsetQuestions = $this->modules->get('InputfieldFieldset');
$fieldsetQuestions->label = $this->_('Questions for the SIMPLE TEXT CAPTCHA');
$form->add($fieldsetQuestions);
$field = $this->modules->get('InputfieldMarkup');
$field->label = $this->_('Manage all questions for the SIMPLE QUESTION CAPTCHA');
$field->value = $this->renderQuestionsList();
$field->columnWidth = 50;
$fieldsetQuestions->add($field);
$field = $this->modules->get('InputfieldMarkup');
$field->label = $this->_('Questions statistics');
$field->value = $this->renderQuestionsChart();
$field->columnWidth = 50;
$fieldsetQuestions->add($field);
$form->add($fieldsetQuestions);
// Failed attempts part
$fieldsetFailedAttempts = $this->modules->get('InputfieldFieldset');
$fieldsetFailedAttempts->label = $this->_('List of all IPs that have been blocked temporarily');
// table for failed attempts
$field = $this->modules->get('InputfieldMarkup');
$field->label = $this->_('Information about all IP addresses that have been temporarily blocked due to too many unsuccessful form submissions.');
// check first if logging of failed attempts is enabled
if (array_key_exists('input_logFailedAttempts', $this->frontendforms_config) && ($this->frontendforms_config['input_logFailedAttempts'])) {
$field->value = $this->renderFailedAttemptsList();
} else {
$text = $this->_('Logging of blocked IPs is disabled.') . '<br>';
$link = '<a href="' . $this->wire('config')->urls->admin . 'module/edit?name=FrontendForms" target="_blank">' . $this->_('FrontendForms configuration') . '</a>';
$text .= sprintf($this->_('If you want to show statistics about blocked IPs, you need to go to the %s and enable it first (Spam protection and security settings for the forms -> Measure 1: Restrict number of failed attempts).'), $link);
$field->value = $text;
}
$field->columnWidth = 50;
$fieldsetFailedAttempts->add($field);
// create the chart field for failed attempts
$chartfield = $this->modules->get('InputfieldMarkup');
$chartfield->label = $this->_('Temporarily Blocked IPs');
$chartfield->value = $this->renderFailedAttemptsChart();
$chartfield->columnWidth = 50;
$fieldsetFailedAttempts->add($chartfield);
$form->add($fieldsetFailedAttempts);
return $form->render();
}
}
/**
* Render the charts for the failed attempts grouped by ID and number of failed attempts
* @return string
*/
public function renderFailedAttemptsChart(): string
{
// page load
$out = '<div id="pageload-fac" style="width:100%;"><p>' . $this->_('This chart shows the number of temporarily blocks for the 10 most temporarily blocked IPs in descending order.') . '</p><canvas id="failed-attempts"></canvas></div>';
$out .= $this->createFailedAttemptsStatusChart();
return $out;
}
/**
* Create the Javascript for the failed attempts chart on the dashboard page
* @return string
*/
protected function createFailedAttemptsStatusChart(): string
{
// run only if failed attempts exist
if ($this->failedAttempts) {
// slice the array after 10 entries
$data = array_slice($this->failedAttempts, 0, 10);
} else {
$data = [0];
}
$keys = array_keys($data);
$data = implode(', ', $data);
$k = [];
foreach ($keys as $key) {
$k[] = '"' . $key . '"';
}
$labels = implode(',', $k);
// output the script tag
return '<script>
const fac = document.getElementById("failed-attempts");
new Chart(fac, {
type: "bar",
data: {
labels: [' . $labels . '],
datasets: [{
label: "' . $this->_('Number of temporary blockings') . '" ,
data: [' . $data . '],
borderWidth: 1,
backgroundColor: ["rgba(255, 99, 132, 0.2)",
"rgba(175, 155, 178, 0.2)",
"rgba(208, 25, 236, 0.2)",
"rgba(25, 36, 30, 0.2)",
"rgba(201, 203, 207, 0.2)",
"rgba(153, 102, 255, 0.2)",
"rgba(54, 162, 235, 0.2)",
"rgba(75, 192, 192, 0.2)",
"rgba(255, 205, 86, 0.2)",
"rgba(255, 159, 64, 0.2)"],
}],
},
options: {
indexAxis: "y",
scales: {
y: {
title: {
display: true,
text: "' . $this->_('IPs') . '"
}
},
x: {
beginAtZero: true,
title: {
display: true,
text: "' . $this->_('Number of temporarily blockings') . '"
},
ticks: {
stepSize: 1
}
}
},
plugins: {
title: {
display: true,
text: "' . $this->_('Number of temporary blockings') . '"
}
}
}
})
</script>';
}
/**
* Render method to show a small table with failed attempts and a bar chart with forms and failed attempts
* @return string
*/
protected function renderFailedAttemptsList(): string
{
$out = '';
if ($this->failedAttempts) {
$out .= '<h3>' . $this->_('Top 10 IPs with the most blockings') . '</h3>';
// create the statistic table for the failed attempts
$out .= '<table id="failedattempts-statistic">';
$out .= '<thead>';
$out .= '<td>' . $this->_('IP') . '</td>';
$out .= '<td>' . $this->_('Number of blockings') . '</td>';
$out .= '<td>' . $this->_('Status') . '</td>';
$out .= '</thead>';
$out .= '<tbody>';
foreach ($this->failedAttempts as $ip => $numberOfFailedAttempts) {
$out .= '<tr>';
$out .= '<td>' . $ip . '</td>';
$out .= '<td>' . $numberOfFailedAttempts . '</td>';
$status = $this->_('Not banned');
$icon = $notbanned_icon = '<i class="fa fa-check"></i>';
$banned_icon = '<i class="fa fa-times"></i>';
// check if this IP is in the list of banned IPs
if (array_key_exists('input_preventIPs', $this->frontendforms_config)) {
$bannedList = $this->frontendforms_config['input_preventIPs'];
if (!empty($bannedList)) {
// create array out of textarea content
$bannedList = array_filter(explode("\n", str_replace("\r", "", $bannedList)));
if (in_array($ip, $bannedList)) {
$icon = $banned_icon;
}
}
}
$out .= '<td>' . $icon . '</td>';
$out .= '</tr>';
}
$out .= '</tbody>';
$out .= '</table>';
$out .= '<ul class="legend">';
$out .= '<li>' . $notbanned_icon . ': ' . $this->_('Not blocked - The IP is not on the list of permanent blocked IPs (Blacklist).') . '</li>';
$out .= '<li>' . $banned_icon . ': ' . $this->_('Blocked - The IP is currently on the list of permanent blocked IPs (Blacklist).') . '</li>';
$out .= '</ul>';
// create the "all failed attempts" button
$button = $this->modules->get('InputfieldButton');
$button->value = $this->_('To all temporarily blocked IPs');
$button->setSecondary();
$button->attr('href', $this->config->urls->admin . 'setup/frontendforms-dashboard/list-of-failed-attempts');
$out .= '<div id="to-all-blocked-ips">'.$button->render().'</div>';
} else {
// no entries
$out .= $this->_('At the moment there are no entries about temporarily blocked IPs in the log files.');
}
return $out;
}
/**
* List all suspicious IPs inside a paginated table
* @return string
* @throws \ProcessWire\WireException
* @throws \ProcessWire\WirePermissionException
*/
public function ___executeListOfFailedAttempts(): string
{
$out = '';
// check if there are entries in the log file
if ($this->failedAttempts) {
// create a paginated array of all grouped logged entries that can be used with pagination later on
$ips = PageArray();
$n = 0;
foreach ($this->failedAttempts as $ip => $numberOfFailedAttempts) {
$n++;
$item = new Page();
$item->set('id', $n);
$item->set('name', $ip);
$item->template = 'admin';
$item->ip = $ip;
$item->attempts = $numberOfFailedAttempts;
$ips->add($item);
}
// default number of items per page to show
$items_per_page = $this->items_per_page;
$start = ($this->wire('input')->pageNum - 1) * $items_per_page;
$ips->setLimit($items_per_page);
$ips->setStart($start);
// slice only if the number of pages is higher than the number of items per page
if ($ips->count > $items_per_page) {
$paginatedIPs = $ips->slice($start, $items_per_page);
$counter = true;
} else {
$paginatedIPs = $ips;
$counter = false;
}
$table = $this->modules->get('MarkupAdminDataTable');
$table->encodeEntities = false;
$table->setEncodeEntities(false);
$table->headerRow([
$this->_('#'),
$this->_('IP'),
$this->_('Number of blocks'),
$this->_('Info'),
$this->_('Status'),
$this->_('Add/remove IP to/from the blacklist ')
]);
$n = 0;
foreach ($paginatedIPs as $item) {
// instantiate the more info button
$infobutton = $this->wire('modules')->get('InputfieldButton');
$infobutton->setSecondary();
$infobutton->setSmall();
$infobutton->value = $this->_('View details about this IP');
$infobutton->attr('data-href', '/detail-view/' . $item->ip);
$infobutton->addClass('pw-panel');
// instantiate button object for adding/removing the IP to/from the blacklist
$button = $this->wire('modules')->get('InputfieldSubmit');
$button->setSmall();
$button->name = 'submit_save_ip';
$button->value = 'add';
$button->setAttribute('data-from_id', 'Inputfield_submit_save_module');
$button->value = $item->ip;
$blockedIPs = $this->frontendforms_config['input_preventIPs'];
if (empty($blockedIPs)) {
$blockedIPs = [];
} else {
$blockedIPs = preg_split('/\r\n|\r|\n/', $blockedIPs);
}
if (in_array($item->ip, $blockedIPs)) {
$status = $this->_('IP is blocked');
// remove button
$button->name = 'submit_remove_ip';
$button->text = $this->_('Remove from blacklist');
$button->setSecondary();
} else {
// create add button
$button->text = $this->_('Add to blacklist');
$status = $this->_('IP is not blocked');
}
$number = $counter ? $start + $n + 1 : $n + 1;
$table->row(
[
$number,
$item->ip,
$item->attempts,
$infobutton->render(),
$status,
$button->render()
]
);
$n++;
}
$out .= '<p>'.$this->_('Any IP addresses that are blacklisted will not be able to submit forms, because in this case the forms will not be displayed.').'<br>';
$out .= $this->_('This is a security measure to exclude potential spammers.').'</p>';
// render the table with the questions
$out .= $ips->getPaginationString($this->_('IPs'));
$out .= '<form id="blocked-ips" name="blocked-ips" action="' . $this->wire('input')->url . '" method="post">';
$out .= $table->render();
$out .= '</form>';
$out .= '<div id="blockedlist-pagination" class="pagination">' . $ips->renderPager() . '</div>';
if (isset($_POST)) {
$ip = null;
// add the given ip to the blacklist
if (array_key_exists('submit_save_ip', $_POST)) {
$ip = $_POST['submit_save_ip'];
// add this ip to the list if it is a valid IP
if (filter_var($ip, FILTER_VALIDATE_IP)) {
$blockedIPs[] = $ip;
}
} else if (array_key_exists('submit_remove_ip', $_POST)) {
// remove the given ip from the blacklist
$ip = $_POST['submit_remove_ip'];
// remove $this IP from the list
$key = array_search($ip, $blockedIPs, true);
if ($key !== false) {
unset($blockedIPs[$key]);
}
}
if (!is_null($ip)) {
// convert it back to a string and save it to the module configuration
$ffdata = $this->frontendForms;
$blockedIPs = array_filter($blockedIPs);
$ffdata['input_preventIPs'] = implode("\n", array_unique($blockedIPs));
$this->wire('modules')->saveConfig('FrontendForms', $ffdata);
// finally redirect to make the changes visible
$this->wire('session')->redirect($this->wire('input')->url);
}
}
} else {
$out .= '<div id="no-results"><p>' . $this->_('There are no temporarily blocked IPs entries inside the log files.') . '</p></div>';
}
// add back to the dashboard button
$backbutton = $this->wire('modules')->get('InputfieldButton');
$backbutton->value = $this->_('Back to the dashboard');
$backbutton->attr('href', $this->config->urls->admin . 'setup/frontendforms-dashboard/');
$out .= $backbutton->render();
return $out;
}
/**
* Overview page for all questions for the SIMPLE TEXT CAPTCHA
* @return string
* @throws \ProcessWire\WireException
* @throws \ProcessWire\WirePermissionException
*/
public function ___executeQuestionsForTheSimpleQuestionCaptcha(): string
{
// render the text over the table
$out = '<p>' . $this->_('Manage all questions for the SIMPLE QUESTION CAPTCHA in one place.') . '</p>';
// render the table including the filter form
$out .= $this->renderQuestionsTable();
// render the back link
$out .= '<div id="backlink"><a href="' . $this->config->urls->admin . 'setup/frontendforms-dashboard"><i class="fa fa-arrow-left"></i> ' . $this->_('Back to the dashboard') . '</a>';