-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathRequestService.php
More file actions
1868 lines (1566 loc) · 77.1 KB
/
RequestService.php
File metadata and controls
1868 lines (1566 loc) · 77.1 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 CommonGateway\CoreBundle\Service;
use Adbar\Dot;
use App\Entity\Application;
use App\Entity\Endpoint;
use App\Entity\Entity;
use App\Entity\Gateway as Source;
use App\Entity\ObjectEntity;
use App\Entity\Mapping;
use App\Event\ActionEvent;
use App\Exception\GatewayException;
use App\Service\SynchronizationService;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\Common\Collections\Criteria;
use Doctrine\ORM\EntityManagerInterface;
use Exception;
use GuzzleHttp\Exception\ClientException;
use GuzzleHttp\Exception\ConnectException;
use GuzzleHttp\Exception\ServerException;
use GuzzleHttp\Promise\Promise;
use GuzzleHttp\Promise\Utils;
use GuzzleHttp\TransferStats;
use Psr\Log\LoggerInterface;
use Ramsey\Uuid\Uuid;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\HttpClient\Exception\JsonException;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\HttpKernel\Exception\NotAcceptableHttpException;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Serializer\Encoder\XmlEncoder;
use Symfony\Component\Serializer\SerializerInterface;
use Symfony\Component\Serializer\Encoder\CsvEncoder;
use Symfony\Component\Serializer\Serializer;
/**
* Handles incoming request from endpoints or controllers that relate to the gateways object structure (eav).
*
* @Author Ruben van der Linde <ruben@conduction.nl>, Wilco Louwerse <wilco@conduction.nl>, Robert Zondervan <robert@conduction.nl>, Barry Brands <barry@conduction.nl>
*
* @license EUPL <https://github.com/ConductionNL/contactcatalogus/blob/master/LICENSE.md>
*
* @category Service
*/
class RequestService
{
/**
* @var EntityManagerInterface
*/
private EntityManagerInterface $entityManager;
/**
* @var CacheService
*/
private CacheService $cacheService;
/**
* @var GatewayResourceService
*/
private GatewayResourceService $resourceService;
/**
* @var MappingService
*/
private MappingService $mappingService;
/**
* @var ValidationService
*/
private ValidationService $validationService;
/**
* @var FileSystemHandleService The fileSystem service
*/
private FileSystemHandleService $fileSystemService;
/**
* @var array
*/
private array $configuration;
/**
* @var array
*/
private array $data;
/**
* @var ObjectEntity
*/
private ObjectEntity $object;
/**
* @var string
*/
private string $identification;
/**
* @var $schema
*/
private $schema;
// @Todo: cast to Entity|Boolean in php 8.
/**
* @var ReadUnreadService
*/
private ReadUnreadService $readUnreadService;
/**
* @var SynchronizationService
*/
private SynchronizationService $syncService;
/**
* @var CallService
*/
private CallService $callService;
/**
* @var Security
*/
private Security $security;
/**
* @var EventDispatcherInterface
*/
private EventDispatcherInterface $eventDispatcher;
/**
* @var SerializerInterface
*/
private SerializerInterface $serializer;
/**
* @var SessionInterface
*/
private SessionInterface $session;
/**
* @var LoggerInterface
*/
private LoggerInterface $logger;
/**
* @var DownloadService
*/
private DownloadService $downloadService;
private array $requestTimes;
/**
* The constructor sets al needed variables.
*
* @param EntityManagerInterface $entityManager The entity manager
* @param GatewayResourceService $resourceService The resource service
* @param MappingService $mappingService The mapping service
* @param ValidationService $validationService The validation service
* @param FileSystemHandleService $fileSystemService The file system service
* @param CacheService $cacheService The cache service
* @param ReadUnreadService $readUnreadService The read unread service
* @param SynchronizationService $syncService The SynchronizationService.
* @param CallService $callService The call service
* @param Security $security Security
* @param EventDispatcherInterface $eventDispatcher Event dispatcher
* @param SerializerInterface $serializer The serializer
* @param SessionInterface $session The current session
* @param LoggerInterface $requestLogger The logger interface
* @param DownloadService $downloadService The download service
*/
public function __construct(
EntityManagerInterface $entityManager,
GatewayResourceService $resourceService,
MappingService $mappingService,
ValidationService $validationService,
FileSystemHandleService $fileSystemService,
CacheService $cacheService,
ReadUnreadService $readUnreadService,
SynchronizationService $syncService,
CallService $callService,
Security $security,
EventDispatcherInterface $eventDispatcher,
SerializerInterface $serializer,
SessionInterface $session,
LoggerInterface $requestLogger,
DownloadService $downloadService
) {
$this->entityManager = $entityManager;
$this->cacheService = $cacheService;
$this->resourceService = $resourceService;
$this->mappingService = $mappingService;
$this->validationService = $validationService;
$this->fileSystemService = $fileSystemService;
$this->readUnreadService = $readUnreadService;
$this->syncService = $syncService;
$this->callService = $callService;
$this->security = $security;
$this->eventDispatcher = $eventDispatcher;
$this->serializer = $serializer;
$this->session = $session;
$this->logger = $requestLogger;
$this->downloadService = $downloadService;
}//end __construct()
/**
* Determines the right content type and serializes the data accordingly.
*
* @param array $data The data to serialize.
* @param mixed $contentType The content type to determine.
*
* @return string The serialized data.
*/
public function serializeData(array $data, &$contentType, ?string $xmlRootNode = null): string
{
$accept = 'json';
if (isset($this->data['accept']) === true) {
$accept = $this->data['accept'];
}
$endpoint = null;
if (isset($this->data['endpoint']) === true) {
$endpoint = $this->data['endpoint'];
}
$encoderSettings = ['xml_encoding' => 'utf-8'];
if ($xmlRootNode) {
$encoderSettings['xml_root_node_name'] = $xmlRootNode;
}
$serializer = new Serializer([], [new XmlEncoder($encoderSettings), new CsvEncoder()]);
// @TODO: Create hal and ld encoding.
switch ($accept) {
case 'pdf':
$content = $this->downloadService->downloadPdf($data);
break;
case 'html':
$content = $this->downloadService->downloadHtml($data);
break;
case 'docx':
$content = $this->downloadService->downloadDocx($data);
break;
case 'xml':
case 'csv':
$content = $serializer->serialize($data, $accept);
break;
case 'jsonld':
case 'jsonhal':
case 'json':
default:
$content = \Safe\json_encode($data);
}
// @TODO: Preparation for checking if accept header is allowed. We probably should be doing this in the EndpointService instead?
// if ($endpoint instanceof Endpoint
// && empty($endpoint->getContentTypes()) === false
// && in_array($accept, $endpoint->getContentTypes()) === false
// ) {
// throw new NotAcceptableHttpException('The content type is not accepted for this endpoint');
// }
if (isset($this->data['headers']['accept']) === true && $this->data['headers']['accept'][0] !== '*/*') {
$contentType = $this->data['headers']['accept'][0];
} else if ($endpoint instanceof Endpoint && $endpoint->getDefaultContentType() !== null) {
$contentType = $endpoint->getDefaultContentType();
} else if (isset($this->data['headers']['accept']) === true && $this->data['headers']['accept'][0] === '*/*') {
$contentType = 'application/json';
}
return $content;
}//end serializeData()
/**
* Determines the right content type and unserializes the content accordingly.
*
* @param string $content The content to unserialize.
* @param string $contentType The content type to use.
*
* @return array The unserialized data.
*/
private function unserializeData(string $content, string $contentType, ?string &$rootNode = null): array
{
$xmlEncoder = new XmlEncoder(['as_collection' => true, 'remove_empty_tags' => false, 'reformat' => false]);
if (str_contains($contentType, 'xml') === true) {
$xml = simplexml_load_string($content);
$namespaces = array_combine(
array_map(
function ($key) {
return '@xmlns:'.$key;
},
array_keys($xml->getDocNamespaces(true))
),
$xml->getDocNamespaces(true)
);
$rootNode = array_key_first($xml->getNamespaces(true)).":".$xml->getName();
$decoded = $xmlEncoder->decode($content, 'xml');
$decoded = array_merge($decoded, $namespaces);
return $decoded;
}
return \Safe\json_decode($content, true);
}//end unserializeData()
/**
* A function to replace Request->query->all() because Request->query->all() will replace some characters with an underscore.
* This function will not.
*
* @param string|null $queryString A queryString from a request if we want to give it to this function instead of using global var $_SERVER.
*
* @return array An array with all query parameters.
*/
public function realRequestQueryAll(?string $queryString = ''): array
{
$vars = [];
if (empty($queryString) === true && empty($this->data['querystring']) === false) {
$queryString = $this->data['querystring'];
}
if (empty($queryString) === true && empty($_SERVER['QUERY_STRING']) === true) {
return $vars;
}
if (empty($queryString) === true && isset($_SERVER['QUERY_STRING']) === true) {
$queryString = $_SERVER['QUERY_STRING'];
}
$pairs = explode('&', $queryString);
foreach ($pairs as $pair) {
$nv = explode('=', $pair);
$name = urldecode($nv[0]);
$value = '';
if (count($nv) == 2) {
$value = urldecode($nv[1]);
}
$this->recursiveRequestQueryKey($vars, $name, explode('[', $name)[0], $value);
}//end foreach
return $vars;
}//end realRequestQueryAll()
/**
* This function adds a single query param to the given $vars array. ?$name=$value
* Will check if request query $name has [...] inside the parameter, like this: ?queryParam[$nameKey]=$value.
* Works recursive, so in case we have ?queryParam[$nameKey][$anotherNameKey][etc][etc]=$value.
* Also checks for queryParams ending on [] like: ?queryParam[$nameKey][] (or just ?queryParam[]), if this is the case
* this function will add given value to an array of [queryParam][$nameKey][] = $value or [queryParam][] = $value.
* If none of the above this function will just add [queryParam] = $value to $vars.
*
* @param array $vars The vars array we are going to store the query parameter in
* @param string $name The full $name of the query param, like this: ?$name=$value
* @param string $nameKey The full $name of the query param, unless it contains [] like: ?queryParam[$nameKey]=$value
* @param string $value The full $value of the query param, like this: ?$name=$value
*
* @return void
*/
private function recursiveRequestQueryKey(array &$vars, string $name, string $nameKey, string $value)
{
$matchesCount = preg_match('/(\[[^[\]]*])/', $name, $matches);
if ($matchesCount > 0) {
$key = $matches[0];
$name = str_replace($key, '', $name);
$key = trim($key, '[]');
if (empty($key) === false) {
$vars[$nameKey] = ($vars[$nameKey] ?? []);
$this->recursiveRequestQueryKey($vars[$nameKey], $name, $key, $value);
} else {
$vars[$nameKey][] = $value;
}
} else {
$vars[$nameKey] = $value;
}
}//end recursiveRequestQueryKey()
/**
* Gets the schemas related to this endpoint.
*
* @return array All necessary info from the schemas related to this endpoint.
*/
private function getAllowedSchemas(): array
{
$allowedSchemas = [
'id' => [],
'name' => [],
'reference' => [],
];
if (isset($this->data['endpoint']) === true) {
foreach ($this->data['endpoint']->getEntities() as $entity) {
$allowedSchemas['id'][] = $entity->getId()->toString();
$allowedSchemas['name'][] = $entity->getName();
$allowedSchemas['reference'][] = $entity->getReference();
}
}
return $allowedSchemas;
}//end getAllowedSchemas()
/**
* This function checks if the requesting user is the owner or is part of the correct Organization to edit the requested object.
*
* @return Response|null A 403 response if the requested user does not have the rights to edit current object.
*/
private function checkOwnerAndOrg(): ?Response
{
if (isset($this->object) !== true || $this->security->getUser() === null) {
return null;
}
$user = $this->security->getUser();
// Check if object owner matches the current user.
if ($this->object->getOwner() !== null && $this->object->getOwner() === $user->getUserIdentifier()) {
return null;
}
// Check if the object or user has no Organization. And if they both have an Organization, check if these Organizations match.
if ($this->object->getOrganization() === null
|| $user->getOrganization() === null
|| $this->object->getOrganization()->getId()->toString() === $user->getOrganization()
) {
return null;
}
$currentUser = [
'id' => $user->getUserIdentifier(),
'name' => $user->getName(),
'organization' => $user->getOrganization(),
];
$this->logger->error("Authentication failed. You are not allowed to view or edit this object $this->identification.", ['currentUser' => $currentUser]);
return new Response(
$this->serializeData(
[
'message' => "Authentication failed. You are not allowed to view or edit this object $this->identification.",
'currentUser' => $currentUser,
],
$contentType
),
Response::HTTP_FORBIDDEN,
['Content-type' => $contentType]
);
}//end checkOwnerAndOrg()
/**
* This function checks if the requesting user has the needed scopes to access the requested endpoint.
*
* @param array $references Schema references which we checks scopes for.
*
* @return Response|null A 403 response if the requested user does not have the needed scopes.
*/
private function checkUserScopes(array $references, string $type = 'schemas'): ?Response
{
$scopes = $this->getScopes();
$loopedSchemas = [];
foreach ($references as $reference) {
$schemaScope = "$type.$reference.{$this->data['method']}";
$loopedSchemas[] = $schemaScope;
if (in_array($schemaScope, $scopes) === true) {
// If true the user is authorized.
return null;
}
}
// If the user doesn't have the normal scope and doesn't have the admin scope, return a 403 forbidden.
if (in_array("admin.{$this->data['method']}", $scopes) === false) {
$implodeString = implode(', ', $loopedSchemas);
$this->logger->error("Authentication failed. You do not have any of the required scopes for this endpoint. ($implodeString)");
return new Response(
$this->serializeData(
[
'message' => "Authentication failed. You do not have any of the required scopes for this endpoint.",
'scopes' => ['anyOf' => $loopedSchemas],
],
$contentType
),
Response::HTTP_FORBIDDEN,
['Content-type' => $contentType]
);
}//end if
return null;
}//end checkUserScopes()
/**
* Get a scopes array for the current user (or of the anonymus if no user s logged in).
*
* @return array
*/
public function getScopes(): ?array
{
// If we have a user, return the user his scopes.
$user = $this->security->getUser();
if (isset($user) === true && $user->getRoles() !== null) {
$scopes = [];
foreach ($user->getRoles() as $role) {
$scopes[] = str_replace('ROLE_', '', $role);
}
return $scopes;
}//end if
// If we don't have a user, return the anonymous security group its scopes.
$anonymousSecurityGroup = $this->entityManager->getRepository('App:SecurityGroup')->findOneBy(['anonymous' => true]);
if ($anonymousSecurityGroup !== null) {
$scopes = [];
foreach ($anonymousSecurityGroup->getScopes() as $scope) {
$scopes[] = $scope;
}
return $scopes;
}
// If we don't have a user or anonymous security group, return an empty array (this will result in a 403 response in the checkUserScopes function).
return [];
}//end getScopes()
/**
* Get the ID from given parameters.
*
* @return string|false
*/
public function getId()
{
// Try to grab an id.
if (isset($this->data['path']['{id}']) === true) {
return $this->data['path']['{id}'];
}
if (isset($this->data['path']['[id]']) === true) {
return $this->data['path']['[id]'];
}
if (isset($this->data['query']['id']) === true) {
return $this->data['query']['id'];
}
if (isset($this->data['path']['id']) === true) {
return$this->data['path']['id'];
}
if (isset($this->data['path']['{uuid}']) === true) {
return $this->data['path']['{uuid}'];
}
if (isset($this->data['query']['uuid']) === true) {
return$this->data['query']['uuid'];
}
if (isset($this->content['id']) === true) {
// the id might also be passed through the object itself.
return $this->content['id'];
}
if (isset($this->content['uuid']) === true) {
return $this->content['uuid'];
}
return false;
}//end getId()
/**
* Get the schema from given parameters returns false if no schema could be established.
*
* @param array $parameters
*
* @return Entity|false
*/
public function getSchema(array $parameters)
{
// If we have an object this is easy.
if (isset($this->object) === true) {
return $this->object->getEntity();
}
// Pull the id or reference from the content.
if (isset($this->content['_self']['schema']['id']) === true) {
$identification = $this->content['_self']['schema']['id'];
}
if (isset($this->content['_self']['schema']['ref']) === true) {
$reference = $this->content['_self']['schema']['ref'];
}
if (isset($this->content['_self']['schema']['reference']) === true) {
$reference = $this->content['_self']['schema']['reference'];
}
// In normal circumstances we expect a all to com form an endpoint so...
if (isset($parameters['endpoint']) === true) {
// The endpoint contains exactly one schema
if (count($this->data['endpoint']->getEntities()) == 1) {
return $this->data['endpoint']->getEntities()->first();
}
// The endpoint contains multiple schema's
if (count($this->data['endpoint']->getEntities()) >= 1) {
// todo: so right now if we dont have an id or ref and multiple options we "guess" the first, it that smart?
$criteria = Criteria::create()->orderBy(['date_created' => Criteria::DESC]);
if (isset($identification) === true) {
$criteria->where(['id' => $identification]);
}
if (isset($reference) === true) {
$criteria->where(['reference' => $reference]);
}
return $this->data['endpoint']->getEntities()->matching($criteria)->first();
}
}//end if
// We only end up here if there is no endpoint or an unlimited endpoint.
if (isset($identification) === true) {
return $this->entityManager->getRepository('App:Entity')->findOneBy(['id' => $identification]);
}
if (isset($reference) === true) {
return $this->entityManager->getRepository('App:Entity')->findOneBy(['reference' => $reference]);
}
// There is no way to establish an schema so.
return false;
}//end getSchema()
private function proxyConfigBuilder(): array
{
if (isset($this->data['headers']['content-type']) === true
&& strpos($this->data['headers']['content-type'][0], 'multipart/form-data') !== false
) {
$post = $this->data['post'];
array_walk(
$post,
function (&$value, $key) {
if (is_array($value) === true
&& in_array('multipart-contents', array_keys($value)) === true
&& in_array('multipart-filename', array_keys($value)) === true
) {
$filename = $value['multipart-filename'];
$value = $value['multipart-contents'];
}
$value = [
'name' => $key,
'contents' => $value,
'filename' => $filename,
];
}
);
return [
'query' => $this->data['query'],
'headers' => $this->data['headers'],
'multipart' => array_values($post),
];
} else if (isset($this->data['headers']['content-type']) === true
&& strpos($this->data['headers']['content-type'][0], 'application/x-www-form-urlencoded') !== false
) {
return [
'query' => $this->data['query'],
'headers' => $this->data['headers'],
'form_params' => $this->data['post'],
];
}//end if
return [
'query' => $this->data['query'],
'headers' => $this->data['headers'],
'body' => $this->data['crude_body'],
];
}//end proxyConfigBuilder()
/**
* Handles a proxy Endpoint.
* todo: we want to merge proxyHandler() and requestHandler() code at some point.
*
* @param array $data The data from the call
* @param array $configuration The configuration from the call
*
* @return Response The data as returned bij the original source
*/
public function proxyHandler(array $data, array $configuration, ?Source $proxy = null, bool $overruleAuth = false): Response
{
$this->data = $data;
$this->configuration = $configuration;
// If we already have a proxy, we can skip these checks.
if ($proxy instanceof Source === false) {
$proxy = $data['endpoint']->getProxy();
// We only do proxying if the endpoint forces it, and we do not have a proxy.
if ($data['endpoint'] instanceof Endpoint === false || $proxy === null) {
$message = !$data['endpoint'] instanceof Endpoint ? "No Endpoint in data['endpoint']" : "This Endpoint has no Proxy: {$data['endpoint']->getName()}";
return new Response(
$this->serializeData(['message' => $message], $contentType),
Response::HTTP_NOT_FOUND,
['Content-type' => $contentType]
);
}//end if
if ($proxy instanceof Source && ($proxy->getIsEnabled() === null || $proxy->getIsEnabled() === false)) {
return new Response(
$this->serializeData(['message' => "This Source is not enabled: {$proxy->getName()}"], $contentType),
Response::HTTP_OK,
// This should be ok, so we can disable Sources without creating error responses?
['Content-type' => $contentType]
);
}
}//end if
$securityResponse = $this->checkUserScopes([$proxy->getReference()], 'sources');
if ($securityResponse instanceof Response === true) {
return $securityResponse;
}
// Work around the _ with a custom function for getting clean query parameters from a request
$this->data['query'] = $this->realRequestQueryAll();
if (isset($this->data['query']['extend']) === true) {
$extend = $this->data['query']['extend'];
// Make sure we do not send this gateway specific query param to the proxy / Source.
unset($this->data['query']['extend']);
}
// Make sure we set object to null in the session, for detecting the correct AuditTrails to create. Also used for DateRead to work correctly!
$this->session->set('object', null);
if (isset($data['path']['{route}']) === true && empty($data['path']['{route}']) === false) {
$this->data['path'] = '/'.$data['path']['{route}'];
} else {
$this->data['path'] = '';
}
if (isset($data['endpoint']) === true && count($data['endpoint']->getFederationProxies()) > 1) {
return $this->federationProxyHandler($data['endpoint']->getFederationProxies(), $this->data['path'], $this->proxyConfigBuilder());
}
// Don't pass gateway authorization to the source.
if ($overruleAuth === false) {
unset($this->data['headers']['authorization']);
}
$url = \Safe\parse_url($proxy->getLocation());
// Make a guzzle call to the source based on the incoming call.
try {
// Check if we are dealing with http, https or something else like a ftp (fileSystem).
if (($url['scheme'] === 'http' || $url['scheme'] === 'https')) {
$result = $this->callService->call(
$proxy,
$this->data['path'],
$this->data['method'],
$this->proxyConfigBuilder(),
false,
true,
$overruleAuth
);
} else {
$result = $this->fileSystemService->call($proxy, $this->data['path']);
$result = new \GuzzleHttp\Psr7\Response(200, [], $this->serializer->serialize($result, 'json'));
}//end if
$contentType = 'application/json';
if (isset($result->getHeaders()['content-type'][0]) === true) {
$contentType = $result->getHeaders()['content-type'][0];
}
if (isset($result->getHeaders()['Content-Type'][0]) === true) {
$contentType = $result->getHeaders()['Content-Type'][0];
}
$xmlRootNode = null;
$resultContent = $this->unserializeData($result->getBody()->getContents(), $contentType, $xmlRootNode);
// Handle _self metadata, includes adding dateRead
if (isset($extend) === true) {
$this->data['query']['extend'] = $extend;
}
$this->handleMetadataSelf($resultContent, $proxy);
$headers = $result->getHeaders();
if (isset($headers['content-length']) === true) {
unset($headers['content-length']);
}
if (isset($headers['Content-Length']) === true) {
unset($headers['Content-Length']);
}
// Let create a response from the guzzle call.
$response = new Response(
$this->serializeData($resultContent, $contentType, $xmlRootNode),
$result->getStatusCode(),
$headers
);
} catch (Exception $exception) {
$statusCode = 500;
if (array_key_exists($exception->getCode(), Response::$statusTexts) === true) {
$statusCode = $exception->getCode();
}
if (method_exists(get_class($exception), 'getResponse') === true && $exception->getResponse() !== null) {
$body = $exception->getResponse()->getBody()->getContents();
$statusCode = $exception->getResponse()->getStatusCode();
$headers = $exception->getResponse()->getHeaders();
if (isset($headers['content-length']) === true) {
unset($headers['content-length']);
}
if (isset($headers['Content-Length']) === true) {
unset($headers['Content-Length']);
}
}
// Catch weird statuscodes (like 0).
if (array_key_exists($statusCode, Response::$statusTexts) === false) {
$statusCode = 502;
}
$content = $this->serializeData(
[
'message' => $exception->getMessage(),
'body' => ($body ?? "Can't get a response & body for this type of Exception: ").get_class($exception),
],
$contentType,
isset($xmlRootNode) === true ? $xmlRootNode : null
);
$response = new Response($content, $statusCode, ($headers ?? ['Content-Type' => $contentType]));
}//end try
// And don so let's return what we have.
return $response;
}//end proxyHandler()
/**
* Checks if the query parameter to relay rating is set and if so, return the value while unsetting the query parameter.
*
* @param array $config The call configuration.
* @return bool
*/
public function useRelayRating(array &$config): bool
{
$returnValue = true;
if (isset($config['query']['_federalization_relay_rating']) === true) {
$returnValue = $config['query']['_federalization_relay_rating'];
unset($config['query']['_federalization_relay_rating']);
}
return $returnValue;
}//end useRelayRating()
/**
* Takes the config array and includes or excludes sources for federated requests based upon query parameters.
*
* @param array $config The call configuration.
* @param Collection $proxies The full list of proxies configured for the endpoint.
*
* @return Collection The list of proxies that remains after including or excluding sources.
*
* @throws Exception Thrown when both include and exclude query parameters are given.
*/
public function getFederationSources(array &$config, Collection $proxies): Collection
{
if (isset($config['query']['_federalization_use_sources']) === true && isset($config['query']['_federalization_exclude_sources']) === true) {
$this->logger->error('Use of sources and exclusion of sources cannot be done in the same request');
throw new Exception('Use of sources and exclusion of sources cannot be done in the same request');
}
$usedSourceIds = [];
$excludedSourceIds = [];
// Returns all proxies when neither uses or excludes are given, this can be done by not setting the query parameters, but also by setting uses to * or excludes to null
if ((isset($config['query']['_federalization_use_sources']) === true && $config['query']['_federalization_use_sources'] === '*')
|| (isset($config['query']['_federalization_exclude_sources']) === true && $config['query']['_federalization_exclude_sources'] === 'null')
|| (isset($config['query']['_federalization_use_sources']) === false && isset($config['query']['_federalization_exclude_sources']) === false)
) {
unset($config['query']['_federalization_exclude_sources'], $config['query']['_federalization_use_sources']);
return $proxies;
} else if (isset($config['query']['_federalization_use_sources']) === true && $config['query']['_federalization_use_sources'] !== '*') {
$usedSourceIds = explode(',', $config['query']['_federalization_use_sources']);
} else if (isset($config['query']['_federalization_exclude_sources']) === true && $config['query']['_federalization_exclude_sources'] !== null) {
$excludedSourceIds = explode(',', $config['query']['_federalization_exclude_sources']);
}
foreach ($proxies as $key => $proxy) {
if (($usedSourceIds !== [] && in_array($proxy->getId()->toString(), $usedSourceIds) === false)
|| ($excludedSourceIds !== [] && in_array($proxy->getId()->toString(), $excludedSourceIds) === true)
) {
$proxies->remove($key);
}
}
unset($config['query']['_federalization_exclude_sources'], $config['query']['_federalization_use_sources']);
return $proxies;
}//end getFederationSources()
/**
* Update configuration from federation query parameters, sets timeout and http_errors, unsets the query parameters.
*
* @param array $config The original call configuration including the federation query parameters.
*
* @return array The updated call configuration.
*/
public function getFederationConfig(array $config): array
{
$config['timeout'] = 3;
$config['http_errors'] = true;
if (isset($config['query']['_federalization_timeout']) === true) {
$config['timeout'] = ($config['query']['_federalization_timeout'] / 1000);
unset($config['query']['_federalization_timeout']);
}
if (isset($config['query']['_federalization_ignore_error']) === true) {
$config['http_errors'] = $config['query']['_federalization_ignore_error'] === "false" ? true : false;
unset($config['query']['_federalization_ignore_error']);
}
return $config;
}//end getFederationConfig()
/**
* Runs a federated request to a multitude of proxies and aggregrates the results.
*
* @param Collection $proxies The proxies to send the request to.
* @param string $path The path to send the request to.
* @param array $config The call configuration.
*
* @return Response The resulting response.
*
* @throws Exception
*/
public function federationProxyHandler(Collection $proxies, string $path, array $config): Response
{
$this->requestTimes = [];
try {
$proxies = $this->getFederationSources($config, $proxies);
} catch (Exception $exception) {
return new Response(\Safe\json_encode(['message' => $exception->getMessage()]), 400, ['content-type' => 'application/json']);
}
$config = $this->getFederationConfig($config);
$promises = [];
foreach ($proxies as $id => $proxy) {
$config['on_stats'] = function (TransferStats $stats) use ($id) {
$this->requestTimes[$id] = $stats->getTransferTime();
};
$promises[$id] = $this->callService->call($proxy, $path, 'GET', $config, true);
}
$responses = Utils::settle($promises)->wait();
$results['_sources'] = [];
$results['results'] = new ArrayCollection();
foreach ($responses as $id => $response) {
if ($response['state'] === 'rejected' && ($response['reason'] instanceof ConnectException || $config['http_errors'] === false)) {
continue;
} else if ($response['state'] === 'rejected' && ($response['reason'] instanceof ServerException || $response['reason'] instanceof ClientException)) {
$this->logger->error($response['reason']->getMessage());
return new Response(\Safe\json_encode(['message' => $response['reason']->getMessage()]), 523, ['content-type' => 'application/json']);
}
$decoded = $this->callService->decodeResponse($proxies[$id], $response['value']);
$decoded['results'] = array_map(
function (array $value) use ($proxies, $id) {
$value['_source'] = $proxies[$id]->getId()->toString();
return $value;
},
$decoded['results']
);
// This if statement is here for the comfort of programmers so IDEs recognise value as Response, the value can never be anything else than value.
if ($response['value'] instanceof \GuzzleHttp\Psr7\Response === false) {
continue;