-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
ProcessChangelogHooks.module
983 lines (883 loc) · 42.9 KB
/
ProcessChangelogHooks.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
<?php namespace ProcessWire;
/**
* Hooks for Process Changelog
*
* This module stores changelog data to custom database table. Separated from main module in order to keep ProcessWire
* from autoloading any unnecessary code.
*
* For detailed information and installation instructions see README.md.
*
* @copyright 2013-2024 Teppo Koivula
* @license https://www.gnu.org/licenses/gpl-2.0.txt GNU General Public License, version 2
*/
class ProcessChangelogHooks extends WireData implements Module, ConfigurableModule {
/**
* Previously logged event data as a hash (used to prevent duplicate entries)
*
* @var string|null
*/
protected $previous_event_hash = null;
/**
* Return information about this module (required)
*
* @return array
*/
public static function getModuleInfo() {
return [
'title' => 'Changelog Hooks',
'summary' => 'Hooks required by Process Changelog for collecting data',
'href' => 'https://processwire.com/modules/process-changelog/',
'author' => 'Teppo Koivula',
'version' => '1.11.3',
'singular' => true,
'autoload' => true,
'requires' => 'ProcessChangelog',
];
}
/**
* Default configuration for this module
*
* The point of putting this in it's own function is so that you don't have to specify
* these defaults more than once.
*
* @return array
*/
public static function getDefaultData() {
return [
'operations' => [
"hid" => __("hid"),
"unhid" => __("unhid"),
"added" => __("added"),
"moved" => __("moved"),
"edited" => __("edited"),
"trashed" => __("trashed"),
"renamed" => __("renamed"),
"deleted" => __("deleted"),
"restored" => __("restored"),
"published" => __("published"),
"unpublished" => __("unpublished"),
],
'ignored_templates' => [],
'ignored_fields' => [],
'ignored_roles' => [],
'ignored_users' => [],
'log_caller' => null,
'data_max_age' => null,
'data_max_age_days' => null,
'page_edit_changelog' => 1,
'schema_version' => 1,
];
}
/**
* Name of the database table used by this module
*
* @var string
*/
const TABLE_NAME = 'process_changelog';
/**
* Schema version for database table used by this module
*
* @var int
*/
const SCHEMA_VERSION = 4;
/**
* Populate the default config data
*
* ProcessWire will automatically overwrite it with anything the user has specifically configured.
* This is done in construct() rather than init() because ProcessWire populates config data after
* construct(), but before init().
*/
public function __construct() {
foreach (self::getDefaultData() as $key => $value) {
$this->$key = $value;
}
}
/**
* Module configuration
*
* @param array $data
* @return InputfieldWrapper
*/
public function getModuleConfigInputfields(array $data) {
// container for fields
$fields = $this->wire(new InputfieldWrapper());
// merge default config settings (custom values overwrite defaults)
$defaults = self::getDefaultData();
$data = array_merge($defaults, $data);
// check for a schema update
if ($data['schema_version'] < self::SCHEMA_VERSION) {
$this->message($this->getDatabaseSchemaUpdateNotice(), Notice::allowMarkup);
}
// logging settings
$logging = $this->modules->get("InputfieldFieldset");
$logging->name = "logging";
$logging->label = __("Logging");
$logging->description = __("These settings define which actions and what kind of data gets logged.");
$logging->icon = "book";
$fields->add($logging);
// which operations should be tracked?
$field = $this->modules->get("InputfieldCheckboxes");
$field->name = "operations";
$field->label = __("Operations");
$field->addOptions($defaults['operations']);
$field->optionColumns = 3;
$field->value = $data['operations'] === $defaults['operations'] ? array_keys($defaults['operations']) : $data['operations'];
$field->description = __("You can choose which operations to keep track of here.");
$field->notes = __("Note that unchecking operations later won't remove rows containing them from database. Instead new rows of those types will no longer be created and existing ones won't be visible anymore.");
$field->icon = "filter";
$logging->add($field);
// should caller (script or URL that triggered this action) be logged?
$field = $this->modules->get("InputfieldSelect");
$field->name = "log_caller";
$field->label = __("Caller logging");
$field->description = __("Enable logging of path/URL for script that triggered action?");
$field->addOptions([
null => __("Disabled"),
'external' => __("For external callers only (CLI and external applications)"),
'all' => __('For all callers (CLI, external applications and ProcessWire itself)'),
]);
$field->notes = __("This can be useful when trying to find out why certain change was triggered. On the other hand it adds to the size of your database table and slightly slows script execution, which is why it's disabled by default.");
$field->icon = "phone";
$field->value = $data[$field->name];
$logging->add($field);
// ignore settings
$ignore_settings = $this->modules->get("InputfieldFieldset");
$ignore_settings->name = "ignore_settings";
$ignore_settings->label = $this->_("Ignore settings");
$ignore_settings->description = $this->_("These options control which templates, fields, roles, and users *don't* get logged. Keep in mind, though, that making changes here will not erase any existing data.");
$ignore_settings->icon = "ban";
$fields->add($ignore_settings);
// templates that should be ignored when logging changes
$field = $this->modules->get("InputfieldAsmSelect");
$field->name = "ignored_templates";
$field->label = __("Ignored templates");
$field->description = __("Ignore these templates when logging changes.");
$field->icon = "cubes";
$field->columnWidth = 50;
$field->addOptions(wire('templates')->getAll()->getArray());
$field->value = $data[$field->name];
$ignore_settings->add($field);
// fields that should be ignored when logging changes
$field = $this->modules->get("InputfieldAsmSelect");
$field->name = "ignored_fields";
$field->label = __("Ignored fields");
$field->description = __("Ignore these fields when logging changes.");
$field->icon = "cube";
$field->columnWidth = 50;
$field->addOptions(wire('fields')->getAll()->getArray());
$field->value = $data[$field->name];
$ignore_settings->add($field);
// roles that should be ignored when logging changes
$field = $this->modules->get("InputfieldAsmSelect");
$field->name = "ignored_roles";
$field->label = __("Ignored roles");
$field->description = __("Ignore these roles when logging changes.");
$field->notes = __("Note that \"guest\" has a special meaning here: with other roles the user is ignored if they have any of the ignored roles, whereas guest users are only ignored if they have the guest role *and no other roles whatsoever*.");
$field->icon = "gears";
$field->columnWidth = 50;
foreach (wire('pages')->find('template=role, check_access=0')->explode(['id', 'name']) as $role) {
$field->addOption($role['id'], $role['name']);
}
$field->value = $data[$field->name];
$ignore_settings->add($field);
// users that should be ignored when logging changes
$field = $this->modules->get("InputfieldPageAutocomplete");
$field->name = "ignored_users";
$field->label = __("Ignored users");
$field->description = __("Ignore these users when logging changes.");
$field->icon = "users";
$field->columnWidth = 50;
$user_templates = wire('config')->userTemplateIds ? implode('|', wire('config')->userTemplateIDs) : 'user';
$field->findPagesSelector = 'template=' . $user_templates . ', check_access=0';
$field->labelFieldName = 'name';
$field->value = $data[$field->name];
$ignore_settings->add($field);
// data retention settings
$data_retention = $this->modules->get("InputfieldFieldset");
$data_retention->name = "data_retention";
$data_retention->label = __("Data retention");
$data_retention->description = __("These settings define how long collected data should be retained for, as well as the circumstances under which it may be erased.");
$data_retention->icon = "database";
$fields->add($data_retention);
// for how long should collected data be retained?
$field = $this->modules->get("InputfieldSelect");
$field->name = "data_max_age";
$field->label = __("Data max age");
$field->description = __("For how long should we retain collected data?");
$field->notes = __("Automatic cleanup requires LazyCron module, which isn't currently installed.");
$field->icon = "calendar";
if ($this->modules->isInstalled("LazyCron")) {
$field->addOptions([
'1 WEEK' => __('1 week'),
'2 WEEK' => __('2 weeks'),
'1 MONTH' => __('1 month'),
'2 MONTH' => __('2 months'),
'3 MONTH' => __('3 months'),
'6 MONTH' => __('6 months'),
'1 YEAR' => __('1 year'),
'num_days' => __('Specific number of days'),
]);
$field->notes = __("Leave empty to disable automatic cleanup.");
$field->value = $data[$field->name];
}
$data_retention->add($field);
// alternative to predefined intervals: number of days to retain collected data
$field = $this->modules->get("InputfieldInteger");
$field->name = "data_max_age_days";
$field->label = __("Data max age in days");
$field->description = __("This setting provides more granular control over the data retention period.");
$field->notes = __("If you leave this field empty, data will be retained indefinitely.");
$field->icon = "clock-o";
$field->value = $data[$field->name] ?? null;
$field->min = 1;
$field->showIf = "data_max_age=num_days";
$data_retention->add($field);
// limit for collected data rows
$field = $this->modules->get("InputfieldInteger");
$field->name = "data_max_rows";
$field->label = __("Data max rows");
$field->description = __("How many rows of data should we retain?");
$field->icon = "ellipsis-v";
$field->value = $data[$field->name] ?? null;
$field->min = 1;
$data_retention->add($field);
// prune data now?
$field = $this->modules->get("InputfieldCheckbox");
$field->name = "prune_data_now";
$field->label = __("Prune data now?");
$field->description = __("If you check this option and save module settings, data retention settings will be applied right away, meaning that any old data will be removed.");
$field->notes = __('Note: this operation may take a long time.');
$field->icon = "trash";
$data_retention->add($field);
// additional settings
$additional_settings = $this->modules->get("InputfieldFieldset");
$additional_settings->name = "additional_settings";
$additional_settings->label = __("Additional settings");
$additional_settings->description = __("Miscellaneous settings for adjusting the behaviour of the module.");
$additional_settings->icon = "sliders";
$fields->add($additional_settings);
// should a Changelog section be added to the Settings tab of the page editor?
$field = $this->modules->get("InputfieldSelect");
$field->name = "page_edit_changelog";
$field->label = __("Add Changelog to the page editor");
$field->description = __("Add a Changelog section to the Settings tab of the page editor?");
if (empty($data['data_max_rows']) && (empty($data['data_max_age']) || $data['data_max_age'] === 'num_days' && empty($data['data_max_age_days']))) {
$field->notes = __("Please note that since you haven't specified a max age or maximum number of rows for your changelog data, disabling the Changelog section may be preferable. Otherwise large amounts of changelog data may result in slow load times for the page editor.");
}
$field->addOptions([
null => __("Disabled"),
1 => __("For everyone"),
2 => __("For users with the Changelog permission"),
3 => __("For superusers only"),
]);
$field->value = $data[$field->name];
$additional_settings->add($field);
// database schema version
$field = $this->modules->get("InputfieldInteger");
$field->name = "schema_version";
$field->label = __("Schema version");
$field->icon = "warning";
$field->value = $data['schema_version'];
$field->collapsed = Inputfield::collapsedYes;
$field->notes = __("Under normal circumstances you should never have to manually modify this field. It can, however, be used to skip over a specific schema update, or let Proces Changelog Hooks know that you've applied the update manually via the database.");
$fields->add($field);
return $fields;
}
/**
* Initialize the module and attach required hooks
*/
public function init() {
// update the database schema (if not the latest one yet)
if ($this->schema_version < self::SCHEMA_VERSION) {
$this->updateDatabaseSchema();
}
// trigger cleanup once a day
if ($this->data_max_age) {
$this->addHook("LazyCron::everyDay", $this, 'cleanup');
}
// trigger data pruning (cleanup) when module config is saved
$this->addHookBefore('Modules::saveConfig', $this, 'saveConfig');
// add hooks that gather information and trigger insert
$this->pages->addHook('added', $this, 'logPageEvent');
$this->pages->addHook('moved', $this, 'logPageEvent');
$this->pages->addHook('renamed', $this, 'logPageEvent');
$this->pages->addHook('deleted', $this, 'logPageEvent');
$this->pages->addHook('saveReady', $this, 'logPageEvent');
$this->pages->addHook('saveFieldReady', $this, 'logPageEvent');
}
/**
* Initialization when $page is known
*
* Attach hook to ProcessPageEdit::buildFormSettings in order to display recent changes in the context of page editor.
*/
public function ready() {
if ($this->page_edit_changelog && $this->page->template == 'admin' && $this->page->process == 'ProcessPageEdit') {
if ($this->page_edit_changelog == 1 || $this->page_edit_changelog == 2 && $this->user->hasPermission('Changelog') || $this->user->isSuperuser()) {
$this->addHookAfter('ProcessPageEdit::buildFormSettings', $this, 'hookPageEdit');
}
}
}
/**
* Adds a Changelog section to the Settings tab in the page editor
*
* @param HookEvent $event
*/
public function hookPageEdit(HookEvent $event) {
$form = $event->return;
$process = $event->object;
$editPage = $process->getPage();
try {
// we're using a subquery and sorting by id in case there's *a lot* of data, in which case MIN(timestamp)
// without an index on the timestamp col (which we don't have, at least for now) could get extremely slow
$stmt = $this->database->prepare("SELECT COUNT(*), (SELECT timestamp FROM " . self::TABLE_NAME . " WHERE pages_id=:id ORDER BY id ASC LIMIT 1) FROM " . self::TABLE_NAME . " WHERE pages_id=:id");
$stmt->bindValue(':id', $editPage->id, \PDO::PARAM_INT);
$stmt->execute();
list($num_edits, $timestamp) = $stmt->fetch(\PDO::FETCH_NUM);
} catch(\Exception $e) {
$this->error($e->getMessage());
$num_edits = 0;
}
if ($num_edits) {
/** @var InputfieldMarkup */
$field = $this->modules->get('InputfieldMarkup');
$processPage = $this->pages->get('process=' . $this->modules->getModuleID('ProcessChangelog'));
$field->label = $this->_('Changelog'); // Changelog field label
$field->icon = "code-fork";
$out = sprintf($this->_n('%d edit since %s', '%d edits since %s', $num_edits), $num_edits, $timestamp);
if ($this->user->hasPermission('changelog')) {
$out .= " - <a href='{$processPage->url}?pages_id={$editPage->id}'>" . $this->_('View History') . "</a>";
}
$field->attr('value', "<p>{$out}</p>");
$form->append($field);
}
}
/**
* Delete data older than defined interval
*
* @param null|string|int|HookEvent $interval Interval, defaults to data_max_age setting
* @param null|int $max_rows max rows of data, defaults to data_max_rows setting
*/
public function cleanup($interval = null, ?int $max_rows = null) {
// called via LazyCron or null value provided for interval, get data_max_age from module config
if ($interval instanceof HookEvent || $interval === null) {
$interval = empty($this->data_max_age) ? null : $this->data_max_age;
}
// in case interval is "num_days", get value from the data_max_age_days setting instead
if ($interval === 'num_days') {
$interval = $this->data_max_age_days ? (int) $this->data_max_age_days : null;
}
// define number of rows
$max_rows = $max_rows ?? $this->data_max_rows ?? null;
$max_rows = $max_rows !== null && (int) $max_rows == $max_rows && (int) $max_rows > 0 ? (int) $max_rows : null;
// delete old data from database
if ($interval !== null) {
$interval = is_int($interval) ? $interval . ' DAY' : $this->database->escapeStr($interval);
$sql = "DELETE FROM " . self::TABLE_NAME . " WHERE timestamp < DATE_SUB(NOW(), INTERVAL $interval)";
try {
$this->database->exec($sql);
} catch(\Exception $e) {
$this->error($e->getMessage());
}
}
// delete extraneous rows from database
if ($max_rows !== null) {
try {
$last_removable_row_query = $this->database->query('SELECT id, timestamp FROM ' . self::TABLE_NAME . ' ORDER BY timestamp DESC, id DESC LIMIT ' . $max_rows . ', 1');
$last_removable_row = $last_removable_row_query->fetch(\PDO::FETCH_NUM);
if ($last_removable_row !== false) {
list($last_removable_row_id, $max_timestamp) = $last_removable_row;
$row_number = $this->database->query('SELECT COUNT(*) FROM ' . self::TABLE_NAME)->fetchColumn();
if ($row_number !== false && (int) $row_number == $row_number && $row_number > $max_rows) {
$sql = 'DELETE FROM ' . self::TABLE_NAME . ' WHERE timestamp <= :max_timestamp AND id <= :last_removable_row_id ORDER BY timestamp ASC, id ASC LIMIT :limit';
$stmt = $this->database->prepare($sql);
$stmt->bindValue(':max_timestamp', $max_timestamp, \PDO::PARAM_STR);
$stmt->bindValue(':last_removable_row_id', $last_removable_row_id, \PDO::PARAM_INT);
$stmt->bindValue(':limit', $row_number - $max_rows, \PDO::PARAM_INT);
$stmt->execute();
}
}
} catch(\Exception $e) {
$this->error($e->getMessage());
}
}
}
/**
* This method gets triggered when module config is saved
*
* @param HookEvent $event
*/
protected function saveConfig(HookEvent $event) {
// bail out early if saving another module's config
$class = $event->arguments[0];
if (is_string($class) && $class !== $this->className || is_object($class) && $class != $this) {
return;
}
// check if "prune data now" option is checked
$data = $event->arguments[1];
if (is_array($data) && !empty($data['prune_data_now']) || $data === 'prune_data_now' && !empty($event->arguments[2])) {
// make sure that latest values are used in case data retention rules are saved during current request
$interval = is_array($data) && !empty($data['data_max_age']) ? $data['data_max_age'] : null;
if ($interval === 'num_days') {
$interval = !empty($data['data_max_age_days']) ? (int) $data['data_max_age_days'] : null;
}
$max_rows = is_array($data) && !empty($data['data_max_rows']) ? $data['data_max_rows'] : null;
// prune data
$is_valid_interval = $interval !== null || !is_array($data) && $this->data_max_age && ($this->data_max_age !== 'num_days' || !empty($this->data_max_age_days));
$is_valid_rows = $max_rows !== null;
if ($is_valid_interval || $is_valid_rows) {
$this->cleanup($interval, $max_rows);
$this->message($this->_('Data was pruned according to rules specified by configured data retention settings.'));
} else {
$this->warning($this->_('Module settings were saved but data retention rules were not specified, so no data was pruned.'));
}
// make sure that "prune data now" option value doesn't get saved
if (is_array($data)) {
unset($data['prune_data_now']);
$event->arguments(1, $data);
}
$event->arguments(2, null);
}
}
/**
* Based on event method and other information available this
* method parses required data and triggers insert method.
*
* @param HookEvent $event
*/
public function logPageEvent(HookEvent $event) {
// variables from event
$page = $event->arguments[0];
$field = isset($event->arguments[1]) && $event->arguments[1] instanceof Field ? $event->arguments[1] : null;
$operation = $event->method == "saveReady" || $event->method == "saveFieldReady" ? "edited" : $event->method;
// check if this event should be logged
if (!$this->shouldLogPageEvent($page, $field, $operation)) {
return;
}
$fields_edited = [];
if ($operation == "edited") {
// skip new pages or pages being restored/trashed
if (!$page->id || $page->parentPrevious) return;
if ($page->isChanged()) {
if ($field && $page->isChanged($field->name)) {
// only one field was edited (saveFieldReady)
$fields_edited[$field->id] = $field->name;
} else {
// one or more fields were edited (saveReady)
foreach ($page->template->fields as $field) {
if ($page->isChanged($field->name)) {
$fields_edited[$field->id] = $field->name;
}
}
}
// filter out any ignored fields
if (!empty($this->ignored_fields) && !empty($fields_edited)) {
$fields_edited = array_diff_key($fields_edited, array_flip($this->ignored_fields));
}
// only continue if at least one field has been changed (and
// if status has changed, trigger a new event for that)
if (empty($fields_edited)) {
if ($page->isChanged("status")) {
$this->triggerStatusEvents($event);
}
if ($this->modules->isInstalled("LanguageSupportPageNames")) {
// if multi-language page names are enabled, we need to
// fake a rename action when non-default name changes
if ($changes = $page->getChanges()) {
foreach ($changes as $change) {
if (strpos($change, "name") === 0 && preg_match("/^name([0-9]+)$/", $change, $matches)) {
$lang = $this->languages->get((int) $matches[1]);
if ($lang && $lang->id) {
$this->pages->uncache($page);
$event->pageNamePrevious = $this->pages->get($page->id)->get($change) ?: $page->name;
$event->pageName = $page->get($change);
$event->pageURL = $page->localUrl($lang);
$event->method = "renamed";
$this->logPageEvent($event);
}
}
}
}
}
return;
}
} else {
// nothing has changed
return;
}
} else if ($operation == "renamed") {
// if previous parent is trash, page is being restored
if ($page->parentPrevious instanceof Page && $page->parentPrevious->id == $this->config->trashPageID) return;
// if current parent is trash, page is being trashed
else if ($page->parent->id == $this->config->trashPageID) return;
} else if ($operation == "moved") {
if ($page->parent->id == $this->config->trashPageID) {
// page is being trashed
$operation = "trashed";
} else if ($page->parentPrevious->id == $this->config->trashPageID) {
// page is being restored
$operation = "restored";
}
}
// details about page being edited, trashed, moved etc.
// note: if details are null, this means that we shouldn't log this event
$details = $this->getPageEventDetails($page, $event, $operation, $fields_edited);
if ($details === null) return;
$this->insert($operation, $page->id, $page->template->id, $details);
// if status has changed and current event doesn't reflect that, log extra event(s)
if ($page->isChanged('status') && !in_array($operation, ["unpublished", "published", "hid", "unhid"])) {
$this->triggerStatusEvents($event);
}
}
/**
* Get details about page being edited, trashed, moved etc.
*
* @param Page $page
* @param HookEvent $event
* @param string $operation
* @param array $fields_edited
* @return array|null
*/
protected function ___getPageEventDetails(Page $page, HookEvent $event, string $operation, array $fields_edited): ?array {
$details = [
'Page title' => $page->title,
'Page name' => $event->pageName ?: $page->name,
'Previous page name' => $event->pageNamePrevious ?: $page->namePrevious,
'Page URL' => $event->pageURL ?: $page->url,
'Previous page URL' => null,
'Template name' => $page->template->name,
'Previous template name' => $page->templatePrevious ? $page->templatePrevious->name : null,
'Fields edited' => empty($fields_edited) ? null : implode(', ', $fields_edited),
];
if ($operation == 'moved') {
$details['Page name'] = $details['Previous page name'];
unset($details['Previous page name']);
}
if ($page->id === 1 && $this->modules->isInstalled('LanguageSupportPageNames')) {
$details['Page URL'] = '/' . ($page->name && $page->name !== Pages::defaultRootName ? $page->name . '/' : '');
}
if ($page->parentPrevious && $operation != 'edited') {
// for pages being edited, current or previous parent is irrelevant (changing the parent will also trigger "moved" operation)
$details['Previous page URL'] = $page->parentPrevious->url . ($page->namePrevious ?: $page->name) . '/';
} else if ($operation == 'renamed') {
if ($page->id === 1 && $this->modules->isInstalled('LanguageSupportPageNames')) {
$details['Previous page URL'] = '/' . ($page->namePrevious && $page->namePrevious !== Pages::defaultRootName ? $page->namePrevious . '/' : '');
} else if ($event->pageNamePrevious || $page->namePrevious) {
$details['Previous page URL'] = ($page->parent->url ?: '/') . ($event->pageNamePrevious ?: $page->namePrevious) . '/';
}
}
// find out which script or URL triggered this particular action
if ($this->log_caller && $caller = $this->getCaller()) {
$details['Caller'] = $caller;
}
$details = array_filter($details, function($value) {
return $value !== null && $value !== '';
});
// prevent duplicate events for the same page
$event_hash = $page->id . '.' . $operation . '.' . md5(json_encode($details));
if ($this->previous_event_hash == $event_hash) {
return null;
}
$this->previous_event_hash = $event_hash;
return $details;
}
/**
* Should we log this Page event?
*
* @param Page $page
* @param Field|null $field
* @param string $operation
* @return bool
*/
protected function ___shouldLogPageEvent(Page $page, ?Field $field, $operation) {
// don't log notifications
if ($operation == "edited" && $field == "notifications" && $page instanceof User) {
return false;
}
// don't log operations for repeaters or admin pages
if ($page instanceof RepeaterPage || $page->template == "admin") {
return false;
}
// don't log operations for ignored templates
if (!empty($this->ignored_templates) && in_array($page->template->id, $this->ignored_templates)) {
return false;
}
// don't log operations by ignored user roles
if (!empty($this->ignored_roles)) {
foreach ($this->ignored_roles as $ignored_role) {
if ($ignored_role == $this->config->guestUserRolePageID) {
// Note: guest role needs special treatment, or ignoring it wouldn't be of any
// real use. In this case we'll only ignore users with **only** the guest role.
if ($this->user->roles->count == 1) {
return false;
}
} else if ($this->user->hasRole($ignored_role)) {
return false;
}
}
}
// don't log operations by ignored users
if (!empty($this->ignored_users) && in_array($this->user->id, $this->ignored_users)) {
return false;
}
// only continue if this operation is set to be logged
if (!in_array($operation, $this->operations)) {
return false;
}
return true;
}
/**
* Trigger additional status-related events for given event
*
* @param HookEvent $event
*/
private function triggerStatusEvents(HookEvent $event) {
$page = $event->arguments[0];
// was this page was hidden or unhidden?
if ((bool) $page->is(Page::statusHidden) !== (bool) ($page->statusPrevious & Page::statusHidden)) {
$event->method = $page->is(Page::statusHidden) ? "hid" : "unhid";
$this->logPageEvent($event);
}
// was this page published or unpublished?
if ((bool) $page->is(Page::statusUnpublished) !== (bool) ($page->statusPrevious & Page::statusUnpublished)) {
$event->method = $page->is(Page::statusUnpublished) ? "unpublished" : "published";
$this->logPageEvent($event);
}
}
/**
* Find out which script / URL triggered current action
*
* @return string|null
*/
private function getCaller() {
$index = $this->config->paths->root . "index.php";
$caller = realpath($_SERVER['SCRIPT_FILENAME']);
$caller_is_processwire = $caller === $index;
if (isset($_SERVER['HTTP_HOST'])) {
if (!isset($_SERVER['REQUEST_URI'])) {
// IIS support, based on http://davidwalsh.name/iis-php-server-request_uri
$qs = isset($_SERVER['QUERY_STRING']) ? "?" . $_SERVER['QUERY_STRING'] : "";
$_SERVER['REQUEST_URI'] = substr($_SERVER['PHP_SELF'], 1) . $qs;
}
$scheme = $this->config->https ? "https://" : "http://";
$caller = $scheme . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
}
if ($this->log_caller == "all" || !$caller_is_processwire) {
return $caller;
}
}
/**
* Insert row into database
*
* @param string $operation
* @param int $pages_id
* @param int $templates_id
* @param array $details
*
* @throws WireException if operation is unknown
*/
private function insert($operation, $pages_id, $templates_id, $details = []) {
if (!in_array($operation, $this->operations)) {
throw new WireException('Unknown operation');
}
$pages_id = (int) $pages_id;
$templates_id = (int) $templates_id;
$user_id = (int) $this->user->id;
$username = $this->user->name;
// validate and encode details to JSON
if ($details) {
foreach ($details as &$detail) {
$detail = str_replace("'", "", $detail);
$detail = wire()->sanitizer->text($detail);
}
$details = json_encode($details);
} else $details = null;
// insert new row into database
$sql = "INSERT INTO " . self::TABLE_NAME . " " .
"(user_id, username, pages_id, templates_id, operation, data) VALUES " .
"(:user_id, :username, :pages_id, :templates_id, :operation, :data) ";
try {
$stmt = $this->database->prepare($sql);
$stmt->bindValue(':user_id', $user_id, \PDO::PARAM_INT);
$stmt->bindValue(':username', $username, \PDO::PARAM_STR);
$stmt->bindValue(':pages_id', $pages_id, \PDO::PARAM_INT);
$stmt->bindValue(':templates_id', $templates_id, \PDO::PARAM_INT);
$stmt->bindValue(':operation', $operation, \PDO::PARAM_STR);
$stmt->bindValue(':data', $details, \PDO::PARAM_STR);
$stmt->execute();
} catch(\Exception $e) {
$this->error($e->getMessage());
}
}
/**
* Update database schema
*
* This method applies incremental updates until latest schema version is
* reached, while also keeping schema_version config setting up to date.
*
* @param bool $force Force schema update, ignoring any checks.
*
* @throws WireException if database schema version isn't recognized
*/
public function updateDatabaseSchema($force = false) {
while ($this->schema_version < self::SCHEMA_VERSION) {
// by default an update can be performed by any user behind the scenes
$can_update = true;
// increment; defaults to 1, but in some cases we may be able to skip over a specific schema update
$increment = 1;
// first we need to figure out which update we're going to trigger, and whether it's one that can be
// triggered in the backgroudn without superuser intervention
switch ($this->schema_version) {
case 1:
// update #1: add templates_id column
$sql = [
"ALTER TABLE `" . self::TABLE_NAME . "` ADD `templates_id` INT(10) UNSIGNED NOT NULL DEFAULT 0 AFTER `pages_id`",
];
break;
case 2:
// update #2: add indexes for templates_id and username
$can_update = $force || ($this->user->isSuperuser() && $this->input->get->update_changelog_database_schema == 2);
if ($can_update) {
set_time_limit(600);
$sql = [
"ALTER TABLE `" . self::TABLE_NAME . "` ADD INDEX `templates_id` (`templates_id`), ADD INDEX `username` (`username`)",
];
}
break;
case 3:
// update #3: drop index for pages_id, add index for pages_id + id
$can_update = $force || ($this->user->isSuperuser() && $this->input->get->update_changelog_database_schema == 3);
if ($can_update) {
set_time_limit(600);
$sql = [
"ALTER TABLE `" . self::TABLE_NAME . "` DROP INDEX `pages_id`",
"ALTER TABLE `" . self::TABLE_NAME . "` ADD INDEX `pages_id__id` (`pages_id`, `id`)",
];
}
break;
default:
throw new WireException("Unrecognized database schema version: {$this->schema_version}");
}
// this update needs to be triggered manually by superuser, just in case; display a notification and
// call to action button if current user is a superuser, otherwise just keep on keeping on
if (!$can_update) {
if (!$this->user->isLoggedin()) {
$this->addHookAfter('ProcessLogin::loginSuccess', function(HookEvent $event) {
if ($event->user->isSuperuser()) {
$event->message($this->getDatabaseSchemaUpdateNotice(), Notice::allowMarkup);
}
});
}
return;
}
// we're ready to execute this update
foreach ($sql as $sql_query) {
$schema_updated = $this->executeDatabaseSchemaUpdate($sql_query);
if (!$schema_updated) {
break;
}
}
// if update fails: log, show notice (if current user is superuser) and continue
if (!$schema_updated) {
$message = sprintf(
$this->_("Running database schema update %d failed"),
$this->schema_version
);
$this->log->save('process-changelog', $message);
if ($this->user->isSuperuser()) {
$this->message($message);
}
return;
}
// all's well that ends well
$this->schema_version += $increment;
$configData = $this->modules->getModuleConfigData($this);
$configData['schema_version'] = $this->schema_version;
$this->modules->saveModuleConfigData($this, $configData);
if ($this->user->isSuperuser()) {
$this->message(sprintf(
$this->_('ProcessChangelog database schema update applied (#%d).'),
$this->schema_version - 1
));
}
}
}
/**
* Execute database schema update
*
* @param string $sql
* @return bool
*/
protected function executeDatabaseSchemaUpdate($sql): bool {
try {
$updated_rows = $this->database->exec($sql);
return $updated_rows !== false;
} catch (\PDOException $e) {
if (isset($e->errorInfo[1]) && in_array($e->errorInfo[1], [1060, 1061, 1091])) {
// 1060 (column already exists), 1061 (duplicate key name), and 1091 (can't drop index) are errors that
// can be safely ignored here; the most likely issue would be that this update has already been applied
return true;
}
// another type of error; log, show notice (if current user is superuser) and return false
$message = sprintf(
'Error updating schema: %s (%s)',
$e->getMessage(),
$e->getCode()
);
$this->log->save('process-changelog', $message);
if ($this->user->isSuperuser()) {
$this->error($message);
}
return false;
}
}
/**
* Get database schema update notice
*
* @return string
*/
protected function getDatabaseSchemaUpdateNotice() {
return sprintf(
$this->_('ProcessChangelog has pending database schema update (#%d). This update may take a while to complete. If an error occurs, module README file contains additional instructions. %s.'),
$this->schema_version,
sprintf(
'<a href="%s">%s</a>',
$this->config->urls->admin . 'module/edit/?name=ProcessChangelogHooks&update_changelog_database_schema=' . (int) $this->schema_version,
$this->_('Update database schema now')
)
);
}
/**
* Called only when this module is installed
*
* Creates new custom database table for storing data.
*/
public function ___install() {
// create required database table. note that updateDatabaseSchema will
// make changes to it's schema, so it's not guaranteed to stay as-is.
$sql = "
CREATE TABLE " . self::TABLE_NAME . " (
id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
user_id INT(10) UNSIGNED NOT NULL DEFAULT 0,
username VARCHAR(128) DEFAULT NULL,
pages_id INT(10) UNSIGNED NOT NULL DEFAULT 0,
operation VARCHAR(128) NOT NULL,
data TEXT DEFAULT NULL,
timestamp TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE = MYISAM;
";
$this->database->exec($sql);
// tell the user that we've created new database table
$this->message("Created Table: " . self::TABLE_NAME);
// update database schema, overriding any checks
$this->updateDatabaseSchema(true);
}
/**
* Called only when this module is uninstalled
*
* Drops database table created during installation.
*/
public function ___uninstall() {
$this->message("Removing database table: " . self::TABLE_NAME);
$this->database->exec("DROP TABLE IF EXISTS " . self::TABLE_NAME);
}
}