-
Notifications
You must be signed in to change notification settings - Fork 206
Expand file tree
/
Copy pathModules.php
More file actions
2579 lines (2359 loc) · 78 KB
/
Copy pathModules.php
File metadata and controls
2579 lines (2359 loc) · 78 KB
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;
/**
* ProcessWire Modules
*
* Loads and manages all runtime modules for ProcessWire
*
* ProcessWire 3.x, Copyright 2023 by Ryan Cramer
* https://processwire.com
*
* #pw-summary Loads and manages all modules in ProcessWire.
* #pw-body =
* The `$modules` API variable is most commonly used for getting individual modules to use their API.
* ~~~~~
* // Getting a module by name
* $m = $modules->get('MarkupPagerNav');
*
* // Getting a module by name (alternate)
* $m = $modules->MarkupPagerNav;
* ~~~~~
*
* #pw-body
*
* Note that when iterating, find(), or calling any other method that returns module(s), excepting get(), a ModulePlaceholder may be
* returned rather than a real Module. ModulePlaceholders are used in instances when the module may or may not be needed at runtime
* in order to save resources. As a result, anything iterating through these Modules should check to make sure it's not a ModulePlaceholder
* before using it. If it's a ModulePlaceholder, then the real Module can be instantiated/retrieved by $modules->get($className).
*
* @method void refresh($showMessages = false) Refresh the cache that stores module files by recreating it
* @method null|Module install($class, $options = array())
* @method bool|int delete($class)
* @method bool uninstall($class)
* @method bool saveModuleConfigData($className, array $configData) Alias of saveConfig() method #pw-internal
* @method bool saveConfig($class, $data, $value = null)
* @method InputfieldWrapper|null getModuleConfigInputfields($moduleName, InputfieldWrapper $form = null) #pw-internal
* @method void moduleVersionChanged(Module $module, $fromVersion, $toVersion) #pw-internal
* @method bool|string isUninstallable($class, $returnReason = false) hookable in 3.0.181+ #pw-internal
*
* @property-read array $installableFiles
* @property-read string $coreModulesDir
* @property-read string $coreModulesPath
* @property-read string $siteModulesPath
* @property-read array $moduleIDs
* @property-read array $moduleNames
* @property-read ModulesInfo $info
* @property-read ModulesLoader $loader
* @property-read ModulesFlags $flags
* @property-read ModulesFiles $files
* @property-read ModulesInstaller $installer
* @property-read ModulesConfigs $configs
* @property-read bool $refreshing
*
*/
class Modules extends WireArray {
/**
* Whether or not module debug mode is active
*
*/
protected $debug = false;
/**
* Flag indicating the module may have only one instance at runtime.
*
*/
const flagsSingular = 1;
/**
* Flag indicating that the module should be instantiated at runtime, rather than when called upon.
*
*/
const flagsAutoload = 2;
/**
* Flag indicating the module has more than one copy of it on the file system.
*
*/
const flagsDuplicate = 4;
/**
* When combined with flagsAutoload, indicates that the autoload is conditional
*
*/
const flagsConditional = 8;
/**
* When combined with flagsAutoload, indicates that the module's autoload state is temporarily disabled
*
*/
const flagsDisabled = 16;
/**
* Indicates module that maintains a configurable interface but with no interactive Inputfields
*
*/
const flagsNoUserConfig = 32;
/**
* Module where no file could be located
*
*/
const flagsNoFile = 64;
/**
* Indicates row is for Modules system cache use and not an actual module
*
* @since 3.0.218
*
*/
const flagsSystemCache = 8192;
/**
* Array of modules that are not currently installed, indexed by className => filename
*
*/
protected $installableFiles = array();
/**
* An array of module database IDs indexed by module name/class
*
*/
protected $moduleIDs = array();
/**
* Array of module names/classes indexed by module ID
*
*/
protected $moduleNames = array();
/**
* Full system paths where modules are stored
*
* index 0 must be the core modules path (/i.e. /wire/modules/)
*
*/
protected $paths = array();
/**
* Have the modules been init'd() ?
*
*/
protected $initialized = false;
/**
* Becomes an array if debug mode is on
*
*/
protected $debugLog = array();
/**
* Array of moduleName => substituteModuleName to be used when moduleName doesn't exist
*
* Primarily for providing backwards compatiblity with modules assumed installed that
* may no longer be in core.
*
* see setSubstitutes() method
*
*/
protected $substitutes = array();
/**
* Instance of ModulesDuplicates
*
* @var ModulesDuplicates
*
*/
protected $duplicates = null;
/**
* Dir for core modules relative to root path, i.e. '/wire/modules/'
*
* @var string
*
*/
protected $coreModulesDir = '';
/**
* Are we currently refreshing?
*
* @var bool
*
*/
protected $refreshing = false;
/**
* Runtime caches
*
* @var array
* @since 3.0.218
*
*/
protected $caches = array();
/**
* @var ModulesInfo
*
*/
protected $info;
/**
* @var ModulesFlags
*
*/
protected $flags;
/**
* @var ModulesFiles
*
*/
protected $files;
/**
* @var ModulesConfigs
*
*/
protected $configs;
/**
* @var ModulesInstaller|null
*
*/
protected $installer = null;
/**
* @var ModulesLoader
*
*/
protected $loader = null;
/**
* Construct the Modules
*
* @param string $path Core modules path (you may add other paths with addPath method)
*
*/
public function __construct($path) {
parent::__construct();
$this->nameProperty = 'className';
$this->usesNumericKeys = false;
$this->indexedByName = true;
$this->addPath($path); // paths[0] is always core modules path
}
/**
* Wired to API
*
* #pw-internal
*
*/
public function wired() {
$this->coreModulesDir = '/' . $this->wire()->config->urls->data('modules');
parent::wired();
$this->info = new ModulesInfo($this);
$this->flags = new ModulesFlags($this);
$this->files = new ModulesFiles($this);
$this->configs = new ModulesConfigs($this);
$this->loader = new ModulesLoader($this);
}
/**
* Get the ModulesDuplicates instance
*
* #pw-internal
*
* @return ModulesDuplicates
*
*/
public function duplicates() {
if($this->duplicates === null) $this->duplicates = $this->wire(new ModulesDuplicates());
return $this->duplicates;
}
/**
* Get the ModulesInstaller instance
*
* #pw-internal
*
* @return ModulesInstaller
*
*/
public function installer() {
if($this->installer === null) $this->installer = new ModulesInstaller($this);
return $this->installer;
}
/**
* Add another modules path, must be called before init()
*
* #pw-internal
*
* @param string $path
*
*/
public function addPath($path) {
$this->paths[] = $path;
}
/**
* Return all assigned module root paths
*
* #pw-internal
*
* @return array of modules paths, with index 0 always being the core modules path.
*
*/
public function getPaths() {
return $this->paths;
}
/**
* Initialize modules
*
* Must be called after construct before this class is ready to use
*
* #pw-internal
*
* @see load()
*
*/
public function init() {
$this->setTrackChanges(false);
$this->loader->loadModulesTable();
$this->info->loadModuleInfoCache();
if(isset($this->paths[1])) {
$this->loader->preloadModules($this->paths[1]); // site modules path
}
foreach($this->paths as $path) {
$this->loader->loadPath($path);
}
$this->loader->loaded();
}
/**
* Trigger 'init' on all autoload modules, which calls their init() methods
*
* #pw-internal
*
*/
public function triggerInit() {
$this->loader->triggerInit();
}
/**
* Trigger 'ready' on all autoload modules, which calls their ready() methods
*
* This is to indicate to them that the API environment is fully ready.
*
* #pw-internal
*
*/
public function triggerReady() {
$this->loader->triggerReady();
}
/**********************************************************************************************
* WIREARRAY OVERRIDES
*
*/
/**
* Modules class accepts only Module instances, per the WireArray interface
*
* #pw-internal
*
* @param Wire $item
* @return bool
*
*/
public function isValidItem($item) {
return $item instanceof Module;
}
/**
* The key/index used for each module in the array is it's class name, per the WireArray interface
*
* #pw-internal
*
* @param Wire $item
* @return string
*
*/
public function getItemKey($item) {
return $this->getModuleClass($item);
}
/**
* There is no blank/generic module type, so makeBlankItem returns null
*
* #pw-internal
*
*/
public function makeBlankItem() {
return null;
}
/**
* Make a new/blank WireArray
*
* #pw-internal
*
*/
public function makeNew() {
// ensures that find(), etc. operations don't initalize a new Modules() class
return $this->wire(new WireArray());
}
/**
* Make a new populated copy of a WireArray containing all the modules
*
* #pw-internal
*
* @return WireArray
*
*/
public function makeCopy() {
// ensures that find(), etc. operations don't initalize a new Modules() class
$copy = $this->makeNew();
foreach($this->data as $key => $value) $copy[$key] = $value;
$copy->resetTrackChanges($this->trackChanges());
return $copy;
}
/**********************************************************************************************
* GETTING/LOADING MODULES
*
*/
/**
* Get the requested Module
*
* - If the module is not installed, but is installable, it will be installed, instantiated, and initialized.
* If you don't want that behavior, call `$modules->isInstalled('ModuleName')` as a conditional first.
* - You can also get/load a module by accessing it directly, like `$modules->ModuleName`.
* - To get a module with additional options, use `$modules->getModule($name, $options)` instead.
*
* ~~~~~
* // Get the MarkupAdminDataTable module
* $table = $modules->get('MarkupAdminDataTable');
*
* // You can also do this
* $table = $modules->MarkupAdminDataTable;
* ~~~~~
*
* @param string|int $key Module name (also accepts database ID)
* @return Module|_Module|null Returns a Module or null if not found
* @throws WirePermissionException If module requires a particular permission the user does not have
* @see Modules::getModule(), Modules::isInstalled()
*
*/
public function get($key) {
// If the module is a ModulePlaceholder, then it will be converted to the real module (included, instantiated, initialized).
return $this->getModule($key);
}
/**
* Get the requested Module (with options)
*
* This is the same as `$modules->get()` except that you can specify additional options to modify default behavior.
* These are the options you can specify in the `$options` array argument:
*
* - `noPermissionCheck` (bool): Specify true to disable module permission checks (and resulting exception). (default=false)
* - `noInstall` (bool): Specify true to prevent a non-installed module from installing from this request. (default=false)
* - `noInit` (bool): Specify true to prevent the module from being initialized or configured. (default=false). See `configOnly` as alternative.
* - `noSubstitute` (bool): Specify true to prevent inclusion of a substitute module. (default=false)
* - `noCache` (bool): Specify true to prevent module instance from being cached for later getModule() calls. (default=false)
* - `noThrow` (bool): Specify true to prevent exceptions from being thrown on permission or fatal error. (default=false)
* - `returnError` (bool): Return an error message (string) on error, rather than null. (default=false)
* - `configOnly` (bool): Populate module config data but do not call its init() method. (default=false) 3.0.169+. Alternative to `noInit`.
* - `configData` (array): Associative array of additional config data to populate to module. (default=[]) 3.0.169+
*
* If the module is not installed, but is installable, it will be installed, instantiated, and initialized.
* If you don't want that behavior, call `$modules->isInstalled('ModuleName')` as a condition first, OR specify
* true for the `noInstall` option in the `$options` argument.
*
* @param string|int $key Module name or database ID.
* @param array $options Optional settings to change load behavior, see method description for details.
* @return Module|_Module|null|string Returns ready-to-use module or NULL|string if not found (string if `returnError` option used).
* @throws WirePermissionException|\Exception If module requires a particular permission the user does not have
* @see Modules::get()
*
*/
public function getModule($key, array $options = array()) {
$needsInit = false;
$noInit = !empty($options['noInit']); // force cancel of Module::init() call?
$initOptions = array(); // options for initModule() call
$find = false; // try to find new location of module file?
$error = '';
if(empty($key)) {
return empty($options['returnError']) ? null : "No module specified";
}
// check for optional module ID and convert to classname if found
if(ctype_digit("$key")) {
$moduleID = (int) $key;
if(!isset($this->moduleNames[$moduleID])) {
return empty($options['returnError']) ? null : "Unable to find module ID $moduleID";
}
$key = $this->moduleNames[$moduleID];
} else {
$moduleID = 0;
$key = wireClassName($key, false);
}
$module = parent::get($key);
if(!$module && !$moduleID) {
// make non case-sensitive for module name ($key)
$lowerKey = strtolower($key);
foreach($this->moduleNames as $className) {
if(strtolower($className) !== $lowerKey) continue;
$module = parent::get($className);
break;
}
}
if(!$module) {
if(empty($options['noSubstitute'])) {
if($this->isInstallable($key) && empty($options['noInstall'])) {
// module is on file system and may be installed, no need to substitute
} else {
$module = $this->getSubstituteModule($key, $options);
if($module) return $module; // returned module is ready to use
}
} else {
$error = "Module '$key' not found and substitute not allowed (noSubstitute=true)";
}
}
if($module) {
// check if it's a placeholder, and if it is then include/instantiate/init the real module
// OR check if it's non-singular, so that a new instance is created
if($module instanceof ModulePlaceholder || !$this->isSingular($module)) {
$placeholder = $module;
$class = $this->getModuleClass($placeholder);
try {
if($module instanceof ModulePlaceholder) $this->includeModule($module);
$module = $this->newModule($class);
} catch(\Exception $e) {
if(empty($options['noThrow'])) throw $e;
return empty($options['returnError']) ? null : "Module '$key' - " . $e->getMessage();
}
// if singular, save the instance so it can be used in later calls
if($module && $this->isSingular($module) && empty($options['noCache'])) $this->set($key, $module);
$needsInit = true;
}
} else if(empty($options['noInstall'])) {
// module was not available to get, see if we can install it
if(array_key_exists($key, $this->getInstallable())) {
// check if the request is for an uninstalled module
// if so, install it and return it
try {
$module = $this->install($key);
} catch(\Exception $e) {
if(empty($options['noThrow'])) throw $e;
if(!empty($options['returnError'])) return "Module '$key' install failed: " . $e->getMessage();
}
$needsInit = true;
if(!$module) $error = "Module '$key' not installed and install failed";
} else {
$error = "Module '$key' is not present or listed as installable";
$find = true;
}
} else {
$error = "Module '$key' is not present and not installable (noInstall=true)";
$find = true;
}
if(!$module && $find) {
// This is reached if module has moved elsewhere in file system, like from:
// site/modules/ModuleName.module to site/modules/ModuleName/ModuleName.module
// Code below tries to find the file to keep it working, but modules need Refresh.
try {
if($this->includeModule($key)) {
$module = $this->newModule($key);
}
} catch(\Exception $e) {
if(empty($options['noThrow'])) throw $e;
$error .= ($error ? " - " : "Module '$key' - ") . $e->getMessage();
return empty($options['returnError']) ? null : $error;
}
}
if(!$module) {
if(!$error) $error = "Unable to get module '$key'";
return empty($options['returnError']) ? null : $error;
}
if(empty($options['noPermissionCheck'])) {
// check that user has permission required to use module
$page = $this->wire()->page;
$user = $this->wire()->user;
if(!$this->hasPermission($module, $user, $page)) {
$error = $this->_('You do not have permission to execute this module') . ' - ' .
wireClassName($module) . " (page=$page)";
if(empty($options['noThrow'])) throw new WirePermissionException($error);
return empty($options['returnError']) ? null : $error;
}
}
if($needsInit && $noInit) {
// forced cancel of init() call
$needsInit = false;
}
if(!$needsInit && (!empty($options['configData']) || !empty($options['configOnly']))) {
// if config data was supplied in options then we have to init()
$needsInit = true;
if(!empty($options['configData'])) $initOptions['configData'] = $options['configData'];
// if forced noInit then tell initModule() to only config and not call Module::init()
if($noInit || !empty($options['configOnly'])) $initOptions['configOnly'] = true;
}
// skip autoload modules because they have already been initialized in the load() method
// unless they were just installed, in which case we need do init now
if($needsInit) {
// if the module is configurable, then load its config data
// and set values for each before initializing the module
$initOptions['clearSettings'] = false;
$initOptions['throw'] = true;
try {
if(!$this->loader->initModule($module, $initOptions)) {
return empty($options['returnError']) ? null : "Module '$module' failed init";
}
} catch(\Exception $e) {
if(empty($options['noThrow'])) throw $e;
return empty($options['returnError']) ? null : "Module '$module' throw Exception on init - " . $e->getMessage();
}
}
return $module;
}
/**
* Get the requested module and reset cache + install it if necessary.
*
* This is exactly the same as getModule() except that this one will rebuild the modules cache if
* it doesn't find the module at first. If the module is on the file system, this
* one will return it in some instances that a regular get() can't.
*
* #pw-internal
*
* @param string|int $key Module className or database ID
* @return Module|null
*
*/
public function getInstall($key) {
$module = $this->getModule($key);
if(!$module) {
$this->refresh();
$module = $this->getModule($key);
}
return $module;
}
/**
* Include the file for a given module, but don't instantiate it
*
* #pw-internal
*
* @param ModulePlaceholder|Module|string Expects a ModulePlaceholder or className
* @param string $file Optionally specify the module filename if you already know it
* @return bool true on success, false on fail or unknown
*
*/
public function includeModule($module, $file = '') {
return $this->loader->includeModule($module, $file);
}
/**
* Create a new Module instance
*
* Given a class name, return the constructed module or null
*
* #pw-internal
*
* @param string $className Module class name
* @param string $moduleName Optional module name only (no namespace)
* @return Module|null
*
*/
public function newModule($className, $moduleName = '') {
if(!$moduleName) {
$moduleName = wireClassName($className, false);
$className = wireClassName($className, true);
}
$debugKey = $this->debug ? $this->debugTimerStart("newModule($moduleName)") : null;
if(!class_exists($className, false)) {
$result = $this->includeModule($moduleName);
if(!$result) return null;
}
if(!class_exists($className, false)) {
// attempt 2.x module in dedicated namespace or root namespace
$className = $this->info->getModuleNamespace($moduleName) . $moduleName;
}
if(ProcessWire::getNumInstances() > 1) {
// in a multi-instance environment, ensures that anything happening during
// the module __construct is using the right instance. necessary because the
// construct method runs before the wire instance is set to the module
$wire1 = ProcessWire::getCurrentInstance();
$wire2 = $this->wire();
if($wire1 !== $wire2) {
ProcessWire::setCurrentInstance($wire2);
} else {
$wire1 = null;
}
} else {
$wire1 = null;
}
try {
$module = $this->wire(new $className());
} catch(\Exception $e) {
$this->error(sprintf($this->_('Failed to construct module: %s'), $className) . " - " . $e->getMessage());
$module = null;
}
if($this->debug) $this->debugTimerStop($debugKey);
if($wire1) ProcessWire::setCurrentInstance($wire1);
return $module;
}
/**
* Check if user has permission for given module
*
* #pw-internal
*
* @param string|object $moduleName Module instance or module name
* @param User|null $user Optionally specify different user to consider than current.
* @param Page|null $page Optionally specify different page to consider than current.
* @param bool $strict If module specifies no permission settings, assume no permission.
* - Default (false) is to assume permission when module doesn't say anything about it.
* - Process modules (for instance) generally assume no permission when it isn't specifically defined
* (though this method doesn't get involved in that, leaving you to specify $strict instead).
*
* @return bool
*
*/
public function hasPermission($moduleName, ?User $user = null, ?Page $page = null, $strict = false) {
return $this->loader->hasPermission($moduleName, $user, $page, $strict);
}
/**********************************************************************************************
* FINDER METHODS
*
*/
/**
* Find modules matching the given prefix (i.e. “Inputfield”)
*
* By default this method returns module class names matching the given prefix.
* To instead retrieve instantiated (ready-to-use) modules, specify boolean true
* for the second argument. Regardless of `$load` argument all returned arrays
* are indexed by module name.
*
* ~~~~~
* // Retrieve array of all Textformatter module names
* $items = $modules->findByPrefix('Textformatter');
*
* // Retrieve array of all Textformatter modules (ready to use)
* $items = $modules->findByPrefix('Textformatter', true);
* ~~~~~
*
* @param string $prefix Specify prefix, i.e. "Process", "Fieldtype", "Inputfield", etc.
* @param bool|int $load Specify one of the following (all indexed by module name):
* - Boolean true to return array of instantiated modules.
* - Boolean false to return array of module names (default).
* - Integer 1 to return array of module info for each matching module.
* - Integer 2 to return array of verbose module info for each matching module.
* - Integer 3 to return array of Module or ModulePlaceholder objects (whatever current state is). Added 3.0.146.
* @return array Returns array of module class names, module info arrays, or Module objects. In all cases, array indexes are class names.
*
*/
public function findByPrefix($prefix, $load = false) {
$results = array();
foreach($this as $moduleName => $value) {
if(stripos($moduleName, $prefix) !== 0) continue;
if($load === false) {
$results[$moduleName] = $moduleName;
} else if($load === true) {
$results[$moduleName] = $this->getModule($moduleName);
} else if($load === 1) {
$results[$moduleName] = $this->getModuleInfo($moduleName);
} else if($load === 2) {
$results[$moduleName] = $this->getModuleInfoVerbose($moduleName);
} else if($load === 3) {
$results[$moduleName] = $value;
} else {
$results[$moduleName] = $moduleName;
}
}
ksort($results);
return $results;
}
/**
* Find modules by matching a property or properties in their module info
*
* @param string|array $selector Specify one of the following:
* - Selector string to match module info.
* - Array of [ 'property' => 'value' ] to match in module info (this is not a selector array).
* - Name of property that will match module if not empty in module info.
* @param bool|int $load Specify one of the following:
* - Boolean true to return array of instantiated modules.
* - Boolean false to return array of module names (default).
* - Integer 1 to return array of module info for each matching module.
* - Integer 2 to return array of verbose module info for each matching module.
* @return array Array of modules, module names or module info arrays, indexed by module name.
*
*/
public function findByInfo($selector, $load = false) {
$selectors = null;
$keys = null;
$results = array();
$verbose = $load === 2;
$properties = array();
$has = '';
if(is_array($selector)) {
// find matching all values in array
$keys = $selector;
$properties = array_keys($keys);
} else if(!ctype_alnum($selector) && Selectors::stringHasOperator($selector)) {
// find by selectors
$selectors = new Selectors($selector);
if(!$verbose) foreach($selectors as $s) {
$properties = array_merge($properties, $s->fields());
}
} else {
// find non-empty property
$has = $selector;
$properties[] = $has;
}
// check if any verbose properties are part of the find
if(!$verbose) {
$moduleInfoVerboseKeys = $this->info->moduleInfoVerboseKeys;
foreach($properties as $property) {
if(!in_array($property, $moduleInfoVerboseKeys)) continue;
$verbose = true;
break;
}
}
$moduleInfoOptions = array(
'verbose' => $verbose,
'minify' => false
);
foreach($this->getModuleInfo('*', $moduleInfoOptions) as $info) {
$isMatch = false;
if($has) {
// simply check if property is non-empty
if(!empty($info[$has])) $isMatch = true;
} else if($selectors) {
// match selector
$total = 0;
$n = 0;
foreach($selectors as $selector) {
$total++;
$values = array();
foreach($selector->fields() as $property) {
if(isset($info[$property])) $values[] = $info[$property];
}
if($selector->matches($values)) $n++;
}
if($n && $n === $total) $isMatch = true;
} else if($keys) {
// match all values in $keys array
$n = 0;
foreach($keys as $key => $value) {
if($value === '*') {
// match any non-empty value
if(!empty($info[$key])) $n++;
} else {
// match exact value
if(isset($info[$key]) && $value == $info[$key]) $n++;
}
}
if($n && $n === count($keys)) $isMatch = true;
}
if($isMatch) {
$moduleName = $info['name'];
if(is_int($load)) {
$results[$moduleName] = $info;
} else if($load === true) {
$results[$moduleName] = $this->getModule($moduleName);
} else {
$results[$moduleName] = $moduleName;
}
}
}
return $results;
}
/**
* Find modules based on a selector string
*
* #pw-internal Almost always recommend using findByPrefix() instead
*
* @param string $selector Selector string
* @return WireArray of found modules, instantiated and ready-to-use
*
*/
public function find($selector) {
// ensures any ModulePlaceholders are loaded in the returned result.
$a = parent::find($selector);
if($a) {
foreach($a as $key => $value) {
$a[$key] = $this->get($value->className());
}
}
return $a;
}
/**********************************************************************************************
* INSTALLER METHODS
*
*/
/**
* Get an associative array [name => filename] for all modules that aren’t currently installed.
*
* #pw-internal
*
* @return array Array of elements with $moduleName => $pathName
*
*/
public function getInstallable() {
return $this->installableFiles;
}
/**
* Is the given module name installed?
*
* @param string $class Just a module class name, or optionally: `ModuleClassName>=1.2.3` (operator and version)
* @return bool True if installed, false if not
*
*/
public function isInstalled($class) {
if(is_object($class)) $class = $this->getModuleClass($class);
$class = (string) $class;
if(empty($class)) return false;
$operator = null;
$requiredVersion = null;
$currentVersion = null;
if(!ctype_alnum($class)) {
// class has something other than just a classname, likely operator + version
if(preg_match('/^([a-zA-Z0-9_]+)\s*([<>=!]+)\s*([\d.]+)$/', $class, $matches)) {
$class = $matches[1];
$operator = $matches[2];
$requiredVersion = $matches[3];
}
}
if($class === 'PHP' || $class === 'ProcessWire') {
$installed = true;
if($requiredVersion !== null) {
$currentVersion = $class === 'PHP' ? PHP_VERSION : $this->wire()->config->version;
}
} else {
$installed = isset($this->data[$class]);
if($installed && $requiredVersion !== null) {
$info = $this->info->getModuleInfo($class);
$currentVersion = $info['version'];
}
}
if($installed && $currentVersion !== null) {
$installed = $this->installer()->versionCompare($currentVersion, $requiredVersion, $operator);
}
return $installed;
}
/**
* Is the given module name installable? (i.e. not already installed)
*