-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsftp_email_class.php
More file actions
1701 lines (1430 loc) · 58.6 KB
/
sftp_email_class.php
File metadata and controls
1701 lines (1430 loc) · 58.6 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: sftp_email_cl.php
Created: 07/22/2020
Updated: 08/03/2020
Programmer: Cuates
Updated By: Cuates
Purpose: Class for all SFTP and Email interactions
*/
// Include configuration file
include ("sftp_email_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 sftp_email_cl extends sftp_email_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 sftp_email_cl()
{
// 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
{
// Set message
$returnArray = array('SError' => trim('Cannot connect to the database/SFTP'));
// 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 - ' . $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 sequence
public function updateSequence($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>');
}
// Register Data
function registerData($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>');
}
// Retrieve data
function getData($param01)
{
// Set title array for sat air
$titleArray = array('Column 01','Column 02', 'Column 03', 'Column 04');
// 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->retrieveMultipleAttribute($titleArray, $query, $params, '1', '1', '<Database_Name>');
}
// Extract ID numbers
function extractIDData($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->retrieveSingleAttribute('Column01', $query, $params, '1', '1', '<Database_Name>');
}
// Validate data in database
function validateData($param01, $param02)
{
// Query
$query = "<Stored_Procedure_Name> @optionMode = '<Option_Mode_Name>', @param01 = :param01, @param02 = :param02";
// Define values into key pair array
$params = array(
':param01' => trim($param01),
':param02' => trim($param02)
);
// Return single attribute from the database
return $this->retrieveSingleValue('Column01', $query, $params, '1', '1', '<Database_Name>');
}
//------- 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
{
// Set error message
$returnArray = array("SRes" => "Error", "SMesg" => "Payload syntax invalid", "Payload" => $payloadArray);
}
}
else
{
// Set error message
$returnArray = array("SRes" => "Error", "SMesg" => "HTTP accept charset invalid", "Payload" => $payloadArray);
}
}
else
{
// Set error message
$returnArray = array("SRes" => "Error", "SMesg" => "Content type invalid", "Payload" => $payloadArray);
}
}
else
{
// Set error message
$returnArray = array("SRes" => "Error", "SMesg" => "HTTP accept invalid", "Payload" => $payloadArray);
}
}
else
{
// Set error message
$returnArray = array("SRes" => "Error", "SMesg" => "Request method invalid", "Payload" => $payloadArray);
}
}
catch(Exception $e)
{
// Catch the error from the try section of code
// Reset array to error message
error_log('Error~Issue with validate JSON Web Service Call - ' . $e->getMessage());
// error log the caught exception
error_log($e->getMessage());
// Set variable
$returnArray = array("SRes" => "Error", "SMesg" => "Issue with validate JSON Web Service Call", "Payload" => $payloadArray);
}
// Return result
return $returnArray;
}
// Recursively change array key case
private function array_change_key_case_recursive($arr, $case = CASE_LOWER)
{
// Return array
$returnArray = 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 code
try
{
// Set array with modified array
// Use keyword makes a copy of the parent variable to be used in the recursion call
$returnArray = array_map(function ($item) use ($case)
{
// Check if the current item is an array
if(is_array($item))
{
// Recursively loop through the next array
$item = $this->array_change_key_case_recursive($item, $case);
}
// Return element
return $item;
}
, array_change_key_case($arr, $case)
);
}
catch (Exception $e)
{
// Catch the error from the try section of code
// Set message
$returnArray = array('SError' => trim('Caught array change key case recursive Execution Failure - ' . $e->getMessage()));
// Error log failure
//error_log($returnArray);
// error log the caught exception
// error_log($e->getMessage());
error_log($e);
}
// Return array
return $returnArray;
}
// Notify developer
public function notifyDeveloper($downloadDir, $errorFilename, $colHeaderArray, $errormessagearray, $to, $to_cc, $to_bcc, $fromEmail, $fromName, $replyTo, $subject, $headers, $message, $xPriority)
{
// Write to file
$writeToFileStatus = $this->writeToFile($downloadDir, $errorFilename, $errormessagearray, $colHeaderArray);
// Explode database message
$writeToFileStatusArray = explode('~', $writeToFileStatus);
// Set response message
$writeToFileStatusResp = reset($writeToFileStatusArray);
$writeToFileStatusMesg = next($writeToFileStatusArray);
// Check if an error message was returned from the class file
if(trim($writeToFileStatusResp) === "Success")
{
// Attach any file to the email
$this->mcl->mailWithAttachment($errorFilename, $downloadDir, $to, $fromEmail, $fromName, $replyTo, $subject, $message, $to_cc, $to_bcc, $xPriority);
}
else
{
// Display error string
// error_log("Error Message Write To File (Error) - " . $writeToFileStatusResp . ': ' . $writeToFileStatusMesg);
// Send email to software engineers for unsent email
mail($to, $subject, $message, $headers);
}
}
// Notify developer
public function notifyEndUser($sendFilename, $DOWNLOADDIR, $to, $fromEmail, $fromName, $replyTo, $subject, $headers, $message, $to_cc, $to_bcc, $xPriority)
{
// Check if an error message was returned from the class file
if(trim($sendFilename) !== "")
{
// Attach any file to the email
$this->mcl->mailWithAttachment($sendFilename, $DOWNLOADDIR, $to, $fromEmail, $fromName, $replyTo, $subject, $message, $to_cc, $to_bcc, $xPriority);
}
else
{
// Send email to software engineers for unsent email
mail($to, $subject, $message, $headers);
}
}
// Write to File
public function writeToFile($path, $filename, $content, $colHeaders)
{
// Initialize variables
$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 code
try
{
// Create file handle
$fp = fopen($path . $filename, 'w');
// Check if the column header is an array
if (is_array($colHeaders))
{
// Loop through array and write to file
foreach ($colHeaders as $colHeadVal)
{
// Write to file
fputcsv($fp, $colHeadVal);
}
}
else
{
// Write to file
fwrite($fp, $colHeaders);
}
// Check if content is an array
if (is_array($content))
{
// Loop through array and write to file
foreach ($content as $val)
{
// Write to file
fputcsv($fp, $val);
}
// Gets information about a file using an open file pointer
$stat = fstat($fp);
// Truncates a file to a given length
$truncateResponse = ftruncate($fp, $stat['size'] - 1);
}
else
{
// Write to file
fwrite($fp, $content);
}
// Close file handle
fclose($fp);
// Check if was written
if (file_exists($path . $filename) && trim($filename) !== "")
{
// Set variable value
$returnValue = "Success~File was written to server";
}
else
{
// Set variable value
$returnValue = "Error~File not written to server";
// Error log message
// error_log($returnValue);
}
}
catch (Exception $e)
{
// Catch the error from the try section of code
// Set message
$returnValue = trim('SError~Caught write to file Execution Failure - ' . $e->getMessage());
// Error log failure
// error_log($returnValue);
// error log the caught exception
// error_log($e->getMessage());
error_log($e);
}
// Return variable
return $returnValue;
}
// Put file onto the server
public function putSFTPFile($filename, $type, $localPath)
{
// 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 code
try
{
// Set array
$connectionStatus = array();
// Connect to SFTP server
$connectionStatus = $this->openConnection($type);
// Check if error with registering process
if (!isset($connectionStatus['SError']) && !array_key_exists('SError', $connectionStatus))
{
// Set variable
$filesize = "";
// Put file on remote server [remote server]/[filename], [local server]/[filename]
$this->sftp->put($this->RemotePath . $filename, $localPath . $filename, \phpseclib\Net\SFTP::SOURCE_LOCAL_FILE);
// Check if the file has been placed in the correct folder
/*
echo $this->sftp->size($remotePath . $filename);
print_r($this->sftp->stat($remotePath . $filename));
print_r($this->sftp->lstat($remotePath . $filename));
*/
// Set the file size to the variable for the return statement
$filesize = $this->sftp->size($this->RemotePath . $filename);
// Check if file size is not empty
if (trim($filesize) !== "")
{
// Set message
$returnValue = trim('Success~' . $filename . " with size of: " . $filesize . " has been transmitted.");
// Error log message
error_log($returnValue);
}
else
{
// Set message
$returnValue = trim('Error~' . $filename . " was not transmitted.");
// Error log message
// error_log($returnValue);
}
// Check if the SFTP server is still connected
if ($this->sftp)
{
// Close connection
$this->sftp->disconnect();
$this->sftp = null;
}
}
else
{
// Else error has occurred
$connectionServerMesg = reset($connectionStatus);
// Set message
$returnValue = trim('SError~Put - ' . $connectionServerMesg);
// Display error string
// error_log($returnValue);
}
}
catch(Exception $e)
{
// Set message
$returnValue = trim('SError~Caught Put SFTP File On Server Failure - ' . $e->getMessage());
// Set message
// error_log($returnValue);
// error log the caught exception
// error_log($e->getMessage());
error_log($e);
}
// Return message
return $returnValue;
}
// Get file from server
public function getSFTPFile($filenameRemote, $type, $localPath, $filenameLocal)
{
// 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 code
try
{
// Set array
$connectionStatus = array();
// Connect to SFTP server
$connectionStatus = $this->openConnection($type);
// Check if error with registering process
if (!isset($connectionStatus['SError']) && !array_key_exists('SError', $connectionStatus))
{
// Get file from remote server [remote server]/[filename], [local server]/[filename]
$this->sftp->get($this->RemotePath . $filenameRemote, $localPath . $filenameLocal);
// Check if was written
if (file_exists($localPath . $filenameLocal) && trim($filenameLocal) !== "")
{
// Set variable value
$returnValue = "Success~File was written to local server";
}
else
{
// Set variable value
$returnValue = "Error~File not written to local server";
// Error log message
// error_log($returnValue);
}
// Check if the SFTP server is still connected
if ($this->sftp)
{
// Close connection
$this->sftp->disconnect();
$this->sftp = null;
}
}
else
{
// Else error has occurred
$connectionServerMesg = reset($connectionStatus);
// Set message
$returnValue = trim('SError~Get - ' . $connectionServerMesg);
// Display error string
// error_log($returnValue);
}
}
catch(Exception $e)
{
// Set message
$returnValue = trim('SError~Caught Get SFTP File From Server Failure - ' . $e->getMessage());
// Set message
// error_log($returnValue);
// error log the caught exception
// error_log($e->getMessage());
error_log($e);
}
// Return message
return $returnValue;
}
// List file(s) from server
public function listSFTPFiles($type, $extensions)
{
// Initialize variable
$returnArray = 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 code
try
{
// Set array
$connectionStatus = array();
// Connect to SFTP server
$connectionStatus = $this->openConnection($type);
// Check if error with registering process
if (!isset($connectionStatus['SError']) && !array_key_exists('SError', $connectionStatus))
{
// List file(s) from remote server [remote server]
$list = $this->sftp->nlist($this->RemotePath);
// Check if retrieval list is an array
if (is_array($list))
{
// Process all file(s) within the return list
foreach ($list as $item => $value)
{
// Explode the string to retrieve file extension
$fileBreakDown = explode('.', $value);
// Check if string contains any matching extensions in the array
if (in_array(strtolower($fileBreakDown[count($fileBreakDown) - 1]), $extensions))
{
// Add string containing extension into the return array
array_push($returnArray, $value);
}
}
}
else
{
// Set message
$returnArray = array('SError' => trim('List Retrieval - ' . $list));
}
// Check if the SFTP server is still connected
if ($this->sftp)
{
// Close connection
$this->sftp->disconnect();
$this->sftp = null;
}
}
else
{
// Else error has occurred
$connectionServerMesg = reset($connectionStatus);
// Set message
$returnArray = array('SError' => trim('Get - ' . $connectionServerMesg));
// Display error string
// error_log($returnArray);
}
}
catch (Exception $e)
{
// Catch the error from the try section of code
// Set message
$returnArray = array('SError' => trim('Caught Get SFTP File From Server Failure - ' . $e->getMessage()));
// Error log failure
// error_log(print_r($returnArray, true));
// error log the caught exception
// error_log($e->getMessage());
error_log($e);
}
// Return message
return $returnArray;
}
// Move file around on server
public function moveSFTPFile($filenameRemote, $type, $fromPath, $toPath, $localPath)
{
// 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 code
try
{
// Set array
$connectionStatus = array();
// Connect to SFTP server
$connectionStatus = $this->openConnection($type);
// Check if error with registering process
if (!isset($connectionStatus['SError']) && !array_key_exists('SError', $connectionStatus))
{
// Set variable
$filesize = "";
$filesizeold = "";
// Put file on remote server [remote server]/[filename], [local server]/[filename]
$this->sftp->put($this->RemotePath . $toPath . $filenameRemote, $localPath . $filenameRemote, \phpseclib\Net\SFTP::SOURCE_LOCAL_FILE);
// Check if the file has been placed in the correct folder
/*
echo $this->sftp->size($remotePath . $filename);
print_r($this->sftp->stat($remotePath . $filename));
print_r($this->sftp->lstat($remotePath . $filename));
*/
// Set the file size to the variable for the return statement
$filesize = $this->sftp->size($this->RemotePath . $toPath . $filenameRemote);
// Check if file size is not empty
if (trim($filesize) !== "")
{
// Put file on remote server [remote server]/[filename], [local server]/[filename]
$this->sftp->delete($this->RemotePath . $fromPath . $filenameRemote);
// Set the file size to the variable for the return statement
$filesizeold = $this->sftp->size($this->RemotePath . $fromPath . $filenameRemote);
// Check if file size is not empty
if (trim($filesizeold) === "")
{
// Set message
$returnValue = trim('Success~' . $filenameRemote . " with size of: " . $filesize . " has been archived and Original " . $filenameRemote . " was removed");
// Error log message
error_log($returnValue);
}
else
{
// Set message
$returnValue = trim('Error~' . $filenameRemote . " with size of: " . $filesize . " has been archived and Original ". $filenameRemote . " was not removed");
// Error log message
// error_log($returnValue);
}
}
else
{
// Set message
$returnValue = trim('Error~' . $filenameRemote . " was not archived");
// Error log message
// error_log($returnValue);
}
// Check if the SFTP server is still connected
if ($this->sftp)
{
// Close connection
$this->sftp->disconnect();
$this->sftp = null;
}
}
else
{
// Else error has occurred
$connectionServerMesg = reset($connectionStatus);
// Set message
$returnValue = trim('SError~Get - ' . $connectionServerMesg);
// Display error string
// error_log($returnValue);
}
}
catch(Exception $e)
{
// Set message
$returnValue = trim('SError~Caught Get SFTP File From Server Failure - ' . $e->getMessage());
// Set message
// error_log($returnValue);
// error log the caught exception
// error_log($e->getMessage());
error_log($e);
}
// Return message
return $returnValue;
}
// Retrieve no attributes with query only
private function retrieveNoAttribute($query, $parameters, $SetNulls = "0", $SetWarnings = "0", $dbName = '<Database_Name>')
{
// 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 code
try