-
Notifications
You must be signed in to change notification settings - Fork 1
/
Engine.php
executable file
·1701 lines (1496 loc) · 92.2 KB
/
Engine.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 PoP\ComponentModel\Engine;
use Exception;
use PoP\ComponentModel\Utils;
use PoP\ComponentModel\Engine_Vars;
use PoP\ComponentModel\GeneralUtils;
use PoP\ComponentModel\DataloadUtils;
use PoP\Hooks\Facades\HooksAPIFacade;
use PoP\ComponentModel\Modules\ModuleUtils;
use PoP\ComponentModel\Configuration\Request;
use PoP\Translation\Facades\TranslationAPIFacade;
use PoP\ComponentModel\Server\Utils as ServerUtils;
use PoP\ComponentModel\CheckpointProcessorManagerFactory;
use PoP\ComponentModel\Facades\Cache\PersistentCacheFacade;
use PoP\ComponentModel\TypeResolvers\TypeResolverInterface;
use PoP\ComponentModel\TypeResolvers\UnionTypeHelpers;
use PoP\ComponentModel\ModuleProcessors\DataloadingConstants;
use PoP\ComponentModel\Facades\Instances\InstanceManagerFacade;
use PoP\ComponentModel\Facades\ModelInstance\ModelInstanceFacade;
use PoP\ComponentModel\Facades\Schema\FeedbackMessageStoreFacade;
use PoP\ComponentModel\Facades\ModulePath\ModulePathHelpersFacade;
use PoP\ComponentModel\Facades\ModulePath\ModulePathManagerFacade;
use PoP\ComponentModel\Facades\Schema\FieldQueryInterpreterFacade;
use PoP\ComponentModel\TypeResolvers\UnionTypeResolverInterface;
use PoP\ComponentModel\Facades\ModuleFilters\ModuleFilterManagerFacade;
use PoP\ComponentModel\Facades\DataStructure\DataStructureManagerFacade;
use PoP\ComponentModel\Settings\SiteConfigurationProcessorManagerFactory;
use PoP\ComponentModel\Facades\ModuleProcessors\ModuleProcessorManagerFacade;
class Engine implements EngineInterface
{
public const CACHETYPE_IMMUTABLEDATASETSETTINGS = 'static-datasetsettings';
public const CACHETYPE_STATICDATAPROPERTIES = 'static-data-properties';
public const CACHETYPE_STATEFULDATAPROPERTIES = 'stateful-data-properties';
public const CACHETYPE_PROPS = 'props';
public $data;
public $helperCalculations;
public $model_props;
public $props;
protected $nocache_fields;
protected $moduledata;
protected $typeResolver_ids_data_fields;
protected $dbdata;
protected $backgroundload_urls;
protected $extra_routes;
protected $cachedsettings;
protected $outputData;
public function getOutputData()
{
return $this->outputData;
}
public function addBackgroundUrl($url, $targets)
{
$this->backgroundload_urls[$url] = $targets;
}
public function getEntryModule(): array
{
$siteconfiguration = SiteConfigurationProcessorManagerFactory::getInstance()->getProcessor();
if (!$siteconfiguration) {
throw new Exception('There is no Site Configuration. Hence, we can\'t continue.');
}
$fullyQualifiedModule = $siteconfiguration->getEntryModule();
if (!$fullyQualifiedModule) {
throw new Exception(sprintf('No entry module for this request (%s)', fullUrl()));
}
return $fullyQualifiedModule;
}
public function sendEtagHeader()
{
// ETag is needed for the Service Workers
// Also needed to use together with the Control-Cache header, to know when to refetch data from the server: https://developers.google.com/web/fundamentals/performance/optimizing-content-efficiency/http-caching
if (HooksAPIFacade::getInstance()->applyFilters('\PoP\ComponentModel\Engine:outputData:addEtagHeader', true)) {
// The same page will have different hashs only because of those random elements added each time,
// such as the unique_id and the current_time. So remove these to generate the hash
$differentiators = array(
POP_CONSTANT_UNIQUE_ID,
POP_CONSTANT_CURRENTTIMESTAMP,
POP_CONSTANT_RAND,
POP_CONSTANT_TIME,
);
$commoncode = str_replace($differentiators, '', json_encode($this->data));
// Also replace all those tags with content that, even if it's different, should not alter the output
// Eg: comments-count. Because adding a comment does not delete the cache, then the comments-count is allowed
// to be shown stale. So if adding a new comment, there's no need for the user to receive the
// "This page has been updated, click here to refresh it." notification
// Because we already got the JSON, then remove entries of the type:
// "userpostactivity-count":1, (if there are more elements after)
// and
// "userpostactivity-count":1
// Comment Leo 22/10/2017: ?module=settings doesn't have 'nocache-fields'
if ($this->nocache_fields) {
$commoncode = preg_replace('/"('.implode('|', $this->nocache_fields).')":[0-9]+,?/', '', $commoncode);
}
// Allow plug-ins to replace their own non-needed content (eg: thumbprints, defined in Core)
$commoncode = HooksAPIFacade::getInstance()->applyFilters('\PoP\ComponentModel\Engine:etag_header:commoncode', $commoncode);
header("ETag: ".hash('md5', $commoncode));
}
}
public function getExtraRoutes()
{
// The extra URIs must be cached! That is because we will change the requested URI in $vars, upon which the hook to inject extra URIs (eg: for page INITIALFRAMES) will stop working
if (!is_null($this->extra_routes)) {
return $this->extra_routes;
}
$this->extra_routes = array();
// The API cannot use getExtraRoutes()!!!!! Because the fields can't be applied to different resources! (Eg: author/leo/ and author/leo/?route=posts)
$vars = Engine_Vars::getVars();
if ($vars['scheme'] == POP_SCHEME_API) {
return $this->extra_routes;
}
if (ServerUtils::enableExtraRoutesByParams()) {
$this->extra_routes = $_REQUEST[GD_URLPARAM_EXTRAROUTES] ?? array();
$this->extra_routes = is_array($this->extra_routes) ? $this->extra_routes : array($this->extra_routes);
}
// Enable to add extra URLs in a fixed manner
$this->extra_routes = HooksAPIFacade::getInstance()->applyFilters(
'\PoP\ComponentModel\Engine:getExtraRoutes',
$this->extra_routes
);
return $this->extra_routes;
}
public function listExtraRouteVars()
{
if ($has_extra_routes = !empty($this->getExtraRoutes())) {
$model_instance_id = ModelInstanceFacade::getInstance()->getModelInstanceId();
$current_uri = removeDomain(Utils::getCurrentUrl());
}
return array($has_extra_routes, $model_instance_id, $current_uri);
}
public function generateData()
{
HooksAPIFacade::getInstance()->doAction('\PoP\ComponentModel\Engine:beginning');
// Process the request and obtain the results
$this->data = $this->helperCalculations = array();
$this->processAndGenerateData();
// See if there are extra URIs to be processed in this same request
if ($extra_routes = $this->getExtraRoutes()) {
// Combine the response for each extra URI together with the original response, merging all JSON objects together, but under each's URL/model_instance_id
// To obtain the nature for each URI, we use a hack: change the current URI and create a new WP object, which will process the query_vars and from there obtain the nature
// First make a backup of the current URI to set it again later
$vars = &Engine_Vars::$vars;
$current_route = $vars['route'];
// Process each extra URI, and merge its results with all others
foreach ($extra_routes as $route) {
// Reset $vars so that it gets created anew
$vars['route'] = $route;
// Process the request with the new $vars and merge it with all other results
$this->processAndGenerateData();
}
// Set the previous values back
$vars['route'] = $current_route;
}
// Add session/site meta
$this->addSharedMeta();
// If any formatter is passed, then format the data accordingly
$this->formatData();
// Keep only the data that is needed to be sent, and encode it as JSON
$this->calculateOutuputData();
// Send the ETag-header
$this->sendEtagHeader();
}
protected function formatData()
{
$dataStructureManager = DataStructureManagerFacade::getInstance();
$formatter = $dataStructureManager->getDataStructureFormatter();
$this->data = $formatter->getFormattedData($this->data);
}
public function calculateOutuputData()
{
$this->outputData = $this->getEncodedDataObject($this->data);
}
// Allow PoPWebPlatform_Engine to override this function
protected function getEncodedDataObject($data)
{
// Comment Leo 14/09/2018: Re-enable here:
// if (true) {
// unset($data['combinedstatedata']);
// }
return $data;
}
public function getModelPropsModuletree(array $module)
{
if ($useCache = ServerUtils::useCache()) {
$cachemanager = PersistentCacheFacade::getInstance();
$useCache = !is_null($cachemanager);
}
$moduleprocessor_manager = ModuleProcessorManagerFacade::getInstance();
$processor = $moduleprocessor_manager->getProcessor($module);
// Important: cannot use it if doing POST, because the request may have to be handled by a different block than the one whose data was cached
// Eg: doing GET on /add-post/ will show the form BLOCK_ADDPOST_CREATE, but doing POST on /add-post/ will bring the action ACTION_ADDPOST_CREATE
// First check if there's a cache stored
if ($useCache) {
$model_props = $cachemanager->getCacheByModelInstance(self::CACHETYPE_PROPS);
}
// If there is no cached one, or not using the cache, generate the props and cache it
if (!$model_props) {
$model_props = array();
$processor->initModelPropsModuletree($module, $model_props, array(), array());
if ($useCache) {
$cachemanager->storeCacheByModelInstance(self::CACHETYPE_PROPS, $model_props);
}
}
return $model_props;
}
// Notice that $props is passed by copy, this way the input $model_props and the returned $immutable_plus_request_props are different objects
public function addRequestPropsModuletree(array $module, array $props)
{
$moduleprocessor_manager = ModuleProcessorManagerFacade::getInstance();
$processor = $moduleprocessor_manager->getProcessor($module);
// The input $props is the model_props. We add, on object, the mutableonrequest props, resulting in a "static + mutableonrequest" props object
$processor->initRequestPropsModuletree($module, $props, array(), array());
return $props;
}
protected function processAndGenerateData()
{
$vars = Engine_Vars::getVars();
// Externalize logic into function so it can be overridden by PoP Web Platform Engine
$dataoutputitems = $vars['dataoutputitems'];
// From the state we know if to process static/staful content or both
$datasources = $vars['datasources'];
// Get the entry module based on the application configuration and the nature
$module = $this->getEntryModule();
// Save it to be used by the children class
// Static props are needed for both static/mutableonrequest operations, so build it always
$this->model_props = $this->getModelPropsModuletree($module);
// If only getting static content, then no need to add the mutableonrequest props
if ($datasources == GD_URLPARAM_DATASOURCES_ONLYMODEL) {
$this->props = $this->model_props;
} else {
$this->props = $this->addRequestPropsModuletree($module, $this->model_props);
}
// Allow for extra operations (eg: calculate resources)
HooksAPIFacade::getInstance()->doAction(
'\PoP\ComponentModel\Engine:helperCalculations',
array(&$this->helperCalculations),
$module,
array(&$this->props)
);
$data = [];
if (in_array(GD_URLPARAM_DATAOUTPUTITEMS_DATASETMODULESETTINGS, $dataoutputitems)) {
$data = array_merge(
$data,
$this->getModuleDatasetSettings($module, $this->model_props, $this->props)
);
}
// Comment Leo 20/01/2018: we must first initialize all the settings, and only later add the data.
// That is because calculating the data may need the values from the settings. Eg: for the resourceLoader,
// calculating $loadingframe_resources needs to know all the Handlebars templates from the sitemapping as to generate file "resources.js",
// which is done through an action, called through getData()
// Data = dbobjectids (data-ids) + feedback + database
if (in_array(GD_URLPARAM_DATAOUTPUTITEMS_MODULEDATA, $dataoutputitems)
|| in_array(GD_URLPARAM_DATAOUTPUTITEMS_DATABASES, $dataoutputitems)
) {
$data = array_merge(
$data,
$this->getModuleData($module, $this->model_props, $this->props)
);
if (in_array(GD_URLPARAM_DATAOUTPUTITEMS_DATABASES, $dataoutputitems)) {
$data = array_merge(
$data,
$this->getDatabases()
);
}
}
list($has_extra_routes, $model_instance_id, $current_uri) = $this->listExtraRouteVars();
if (in_array(GD_URLPARAM_DATAOUTPUTITEMS_META, $dataoutputitems)
) {
// Also add the request, session and site meta.
// IMPORTANT: Call these methods after doing ->getModuleData, since the background_urls and other info is calculated there and printed here
if ($requestmeta = $this->getRequestMeta()) {
$data['requestmeta'] = $has_extra_routes ? array($current_uri => $requestmeta) : $requestmeta;
}
}
// Comment Leo 14/09/2018: Re-enable here:
// // Combine the statelessdata and mutableonrequestdata objects
// if ($data['modulesettings']) {
// $data['modulesettings']['combinedstate'] = array_merge_recursive(
// $data['modulesettings']['immutable'] ?? array()
// $data['modulesettings']['mutableonmodel'] ?? array()
// $data['modulesettings']['mutableonrequest'] ?? array(),
// );
// }
// if ($data['moduledata']) {
// $data['moduledata']['combinedstate'] = array_merge_recursive(
// $data['moduledata']['immutable'] ?? array()
// $data['moduledata']['mutableonmodel'] ?? array()
// $data['moduledata']['mutableonrequest'] ?? array(),
// );
// }
// if ($data['datasetmoduledata']) {
// $data['datasetmoduledata']['combinedstate'] = array_merge_recursive(
// $data['datasetmoduledata']['immutable'] ?? array()
// $data['datasetmoduledata']['mutableonmodel'] ?? array()
// $data['datasetmoduledata']['mutableonrequest'] ?? array(),
// );
// }
// Do array_replace_recursive because it may already contain data from doing 'extra-uris'
$this->data = array_replace_recursive(
$this->data,
$data
);
}
protected function addSharedMeta()
{
$vars = Engine_Vars::getVars();
// Externalize logic into function so it can be overridden by PoP Web Platform Engine
$dataoutputitems = $vars['dataoutputitems'];
if (in_array(GD_URLPARAM_DATAOUTPUTITEMS_META, $dataoutputitems)
) {
// Also add the request, session and site meta.
// IMPORTANT: Call these methods after doing ->getModuleData, since the background_urls and other info is calculated there and printed here
// If it has extra-uris, pass along this information, so that the client can fetch the setting from under $model_instance_id ("mutableonmodel") and $uri ("mutableonrequest")
if ($this->getExtraRoutes()) {
$this->data['requestmeta'][POP_JS_MULTIPLEROUTES] = true;
}
if ($sitemeta = $this->getSiteMeta()) {
$this->data['sitemeta'] = $sitemeta;
}
if (in_array(GD_URLPARAM_DATAOUTPUTITEMS_SESSION, $dataoutputitems)) {
if ($sessionmeta = $this->getSessionMeta()) {
$this->data['sessionmeta'] = $sessionmeta;
}
}
}
}
public function getModuleDatasetSettings(array $module, $model_props, array &$props)
{
if ($useCache = ServerUtils::useCache()) {
$cachemanager = PersistentCacheFacade::getInstance();
$useCache = !is_null($cachemanager);
}
$moduleprocessor_manager = ModuleProcessorManagerFacade::getInstance();
$ret = array();
$processor = $moduleprocessor_manager->getProcessor($module);
// From the state we know if to process static/staful content or both
$vars = Engine_Vars::getVars();
$dataoutputmode = $vars['dataoutputmode'];
// Templates: What modules must be executed after call to loadMore is back with data:
// CB: list of modules to merge
$this->cachedsettings = false;
// First check if there's a cache stored
if ($useCache) {
$immutable_datasetsettings = $cachemanager->getCacheByModelInstance(self::CACHETYPE_IMMUTABLEDATASETSETTINGS);
}
// If there is no cached one, generate the configuration and cache it
$this->cachedsettings = false;
if ($immutable_datasetsettings) {
$this->cachedsettings = true;
} else {
$immutable_datasetsettings = $processor->getImmutableSettingsDatasetmoduletree($module, $model_props);
if ($useCache) {
$cachemanager->storeCacheByModelInstance(self::CACHETYPE_IMMUTABLEDATASETSETTINGS, $immutable_datasetsettings);
}
}
// If there are multiple URIs, then the results must be returned under the corresponding $model_instance_id for "mutableonmodel", and $url for "mutableonrequest"
list($has_extra_routes, $model_instance_id, $current_uri) = $this->listExtraRouteVars();
if ($dataoutputmode == GD_URLPARAM_DATAOUTPUTMODE_SPLITBYSOURCES) {
if ($immutable_datasetsettings) {
$ret['datasetmodulesettings']['immutable'] = $immutable_datasetsettings;
}
} elseif ($dataoutputmode == GD_URLPARAM_DATAOUTPUTMODE_COMBINED) {
// If everything is combined, then it belongs under "mutableonrequest"
if ($combined_datasetsettings = $immutable_datasetsettings) {
$ret['datasetmodulesettings'] = $has_extra_routes ? array($current_uri => $combined_datasetsettings) : $combined_datasetsettings;
}
}
return $ret;
}
public function getRequestMeta()
{
$meta = array(
POP_CONSTANT_ENTRYMODULE => $this->getEntryModule()[1],
POP_UNIQUEID => POP_CONSTANT_UNIQUE_ID,
GD_URLPARAM_URL => Utils::getCurrentUrl(),
'modelinstanceid' => ModelInstanceFacade::getInstance()->getModelInstanceId(),
);
if ($this->backgroundload_urls) {
$meta[GD_URLPARAM_BACKGROUNDLOADURLS] = $this->backgroundload_urls;
};
// Starting from what modules must do the rendering. Allow for empty arrays (eg: modulepaths[]=somewhatevervalue)
$modulefilter_manager = ModuleFilterManagerFacade::getInstance();
$not_excluded_module_sets = $modulefilter_manager->getNotExcludedModuleSets();
if (!is_null($not_excluded_module_sets)) {
// Print the settings id of each module. Then, a module can feed data to another one by sharing the same settings id (eg: self::MODULE_BLOCK_USERAVATAR_EXECUTEUPDATE and PoP_UserAvatarProcessors_Module_Processor_UserBlocks::MODULE_BLOCK_USERAVATAR_UPDATE)
$filteredsettings = array();
foreach ($not_excluded_module_sets as $modules) {
$filteredsettings[] = array_map(
[ModuleUtils::class, 'getModuleOutputName'],
$modules
);
}
$meta['filteredmodules'] = $filteredsettings;
}
// Any errors? Send them back
if (Utils::$errors) {
if (count(Utils::$errors) > 1) {
$meta[GD_URLPARAM_ERROR] = TranslationAPIFacade::getInstance()->__('Ops, there were some errors:', 'pop-engine').implode('<br/>', Utils::$errors);
} else {
$meta[GD_URLPARAM_ERROR] = TranslationAPIFacade::getInstance()->__('Ops, there was an error: ', 'pop-engine').Utils::$errors[0];
}
}
return HooksAPIFacade::getInstance()->applyFilters(
'\PoP\ComponentModel\Engine:request-meta',
$meta
);
}
public function getSessionMeta()
{
return HooksAPIFacade::getInstance()->applyFilters(
'\PoP\ComponentModel\Engine:session-meta',
array()
);
}
public function getSiteMeta()
{
$meta = array();
if (Utils::fetchingSite()) {
$vars = Engine_Vars::getVars();
$meta[GD_URLPARAM_VERSION] = $vars['version'];
$meta[GD_URLPARAM_DATAOUTPUTMODE] = $vars['dataoutputmode'];
$meta[GD_URLPARAM_DATABASESOUTPUTMODE] = $vars['dboutputmode'];
if ($vars['format']) {
$meta[GD_URLPARAM_SETTINGSFORMAT] = $vars['format'];
}
if ($vars['mangled']) {
$meta[Request::URLPARAM_MANGLED] = $vars['mangled'];
}
if (ServerUtils::enableConfigByParams() && $vars['config']) {
$meta[POP_URLPARAM_CONFIG] = $vars['config'];
}
if ($vars['stratum']) {
$meta[GD_URLPARAM_STRATUM] = $vars['stratum'];
}
// Tell the front-end: are the results from the cache? Needed for the editor, to initialize it since WP will not execute the code
if (!is_null($this->cachedsettings)) {
$meta['cachedsettings'] = $this->cachedsettings;
};
}
return HooksAPIFacade::getInstance()->applyFilters(
'\PoP\ComponentModel\Engine:site-meta',
$meta
);
}
private function combineIdsDatafields(&$typeResolver_ids_data_fields, $typeResolver_class, $ids, $data_fields, $conditional_data_fields = [])
{
$typeResolver_ids_data_fields[$typeResolver_class] = $typeResolver_ids_data_fields[$typeResolver_class] ?? array();
foreach ($ids as $id) {
// Make sure to always add the 'id' data-field, since that's the key for the dbobject in the client database
$typeResolver_ids_data_fields[$typeResolver_class][(string)$id]['direct'] = $typeResolver_ids_data_fields[$typeResolver_class][(string)$id]['direct'] ?? array('id');
$typeResolver_ids_data_fields[$typeResolver_class][(string)$id]['direct'] = array_values(array_unique(array_merge(
$typeResolver_ids_data_fields[$typeResolver_class][(string)$id]['direct'],
$data_fields ?? array()
)));
// The conditional data fields have the condition data fields, as key, and the list of conditional data fields to load if the condition one is successful, as value
$typeResolver_ids_data_fields[$typeResolver_class][(string)$id]['conditional'] = $typeResolver_ids_data_fields[$typeResolver_class][(string)$id]['conditional'] ?? array();
foreach ($conditional_data_fields as $conditionDataField => $conditionalDataFields) {
$typeResolver_ids_data_fields[$typeResolver_class][(string)$id]['conditional'][$conditionDataField] = array_merge(
$typeResolver_ids_data_fields[$typeResolver_class][(string)$id]['conditional'][$conditionDataField] ?? [],
$conditionalDataFields
);
}
}
}
private function doAddDatasetToDatabase(&$database, $database_key, $dataitems)
{
// Save in the database under the corresponding database-key (this way, different dataloaders, like 'list-users' and 'author',
// can both save their results under database key 'users'
if (!$database[$database_key]) {
$database[$database_key] = $dataitems;
} else {
$dbKey = $database_key;
// array_merge_recursive doesn't work as expected (it merges 2 hashmap arrays into an array, so then I manually do a foreach instead)
foreach ($dataitems as $id => $dbobject_values) {
if (!$database[$dbKey][(string)$id]) {
$database[$dbKey][(string)$id] = array();
}
$database[$dbKey][(string)$id] = array_merge(
$database[$dbKey][(string)$id],
$dbobject_values
);
}
}
}
private function addDatasetToDatabase(&$database, TypeResolverInterface $typeResolver, string $dbKey, $dataitems, array $resultIDItems, bool $addEntryIfError = false)
{
// Do not create the database key entry when there are no items, or it produces an error when deep merging the database object in the webplatform with that from the response
if (!$dataitems) {
return;
}
$isUnionTypeResolver = $typeResolver instanceof UnionTypeResolverInterface;
if ($isUnionTypeResolver) {
$instanceManager = InstanceManagerFacade::getInstance();
// Get the actual type for each entity, and add the entry there
$convertedTypeResolverClassDataItems = $convertedTypeResolverClassDBKeys = [];
$noTypeResolverDataItems = [];
foreach ($dataitems as $resultItemID => $dataItem) {
// Obtain the type of the object
$exists = false;
if ($resultItem = $resultIDItems[$resultItemID]) {
$targetTypeResolver = $typeResolver->getTargetTypeResolver($resultItem);
if (!is_null($targetTypeResolver)) {
$exists = true;
// The ID will contain the type. Remove it
list(
$resultItemDBKey,
$resultItemID
) = UnionTypeHelpers::extractDBObjectTypeAndID($resultItemID);
$convertedTypeResolverClass = get_class($targetTypeResolver);
$convertedTypeResolverClassDataItems[$convertedTypeResolverClass][$resultItemID] = $dataItem;
$convertedTypeResolverClassDBKeys[$convertedTypeResolverClass] = $resultItemDBKey;
}
}
if (!$exists && $addEntryIfError) {
// If the UnionTypeResolver doesn't have a type to process the dataItem, show the error under its own ID
$noTypeResolverDataItems[$resultItemID] = $dataItem;
}
}
foreach ($convertedTypeResolverClassDataItems as $convertedTypeResolverClass => $convertedDataItems) {
$convertedTypeResolver = $instanceManager->getInstance($convertedTypeResolverClass);
$convertedDBKey = $convertedTypeResolverClassDBKeys[$convertedTypeResolverClass];
$this->addDatasetToDatabase($database, $convertedTypeResolver, $convertedDBKey, $convertedDataItems, $resultIDItems, $addEntryIfError);
}
// Add the errors under the UnionTypeResolver key
if ($noTypeResolverDataItems) {
$this->doAddDatasetToDatabase($database, $dbKey, $noTypeResolverDataItems);
}
} else {
$this->doAddDatasetToDatabase($database, $dbKey, $dataitems);
}
}
protected function getInterreferencedModuleFullpaths(array $module, array &$props)
{
$paths = array();
$this->addInterreferencedModuleFullpaths($paths, array(), $module, $props);
return $paths;
}
private function addInterreferencedModuleFullpaths(&$paths, $module_path, array $module, array &$props)
{
$moduleprocessor_manager = ModuleProcessorManagerFacade::getInstance();
$processor = $moduleprocessor_manager->getProcessor($module);
$moduleFullName = ModuleUtils::getModuleFullName($module);
$modulefilter_manager = ModuleFilterManagerFacade::getInstance();
// If modulepaths is provided, and we haven't reached the destination module yet, then do not execute the function at this level
if (!$modulefilter_manager->excludeModule($module, $props)) {
// If the current module loads data, then add its path to the list
if ($interreferenced_modulepath = $processor->getDataFeedbackInterreferencedModulepath($module, $props)) {
$referenced_modulepath = ModulePathHelpersFacade::getInstance()->stringifyModulePath($interreferenced_modulepath);
$paths[$referenced_modulepath] = $paths[$referenced_modulepath] ?? array();
$paths[$referenced_modulepath][] = array_merge(
$module_path,
array(
$module
)
);
}
}
$submodule_path = array_merge(
$module_path,
array(
$module,
)
);
// Propagate to its inner modules
$submodules = $processor->getAllSubmodules($module);
$submodules = $modulefilter_manager->removeExcludedSubmodules($module, $submodules);
// This function must be called always, to register matching modules into requestmeta.filtermodules even when the module has no submodules
$modulefilter_manager->prepareForPropagation($module, $props);
foreach ($submodules as $submodule) {
$this->addInterreferencedModuleFullpaths($paths, $submodule_path, $submodule, $props[$moduleFullName][POP_PROPS_SUBMODULES]);
}
$modulefilter_manager->restoreFromPropagation($module, $props);
}
protected function getDataloadingModuleFullpaths(array $module, array &$props)
{
$paths = array();
$this->addDataloadingModuleFullpaths($paths, array(), $module, $props);
return $paths;
}
private function addDataloadingModuleFullpaths(&$paths, $module_path, array $module, array &$props)
{
$moduleprocessor_manager = ModuleProcessorManagerFacade::getInstance();
$processor = $moduleprocessor_manager->getProcessor($module);
$moduleFullName = ModuleUtils::getModuleFullName($module);
$modulefilter_manager = ModuleFilterManagerFacade::getInstance();
// If modulepaths is provided, and we haven't reached the destination module yet, then do not execute the function at this level
if (!$modulefilter_manager->excludeModule($module, $props)) {
// If the current module loads data, then add its path to the list
if ($processor->moduleLoadsData($module)) {
$paths[] = array_merge(
$module_path,
array(
$module
)
);
}
}
$submodule_path = array_merge(
$module_path,
array(
$module,
)
);
// Propagate to its inner modules
$submodules = $processor->getAllSubmodules($module);
$submodules = $modulefilter_manager->removeExcludedSubmodules($module, $submodules);
// This function must be called always, to register matching modules into requestmeta.filtermodules even when the module has no submodules
$modulefilter_manager->prepareForPropagation($module, $props);
foreach ($submodules as $submodule) {
$this->addDataloadingModuleFullpaths($paths, $submodule_path, $submodule, $props[$moduleFullName][POP_PROPS_SUBMODULES]);
}
$modulefilter_manager->restoreFromPropagation($module, $props);
}
protected function assignValueForModule(&$array, $module_path, array $module, $key, $value)
{
$array_pointer = &$array;
foreach ($module_path as $submodule) {
// Notice that when generating the array for the response, we don't use $module anymore, but $moduleOutputName
$submoduleOutputName = ModuleUtils::getModuleOutputName($submodule);
// If the path doesn't exist, create it
if (!isset($array_pointer[$submoduleOutputName][GD_JS_SUBMODULES])) {
$array_pointer[$submoduleOutputName][GD_JS_SUBMODULES] = array();
}
// The pointer is the location in the array where the value will be set
$array_pointer = &$array_pointer[$submoduleOutputName][GD_JS_SUBMODULES];
}
$moduleOutputName = ModuleUtils::getModuleOutputName($module);
$array_pointer[$moduleOutputName][$key] = $value;
}
public function validateCheckpoints($checkpoints)
{
$checkpointprocessor_manager = CheckpointProcessorManagerFactory::getInstance();
// Iterate through the list of all checkpoints, process all of them, if any produces an error, already return it
foreach ($checkpoints as $checkpoint) {
$result = $checkpointprocessor_manager->getProcessor($checkpoint)->process($checkpoint);
if (GeneralUtils::isError($result)) {
return $result;
}
}
return true;
}
protected function getModulePathKey($module_path, array $module)
{
$moduleFullName = ModuleUtils::getModuleFullName($module);
return $moduleFullName.'-'.implode('.', $module_path);
}
// This function is not private, so it can be accessed by the automated emails to regenerate the html for each user
public function getModuleData($root_module, $root_model_props, $root_props)
{
$instanceManager = InstanceManagerFacade::getInstance();
if ($useCache = ServerUtils::useCache()) {
$cachemanager = PersistentCacheFacade::getInstance();
$useCache = !is_null($cachemanager);
}
$moduleprocessor_manager = ModuleProcessorManagerFacade::getInstance();
$root_processor = $moduleprocessor_manager->getProcessor($root_module);
// From the state we know if to process static/staful content or both
$vars = Engine_Vars::getVars();
$datasources = $vars['datasources'];
$dataoutputmode = $vars['dataoutputmode'];
$dataoutputitems = $vars['dataoutputitems'];
$add_meta = in_array(GD_URLPARAM_DATAOUTPUTITEMS_META, $dataoutputitems);
$immutable_moduledata = $mutableonmodel_moduledata = $mutableonrequest_moduledata = array();
$immutable_datasetmoduledata = $mutableonmodel_datasetmoduledata = $mutableonrequest_datasetmoduledata = array();
if ($add_meta) {
$immutable_datasetmodulemeta = $mutableonmodel_datasetmodulemeta = $mutableonrequest_datasetmodulemeta = array();
}
$this->dbdata = array();
// Save all the BACKGROUND_LOAD urls to send back to the browser, to load immediately again (needed to fetch non-cacheable data-fields)
$this->backgroundload_urls = array();
// Load under global key (shared by all pagesections / blocks)
$this->typeResolverClass_ids_data_fields = array();
// Allow PoP UserState to add the lazy-loaded userstate data triggers
HooksAPIFacade::getInstance()->doAction(
'\PoP\ComponentModel\Engine:getModuleData:start',
$root_module,
array(&$root_model_props),
array(&$root_props),
array(&$this->helperCalculations),
$this
);
// First check if there's a cache stored
if ($useCache) {
$immutable_data_properties = $cachemanager->getCacheByModelInstance(self::CACHETYPE_STATICDATAPROPERTIES);
$mutableonmodel_data_properties = $cachemanager->getCacheByModelInstance(self::CACHETYPE_STATEFULDATAPROPERTIES);
}
// If there is no cached one, generate the props and cache it
if (!$immutable_data_properties) {
$immutable_data_properties = $root_processor->getImmutableDataPropertiesDatasetmoduletree($root_module, $root_model_props);
$mutableonmodel_data_properties = $root_processor->getMutableonmodelDataPropertiesDatasetmoduletree($root_module, $root_model_props);
if ($useCache) {
$cachemanager->storeCacheByModelInstance(self::CACHETYPE_STATICDATAPROPERTIES, $immutable_data_properties);
$cachemanager->storeCacheByModelInstance(self::CACHETYPE_STATEFULDATAPROPERTIES, $mutableonmodel_data_properties);
}
}
$model_data_properties = array_merge_recursive(
$immutable_data_properties,
$mutableonmodel_data_properties
);
if ($datasources == GD_URLPARAM_DATASOURCES_ONLYMODEL) {
$root_data_properties = $model_data_properties;
} else {
$mutableonrequest_data_properties = $root_processor->getMutableonrequestDataPropertiesDatasetmoduletree($root_module, $root_props);
$root_data_properties = array_merge_recursive(
$model_data_properties,
$mutableonrequest_data_properties
);
}
// Get the list of all modules which calculate their data feedback using another module's results
$interreferenced_modulefullpaths = $this->getInterreferencedModuleFullpaths($root_module, $root_props);
// Get the list of all modules which load data, as a list of the module path starting from the top element (the entry module)
$module_fullpaths = $this->getDataloadingModuleFullpaths($root_module, $root_props);
$module_path_manager = ModulePathManagerFacade::getInstance();
// The modules below are already included, so tell the filtermanager to not validate if they must be excluded or not
$modulefilter_manager = ModuleFilterManagerFacade::getInstance();
$modulefilter_manager->neverExclude(true);
foreach ($module_fullpaths as $module_path) {
// The module is the last element in the path.
// Notice that the module is removed from the path, providing the path to all its properties
$module = array_pop($module_path);
$moduleFullName = ModuleUtils::getModuleFullName($module);
// Artificially set the current path on the path manager. It will be needed in getDatasetmeta, which calls getDataloadSource, which needs the current path
$module_path_manager->setPropagationCurrentPath($module_path);
// Data Properties: assign by reference, so that changes to this variable are also performed in the original variable
$data_properties = &$root_data_properties;
foreach ($module_path as $submodule) {
$submoduleFullName = ModuleUtils::getModuleFullName($submodule);
$data_properties = &$data_properties[$submoduleFullName][GD_JS_SUBMODULES];
}
$data_properties = &$data_properties[$moduleFullName][POP_CONSTANT_DATAPROPERTIES];
$datasource = $data_properties[DataloadingConstants::DATASOURCE];
// If we are only requesting data from the model alone, and this dataloading module depends on mutableonrequest, then skip it
if ($datasources == GD_URLPARAM_DATASOURCES_ONLYMODEL && $datasource == POP_DATALOAD_DATASOURCE_MUTABLEONREQUEST) {
continue;
}
// Load data if the property Skip Data Load is not true
$load_data = !$data_properties[DataloadingConstants::SKIPDATALOAD];
// ------------------------------------------
// Checkpoint validation
// ------------------------------------------
// Load data if the checkpoint did not fail
if ($load_data && $checkpoints = $data_properties[GD_DATALOAD_DATAACCESSCHECKPOINTS]) {
// Check if the module fails checkpoint validation. If so, it must not load its data or execute the actionexecuter
$dataaccess_checkpoint_validation = $this->validateCheckpoints($checkpoints);
$load_data = !GeneralUtils::isError($dataaccess_checkpoint_validation);
}
// The $props is directly moving the array to the corresponding path
$props = &$root_props;
$model_props = &$root_model_props;
foreach ($module_path as $submodule) {
$submoduleFullName = ModuleUtils::getModuleFullName($submodule);
$props = &$props[$submoduleFullName][POP_PROPS_SUBMODULES];
$model_props = &$model_props[$submoduleFullName][POP_PROPS_SUBMODULES];
}
if (in_array(
$datasource,
array(
POP_DATALOAD_DATASOURCE_IMMUTABLE,
POP_DATALOAD_DATASOURCE_MUTABLEONMODEL,
)
)
) {
$module_props = &$model_props;
} elseif ($datasource == POP_DATALOAD_DATASOURCE_MUTABLEONREQUEST) {
$module_props = &$props;
}
$processor = $moduleprocessor_manager->getProcessor($module);
// The module path key is used for storing temporary results for later retrieval
$module_path_key = $this->getModulePathKey($module_path, $module);
// If data is not loaded, then an empty array will be saved for the dbobject ids
$dataset_meta = $dbObjectIDs = $typeDBObjectIDs = array();
$executed = $dbObjectIDOrIDs = $typeDBObjectIDOrIDs = $typeResolver_class = null;
if ($load_data) {
// ------------------------------------------
// Action Executers
// ------------------------------------------
// Allow to plug-in functionality here (eg: form submission)
// Execute at the very beginning, so the result of the execution can also be fetched later below
// (Eg: creation of a new location => retrieving its data / Adding a new comment)
// Pass data_properties so these can also be modified (eg: set id of newly created Location)
if ($actionExecuterClass = $processor->getActionexecuterClass($module)) {
if ($processor->executeAction($module, $props)) {
// Validate that the actionexecution must be triggered through its own checkpoints
$execute = true;
if ($actionexecution_checkpoints = $data_properties[GD_DATALOAD_ACTIONEXECUTIONCHECKPOINTS]) {
// Check if the module fails checkpoint validation. If so, it must not load its data or execute the actionexecuter
$actionexecution_checkpoint_validation = $this->validateCheckpoints($actionexecution_checkpoints);
$execute = !GeneralUtils::isError($actionexecution_checkpoint_validation);
}
if ($execute) {
$instanceManager = InstanceManagerFacade::getInstance();
$actionexecuter = $instanceManager->getInstance($actionExecuterClass);
$executed = $actionexecuter->execute($data_properties);
}
}
}
// Allow modules to change their data_properties based on the actionexecution of previous modules.
$processor->prepareDataPropertiesAfterActionexecution($module, $module_props, $data_properties);
// Re-calculate $data_load, it may have been changed by `prepareDataPropertiesAfterActionexecution`
$load_data = !$data_properties[DataloadingConstants::SKIPDATALOAD];
if ($load_data) {
$typeResolver_class = $processor->getTypeResolverClass($module);
$typeResolver = $instanceManager->getInstance((string)$typeResolver_class);
$isUnionTypeResolver = $typeResolver instanceof UnionTypeResolverInterface;
// ------------------------------------------
// Data Properties Query Args: add mutableonrequest data
// ------------------------------------------
// Execute and get the ids and the meta
$dbObjectIDOrIDs = $processor->getDBObjectIDOrIDs($module, $module_props, $data_properties);
// If the type is union, we must add the type to each object
if (!is_null($dbObjectIDOrIDs)) {
if ($isUnionTypeResolver) {
$typeDBObjectIDOrIDs = $typeResolver->getQualifiedDBObjectIDOrIDs($dbObjectIDOrIDs);
} else {
$typeDBObjectIDOrIDs = $dbObjectIDOrIDs;
}
}
$dbObjectIDs = is_array($dbObjectIDOrIDs) ? $dbObjectIDOrIDs : array($dbObjectIDOrIDs);
$typeDBObjectIDs = is_array($typeDBObjectIDOrIDs) ? $typeDBObjectIDOrIDs : array($typeDBObjectIDOrIDs);
// Store the ids under $data under key dataload_name => id
$data_fields = $data_properties['data-fields'] ?? array();
$conditional_data_fields = $data_properties['conditional-data-fields'] ?? array();
$this->combineIdsDatafields($this->typeResolverClass_ids_data_fields, $typeResolver_class, $typeDBObjectIDs, $data_fields, $conditional_data_fields);
// Add the IDs to the possibly-already produced IDs for this typeResolver
$this->initializeTypeResolverEntry($this->dbdata, $typeResolver_class, $module_path_key);
$this->dbdata[$typeResolver_class][$module_path_key]['ids'] = array_merge(
$this->dbdata[$typeResolver_class][$module_path_key]['ids'],
$typeDBObjectIDs
);
// The supplementary dbobject data is independent of the typeResolver of the block.
// Even if it is STATIC, the extend ids must be loaded. That's why we load the extend now,
// Before checking below if the checkpoint failed or if the block content must not be loaded.
// Eg: Locations Map for the Create Individual Profile: it allows to pre-select locations,
// these ones must be fetched even if the block has a static typeResolver
// If it has extend, add those ids under its typeResolver_class
$dataload_extend_settings = $processor->getModelSupplementaryDbobjectdataModuletree($module, $model_props);
if ($datasource == POP_DATALOAD_DATASOURCE_MUTABLEONREQUEST) {
$dataload_extend_settings = array_merge_recursive(
$dataload_extend_settings,
$processor->getMutableonrequestSupplementaryDbobjectdataModuletree($module, $props)
);
}
foreach ($dataload_extend_settings as $extend_typeResolver_class => $extend_data_properties) {
// Get the info for the subcomponent typeResolver
$extend_data_fields = $extend_data_properties['data-fields'] ? $extend_data_properties['data-fields'] : array();
$extend_conditional_data_fields = $extend_data_properties['conditional-data-fields'] ? $extend_data_properties['conditional-data-fields'] : array();
$extend_ids = $extend_data_properties['ids'];
$this->combineIdsDatafields($this->typeResolverClass_ids_data_fields, $extend_typeResolver_class, $extend_ids, $extend_data_fields, $extend_conditional_data_fields);
// This is needed to add the typeResolver-extend IDs, for if nobody else creates an entry for this typeResolver
$this->initializeTypeResolverEntry($this->dbdata, $extend_typeResolver_class, $module_path_key);
}
// Keep iterating for its subcomponents
$this->integrateSubcomponentDataProperties($this->dbdata, $data_properties, $typeResolver_class, $module_path_key);
}
}