forked from teppokoivula/VersionControl
-
Notifications
You must be signed in to change notification settings - Fork 0
/
VersionControl.module
1802 lines (1621 loc) · 79.5 KB
/
VersionControl.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
/**
* Version Control
*
* This module makes it possible to store, review, and restore earlier values
* of specific fields or even entire pages. Changes are automatically tracked
* for enabled fields and templates and earlier versions can be reviews and
* restored either via Page Edit GUI or the API.
*
* Behind the scenes the hooks provided by ProcessWire are used to capture any
* changes to individual fields and store them in a series of custom database
* tables, along with required metadata, such as a running revision number.
*
* @copyright 2013-2021 Teppo Koivula
* @license http://www.gnu.org/licenses/gpl-2.0.txt GNU General Public License, version 2
* @todo regenerate data when fields are added to a tracked Template/Fieldgroup (see ProcessWire issue #1247)
*/
class VersionControl extends WireData implements Module, ConfigurableModule {
/**
* Return information about this module (required)
*
* @return array
*/
public static function getModuleInfo() {
return array(
'title' => 'Version Control',
'summary' => 'Version control features for page content.',
'href' => 'https://modules.processwire.com/modules/version-control/',
'author' => 'Teppo Koivula',
'version' => '1.3.3',
'singular' => true,
'autoload' => true,
'installs' => array(
'LazyCron',
'PageSnapshot',
'ProcessVersionControl',
),
'requires' => array(
'ProcessWire>=2.4.1',
),
);
}
/**
* 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
*/
static public function getDefaultData() {
return array(
'compatible_fieldtypes' => array(
'FieldtypeEmail',
'FieldtypeDatetime',
'FieldtypeText',
'FieldtypeTextLanguage',
'FieldtypeTextarea',
'FieldtypeTextareas',
'FieldtypeTextareaLanguage',
'FieldtypePageTitle',
'FieldtypePageTitleLanguage',
'FieldtypeCheckbox',
'FieldtypeInteger',
'FieldtypeFloat',
'FieldtypeURL',
'FieldtypePage',
'FieldtypeModule',
'FieldtypeFile',
'FieldtypeImage',
'FieldtypeSelector',
'FieldtypeOptions',
),
'enabled_templates' => array(),
'cleanup_methods' => array(
'deleted_pages',
'deleted_fields',
'changed_template',
'removed_fieldgroup_fields',
),
'enable_all_templates' => false,
);
}
/**
* Container for field data
*
* @var array
*/
protected $page_data = array();
/**
* Container for local variables
*
* @var array
*/
protected $data = array();
/**
* Container for hash format filenames within image inputfields
*
* @var array
*/
protected $hash_map = array();
/**
* Container for runtime user information cache
*
* @var array
*/
protected $users_cache = array();
/**
* Name of the revisions database table
*
* Revisions table keeps track of revision numbers, which are system wide,
* and stores important metadata, such as dates, user ID's, and page ID's.
*
* @var string
*/
const TABLE_REVISIONS = 'version_control__revisions';
/**
* Name of the database table containing actual field values
*
* @var string
*/
const TABLE_DATA = 'version_control__data';
/**
* Name of the databae table containing metadata for stored files
*
* Having file metadata stored in the database makes tasks such as mime
* type checking and fetching file sizes and file hashes fast. Another
* benefit is easier and more efficient cleanup for orphaned files.
*
* @var string
*/
const TABLE_FILES = 'version_control__files';
/**
* Name of the database table connecting file metadata with field values
*
* @var string
*/
const TABLE_DATA_FILES = 'version_control__data_files';
/**
* 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
*
* Note: some configuration inputfields are pulled from the companion module
* ProcessVersionControl. This is an attempt to make configuration options
* for the module bundle easier to grasp (and harder to miss).
*
* @param array $data
* @return InputfieldWrapper
*/
static public function getModuleConfigInputfields(array $data) {
// this is a container for fields, basically like a fieldset
$fields = new InputfieldWrapper();
// since this is a static function, we can't use $this->modules, so get them from the global wire() function
$modules = wire('modules');
// merge default config settings (custom values overwrite defaults)
$defaults = self::getDefaultData();
$data = array_merge($defaults, $data);
// fieldset: general settings
$fieldset = $modules->get("InputfieldFieldset");
$fieldset->label = __("General Settings");
$fieldset->icon = "cogs";
$fields->add($fieldset);
// for which templates should we track values?
$field = $modules->get("InputfieldAsmSelect");
$field->name = "enabled_templates";
$field->label = __("Enable version control for these templates");
$field->icon = "file-o";
if (isset($data['enable_all_templates']) && $data['enable_all_templates']) {
$field->collapsed = Inputfield::collapsedLocked;
$field->notes = __("This setting has no effect because version control is currently enabled for all templates via Advanced Settings.");
} else {
$field->notes = __("Removing a template from here will also remove any data stored for it.");
}
foreach (wire('templates')->getAll() as $key => $template) {
if ($template->name != "language") $field->addOption($key, $template);
}
if (isset($data['enabled_templates'])) $field->value = $data['enabled_templates'];
$fieldset->add($field);
// for which fields should we track values?
$field = $modules->get("InputfieldAsmSelect");
$field->name = "enabled_fields";
$field->label = __("Enable version control for these fields");
$field->notes = __("Only fields of compatible fieldtypes can be selected. If no fields are selected, all fields of compatible fieldtypes are considered enabled. Removing a field from here will also remove any data stored for it.");
$field->icon = "file-text-o";
$types = implode("|", $data['compatible_fieldtypes']);
$field->addOptions(wire('fields')->find("type=$types")->getArray());
if (isset($data['enabled_fields'])) $field->value = $data['enabled_fields'];
$fieldset->add($field);
// display config options from the Process module
if (wire('modules')->isInstalled('ProcessVersionControl')) {
$p = wire('modules')->get('ProcessVersionControl');
$p_data = wire('modules')->getModuleConfigData('ProcessVersionControl');
// note: we're calling static method getDefaultData non-statically here intentionally;
// this makes it easier to switch between VersionControl 1.x and 2.x.
$p_fields = $p->getModuleConfigInputfields($p_data);
foreach ($p_fields as $p_field) {
$p_field->name .= "_p";
if ($p_field->collapsed == Inputfield::collapsedHidden) {
$p_field->collapsed = Inputfield::collapsedNo;
} else {
$p_field->collapsed = Inputfield::collapsedHidden;
}
if ($p_field instanceof InputfieldWrapper) {
foreach ($p_field as $p_subfield) {
$p_subfield->name .= "_p";
if ($p_subfield->showIf) {
$p_subfield->showIf = str_replace("=", "_p=", $p_subfield->showIf);
}
$p_field->add($p_subfield);
}
}
}
$fields->add($p_fields);
}
// fieldset: cleanup settings
$fieldset = $modules->get("InputfieldFieldset");
$fieldset->label = __("Cleanup Settings");
$fieldset->icon = "trash-o";
$fields->add($fieldset);
// for how long should collected data be retained?
if ($modules->isInstalled("LazyCron")) {
$field = $modules->get("InputfieldSelect");
$field->addOption('1 WEEK', __('1 week'));
$field->addOption('2 WEEK', __('2 weeks'));
$field->addOption('1 MONTH', __('1 month'));
$field->addOption('2 MONTH', __('2 months'));
$field->addOption('3 MONTH', __('3 months'));
$field->addOption('6 MONTH', __('6 months'));
$field->addOption('1 YEAR', __('1 year'));
$field->notes = __("Leave empty to disable automatic time-based cleanup.");
if (isset($data['data_max_age'])) $field->value = $data['data_max_age'];
} else {
$field = $modules->get("InputfieldMarkup");
$field->description = __("Automatic cleanup requires Lazy Cron module.");
}
$field->label = __("For how long should we retain collected data?");
$field->name = "data_max_age";
$fieldset->add($field);
// should we limit the amount of revisions saved for each field + page combination?
$field = $modules->get("InputfieldSelect");
$field->name = "data_row_limit";
$field->label = __("Revisions retained for each field + page combination");
$field->addOptions(array(10 => '10', 20 => '20', 50 => '50', 100 => '100'));
$field->notes = __("Leave empty to not impose limits for stored revisions.");
if (isset($data['data_row_limit'])) $field->value = $data['data_row_limit'];
$fieldset->add($field);
// which cleanup methods (or features) should we enable?
$field = $modules->get("InputfieldCheckboxes");
$field->name = "cleanup_methods";
$field->label = __("Additional cleanup methods");
$field->addOptions(array(
'deleted_pages' => __("Delete all stored data for deleted pages"),
'deleted_fields' => __("Delete all stored data for deleted fields"),
'changed_template' => __("Delete data stored for non-existing fields after template is changed"),
'removed_fieldgroup_fields' => __("Delete data stored for fields that are removed from page's fieldgroup"),
));
if (isset($data['cleanup_methods'])) $field->value = $data['cleanup_methods'];
$fieldset->add($field);
// fieldset: advanced settings
$fieldset = $modules->get("InputfieldFieldset");
$fieldset->label = __("Advanced Settings");
$fieldset->icon = "graduation-cap";
$fieldset->collapsed = Inputfield::collapsedYes;
$fields->add($fieldset);
// define fieldtypes considered compatible with this module
$field = $modules->get("InputfieldAsmSelect");
$field->name = "compatible_fieldtypes";
$field->label = __("Compatible fieldtypes");
$field->description = __("Fieldtypes considered compatible with this module.");
$field->icon = 'list-alt';
$selectable_fieldtypes = $modules->find('className^=Fieldtype');
foreach ($selectable_fieldtypes as $key => $fieldtype) {
// remove native fieldtypes known to be incompatible
if ($fieldtype == "FieldtypePassword" || strpos($fieldtype->name, "FieldtypeFieldset") === 0) {
unset($selectable_fieldtypes[$key]);
}
}
$field->addOptions($selectable_fieldtypes->getArray());
$field->notes = __("Please note that selecting any fieldtypes not selected by default may result in various problems.");
if (isset($data['compatible_fieldtypes'])) $field->value = $data['compatible_fieldtypes'];
$fieldset->add($field);
// enable version control for *all* templates
$field = $modules->get("InputfieldCheckbox");
$field->name = "enable_all_templates";
$field->label = __("Enable version control for all templates");
$field->description = __("If this option is selected, Version Control will track changes to all templates.");
$field->notes = __("This could result in very large amounts of collected data, and cause other unexpected side effects!");
$field->attr('checked', isset($data['enable_all_templates']) && $data['enable_all_templates']);
$fieldset->add($field);
return $fields;
}
/**
* Initialization function
*
* @todo storing files on delete (requires core changes)
*/
public function init() {
// remove expired data rows daily
$this->addHook("LazyCron::everyDay", $this, 'cleanup');
// handle saving config data for the Process module
$this->addHookBefore('Modules::saveModuleConfigData', $this, 'saveConfigData');
// regenerate base data when enabled templates change
$this->addHookAfter('Modules::saveModuleConfigData', $this, 'regenerateData');
if ($this->enable_all_templates || count($this->enabled_templates)) {
// add hooks that gather and store data
$this->addHookBefore('Pages::saveReady', $this, 'restoreFiles');
$this->addHook('Pages::saveReady', $this, 'gather');
$this->addHookBefore('Pages::saveField', $this, 'gather');
$this->addHookAfter('Pages::save', $this, 'insert');
$this->addHookAfter('Pages::saveField', $this, 'insert');
// add hooks that clear obsolete or orphaned data (cleanup)
$this->addHookAfter('Pages::deleted', $this, 'cleanupDeletedPage');
$this->addHookBefore('Fields::delete', $this, 'cleanupDeletedField');
$this->addHook('Pages::templateChanged', $this, 'cleanupChangedTemplate');
$this->addHookBefore('Fieldgroups::save', $this, 'cleanupRemovedFieldgroupFields');
// add hooks that add additional scripts, styles and markup
$this->addHookAfter('ProcessPageEdit::execute', $this, 'inject');
$this->addhookAfter('ProcessPageEdit::buildForm', $this, 'buildFormHistory');
// add hooks that alter image and file inputfield output on the fly
$this->addHookBefore('InputfieldImage::renderItem', $this, 'captureHash');
$this->addHookBefore('InputfieldFile::renderItem', $this, 'captureHash');
$this->addHookAfter('InputfieldFile::renderList', $this, 'replaceHashes');
// add hook that removes hashes within text content of rendered page
$this->addHookAfter('Page::render', $this, 'replaceTextHashes');
// add new property versionControlFields to Template object
$this->addHookProperty('Template::versionControlFields', $this, 'versionControlFields');
// add new property versionControlRevision to Page object
$this->addHookProperty('Page::versionControlRevision', $this, 'versionControlRevision');
// add new method versionControlRevisions to Page object
$this->addHook('Page::versionControlRevisions', $this, 'versionControlRevisions');
}
}
/**
* Delete data older than max age defined in module settings
*
*/
protected function cleanup() {
// check if this cleanup method is disabled
if (!$this->data_max_age) return;
// prepare params
$t1 = self::TABLE_REVISIONS;
$t2 = self::TABLE_DATA;
$interval = $this->database->escapeStr($this->data_max_age);
// prepare and execute statement
$stmt = $this->database->prepare("DELETE $t1, $t2 FROM $t1, $t2 WHERE $t1.timestamp < DATE_SUB(NOW(), INTERVAL $interval) AND $t2.revisions_id = $t1.id");
$stmt->execute();
// request cleanup for files
$this->cleanupFiles();
}
/**
* Delete files no longer referenced in any data rows
*
*/
protected function cleanupFiles() {
// first clean up data files junction table
$this->database->query("DELETE FROM " . self::TABLE_DATA_FILES . " WHERE data_id NOT IN (SELECT DISTINCT id FROM " . self::TABLE_DATA . ")");
// find files without connections to stored data rows
$stmt = $this->database->prepare("SELECT * FROM " . self::TABLE_FILES . " WHERE id NOT IN (SELECT DISTINCT files_id from " . self::TABLE_DATA_FILES . ")");
$stmt->execute();
$stmt_del = null;
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
// remove file
$dir = $this->path . substr($row['filename'], 0, 2) . "/";
$file = $dir . $row['filename'];
if (is_file($file)) unlink($file);
// remove file variations (thumbs)
$path_parts = pathinfo($file);
$variations = scandir($dir . "variations");
foreach ($variations as $variation) {
if (strpos($variation, $path_parts['filename']) === 0) {
unlink($dir . "variations/" . $variation);
}
}
// if containing directory is now empty, remove that too
if (count(scandir($dir)) == 1) wireRmdir($dir, true);
// delete related row from files database table
if (!$stmt_del) $stmt_del = $this->database->prepare("DELETE FROM " . self::TABLE_FILES . " WHERE id = :id");
$stmt_del->bindValue(':id', (int) $row['id'], PDO::PARAM_INT);
$stmt_del->execute();
}
}
/**
* Delete data that exceeds row limit defined in module settings
*
* Row limit applies to each unique page + field combination.
*
* @param int $pages_id
* @param int $fields_id
*/
protected function cleanupExcessRows($pages_id, $fields_id) {
if (!$this->data_row_limit) return;
$ids = [];
$t1 = self::TABLE_REVISIONS;
$t2 = self::TABLE_DATA;
$stmt = $this->database->prepare("SELECT $t1.id FROM $t1, $t2 WHERE $t1.pages_id = :pages_id AND $t2.fields_id = :fields_id AND $t2.revisions_id = $t1.id ORDER BY timestamp DESC LIMIT :offset, 18446744073709551615");
$stmt->bindValue(':pages_id', (int) $pages_id, PDO::PARAM_INT);
$stmt->bindValue(':fields_id', (int) $fields_id, PDO::PARAM_INT);
$stmt->bindValue(':offset', (int) $this->data_row_limit, \PDO::PARAM_INT);
$stmt->execute();
while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
$ids[] = $row['id'];
}
if (!empty($ids)) {
$ids_string = implode(',', $ids);
$this->database->query("DELETE FROM $t1 WHERE id IN ($ids_string)");
$this->database->query("DELETE FROM $t2 WHERE revisions_id IN ($ids_string)");
$this->cleanupFiles();
}
}
/**
* Remove previously stored data for deleted page
*
* Note that this is the only cleanup method that can delete revisions in
* addition to data. This is intentional, since revisions are always tied
* to pages.
*
* @param HookEvent $event
*/
protected function cleanupDeletedPage(HookEvent $event) {
// check if this cleanup method is disabled
if (!in_array('deleted_pages', $this->cleanup_methods)) return;
$page = $event->arguments[0];
if ($page instanceof Page) {
$t1 = self::TABLE_REVISIONS;
$t2 = self::TABLE_DATA;
$stmt = $this->database->prepare("DELETE $t1, $t2 FROM $t1 LEFT OUTER JOIN $t2 ON $t2.revisions_id = $t1.id WHERE $t1.pages_id = :pages_id");
$stmt->bindValue(':pages_id', (int) $page->id, PDO::PARAM_INT);
$stmt->execute();
$this->cleanupFiles();
}
}
/**
* Remove previously stored data for deleted field
*
* @param HookEvent $event
*/
protected function cleanupDeletedField(HookEvent $event) {
// check if this cleanup method is disabled
if (!in_array('deleted_fields', $this->cleanup_methods)) return;
$field = $event->arguments[0];
if ($field instanceof Field) {
$stmt = $this->database->prepare("DELETE FROM " . self::TABLE_DATA . " WHERE fields_id = :fields_id");
$stmt->bindValue(':fields_id', (int) $field->id, PDO::PARAM_INT);
$stmt->execute();
$this->cleanupFiles();
}
}
/**
* Remove obsoleted data after template change
*
* @param HookEvent $event
*/
protected function cleanupChangedTemplate(HookEvent $event) {
// check if this cleanup method is disabled
if (!in_array('changed_template', $this->cleanup_methods)) return;
$page = $event->arguments[0];
if ($page instanceof Page) {
$fields = implode(",", array_keys($page->template->fields->getArray()));
$stmt = $this->database->prepare("DELETE FROM " . self::TABLE_DATA . " WHERE revisions_id IN (SELECT id FROM " . self::TABLE_REVISIONS . " WHERE pages_id = :pages_id) AND fields_id NOT IN ($fields)");
$stmt->bindValue(':pages_id', (int) $page->id, PDO::PARAM_INT);
$stmt->execute();
$this->cleanupFiles();
}
}
/**
* Remove previously stored data for fields removed from fieldgroups
*
* @param HookEvent $event
*/
protected function cleanupRemovedFieldgroupFields(HookEvent $event) {
// check if this cleanup method is disabled
if (!in_array('removed_fieldgroup_fields', $this->cleanup_methods)) return;
// find out if fields are actually going to be removed (permanent/global
// flags can result in WireExceptions, terminating removal entirely) and
// which of those (if any) can have rows in version control data table
$removed_fields = array();
$removed_fields_by_template = array();
$item = $event->arguments[0];
if ($item instanceof Fieldgroup && $item->id && $item->removedFields) {
$removed_fields = $item->removedFields->getArray();
$enabled_templates = $this->enable_all_templates ? "" : "id=" . implode("|", $this->enabled_templates) . ", ";
foreach ($this->templates->find("{$enabled_templates}fieldgroups_id={$item->id}") as $template) {
foreach ($removed_fields as $id => $field) {
if (($field->flags & Field::flagGlobal) && !$template->noGlobal) return;
if ($field->flags & Field::flagPermanent) return;
if (!in_array($field->type, $this->compatible_fieldtypes)) unset($removed_fields[$id]);
if (count($this->enabled_fields) && !in_array($id, $this->enabled_fields)) unset($removed_fields[$id]);
if (!isset($removed_fields_by_template[$template->id])) $removed_fields_by_template[$template->id] = array();
$removed_fields_by_template[$template->id][] = (int) $field->id;
}
if (!count($removed_fields)) return;
}
}
// if we got this far and removed fields were found, delete data rows
if (count($removed_fields)) {
foreach ($removed_fields_by_template as $template_id => $field_ids) {
if ($field_count = count($field_ids)) {
$page_ids = array_values($this->pages->find("template={$template_id}, include=all")->getArray());
if ($page_count = count($page_ids)) {
$stmt = $this->database->prepare("DELETE FROM " . self::TABLE_DATA . " WHERE fields_id IN (" . rtrim(str_repeat('?, ', $field_count), ', ') . ") AND revisions_id IN (SELECT id FROM " . self::TABLE_REVISIONS . " WHERE pages_id IN (" . rtrim(str_repeat('?, ', $page_count), ', ') . "))");
$stmt->execute(array_merge($field_ids, $page_ids));
}
}
}
$this->cleanupFiles();
}
}
/**
* Capture hash format filenames from an image inputfield
*
* @param HookEvent $event
*/
protected function captureHash(HookEvent $event) {
$item = $event->arguments[0];
if ($item->_version_control_basename) {
if (!isset($this->hash_map[">$item->basename<"])) {
$this->hash_map[">$item->basename<"] = ">$item->_version_control_basename<";
}
}
}
/**
* Replace previously captured hash filenames with clean basenames
*
* @param HookEvent $event
*/
protected function replaceHashes(HookEvent $event) {
if (count($this->hash_map)) {
$event->return = str_replace(
array_keys($this->hash_map),
array_values($this->hash_map),
$event->return
);
}
}
/**
* Attempt to replace hashes within text content of rendered page output
*
* This only applies to preview mode, i.e. checking out the content of a
* specific page in given revision.
*
* @param HookEvent $event
*/
protected function replaceTextHashes(HookEvent $event) {
if ($this->input->get->revision) {
$event->return = preg_replace("#[a-z0-9]{40}\.(?![a-z0-9\._-]*(\"|'))#i", "", $event->return);
}
}
/**
* Update file fields if Page has variable _version_control_filedata set
* or if special POST variable 'version_control_filedata' was received.
*
* Note: Page variable is set by PageSnapshot during API usage, while
* POST variable is added by ProcessVersionControl during page edit.
*
* @param HookEvent $event
*/
protected function restoreFiles(HookEvent $event) {
$page = $event->arguments[0];
if (!$page->_version_control_filedata) {
$page->_version_control_filedata = $this->input->post->version_control_filedata;
}
if ($page->_version_control_filedata) {
$page_current = clone($page);
$page_current->uncache();
// remove hooks PageSnapshot uses to prevent installing pagefiles
$this->modules->PageSnapshot->removePagefileHooks();
foreach ($page->_version_control_filedata as $filedata) {
$filedata = json_decode($filedata, true);
foreach ($filedata as $field => $items) {
// remove old files from disk and then from field itself
foreach ($page_current->$field as $file) $file->unlink();
$page->$field->deleteAll();
// insert new files into field (field copies files to correct
// location itself, but we'll have to rename them to original
// filename by removing hash prefixes added for storage)
if (is_array($items)) {
foreach ($items as $item) {
$page->$field = $item['filename'];
$basename = basename($item['filename']);
$clean_basename = substr($basename, strpos($basename, '.')+1);
$page->$field->last()->rename(str_replace($basename, $clean_basename, $item['filename']));
$page->$field->last()->description = $item['description'];
$page->$field->last()->modified = $item['modified'];
$page->$field->last()->created = $item['created'];
if (isset($item['tags'])) $page->$field->last()->tags = $item['tags'];
}
}
// remove hook responsible for native unlink behaviour
foreach ($page->filesManager->getHooks() as $hook) {
if (isset($hook['toObject']) && $hook['toObject'] instanceof Pagefiles && $hook['toObject']->field->name == $field) {
$page->filesManager->removeHook($hook['id']);
}
}
}
}
unset($page->_version_control_filedata);
}
}
/**
* After page has been edited track changed fields and trigger insert method
* to save their values to database or any other applicable storage medium.
*
* @param HookEvent|Page $object
*/
protected function gather($object) {
if ($object instanceof HookEvent) $page = $object->arguments[0];
else if ($object instanceof Page) $page = $object;
else throw new WireException("Wrong param type: expecting HookEvent or Page");
// if page has no id, it's currently being added
$page_id = $page->id ? $page->id : 0;
// check if tracking values has been enabled for template of current
// page or (in case of repeater pages) template of containing page
$template = $page->template;
if ($page instanceof RepeaterPage) $template = $page->getForPage()->template;
if (!$object instanceof Page && !$this->isEnabledTemplate($template)) return;
if ($object instanceof Page || $page->isChanged()) {
foreach ($page->template->fields as $field) {
if (!$object instanceof Page && !$page->isChanged($field->name)) continue;
if (!$page->id && $field->type instanceof FieldtypeFile) continue;
if (!in_array($field->type, $this->compatible_fieldtypes)) continue;
if (count($this->enabled_fields) && !in_array($field->id, $this->enabled_fields)) continue;
$data = $page->get($field->name);
// continue only if either the page in question exists (i.e.
// old field was cleared) or page is new and field has value
if ($page->id || !is_null($data) && $data != "") {
if (!isset($this->page_data[$page_id])) $this->page_data[$page_id] = array();
$data_array = array();
if ($data instanceof Pagefiles) {
// note: originally 'sort' value of each item was
// used instead of custom counter, but that's not
// always available (when working over API).
$count = 0;
foreach ($data as $item) {
$data_item = array(
'original_filename' => $item->filename,
'filename' => hash_file('sha1', $item->filename) . "." . $item->basename,
'description' => $item->description,
'modified' => $item->modified,
'created' => $item->created,
);
if ($field->useTags) $data_item['tags'] = $item->tags;
$data_array[$count.'.data'] = json_encode($data_item);
++$count;
}
if (!count($data_array)) $data_array['0.data'] = null;
} else if ($data instanceof LanguagesPageFieldValue) {
foreach ($data->getChanges() as $key) {
if ($key == 'data') continue;
$data_array[$key] = $data->getLanguageValue(str_replace('data', '', $key));
}
} else {
$data_array = array('data' => $data);
}
$this->page_data[$page_id][$field->id] = $data_array;
}
}
}
}
/**
* Store new data in database (and disk, if files or images are involved)
*
* @param HookEvent|Page $object
* @todo consider adding support for automatically compressing file data
*/
protected function insert($object) {
// return if no page data exists
if (!$this->page_data) return;
// fetch page object
if ($object instanceof HookEvent) $page = $object->arguments[0];
else if ($object instanceof Page) $page = $object;
else throw new WireException("Wrong param type: expecting HookEvent or Page");
// return if current page is repeater parent (for-page-n or for-field-n)
if ($page->template == "admin" && strpos($page->name, "for-") === 0) return;
// fetch page data
if (!isset($this->page_data[$page->id]) && isset($this->page_data[0])) {
// handle new pages; '0' is a placeholder required if we want to
// store even the initial values of fields under version control
$this->page_data[$page->id] = $this->page_data[0];
unset($this->page_data[0]);
}
$page_data = isset($this->page_data[$page->id]) ? $this->page_data[$page->id] : null;
if ($object instanceof HookEvent && $object->method == "saveField") {
// if method is saveField, save data for that specific field only
$field = $object->arguments[1];
if (!$field instanceof Field) {
$field = $this->fields->get('name=' . $this->sanitizer->fieldName($field));
if (!$field instanceof Field) return;
}
$page_data = isset($page_data[$field->id]) ? array($field->id => $page_data[$field->id]) : null;
}
if (!$page_data) return;
// fetch current revision (parent) and user details
$parent = $page->_version_control_parent;
$users_id = $this->user->id;
$username = $this->user->name;
// revision ID placeholder
$revisions_id = 0;
foreach ($page_data as $fields_id => $field_data) {
// if revision isn't assigned yet, get next available revision ID
if (!$revisions_id) {
$stmt = $this->database->prepare("INSERT INTO " . self::TABLE_REVISIONS . " (parent, pages_id, users_id, username) VALUES (:parent, :pages_id, :users_id, :username)");
$stmt->bindValue(':parent', $parent ? $parent : null, PDO::PARAM_INT);
$stmt->bindValue(':pages_id', $page->id, PDO::PARAM_INT);
$stmt->bindValue(':users_id', $users_id, PDO::PARAM_INT);
$stmt->bindValue(':username', $username, PDO::PARAM_STR);
$stmt->execute();
$revisions_id = $this->database->lastInsertId();
$page->_version_control_revision = $revisions_id;
// if parent isn't assigned yet, use ID of previous revision
if (!$parent) {
$stmt = $this->database->prepare("SELECT id FROM " . self::TABLE_REVISIONS . " WHERE pages_id = :pages_id AND id < :revisions_id ORDER BY id DESC LIMIT 1");
$stmt->bindValue(':pages_id', $page->id, PDO::PARAM_INT);
$stmt->bindValue(':revisions_id', $revisions_id, PDO::PARAM_INT);
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
if ($result) {
$stmt = $this->database->prepare("UPDATE " . self::TABLE_REVISIONS . " SET parent = :parent WHERE id = :revisions_id");
$stmt->bindValue(':parent', (int) $result['id'], PDO::PARAM_INT);
$stmt->bindValue(':revisions_id', $revisions_id, PDO::PARAM_INT);
$stmt->execute();
}
}
}
// insert field data to another table
$sql_fields = "revisions_id, fields_id, property, data";
foreach ($field_data as $property => $data) {
// FieldtypeTextareas
if ($data instanceof TextareasData || $data instanceof \ProcessWire\TextareasData) {
$field = $data->getField();
$data = $field->type->___sleepValue($page, $field, $data);
}
$file_id = null;
// dot means that this is multipart property (n.data), which
// can *at the moment* be used to identify file/image fields
if (strpos($property, ".") && !is_null($data)) {
// decode JSON data to get proper file information; copy
// original file to storage unless it's already there
$data = json_decode($data, true);
$dir = $this->path . substr($data['filename'], 0, 2) . "/";
$file = $dir . $data['filename'];
// if this is an existing file, fetch ID from files table;
// otherwise store as a new file and add row to said table
if (is_file($file)) {
$stmt = $this->database->prepare("SELECT id FROM " . self::TABLE_FILES . " WHERE filename = :filename");
$stmt->bindValue(':filename', $data['filename'], PDO::PARAM_STR);
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
$file_id = $result['id'];
} else {
if (!is_dir($dir)) wireMkdir($dir . "variations", true);
copy($data['original_filename'], $file);
$mime_type = '';
if ($this->use_fileinfo) {
// PECL fileinfo extension is not enabled by
// default in Windows, so we check first
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime_type = finfo_file($finfo, $file);
finfo_close($finfo);
} else if ($this->use_mime_content_type) {
$mime_type = mime_content_type($file);
}
$size = filesize($file);
if (!$size) $size = 0;
$stmt = $this->database->prepare("INSERT INTO " . self::TABLE_FILES . " (filename, mime_type, size) VALUES (:filename, :mime_type, :size)");
$stmt->bindValue(':filename', $data['filename'], PDO::PARAM_STR);
$stmt->bindValue(':mime_type', $mime_type, PDO::PARAM_STR);
$stmt->bindValue(':size', $size, PDO::PARAM_INT);
$stmt->execute();
$file_id = $this->database->lastInsertId();
}
unset($data['original_filename']);
// re-encode JSON data
$data = json_encode($data);
}
$stmt = $this->database->prepare("INSERT INTO " . self::TABLE_DATA . " (revisions_id, fields_id, property, data) VALUES (:revisions_id, :fields_id, :property, :data)");
$stmt->bindValue(':revisions_id', $revisions_id, PDO::PARAM_INT);
$stmt->bindValue(':fields_id', $fields_id, PDO::PARAM_INT);
$stmt->bindValue(':property', $property, PDO::PARAM_STR);
$stmt->bindValue(':data', $data, PDO::PARAM_STR);
$stmt->execute();
if ($file_id) {
// if data row is related to file, add row to junction table
$data_id = $this->database->lastInsertId();
$stmt = $this->database->prepare("INSERT INTO " . self::TABLE_DATA_FILES . " (data_id, files_id) VALUES (:data_id, :file_id)");
$stmt->bindValue(':data_id', $data_id, PDO::PARAM_INT);
$stmt->bindValue(':file_id', $file_id, PDO::PARAM_INT);
$stmt->execute();
}
}
// remove processed items from page data
unset($this->page_data[$page->id][$fields_id]);
if (!$this->page_data[$page->id]) unset($this->page_data[$page->id]);
// enforce row limit setting
$this->cleanupExcessRows($page->id, $fields_id);
// clear revision cache
$page->_version_control_revisions = null;
}
}
/**
* This function is executed before page markup has been created
*
* Used for injecting custom scripts, styles and/or markup to admin
* page. Purpose of these is to allow viewing and possibly managing
* version history.
*
* @param HookEvent $event
*/
protected function inject(HookEvent $event) {
// this only applies to GET requests
if ($_SERVER['REQUEST_METHOD'] !== "GET") return;
// make sure that current user has version-control permission
if (!$this->user->hasPermission('version-control')) return;
// make sure that value tracking is enabled for template of
// the page currently being edited
if ($this->input->get->id) $page = $this->pages->get((int) $this->input->get->id);
if (!$page || !$page->id || !$this->isEnabledTemplate($page->template)) return;
// inject scripts and styles
$class = $this->className();
$info = $this->getModuleInfo();
$version = $info['version'];
if (is_file($this->config->paths->$class . "$class.min.css")) $this->config->styles->add($this->config->urls->$class . "$class.min.css?v=$version");
if (is_file($this->config->paths->$class . "$class.min.js")) $this->config->scripts->add($this->config->urls->$class . "$class.min.js?v=$version");
// inject settings and translations
$process = $this->modules->getModuleID("ProcessVersionControl");
$processPage = $this->pages->get("process=$process");
$this->config->js($class, array(
'i18n' => array(
'compareWithCurrent' => __("Compare with current"),
'editDisabled' => __("Editing this data is currently disabled. Restore it by saving the page or switch to current version first."),
'commentPrompt' => __("Type in comment text for this revision (max 255 characters)"),
'closePreview' => __("This is the page as it appeared on %s. Click here to close the preview."),
'confirmRestore' => __("Are you sure that you want to revert this page to an earlier revision?"),
'diffSideBySide' => __("Show side by side"),
'diffList' => __("Show as a list"),
),
'diff' => array(
'timeout' => (int) $this->diff_timeout,
'editCost' => (int) $this->diff_efficiency_cleanup_edit_cost,
'cleanup' => ucfirst($this->diff_cleanup),
),
'pageID' => $page->id,
'moduleDir' => $this->config->urls->{$this->className()},
'processPage' => $processPage->url(),
));
}
/**
* Build the 'history' tab on the Page Edit form
*
* @param HookEvent $event
*/
protected function buildFormHistory(HookEvent $event) {
// make sure that current user has version-control permission
if (!$this->user->hasPermission('version-control')) return;
// fetch the page being edited
$form = $event->return;
$page = $this->pages->get((int) $form->get('id')->value);
// make sure that version control is enabled for the template of the
// page being edited
if (!$this->isEnabledTemplate($page->template)) return;
// fetch history data for the page being edited
$limit = 25;
$start = $this->input->get->page ? ($this->input->get->page-1)*$limit : 0;
$data = $this->getHistory($page, $start, $limit, array(
'users_id' => $this->input->get->users_id,
));
if (!$data) return;
// define history tab position
$this->addHookAfter('ProcessPageEdit::getTabs', $this, 'addTabHistory');
// pager markup
$pager = "";
if ($data['total'] > $data['limit']) {
$pager_links = 20;
$pager_page = (int) $data['start']/$data['limit']+1;
$pager_pages = ceil($data['total']/$data['limit']);
$pager = $this->renderPager($pager_links, $pager_page, $pager_pages);
}
// wrapper element (history tab)
$wrapper = new InputfieldWrapper;
$wrapper->attr('id', $this->className() . 'History');
$wrapper->attr('title', __('History')); // Tab Label: History
if (isset($this->input->get->users_id) || isset($this->input->get->page)) {
$wrapper->attr('data-active', true);