-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmulti_curl_class.php
More file actions
2323 lines (1940 loc) · 81 KB
/
multi_curl_class.php
File metadata and controls
2323 lines (1940 loc) · 81 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
/*
File: multi_curl_class.php
Created: 07/22/2020
Updated: 08/03/2020
Programmer: Cuates
Updated By: Cuates
Purpose: Multi curl call interaction
*/
// Include configuration file
include ("multi_curl_config.php");
// Set include path
// Third party library needs to be downloaded from the internet and configured for the server system
set_include_path(get_include_path() . PATH_SEPARATOR . 'phpseclib/');
// Include dependent files
require_once ('phpseclib/Net/SFTP.php');
// Require once advance mail class file
require_once ("mailclass.php");
// Create the class for the db web service class
class multi_curl_call_class extends multi_curl_config
{
// PHP 5+ Style constructor
public function __construct()
{
// This function needs to be here so the class can be executed when called
// Create object of mail class
$this->mcl = new mailclass();
}
// PHP 4 Style constructor
public function multi_curl_call_class()
{
// Call the constructor
self::__construct();
}
// Open connection function to an internal or external server
private function openConnection($type = "notype")
{
// Set variable
$returnArray = array();
// Try to execute the command(s)
try
{
// Set variables with database settings
$this->setConfigVars($type);
// Set array to variable
$conVars = $this->getConfigVars();
// Set all credentials and information
$this->Driver = reset($conVars); // Driver
$this->Server = next($conVars); // Server name
$this->Port = next($conVars); // Server port
$this->Database = next($conVars); // Database name
$this->User = next($conVars); // User name
$this->Pass = next($conVars); // Password
$this->URL = next($conVars); // URL
$this->URLAPI = next($conVars); // URL API
$this->RemotePath = next($conVars); // Remote directory
$this->subscriptionKey = next($conVars); // Subscription Key
$this->appKey = next($conVars); // App Key
// Check database name. The data Name is set to make sure that we are connecting with a database
if(preg_match('/MSSQL<Database_Name>[a-zA-Z]{1,}/i', $type))
{
// error_log('odbc:Driver=' . $this->Driver . '; Servername=' . $this->Server . '; Port=' . $this->Port . '; Database=' . $this->Database . '; UID=' . $this->User . '; PWD=' . $this->Pass . '; Type=' . $type);
// Connect to a database
$this->pdo = new PDO('odbc:Driver=' . $this->Driver . '; Servername=' . $this->Server . '; Port=' . $this->Port . '; Database=' . $this->Database . '; UID=' . $this->User . '; PWD=' . $this->Pass . ';'); // The developer will need to configure the driver of choice
// Throw exception if given by the database server
// This will help when the database returns a hard error
$this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
else if(preg_match('/PGSQL<Database_Name>[a-zA-Z]{1,}/i', $type))
{
// error_log('pgsql:host=' . $this->Server . '; port=' . $this->Port . '; dbname=' . $this->Database . '; user=' . $this->User . '; password=' . $this->Pass . ';');
// Connect to a database
$this->pdo = new PDO('pgsql:host=' . $this->Server . '; port=' . $this->Port. '; dbname=' . $this->Database . '; user=' . $this->User . '; password=' . $this->Pass . ';'); // The developer will need to configure the driver of choice
// Throw exception if given by the database server
// This will help when the database returns a hard error
$this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
else if(preg_match('/MySQL<Database_Name>[a-zA-Z]{1,}/i', $type))
{
// error_log('mysql:host=' . $this->Server . '; port=' . $this->Port . '; dbname=' . $this->Database . ', user=' . $this->User . ', password=' . $this->Pass);
// Connect to a database
$this->pdo = new PDO('mysql:host=' . $this->Server . '; port=' . $this->Port. '; dbname=' . $this->Database, $this->User, $this->Pass); // The developer will need to configure the driver of choice
// Throw exception if given by the database server
// This will help when the database returns a hard error
$this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
else if(preg_match('/^<SFTP_Name>$/i', $type))
{
// Create an object with connection
$this->sftp = new \phpseclib\Net\SFTP($this->Server, $this->Port);
// Check if user has proper credentials
if ($this->sftp->login($this->User, $this->Pass))
{
// Error log connection to the end user's server
}
else
{
// Set message
$returnArray = array('SError' => trim('SFTP Failed to Establish a Connection'));
// Error log database connection error
// error_log(print_r($returnArray, true));
}
}
else if(preg_match('/<Web_Service_>[a-zA-Z]{1,}/i', $type))
{
}
else
{
// Set message
$returnArray = array('SError' => trim('Cannot connect to the database/SFTP/Web Service'));
// Error log database connection error
// error_log(print_r($returnArray, true));
}
}
catch (PDOException $e)
{
// Otherwise retains and outputs the potential error
// Set message
$returnArray = array('SError' => trim('Caught - PDO cannot connect to the database - ' . $e->getMessage()));
// Error log database connection error
// error_log(print_r($returnArray, true));
// error log the caught exception
// error_log($e->getMessage());
error_log($e);
}
catch (Exception $e)
{
// Catch the error from the try section of code
// Set message
$returnArray = array('SError' => trim('Caught - cannot connect to the database/SFTP/Web Service - ' . $e->getMessage()));
// Error log database connection error
// error_log(print_r($returnArray, true));
// error log the caught exception
// error_log($e->getMessage());
error_log($e);
}
// Return message
return $returnArray;
}
//**---------- Do not modify anything above this commented line ----------**//
// Update date time stamp
public function updateDateTimeStamp($param01)
{
// Query
$query = "<Stored_Procedure_Name> @optionMode = '<Option_Mode_Name>', @param01 = :param01";
// Define values into key pair array
$params = array(
':param01' => trim($param01)
);
// Return single attribute from the database
return $this->retrieveSingleValue('Column01', $query, $params, '1', '1', '<Database_Name>');
}
// Call a stored procedure to access information from the database
public function extractData()
{
// Query
$query = "<Stored_Procedure_Name> @optionMode = '<Option_Mode_Name>'";
// Define values into key pair array
$params = array(
);
// Retrieve values
return $this->retrieveSingleAttribute('Column01', $query, $params, '1', '1', '<Database_Name>');
}
// Call a stored procedure to access information from the database
public function extractParam01Data($param01)
{
// Set title array
$titleArray = array('Column01', 'Column02', 'Column03');
// Query
$query = "<Stored_Procedure_Name> @optionMode = '<Option_Mode_Name>', @param01 = :param01";
// Define values into key pair array
$params = array(
':param01' => trim($param01)
);
// Retrieve values
return $this->retrieveMultipleColumnRecordAttribute($titleArray, $query, $params, '1', '1', '<Database_Name>');
}
// Call a stored procedure to bulk update information from another database
public function updateDataInformation($param01)
{
// Query
$query = "<Stored_Procedure_Name> @optionMode = '<Option_Mode_Name>', @param01 = :param01";
// Define values into key pair array
$params = array(
':param01' => trim($param01)
);
// Retrieve values
return $this->retrieveSingleValue('Column01', $query, $params, '1', '1', '<Database_Name>');
}
// Call a stored procedure to bulk insert information from another database
public function insertDataInformation($param01)
{
// Query
$query = "<Stored_Procedure_Name> @optionMode = '<Option_Mode_Name>', @param01 = :param01";
// Define values into key pair array
$params = array(
':param01' => trim($param01)
);
// Retrieve values
return $this->retrieveSingleValue('Column01', $query, $params, '1', '1', '<Database_Name>');
}
// Call a stored procedure to access information from the database
public function extractTimeStampDate($param01)
{
// Query
$query = "<Stored_Procedure_Name> @optionMode = '<Option_Mode_Name>', @param01 = :param01";
// Define values into key pair array
$params = array(
':param01' => trim($param01)
);
// Retrieve values
return $this->retrieveSingleAttribute('Column01', $query, $params, '1', '1', '<Database_Name>');
}
// Validate Data
public function validateData($Old, $New, $searchNnumber)
{
// Query
$query = "<Stored_Procedure_Name> @optionMode = '<Option_Mode_Name>', @Old = :Old, @New = :New, @searchNnumber = :searchNnumber";
// Define values into key pair array
$params = array(
':Old' => trim($Old),
':New' => trim($New),
':searchNnumber' => trim($searchNnumber)
);
// Return single attribute from the database
return $this->retrieveSingleValue('Column01', $query, $params, '1', '1', '<Database_Name>');
}
// Authenticate via API call
public function authenticateAPI()
{
return $this->authenticateCURLCall("<Web_Service_Authentication>");
}
// Authenticate API
private function authenticateCURLCall($type = "<Web_Service_Authentication>")
{
// Initialize variable
$returnValue = "";
// Function to catch exception errors
set_error_handler(function ($errno, $errstr, $errfile, $errline)
{
throw new ErrorException($errstr, $errno, 0, $errfile, $errline);
});
// Try to execute the following CURL call
try
{
// Set array
$connectionStatus = array();
// Connect to server
$connectionStatus = $this->openConnection($type);
// Check if error with connecting to server
if (!isset($connectionStatus['SError']) && !array_key_exists('SError', $connectionStatus))
{
// Setup the url string with the API query string intended for this call
$urlQueryString = "";
$urlQueryString .= $this->URL;
$urlQueryString .= $this->URLAPI;
// Setup the CURL call for the API
// Initialize the curl call
$ch = curl_init();
// Set curl option calls
// Set up the headers to be sent with the information in the curl call
$headers = array(
'Accept: application/json',
'Accept-Charset: UTF-8',
'Content-Type: application/json'
);
// Payload to be sent to the server for access token value
$payload = '{
"username": "' . $this->User . '",
"password": "'. $this->Pass . '"
}';
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSLVERSION, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
curl_setopt($ch, CURLOPT_URL, $urlQueryString);
// Execute the curl call
$result = curl_exec($ch);
// Retrieve any curl errors
$ch_error = curl_error($ch);
// Close curl
curl_close($ch);
// Check if there were any errors when executing the curl call
if ($ch_error)
{
// Return message
$returnValue = trim("Error~" . $ch_error);
// error_log($returnValue);
}
else
{
// Return message
$returnValue = trim("Success~" . $result);
// error_log($returnValue);
}
}
else
{
// Else error has occurred
$connectionServerMesg = reset($connectionStatus);
// Set message
$returnValue = trim('SError~' . $connectionServerMesg);
// Display message
// error_log($returnValue);
}
}
catch(Exception $e)
{
// Catch the error from the try section of code
// Set message
$returnValue = trim('SError~Caught post Authentication Curl call ' . $e->getMessage());
// error log the caught exception
// error_log($e->getMessage());
error_log($e);
}
// Return message
return $returnValue;
}
// Search via API call
public function searchMultiAPI($urlQuery, $authToken, $numberArray)
{
return $this->searchMulti($urlQuery, $authToken, $numberArray, "<Web_Service_Search>");
}
// Search from data Multi curl call
private function searchMulti($urlQuery, $authToken, $valueArray, $type = "<Web_Service_Search>")
{
// Initialize variable
$returnValue = array();
// Function to catch exception errors
set_error_handler(function ($errno, $errstr, $errfile, $errline)
{
throw new ErrorException($errstr, $errno, 0, $errfile, $errline);
});
// Try to execute the following CURL call
try
{
// Set array
$connectionStatus = array();
// Connect to server
$connectionStatus = $this->openConnection($type);
// Check if error with connecting to server
if (!isset($connectionStatus['SError']) && !array_key_exists('SError', $connectionStatus))
{
// Set parameter of array
$sizeOfValueArray = sizeof($valueArray);
// Make sure the rolling window isn't greater than the # of urls
// 10 is a good number as it will not overload the external/internal server
$limit = 10;
$limit = ($sizeOfValueArray < $limit) ? $sizeOfValueArray : $limit;
// Initialize parameters
$master = curl_multi_init();
$overallValue = 0;
// Start the first batch of requests
foreach($valueArray as $valueData)
{
// Setup the url string with the API query string intended for this call
$urlQueryString = "";
$urlQueryString .= $this->URL;
$urlQueryString .= $this->URLAPI;
$urlQueryString .= $urlQuery;
$urlQueryString .= '&dataNumber=' . $valueData;
// Initialize the curl call
$ch = curl_init();
// Set up the headers to be sent with the information in the curl call
$headers = array(
'Accept: application/json',
'Accept-Charset: UTF-8',
'Content-Type: application/json',
'Authorization: ' . $authToken
);
// Payload to be sent to the server
$payload = '{
"search":
{
"searchTerms":
{
"param01": "' . $valueData . '"
}
}
}';
// Setup the option for CURL
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSLVERSION, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
curl_setopt($ch, CURLOPT_URL, $urlQueryString);
// Add curl init to master multi curl handle
curl_multi_add_handle($master, $ch);
// Increment total processed
$overallValue++;
// Check if total data has exceeded the limit
if ($overallValue >= $limit)
{
// Break out of loop as limit has been reached
break;
}
}
// Check if data are present to perform curls
if ($overallValue > 0)
{
// Perform the multi curl call
// Execute the multi handle
do
{
// Check if there is an execution running
// Run the sub-connections of hte current cURL handle
// Process each of the handles in the stack
$execrun = curl_multi_exec($master, $running);
// Check if the curl multi execute is OK
if($execrun != CURLM_OK)
{
error_log('Curl Error Break');
// Break loop as there was an issue with the curl multi exec function call
break;
}
// This will pause the loop
// Wait for activity on any curl multi connection
// Blocks until there is activity on any of the curl multi connections
$ready = curl_multi_select($master);
// A request was just completed find out which one
while($done = curl_multi_info_read($master))
{
// Get handle information
$info = curl_getinfo($done['handle']);
// Retrieve URL parts of the handle
$parts = parse_url($info['url']);
// Retrieve the query from the URL
parse_str($parts['query'], $query);
// Retrieve data parameter value from URL query
$numberValue = $query['dataNumber'];
// Get return message from the handle
$output = curl_multi_getcontent($done['handle']);
// Store the output from the handle into an array
$returnValue[$numberValue] = $output;
// Check if the size of the array is greater than the incremental count plus one
if($sizeOfValueArray >= $overallValue + 1)
{
// Start a new request (it's important to do this before removing the old one)
// Setup the url string with the API query string intended for this call
$urlQueryString = "";
$urlQueryString .= $this->URL;
$urlQueryString .= $this->URLAPI;
$urlQueryString .= $urlQuery;
$urlQueryString .= '&dataNumber=' . $valueArray[$overallValue];
// Setup the CURL call for values
// Initialize the curl call
$ch = curl_init();
// Set curl option calls
// Set up the headers to be sent with the information in the curl call
$headers = array(
'Accept: application/json',
'Accept-Charset: UTF-8',
'Content-Type: application/json',
'Authorization: ' . $authToken
);
// Payload to be sent to the server
$payload = '{
"search":
{
"searchTerms":
{
"param01": "' . $valueArray[$overallValue] . '"
}
}
}';
// Setup the option for CURL
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSLVERSION, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
curl_setopt($ch, CURLOPT_URL, $urlQueryString);
// Add curl init to master multi curl handle
curl_multi_add_handle($master, $ch);
// Increment total processed
$overallValue++;
}
// Remove the curl handle that just completed
curl_multi_remove_handle($master, $done['handle']);
// To totally close the handle
curl_close($done['handle']);
}
}
while ($running); // Continue while there is still a curl executing else exit
// Close multi curl master
curl_multi_close($master);
}
}
else
{
// Else error has occurred
$connectionServerMesg = reset($connectionStatus);
// Set message
$returnValue = trim('SError~' . $connectionServerMesg);
// Display message
// error_log($returnValue);
}
}
catch(Exception $e)
{
// Catch the error from the try section of code
// Set message
$returnValue = array('SError' => 'Caught post Search Curl call(s) ' . $e->getMessage());
// error log the caught exception
// error_log($e->getMessage());
error_log($e);
}
// Return message
// return $returnValue;
return $returnValue;
}
// Update data via API call
public function postUpdateDataMultiAPI($postFields, $authToken)
{
return $this->postUpdateDataMulti($postFields, $authToken, "<Web_Service_Update>");
}
// Update Data from database with CURL call
private function postUpdateDataMulti($postFields, $authToken, $type = "<Web_Service_Update>")
{
// Initialize variable
$returnValue = array();
// Function to catch exception errors
set_error_handler(function ($errno, $errstr, $errfile, $errline)
{
throw new ErrorException($errstr, $errno, 0, $errfile, $errline);
});
// Try to execute the following CURL call
try
{
// Set array
$connectionStatus = array();
// Connect to server
$connectionStatus = $this->openConnection($type);
// Check if error with connecting to server
if (!isset($connectionStatus['SError']) && !array_key_exists('SError', $connectionStatus))
{
// Set parameter of array
$sizeOfPostFields = sizeof($postFields);
// make sure the rolling curl call isn't greater than the number of values in array
$limit = 10;
// $limit = 14;
$limit = ($sizeOfPostFields < $limit) ? $sizeOfPostFields : $limit;
// Initialize parameters
$master = curl_multi_init();
$overallFoundValue = 0;
// Start the first batch of requests
foreach($postFields as $postFieldData)
{
// Decode JSON message
$postFieldDataResponse = json_decode($postFieldData, true);
// Extract data from string
$numberSearchStringResponse = isset($postFieldDataResponse[0]['root']['param01']) ? trim($postFieldDataResponse[0]['root']['param01']) : trim('');
// Setup the url string with the API query string intended for this call
$urlQueryString = "";
$urlQueryString .= $this->URL;
$urlQueryString .= $this->URLAPI;
$urlQueryString .= '?numberPOST=' . $numberSearchStringResponse;
// Initialize the curl call
$ch = curl_init();
// Set up the headers to be sent with the information in the curl call
$headers = array(
'Accept: application/json',
'Accept-Charset: UTF-8',
'Content-Type: application/json',
'Authorization: ' . $authToken
);
// Payload to be sent to the server
$payload = $postFields;
// Setup the option for CURL
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSLVERSION, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
curl_setopt($ch, CURLOPT_URL, $urlQueryString);
// Add curl init to master multi curl handle
curl_multi_add_handle($master, $ch);
// Increment total processed
$overallFoundValue++;
// Break out of loop as limit has been reached
if ($overallFoundValue >= $limit)
{
// Break out of loop as limit has been reached
break;
}
}
// Check if data is present to perform curls
if ($overallFoundValue > 0)
{
// Perform the multi curl call
// Execute the multi handle
do
{
// Check if there is an execution running
// Run the sub-connections of hte current cURL handle
// Process each of the handles in the stack
$execrun = curl_multi_exec($master, $running);
// Check if the curl multi execute is OK
if($execrun != CURLM_OK)
{
error_log('Update POST Curl Error Break');
// Break loop as there was an issue with the curl multi exec function call
break;
}
// This will pause the loop
// Wait for activity on any curl multi connection
// Blocks until there is activity on any of the curl multi connections
$ready = curl_multi_select($master);
// A request was just completed find out which one
while($done = curl_multi_info_read($master))
{
// Get handle information
$info = curl_getinfo($done['handle']);
// Retrieve URL parts of the handle
$parts = parse_url($info['url']);
// Retrieve the query from the URL
parse_str($parts['query'], $query);
// Retrieve data parameter value from URL query
$numberValue = $query['numberPOST'];
// Get return message from the handle
$output = curl_multi_getcontent($done['handle']);
// Store the output from the handle into an array
$returnValue[$numberValue] = $output;
// Check if the size of the array is greater than the incremental count plus one
if($sizeOfPostFields >= $overallFoundValue + 1)
{
// Extract data from string
$postFieldArrayList = $postFields[$overallFoundValue];
// Decode JSON message
$postFieldDataResponse = json_decode($postFieldArrayList, true);
// Extract data from string
$numberSearchStringResponse = isset($postFieldDataResponse[0]['root']['param01']) ? trim($postFieldDataResponse[0]['root']['param01']) : trim('');
// Setup the url string with the API query string intended for this call
$urlQueryString = "";
$urlQueryString .= $this->URL;
$urlQueryString .= $this->URLAPI;
$urlQueryString .= '?numberPOST=' . $numberSearchStringResponse;
// Initialize the curl call
$ch = curl_init();
// Set up the headers to be sent with the information in the curl call
$headers = array(
'Accept: application/json',
'Accept-Charset: UTF-8',
'Content-Type: application/json',
'Authorization: ' . $authToken
);
// Payload to be sent to the server
$payload = $postFieldArrayList;
// Setup the option for CURL
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSLVERSION, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
curl_setopt($ch, CURLOPT_URL, $urlQueryString);
// Add curl init to master multi curl handle
curl_multi_add_handle($master, $ch);
// Increment total processed
$overallFoundValue++;
}
// Remove the curl handle that just completed
curl_multi_remove_handle($master, $done['handle']);
// To totally close the handle
curl_close($done['handle']);
}
}
while ($running); // Continue while there is still a curl executing else exit
// Close multi curl master
curl_multi_close($master);
}
}
else
{
// Else error has occurred
$connectionServerMesg = reset($connectionStatus);
// Set message
$returnValue = trim('SError~' . $connectionServerMesg);
// Display message
// error_log($returnValue);
}
}
catch(Exception $e)
{
// Catch the error from the try section of code
// Set message
$returnValue = array('SError' => 'Caught post Update Curl call(s) ' . $e->getMessage());
// error log the caught exception
// error_log($e->getMessage());
error_log($e);
}
// Return message
return $returnValue;
}
//------- Do not modify anything below this commented line -------//
// Convert accent characters from other countries to en US characters
public function enUSCharsConvert($inputString)
{
// Array containing characters that cannot be converted by iconv function
$replace = array('ъ' => '-', 'Ь' => '-', 'Ъ' => '-', 'ь' => '-', 'а' => 'a', 'А' => 'a', 'א' => 'A', 'א' => 'a', 'Þ' => 'B', 'þ' => 'b', 'б' => 'b', 'Б' => 'b', 'ב' => 'b', '©' => 'c', 'ц' => 'c', 'Ц' => 'c', 'ץ' => 'C', 'צ' => 'c', 'Ч' => 'ch', 'ч' => 'ch', 'ד' => 'd', 'Đ' => 'd', 'đ' => 'd', 'д' => 'd', 'Д' => 'D', 'ð' => 'd', 'є' => 'e', 'Є' => 'e', 'ע' => 'e', 'е' => 'e', 'Е' => 'e', 'Ə' => 'e', 'ə' => 'e', 'ф' => 'f', 'Ф' => 'f', 'ƒ' => 'f', 'Г' => 'g', 'г' => 'g', 'ג' => 'g', 'Ґ' => 'g', 'ґ' => 'g', 'ח' => 'h', 'ħ' => 'h', 'Ħ' => 'h', 'Х' => 'h', 'х' => 'h', 'ה' => 'h', 'ı' => 'i', 'И' => 'i', 'и' => 'i', 'י' => 'i', 'Ї' => 'i', 'ї' => 'i', 'І' => 'i', 'і' => 'i', 'й' => 'j', 'Й' => 'j', 'я' => 'ja', 'Я' => 'ja', 'Э' => 'je', 'э' => 'je', 'ё' => 'jo', 'Ё' => 'jo', 'ю' => 'ju', 'Ю' => 'ju', 'ĸ' => 'k', 'כ' => 'k', 'К' => 'k', 'к' => 'k', 'ך' => 'k', 'Ŀ' => 'l', 'ŀ' => 'l', 'Л' => 'l', 'л' => 'l', 'מ' => 'm', 'ל' => 'l', 'М' => 'm', 'м' => 'm', 'ם' => 'm', 'н' => 'n', 'Н' => 'n', 'ן' => 'n', 'ŋ' => 'n', 'Ŋ' => 'n', 'נ' => 'n', 'Ø' => 'O', 'ø' => 'o', 'о' => 'o', 'О' => 'o', 'Ø' => 'O', 'ø' => 'o', 'ף' => 'p', 'פ' => 'p', 'п' => 'p', 'П' => 'p', 'ר' => 'r', 'ק' => 'q', '®' => 'r', 'Р' => 'r', 'р' => 'r', 'с' => 's', 'С' => 's', 'ס' => 's', 'Щ' => 'sch', 'щ' => 'sch', 'ш' => 'sh', 'Ш' => 'sh', '™' => 'tm', 'т' => 't', 'Т' => 't', 'ט' => 't', 'ŧ' => 't', 'Ŧ' => 't', 'ת' => 't', 'у' => 'u', 'У' => 'u', 'в' => 'v', 'В' => 'v', 'ו' => 'v', 'ש' => 'w', 'ы' => 'y', 'Ы' => 'y', 'З' => 'z', 'з' => 'z', 'ז' => 'z', 'Ж' => 'zh', 'ж' => 'zh');
// Translate characters or replace substrings
$inputString = strtr($inputString, $replace);
// Convert string to requested character encoding
$inputString = iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', $inputString);
// Return string with modifications
return $inputString;
}
// Validate web service headers
public function validateWebServiceCall($valRequestMethod, $validRequestMethod, $valHttpAccept, $valContentType, $valHttpAcceptCharSet)
{
// Initialize array
$returnArray = array();
// Try to execute the following code
try
{
// Check if Request Method is provided
if ($valRequestMethod === $validRequestMethod)
{
// Check if HTTP Accept is provided
if ($valHttpAccept === "application/json")
{
// Check if Content Type is provided
if ($valContentType === "application/json")
{
// Check if HTTP Accept Charset is provided
if ($valHttpAcceptCharSet === "UTF-8")
{
// Store parameters into array
$returnArray = array("SRes" => "Success", "SMesg" => "Request Processed");
}
else
{
// Set error message
$returnArray = array("SRes" => "Error", "SMesg" => "HTTP accept charset invalid");
}
}
else
{
// Set error message
$returnArray = array("SRes" => "Error", "SMesg" => "Content type invalid");
}
}
else
{
// Set error message
$returnArray = array("SRes" => "Error", "SMesg" => "HTTP accept invalid");
}
}
else
{
// Set error message
$returnArray = array("SRes" => "Error", "SMesg" => "Request method invalid");
}
}
catch(Exception $e)
{
// Catch the error from the try section of code
// Reset array to error message
error_log('Error~Issue with validate Web Service Call - ' . $e->getMessage());
// error log the caught exception
error_log($e->getMessage());
// Set variable
$returnArray = array("SRes" => "Error", "SMesg" => "Issue with validate Web Service Call");
}
// Return result
return $returnArray;
}
// Validate web service headers JSON
public function validateJSONWebServiceCall($valRequestMethod, $validRequestMethod, $valHttpAccept, $valContentType, $valHttpAcceptCharSet, $valPayload)
{
// Initialize array
$returnArray = array();
$payloadArray = array();
// Try to execute the following code
try
{
// Convert payload value to JSON
$valPayload = ($valPayload !== "") ? json_decode($valPayload, true) : trim("");
// Validate payload for JSON
$validatePayload = ($valPayload !== "") ? json_last_error() : trim("");
// Check if Request Method is provided
if ($valRequestMethod === $validRequestMethod)
{
// Check if HTTP Accept is provided
if ($valHttpAccept === "application/json")
{
// Check if Content Type is provided
if ($valContentType === "application/json")
{
// Check if HTTP Accept Charset is provided
if ($valHttpAcceptCharSet === "UTF-8")
{
// Check if payload is in proper format
if ($validatePayload === JSON_ERROR_NONE)
{
// Set result array and change key case
$payloadArray = $this->array_change_key_case_recursive($valPayload, CASE_LOWER);
// Check if not server error
if(!isset($payloadArray['SError']) && !array_key_exists('SError', $payloadArray))
{
// Store parameters into array
$returnArray = array("SRes" => "Success", "SMesg" => "Request Processed", "Payload" => $payloadArray);
}
else
{
// Store parameters into array
// $returnArray = $payloadArray;
$returnArray = array("SRes" => "Error", "SMesg" => "Array Change Key Case Recursive Error", "Payload" => $payloadArray);
}
}
else if ($validatePayload === "")
{
// Set error message
$returnArray = array("SRes" => "Error", "SMesg" => "Payload/Parameter was not provided", "Payload" => $payloadArray);
}
else
{