-
Notifications
You must be signed in to change notification settings - Fork 10
/
RockMigrations.module.php
6769 lines (6116 loc) · 202 KB
/
RockMigrations.module.php
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 DateTime;
use DirectoryIterator;
use ReflectionClass;
use RockMatrix\Block as RockMatrixBlock;
use RockMigrations\Deployment;
use RockMigrations\MagicPages;
use RockMigrations\WatchFile;
use RockPageBuilder\Block as RockPageBuilderBlock;
use RockShell\Application;
use Symfony\Component\Yaml\Yaml;
use Tracy\Dumper;
use TracyDebugger;
/**
* Provide access to RockMigrations
* @return RockMigrations
*/
function rockmigrations(): RockMigrations
{
return wire()->modules->get('RockMigrations');
}
/**
* @author Bernhard Baumrock, 19.01.2022
* @license MIT
* @link https://www.baumrock.com
*/
class RockMigrations extends WireData implements Module, ConfigurableModule
{
const debug = false;
const cachename = 'rockmigrations-last-run';
const outputLevelDebug = 'debug';
const outputLevelQuiet = 'quiet';
const outputLevelVerbose = 'verbose';
// global processwire fields
const field_pagename = "_pw_page_name";
const field_email = "email";
// time constants (seconds)
// see https://i.imgur.com/vfTasHa.png
const oneMinute = 60;
const oneHour = self::oneMinute * 60;
const oneDay = self::oneHour * 24;
const oneWeek = self::oneDay * 7;
const oneMonth = self::oneDay * 30;
const oneYear = self::oneDay * 365;
private $cacheDelete = "";
private $cacheDeleteOnSave = "";
/** @var WireData */
public $conf;
public $configRaw;
public $configForced;
/** @var WireData */
public $fieldSuccessMessages;
private $indent = 0;
/**
* Flag that is set true when migrations are running
* @var bool
*/
public $ismigrating = false;
/**
* Timestamp of last run migration
* @var int
**/
private $lastrun;
private $lastRunLogfile;
private $migrateAll = false;
private $migrated = [];
private $noMigrate = false;
public $noYaml = false;
private $outputLevel = self::outputLevelQuiet;
/** @var string */
public $path;
private $readyClasses = [];
/** @var WireArray */
private $watchlist;
public function __construct()
{
parent::__construct();
$this->path = $this->wire->config->paths($this);
$this->wire->classLoader->addNamespace("RockMigrations", __DIR__ . "/classes");
// load all constant-traits in /site/modules/*/
$file = wire()->config->paths->site . "RockMigrationsConstants.php";
if (is_file($file)) require_once $file;
$dir = wire()->config->paths->siteModules;
foreach (glob($dir . '*/RockMigrationsConstants.php') as $file) {
require_once $file;
}
$this->watchlist = $this->wire(new WireArray());
$this->lastrun = (int)$this->wire->cache->get(self::cachename);
}
public function init()
{
$this->wire->classLoader->addNamespace("RockMigrations", __DIR__ . "/classes");
$this->wire->classLoader->addNamespace("ProcessWire", wire()->config->paths->assets . 'RockMigrations');
$config = $this->wire->config;
$this->wire('rockmigrations', $this);
$this->lastRunLogfile = wire()->config->paths->logs . 'rockmigrations-lastrun.txt';
$this->installModule('MagicPages');
if ($config->debug) $this->setOutputLevel(self::outputLevelVerbose);
// for development
// $this->watch($this, false);
$this->disableProcache();
// merge config from config[-local].php
$this->mergeConfig();
// load tweaks
$this->loadTweaks();
// add hooks and session variables for inputfield success messages
$this->addSuccessMessageFeature();
// this creates folders that are necessary for PW and that might have
// been deleted on deploy
// for example this will create the sessions folder if it does not exist
$this->createNeededFolders();
// add things to watch
$this->watchFiles();
$this->watchModules();
// autoload pageclasses and repeater pageclasses
$this->autoloadClasses();
// hooks
wire()->addHookAfter("Modules::refresh", $this, "triggerMigrations");
wire()->addHookBefore("InputfieldForm::render", $this, "showEditInfo");
wire()->addHookBefore("InputfieldForm::render", $this, "showCopyCode");
wire()->addHookBefore("Modules::uninstall", $this, "unwatchBeforeUninstall");
wire()->addHookAfter("Modules::install", $this, "migrateAfterModuleInstall");
wire()->addHookAfter("Page(template=admin)::render", $this, "addColorBar");
wire()->addHookBefore("InputfieldForm::render", $this, "addRmHints");
wire()->addHookAfter("Modules::refresh", $this, "hookModulesRefresh");
wire()->addHookAfter("Pages::saved", $this, "resetCachesOnSave");
wire()->addHookAfter("Modules::install", $this, "hookModuleInstall");
// core enhancements
wire()->addHookProperty("Pagefile::isImage", $this, "hookIsImage");
wire()->addHookMethod("Pagefile::resizedUrl", $this, "hookPagefileResizedUrl");
// other actions on init()
$this->loadFilesOnDemand();
$this->createSnippetfiles();
}
protected function hookModuleInstall(HookEvent $event): void
{
$moduleName = $event->arguments(0);
if (!$moduleName) {
throw new WireException('Module name is missing.');
}
$module = wire()->modules->get($moduleName);
if (!$module) {
throw new WireException('Module not found: ' . $moduleName);
}
if (!$this->pageClassFiles($module)) {
return;
}
}
public function ready()
{
$this->hideFromGuests();
$this->forceMigrate();
// other actions
$this->migrateWatchfiles();
$this->changeFooter();
// trigger ready() of tweaks
foreach ($this->tweaks->find("enabled=1") as $tweak) $tweak->ready();
// trigger ready() of repeater pageclasses
foreach ($this->readyClasses as $class) $class->ready();
// load RockMigrations.js on backend
if ($this->wire->page->template == 'admin') {
$this->addScripts(__DIR__ . "/RockMigrations.js");
$this->addStyles(__DIR__ . "/RockMigrations.admin.css");
// fix ProcessWire language tabs issue
if ($this->wire->languages) {
$this->wire->config->js('rmUserLang', $this->wire->user->language->id);
}
// send preview password to JS in backend
wire()->config->js('previewPassword', $this->previewPassword);
}
}
/** ##### regular methods ##### */
/**
* Add a runtime field to an inputfield wrapper
*
* Usage:
* $rm->addAfter($form, 'title', [
* 'type' => 'markup',
* 'label' => 'foo',
* 'value' => 'bar',
* ]);
*
* @return Inputfield
*/
public function addAfter($wrapper, $existingItem, $newItem)
{
if (!$existingItem instanceof Inputfield) $existingItem = $wrapper->get($existingItem);
$wrapper->add($newItem);
$newItem = $wrapper->children()->last();
$wrapper->insertAfter($newItem, $existingItem);
return $newItem;
}
/**
* Add color-bar to DDEV and staging sites
*/
public function addColorBar(HookEvent $event)
{
if (!$this->colorBar) return;
$search = "</body";
$host = $this->wire->config->httpHost;
if (str_contains($host, ".ddev.site")) {
$col = '#2E7D32';
$label = 'DEV';
} elseif (str_contains($host, "staging")) {
$col = '#EF6C00';
$label = 'STAGING';
} else return;
$style = "position:fixed;left:0;top:0;width:100%;background-color:$col;color:white;text-align:center;font-size:8px;";
$event->return = str_replace(
$search,
"<div class='rm-colorbar' style='$style'>$label</div>$search",
$event->return
);
}
/**
* Add field to template
*
* @param Field|string $field
* @param Template|string $template
* @return void
*/
public function addFieldToTemplate($field, $template, $afterfield = null, $beforefield = null)
{
$field = $this->getField($field);
if (!$field) return; // logging is done in getField()
$template = $this->getTemplate($template);
if (!$template) return; // logging is done in getTemplate()
if (!$afterfield and !$beforefield) {
if ($template->fields->has($field)) return;
}
$afterfield = $this->getField($afterfield);
$beforefield = $this->getField($beforefield);
$fg = $template->fieldgroup;
/** @var Fieldgroup $fg */
if ($afterfield) $fg->insertAfter($field, $afterfield);
elseif ($beforefield) $fg->insertBefore($field, $beforefield);
else $fg->add($field);
// add end field for fieldsets
if (
$field->type instanceof FieldtypeFieldsetOpen
and !$field->type instanceof FieldtypeFieldsetClose
) {
$closer = $field->type->getFieldsetCloseField($field, false);
$this->addFieldToTemplate($closer, $template, $field);
}
// TODO fix this!
// quickfix to prevent integrity constraint errors in backend
try {
$fg->save();
} catch (\Throwable $th) {
$this->log($th->getMessage());
}
}
/**
* Add fields to template.
*
* Simple:
* $rm->addFieldsToTemplate(['field1', 'field2'], 'yourtemplate');
*
* Add fields at special positions:
* $rm->addFieldsToTemplate([
* 'field1',
* 'field4' => 'field3', // this will add field4 after field3
* ], 'yourtemplate');
*
* @param array $fields
* @param string $template
* @param bool $sortFields
* @return void
*/
public function addFieldsToTemplate($fields, $template, $sortFields = false)
{
foreach ($fields as $k => $v) {
// if the key is an integer, it's a simple field
if (is_int($k)) $this->addFieldToTemplate((string)$v, $template);
else $this->addFieldToTemplate((string)$k, $template, $v);
}
if ($sortFields) $this->setFieldOrder($fields, $template);
}
/**
* Add a new language or return existing
*
* Also installs language support if missing.
*
* @param string $name Name of the language
* @param string $title Optional title of the language
* @return Language Language that was created
*/
public function addLanguage(string $name, string $title = null)
{
// Make sure Language Support is installed
$languages = $this->addLanguageSupport();
if (!$languages) return $this->log("Failed installing LanguageSupport");
$lang = $this->getLanguage($name);
if (!$lang->id) {
$lang = $languages->add($name);
$languages->reloadLanguages();
}
if ($title) $lang->setAndSave('title', $title);
return $lang;
}
/**
* Install the languagesupport module
* @return Languages
*/
public function addLanguageSupport()
{
if (!$this->modules->isInstalled("LanguageSupport")) {
$this->wire->pages->setOutputFormatting(false);
$ls = $this->installModule("LanguageSupport", ['force' => true]);
if (!$this->wire->languages) $ls->init();
}
return $this->wire->languages;
}
/**
* Add a permission to given role
*
* @param string|int $permission
* @param string|int $role
* @return boolean
*/
public function addPermissionToRole($permission, $role)
{
$role = $this->getRole($role);
if (!$role) return $this->log("Role $role not found");
$role->of(false);
$role->addPermission($permission);
return $role->save();
}
public function addRmHints(HookEvent $event)
{
if (!$this->wire->user->isSuperuser()) return;
$form = $event->object;
$showHints = false;
if ($form->id == 'ProcessTemplateEdit') $showHints = true;
elseif ($form->id == 'ProcessFieldEdit') $showHints = true;
if (!$showHints) return;
$form->addClass('rm-hints');
}
/**
* Add role to user
*
* @param string $role
* @param User|string $user
* @return void
*/
public function addRoleToUser($role, $user)
{
$role = $this->getRole($role);
$user = $this->getUser($user);
$msg = "Cannot add role to user";
if (!$role) return $this->log("$msg - role not found");
if (!$user) return $this->log("$msg - user not found");
$user->of(false);
$user->addRole($role);
$user->save();
}
/**
* Add scripts to $config->scripts and add cache busting timestamp
*/
public function addScripts($scripts)
{
if (!is_array($scripts)) $scripts = [$scripts];
foreach ($scripts as $script) {
$path = $this->filePath($script);
// if file is not found we silently skip it
// it is silent because of MagicPages::addPageAssets
if (!is_file($path)) continue;
$url = str_replace(
$this->wire->config->paths->root,
$this->wire->config->urls->root,
$path
);
$this->wire->config->scripts->add($url . "?m=" . filemtime($path));
}
}
/**
* Add styles to $config->styles and add cache busting timestamp
*/
public function addStyles($styles)
{
if (!is_array($styles)) $styles = [$styles];
foreach ($styles as $style) {
$path = $this->filePath($style);
// check if it is a less file
if (pathinfo($path, PATHINFO_EXTENSION) === 'less') {
$path = $this->saveCSS($path);
}
// if file is not found we silently skip it
// it is silent because of MagicPages::addPageAssets
if (!is_file((string)$path)) continue;
$url = str_replace(
$this->wire->config->paths->root,
$this->wire->config->urls->root,
$path
);
$this->wire->config->styles->add($url . "?m=" . filemtime($path));
}
}
/**
* Add the possibility to add success messages on inputfields
*/
private function addSuccessMessageFeature()
{
// setup and load the session variable that stores success messages
$this->fieldSuccessMessages = $this->wire(new WireData());
$this->fieldSuccessMessages->setArray(
$this->wire->session->rmFieldSuccessMessages ?: []
);
// add hook that renders success messages on the inputfields
// rendering the message will also remove the message from the storage
$this->addHookBefore("Inputfield::render", function ($event) {
$field = $event->object;
$messages = $this->fieldSuccessMessages;
foreach ($messages as $name => $msg) {
if ($field->name !== $name) continue;
$field->prependMarkup .= "<div class='uk-alert-success' uk-alert>
<a class='uk-alert-close' uk-close></a>
$msg
</div>";
$messages->remove($name);
$this->wire->session->rmFieldSuccessMessages = $messages->getArray();
}
});
}
/**
* Add given permission to given template for given role
*
* Example for single template:
* $rm->addTemplateAccess("my-template", "my-role", "edit");
*
* Example for multiple templates/roles/permissions:
* $rm->addTemplateAccess([
* 'home',
* 'basic-page',
* ],
* [
* 'admin',
* 'author',
* ],
* [
* 'add',
* 'edit',
* ]);
*
* @param mixed string|array $templates template name or array of names
* @param mixed string|array $roles role name or array of names
* @param mixed string|array $accs permission name or array of names
* @return void
*/
public function addTemplateAccess($templates, $roles, $accs)
{
if (!is_array($templates)) $templates = [$templates];
if (!is_array($roles)) $roles = [$roles];
if (!is_array($accs)) $accs = [$accs];
foreach ($roles as $role) {
if (!$role = $this->getRole($role)) continue;
foreach ($templates as $tpl) {
$tpl = $this->getTemplate($tpl);
if (!$tpl) continue; // log is done above
foreach ($accs as $acc) {
$tpl->addRole($role, $acc);
}
$tpl->save();
}
}
}
/**
* Add xdebug launcher file for DDEV to PW root
*/
private function addXdebugLauncher()
{
if (!$this->addXdebugLauncher) return;
$src = __DIR__ . "/.vscode/launch.json";
$dst = $this->wire->config->paths->root . ".vscode/launch.json";
if (!is_file($dst)) $this->wire->files->copy($src, $dst);
}
/**
* Allow requests from this ip even if site is hidden from guests
* This is to support multi-domain setups where viewing a new domain
* would result in a redirect to the login-screen even though the preview
* password was present on the prior request.
*/
private function allowIP(): void
{
$ip = $this->wire->session->getIP();
$key = "hidefromguests-allow-$ip";
$this->wire->cache->save($key, $ip, self::oneMinute * 30);
}
/**
* Register autoloader for all classes in given folder
* This will NOT trigger init() or ready()
* You can also use $rm->initClasses() with setting autoload=true
*/
public function autoload($path, $namespace)
{
$path = Paths::normalizeSeparators($path);
spl_autoload_register(function ($class) use ($path, $namespace) {
if (strpos($class, "$namespace\\") !== 0) return;
$name = substr($class, strlen($namespace) + 1);
$file = "$path/$name.php";
if (is_file($file)) require_once($file);
});
}
/**
* Autoload classes and traits inside your module's directory
* This will load all php classes in the following folders:
* /site/modules/MyModule/classLoader
* /site/modules/MyModule/pageClasses
* /site/modules/MyModule/repeaterPageClasses
*/
public function autoloadClasses(): void
{
// add classloader for all autoloadClasses folders
// load dirs from cache for better performance
$dirs = $this->cache("autoload-classloader-classes", function () {
return glob($this->wire->config->paths->siteModules . "*/classLoader");
});
foreach ($dirs as $dir) {
// if $dir is not within current site root we have an outdated cache
if (!str_starts_with($dir, $this->wire->config->paths->siteModules)) {
$this->wire->cache->delete("autoload-classloader-classes");
$this->wire->cache->delete("autoload-repeater-pageclasses");
$this->autoloadClasses();
return;
}
$namespace = basename(dirname($dir));
$this->wire->classLoader->addNamespace($namespace, $dir);
}
// autoload regular pageclasses
foreach ($this->wire->modules as $module) {
if (!$module instanceof Module) continue;
$this->pageClassLoader($module, "pageClasses");
}
// autoload repeater pageclasses
// load classes from cache for better performance
$classes = $this->cache("autoload-repeater-pageclasses", function () {
$classes = [];
$dirs = glob($this->wire->config->paths->siteModules . "*/repeaterPageClasses");
foreach ($dirs as $dir) {
$classes[$dir] = glob("$dir/*.php");
}
return $classes;
});
foreach ($classes as $dir => $files) {
if (!str_starts_with($dir, $this->wire->config->paths->siteModules)) {
$this->wire->cache->delete("autoload-classloader-classes");
$this->wire->cache->delete("autoload-repeater-pageclasses");
$this->autoloadClasses();
return;
}
$namespace = basename(dirname($dir));
$this->wire->classLoader->addNamespace($namespace, $dir);
foreach ($files as $file) {
$name = substr(basename($file), 0, -4);
$class = "\\$namespace\\$name";
try {
$tmp = new $class();
$field = $this->wire->fields->get($tmp::field);
if (!$field) continue;
$field->type->setCustomPageClass($field, $class);
if (method_exists($tmp, "init")) $tmp->init();
if (method_exists($tmp, "ready")) $this->readyClasses[] = $tmp;
} catch (\Throwable $th) {
$this->log($th->getMessage());
}
}
}
}
/**
* Get basename of file or object
* @return string
*/
public function basename($file)
{
return basename($this->filePath($file));
}
/**
* Get data from cache that is automatically recreated on Modules::refresh
*
* Note: The ->cache() call must happen on every request so that the
* Modules::refresh knows about all the caches it has to delete!
*
* For development/debugging you can set $debug = true to always get the
* non-cached value from the callback.
*
* Usage:
* $rm->cache("my-cache", function() { return date("H:i:s"); });
*/
public function cache(
string $name,
callable $create,
$debug = false,
bool $deleteOnSave = false,
) {
// when used from the cli we always return a fresh version of the callback
// this is to make sure on deployment we always get the latest version of
// data so that we don't get missing dependency errors in autoloadClasses()
if ($this->isCLI()) $debug = true;
if ($debug) $this->wire->cache->delete($name);
$val = $this->wire->cache->get($name, WireCache::expireNever, $create);
$this->cacheDelete .= ",$name";
if ($deleteOnSave) $this->cacheDeleteOnSave .= ",$name";
return $val;
}
/**
* Add deployment info to backend pages
*/
public function changeFooter()
{
if ($this->wire->page->template != 'admin') return;
$str = "";
if ($this->addHost) {
$str = $this->wire->config->httpHost;
$time = date("Y-m-d H:i:s", filemtime($this->wire->config->paths->root));
if ($this->wire->user->isSuperuser()) {
$dir = $this->wire->config->paths->root;
$str = "<span title='$dir @ $time' uk-tooltip>$str</span>";
}
}
// add version number if package.json is found in root
$f = $this->wire->config->paths->root . "package.json";
if ($this->addVersion and file_exists($f)) {
$version = json_decode(file_get_contents($f))->version;
$str .= " <small>v$version</small>";
}
if (!$str) return;
$this->wire->addHookAfter('AdminThemeUikit::renderFile', function ($event) use ($str) {
$file = $event->arguments(0); // full path/file being rendered
if (basename($file) !== '_footer.php') return;
$event->return = str_replace("ProcessWire", $str, $event->return);
}, ['priority' => 999]);
}
/**
* Set columnWidth for multiple fields of a form
*
* Usage:
* $rm->columnWidth($form, [
* 'foo' => 33,
* 'bar' => 33,
* 'baz' => 33,
* ]);
*/
public function columnWidth(InputfieldWrapper $form, array $fields)
{
foreach ($fields as $name => $width) {
if ($f = $form->get($name)) $f->columnWidth($width);
}
}
/**
* Thx Adrian
* https://github.com/adrianbj/ProcessAdminActions/blob/master/actions/CopyRepeaterItemsToOtherPage.action.php
*
* Usage of newFieldnames:
* [
* 'oldFieldName' => 'newFieldName',
* ]
*/
public function copyRepeaterItems(
Page|string|int $sourcePage,
Field|string|int $sourceField,
Field|string|int $targetField,
Page|string|int $targetPage = null,
bool $resetTarget = false,
array $newFieldnames = [],
): void {
$sourcePage = $this->getPage($sourcePage);
$sourcePage->of(false);
$targetPage = $targetPage ? $this->getPage($targetPage) : $sourcePage;
$targetPage->of(false);
$sourceField = $this->getField($sourceField);
$targetField = $this->getField($targetField);
$sourceItems = $sourcePage->get($sourceField->name);
$targetItems = $targetPage->get($targetField->name);
// reset target before copy?
if ($resetTarget) {
$targetItems->removeAll();
$targetPage->save($targetField->name);
}
// copy items
foreach ($sourceItems as $item) {
// create new item
$clone = $targetItems->getNew();
$clone->save();
// populate all fields
foreach ($item->fields as $field) {
$fieldname = $field->name;
$targetName = $fieldname;
// move content to the same field or to another one?
if (in_array($fieldname, array_keys($newFieldnames))) {
$targetName = $newFieldnames[$fieldname];
}
// set new value
$clone->set($targetName, $item->getUnformatted($fieldname));
}
// copy files?
if (PagefilesManager::hasFiles($item)) {
$clone->filesManager->init($clone);
$item->filesManager->copyFiles($clone->filesManager->path());
}
// save changes
$clone->save();
}
// save page
$targetPage->setAndSave($targetField->name, $targetItems);
}
private function createConstantTraits(): void
{
// only do this if debug mode is enabled
if (!wire()->config->debug) return;
$this->log("--- create PHP constant traits ---");
// get files from watchlist
$list = $this->sortedWatchlist();
// get all RM config files with priority 1000
$configFiles = $list['#1000'] ?? [];
// loop over all files and populate $constants array
$const = [];
$constants = [];
foreach ($configFiles as $file) {
$tag = $this->getConfigFileTag($file);
// skip files that have no tag (not part of a module)
// these files are located in /site/RockMigrations/*
if (!$tag) {
$const[] = $file;
} else {
if (!array_key_exists($tag, $constants)) $constants[$tag] = [];
$constants[$tag][] = $file;
}
}
// write constant trait for site migrations
if (count($const)) {
$dst = wire()->config->paths->site . "RockMigrationsConstants.php";
// if file does not exist we don't create it
if (is_file($dst)) {
$content = "<?php\n\nnamespace ProcessWire;\n";
$content .= "\n// DO NOT MODIFY THIS FILE!";
$content .= "\n// IT IS AUTO-GENERATED BY ROCKMIGRATIONS!\n";
$content .= "\nclass RockMigrationsConstants\n{\n";
foreach ($const as $file) {
$type = $this->getConfigFileType($file, true);
$shortName = $this->getConfigFileName($file, true, true);
if (str_starts_with($shortName, '.')) continue;
$longName = $this->getConfigFileName($file);
$content .= " const {$type}_$shortName = '$longName';\n";
}
$content .= "}\n";
// write content to file
wire()->files->filePutContents($dst, $content);
$this->log("Created $dst");
}
}
// write constant traits for module migrations
foreach ($constants as $tag => $files) {
// built destination file path
$dst = wire()->config->paths->siteModules . "$tag/RockMigrationsConstants.php";
// if file does not exist we don't create it
if (!is_file($dst)) continue;
// build content of file
$content = "<?php\n\nnamespace $tag;\n";
$content .= "\n// DO NOT MODIFY THIS FILE!";
$content .= "\n// IT IS AUTO-GENERATED BY ROCKMIGRATIONS!\n";
$content .= "\ntrait RockMigrationsConstants\n{\n";
foreach ($files as $file) {
$type = $this->getConfigFileType($file, true);
$shortName = $this->getConfigFileName($file, true, true);
if (str_starts_with($shortName, '.')) continue;
$longName = $this->getConfigFileName($file);
$content .= " const {$type}_$shortName = '$longName';\n";
}
$content .= "}\n";
// write content to file
wire()->files->filePutContents($dst, $content);
$this->log("Created $dst");
}
}
/**
* Create a field of the given type
*
* If run multiple times it will only update field data.
*
* Usage:
* $rm->createField('myfield');
*
* $rm->createField('myfield', 'text', [
* 'label' => 'My great field',
* ]);
*
* Alternate array syntax:
* $rm->createField('myfield', [
* 'type' => 'text',
* 'label' => 'My field label',
* ]);
*
* @param string $name
* @param string|array $type|$options
* @param array $options
* @return Field|false
*/
public function createField($name, $type = 'text', $options = [])
{
if (is_array($type)) {
$options = $type;
if (!array_key_exists('type', $options)) $options['type'] = 'text';
$type = $options['type'];
}
$field = $this->getField($name, true);
// field does not exist
if (!$field) {
// get type
$type = $this->getFieldtype($type);
if (!$type) return; // logging above
// create the new field
$_name = $this->wire->sanitizer->fieldName($name);
if ($_name !== $name) throw new WireException("Invalid fieldname ($name)!");
// get fieldClass as string if implemented for that FieldType
/** @var string $fieldClass */
$fieldClass = $type->getFieldClass();
$fieldClass = "ProcessWire\\$fieldClass";
if (class_exists($fieldClass)) {
// use the specific class to create new field if it exists
$field = $this->wire(new $fieldClass());
} else {
$field = $this->wire(new Field());
}
$field->type = $type;
$field->name = $_name;
$field->label = $_name; // set label (mandatory since ~3.0.172)
$field->save();
// create end field for fieldsets
if ($field->type instanceof FieldtypeFieldsetOpen) {
$field->type->getFieldsetCloseField($field, true);
}
// this will auto-generate the repeater template
if ($field->type instanceof FieldtypeRepeater) {
$field->type->getRepeaterTemplate($field);
}
}
// set options
$options = array_merge($options, ['type' => $type]);
$field = $this->setFieldData($field, $options);
return $field;
}
/**
* Create fields from array
*
* Usage:
* $rm->createFields([
* 'field1' => [...],
* 'field2' => [...],
* ]);
*/
public function createFields($fields): void
{
foreach ($fields as $name => $data) {
if (is_int($name)) {
$name = $data;
$data = [];
}
$this->createField($name, $data);
}
}
private function createNeededFolders()
{
$dir = $this->wire->config->paths->assets . "sessions";
if (!is_dir($dir)) $this->wire->files->mkdir($dir);
}
/**
* Make all pages having given template be created on top of the list
* @return void
*/
public function createOnTop($tpl)
{
$tpl = $this->wire->templates->get((string)$tpl);
$this->addHookAfter("Pages::added", function (HookEvent $event) {
$page = $event->arguments(0);
$this->wire->pages->sort($page, 0);
});
}
/**
* Create a new Page