-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathphpDTAUS.php
725 lines (618 loc) · 25.3 KB
/
phpDTAUS.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
<?php
/**
* phpDTAUS helps you creating so-called DTAUS (Datenaustauschverfahren) files. This file format
* was devised by the German ZKA or Zentraler Kreditausschuss (Central Credit Committee) in the
* mid-seventies. It is used for the automated processing of wire transfers and direct debits in
* Germany. The files created with this class are either sent to the bank (via email or any other
* means) or imported into online banking software for processing.
*
* To check the validity of the file you may visit http://www.xpecto.de/content/dtauschecker. There
* you simply upload the created file. If everything is alright, you should get a message that the
* file is valid, as well as a list of the transactions that were encoded in the file.
*
* @author Alexander Serbe <[email protected]>
* @version 1.0
* @copyright Copyright 2012 by progressive design and technology
* @license http://www.gnu.org/licenses/gpl-3.0.txt GNU General Public License
*
* ------------------------------------------------------------------------------------------------
*
* phpDTAUS 1.0
* Copyright (c) 2010 by progressive design and technology
*
* This program is free software: you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
* You should have received a copy of the GNU Lesser General Public License along with this
* program. If not, see <http://www.gnu.org/licenses/>.
*/
class phpDTAUS
{
/**
* Array of checksums for account numbers, bank codes, and amounts. These values are added to
* the footer of the DTAUS file to verify its content.
* @var array $_checksums
*/
protected $_checksums = array(
'accountNumbers' => 0,
'bankCodes' => 0,
'amounts' => 0
);
/**
* Default mapping for CSV files. This mapping is used, if none is specified in the call to
* readCsv().
* @var array $_csvDefaultMapping
*/
protected $_csvDefaultMapping = array(
'name' => 0,
'bankCode' => 1,
'account' => 2,
'amount' => 3,
'ref' => 4,
'type' => 5,
'customerId' => 6
);
/**
* Array of formatted C-records. C-records in a DTAUS file contain the actual transactions.
* @var array $_entries
*/
protected $_entries = array();
/**
* Array of C-record extensions. Every C-record may contain a certain number of extensions.
* These extensions may contain additional information on the beneficiary of the payment,
* the reference and the payer. Please note that only a specified number for each type of
* extension are allowed:
* + max. 1 extension for the beneficiary,
* + max. 13 extensions for the reference, and
* + max. 1 extension for the payer
*/
protected $_extensions = array();
/**
* Account number of the originator.
* @var integer $_originatorAccount
*/
protected $_originatorAccount;
/**
* Bank code of the originator's bank.
* @var integer $_originatorBankCode
*/
protected $_originatorBankCode;
/**
* Name of the originator.
* @var string $_originatorName
*/
protected $_originatorName;
protected $_type;
/**
* Constructor. Checks input parameters and stores them in the appropriate member variables.
* Throws an InvalidArgumentException in case one or more parameters do not meet the given
* specifications.
*
* @throws InvalidArgumentException
* @param string $originatorName Name of the originator
* @param integer $originatorBankCode Bank code of the originator's bank
* @param integer $originatorAccount Account number of the originator
* @param string $type
*/
public function __construct($originatorName, $originatorBankCode, $originatorAccount, $type = 'L')
{
if (strlen(trim($originatorName)) == 0) {
throw new InvalidArgumentException('Please set the name of the originator of the transfer.');
}
if (strlen(trim($originatorBankCode)) == 0) {
throw new InvalidArgumentException('Please set the bank code of the originator of the transfer.');
} elseif (strlen(trim($originatorBankCode)) != 8) {
throw new InvalidArgumentException('Please check the bank code of the originator of the transfer. German bank codes are exactly eight digits long. The bank code you entered is ' . strlen(trim($originatorBankCode)) . ' digits long.');
}
if (strlen(trim($originatorAccount)) == 0) {
throw new InvalidArgumentException('Please enter the account number of the originator of the transfer.');
} elseif (strlen(trim($originatorAccount)) > 10) {
throw new InvalidArgumentException('Please check the account number of the originator of the transfer. German account numbers cannot be longer than 10 digits. The account number you enteres was ' . strlen(trim($originatorAccount)) . ' digits long.');
}
if (strlen(trim($type)) == 0) {
throw new InvalidArgumentException('Please enter the type of the transactions.');
} elseif (strtoupper($type) != 'L' && strtoupper($type) != 'G') {
throw new InvalidArgumentException('The two possible transaction types are \'L\' for direct debit or \'G\' for wire transfers.');
}
$this->_originatorName = trim($originatorName);
$this->_originatorBankCode = trim($originatorBankCode);
$this->_originatorAccount = trim($originatorAccount);
if (strtoupper($type) == 'L') {
$this->_type = '05';
} else {
$this->_type = '51';
}
}
/**
* Adds a transaction (C-record).
*
* @return void
* @param string $name Name of the payee or the payer
* @param integer $bankCode Bank code of the payee or payer
* @param integer $account Account number of the payee or payer
* @param float $amount Amount
* @param string $ref Reference
* @param string $type Key (04 = debiting [Abbuchung], 05 = direct debit [Einzug], 51 = bank transfer [Überweisung], 53 = salary [Gehalt], 54 = capital-forming benefits [Vermögenswirksame Leistungen])
* @param integer $customerId Internal customer ID
*/
public function addTransaction($name, $bankCode, $account, $amount, $ref = '', $type = '05', $customerId = 0)
{
$tmp = 'C';
$tmp .= '00000000';
$tmp .= $this->_prepString($bankCode, array('length' => 8, 'fill' => false));
$tmp .= $this->_prepString($account, array('length' => 10, 'fill' => true, 'char' => '0', 'align' => 'right'));
if ($customerId > 0) {
$tmp .= $this->_prepString(
$customerId,
array(
'length' => 13,
'fill' => true,
'char' => '0',
'align' => 'left'
)
);
} else {
$tmp .= '0000000000000';
}
$tmp .= $type;
$tmp .= '000';
$tmp .= ' ';
$tmp .= '00000000000';
$tmp .= $this->_originatorBankCode;
$tmp .= $this->_prepString(
$this->_originatorAccount,
array(
'length' => 10,
'fill' => true,
'char' => '0',
'align' => 'left'
)
);
$tmp .= $this->_prepString(
number_format($amount, 2, '', ''),
array(
'length' => 11,
'fill' => true,
'char' => '0',
'align' => 'right'
)
);
$tmp .= ' ';
$tmpExt = $this->_prepString(
$name,
array(
'length' => 27,
'fill' => true,
'char' => ' ',
'align' => 'left',
'transform' => 'upper',
'replaceUmlauts' => true,
'truncate' => true,
'multiline' => true,
'maxLines' => 2
)
);
if (is_array($tmpExt)) {
$this->_extensions[] = array('03', $tmpExt[1]);
$tmp .= $tmpExt[0];
} else {
$tmp .= $tmpExt;
}
$tmp .= ' ';
$tmp .= $this->_prepString(
$this->_originatorName,
array(
'length' => 27,
'fill' => true,
'char' => ' ',
'align' => 'left',
'transform' => 'upper',
'replaceUmlauts' => true,
'mutliline' => true
)
);
$tmpExt = $this->_prepString(
$ref,
array(
'length' => 27,
'fill' => true,
'char' => ' ',
'align' => 'left',
'transform' => 'upper',
'replaceUmlauts' => true,
'truncate' => true,
'multiline' => true,
'maxLines' => 13
)
);
if (is_array($tmpExt)) {
for ($i=1, $m=count($tmpExt)-1; $i<$m; $i++) {
$this->_extensions[] = array('02', $tmpExt[$i]);
}
$tmp .= $tmpExt[0];
} else {
$tmp .= $tmpExt;
}
$tmp .= '1';
$tmp .= ' ';
$cntExt = count($this->_extensions);
$tmp .= $this->_prepString($cntExt, array('length' => 2, 'fill' => true, 'char' => '0', 'align' => 'right'));
if ($cntExt == 0) {
$tmp .= ' ';
$tmp .= ' ';
} elseif ($cntExt == 1) {
$tmp .= $this->_extensions[0][0];
$tmp .= $this->_extensions[0][1];
$tmp .= ' ';
} elseif ($cntExt > 1) {
$tmp .= $this->_extensions[0][0];
$tmp .= $this->_extensions[0][1];
$tmp .= $this->_extensions[1][0];
$tmp .= $this->_extensions[1][1];
}
$tmp .= ' ';
for ($i=2; $i<$cntExt; $i++) {
$tmp .= $this->_extensions[$i][0];
$tmp .= $this->_extensions[$i][1];
}
$recLength = 187 + $cntExt * 29;
$tmp = $this->_prepString(
$recLength,
array(
'length' => 4,
'fill' => true,
'char' => '0',
'align' => 'right'
)
) . $tmp;
$this->_entries[] = $tmp;
$this->_checksums['accountNumbers'] += $this->_prepString(
$account,
array(
'length' => 10,
'fill' => true,
'char' => '0',
'align' => 'right'
)
);
$this->_checksums['bankCodes'] += $bankCode;
$this->_checksums['amounts'] += $amount;
}
/**
* Reads a CSV file and adds the transactions to a DTAUS file.
*
* @return void
* @throws LogicException
* @param string $file The CSV file
* @param array $mapping Mapping for the CSV columns. If this parameter is empty, the default mapping in $_csvDefaultMapping will be used.
* @param string $defaultRef Default reference for transactions. Used when none is given in CSV file
*/
public function readCsv($file, $mapping=null, $defaultRef='')
{
if (! file_exists($file)) {
throw new LogicException('The file ' . $file . ' does not exist.');
}
$csvTransactions = array();
if (($handle = fopen($file, 'r')) !== false) {
while (($data = fgetcsv($handle, 1000, ';')) !== false ) {
$csvTransactions[] = $data;
}
fclose($handle);
}
if (count($csvTransactions) == 0) {
throw new LogicException('The file ' . $file . ' appears to be empty.');
}
if (empty($mapping)) {
$mapping = $this->_csvDefaultMapping;
}
for ($i = 0, $max = count($csvTransactions); $i < $max; $i++) {
$tmp = $csvTransactions[$i];
if (!is_array($tmp) || count($tmp) == 0) {
continue;
}
$name = $tmp[$mapping['name']];
$bankcode = $tmp[$mapping['bankCode']];
$account = $tmp[$mapping['account']];
$amount = $tmp[$mapping['amount']];
if (! empty($mapping['ref'])) {
$ref = $tmp[$mapping['ref']];
} else {
$ref = '';
}
if (! empty($mapping['type'])) {
$type = $tmp[$mapping['type']];
} else {
$type = '';
}
if (! empty($mapping['customerId'])) {
$customerId = $tmp[$mapping['customerId']];
} else {
$customerId = '';
}
if (strlen($name) == 0) {
throw new LogicException('A record in the file does have an empty name field.');
}
if (strlen($bankcode) == 0) {
throw new LogicException('A record in the file does have an empty bank code field.');
}
if (strlen($account) == 0) {
throw new LogicException('A record in the file does have an empty account number field.');
}
if (strlen($amount) == 0 ) {
throw new LogicException('A record in the file does have an empty amount field.');
}
if (strlen($ref) == 0) {
if (strlen($defaultRef) == 0) {
throw new LogicException('A record in the file does have an empty reference field and no global reference has been set.');
} else {
$ref = $defaultRef;
}
}
if (strlen($type) == 0) {
$type = $this->_type;
}
if (strlen($customerId) == 0) {
$customerId = 0;
}
$this->addTransaction($name, $bankcode, $account, $amount, $ref, $type, $customerId);
}
}
/**
* Creates a DTAUS file and returns it
*
* @return string
* @throws LogicException
* @throws InvalidArgumentException
* @param string $type Type. Either L for debit (Lastschrift) or G for credit note (Gutschrift)
* @param string $ref Collective reference number of the client
* @param string $execDate Alternative execution date (ddmmyyyy)
*/
public function createDtaus($type = 'L', $ref = "0", $execDate = '')
{
if (count($this->_entries) == 0) {
throw new LogicException('No transactions found.');
}
$tmp = $this->_header($type, $ref, $execDate);
for ($i = 0, $max = count($this->_entries); $i < $max; $i++) {
$tmp .= $this->_entries[$i];
}
$tmp .= $this->_footer();
return $tmp;
}
/**
* Transform a string into the desired format. The options array may contain none or several
* of the following elements:
* + length (integer) - the max. length of the converted string (defaults to '10').
* + fill (boolean) - whether or not to fill the string to the length specified in 'length'
* (default TRUE).
* + char (string) - character to be used to fill the string (default ' ' [space]).
* + align (string) - whether to fill the string to the left with the character specified
* in 'char' or to the right (default 'left'). Possible values are 'left' and
* 'right'.
* + transform (string) - whether to transform the result string to upper case ('upper'),
* to lower case ('lower'), or not at all ('none'). Default is 'none'.
* + replaceUmlauts (boolean) - whether or not to transliterate German umlauts. Default is
* FALSE.
* + truncate (boolean) - whether or not to truncate the result string if it is longer then
* 'length'. Default is FALSE.
* + multiline (boolean) - determines if multiple lines should be created if necessary.
* Default is FALSE.
* + maxLines (integer) - max. number of lines to be created if 'multiline' is set to TRUE.
* Default is '0'. Setting 'maxlines' to zero and 'multiline' to TRUE will result in as
* many lines as are required to split the whole input string.
*
* @return string
* @throws InvalidArgumentException
* @throws LengthException
* @param string $str The source string
* @param array $options Array of options described above
*/
protected function _prepString($str, $options = array())
{
$str = trim($str);
// Check input string
if (strlen($str) == 0) {
throw new InvalidArgumentException('String $str cannot be empty.');
}
// Set options from $options array
$len = (!array_key_exists('length', $options) || (int) $options['length'] == 0) ? 10 : (int) $options['length'];
$fill = (!array_key_exists('fill', $options) || !is_bool($options['fill'])) ? true : $options['fill'];
$char = (!array_key_exists('char', $options) || strlen(trim($options['char'])) == 0) ? ' ' : (int) $options['char'];
$align = (!array_key_exists('align', $options) || strlen(trim($options['align'])) == 0) ? 'left' : $options['align'];
$transform = (!array_key_exists('transform', $options) || strlen(trim($options['transform'])) == 0) ? 'none' : $options['transform'];
$replaceUmlauts = (!array_key_exists('replaceUmlauts', $options) || !is_bool($options['replaceUmlauts'])) ? false : $options['replaceUmlauts'];
$truncate = (!array_key_exists('truncate', $options) || !is_bool($options['truncate'])) ? false : $options['truncate'];
$multiline = (!array_key_exists('multiline', $options) || !is_bool($options['multiline'])) ? false : $options['multiline'];
$maxLines = (!array_key_exists('maxLines', $options) || (int) $options['maxLines'] == 0) ? 0 : (int) $options['maxLines'];
// Check options
if (strlen(trim($char)) > 1) {
throw new InvalidArgumentException('Option \'char\' cannot exceed one character.');
}
if ($align != 'left' && $align != 'right') {
throw new InvalidArgumentException('Option \'align\' must be either \'left\' or \'right\'.');
}
if ($transform != 'upper' && $transform != 'lower' && $transform != 'none') {
throw new InvalidArgumentException('Option \'transform\' must be \'upper\', \'lower\', or \'none\'.');
}
// Process string
// Transliterate German umlauts if required and the German 'ß'. This has to be done first,
// since it changes the total length of the string.
if ($replaceUmlauts) {
// Umlauts are transliterated by appending an 'e' to the base vowel.
$str = str_replace(
array('ä', 'ö', 'ü', 'Ä', 'Ö', 'Ü', 'ß'),
array('ae', 'oe', 'ue', 'Ae', 'Oe', 'Ue', 'ss'),
$str
);
}
// Next we transform the string to upper or lower case, if requested
if ($transform == 'upper') {
$str = strtoupper($str);
} elseif($transform == 'lower') {
$str = strtolower($str);
}
// Truncate the string if requested (mind multiline and maxLines settings)
if ($truncate && (strlen($str) > $len) && $multiline) {
$returnArray = str_split($str, $len);
if ($maxLines > 0) {
$returnArray = array_slice($returnArray, 0, $maxLines);
}
} elseif ($truncate && (strlen($str) > $len) && !$multiline ) {
$returnArray = array(substr($str, 0, $len));
} elseif (! $truncate && (strlen($str) > $len)) {
throw new LengthException('String ' . $str . ' is too long and truncating it has been prohibited.');
//echo $str . ' LENGTH EXCEPTION<hr />';
} else {
$returnArray = array($str);
}
// Fill the string either to the left or to the right as requested.
if ($fill && strlen($char) > 0 && ($align == 'left' || $align == 'right')) {
for ($i = 0, $m = count($returnArray); $i < $m; $i++ ) {
while (strlen($returnArray[$i]) < $len) {
if ($align == 'left') {
$returnArray[$i] = $returnArray[$i] . $char;
} elseif ($align == 'right') {
$returnArray[$i] = $char . $returnArray[$i];
}
}
}
}
if (count($returnArray) == 1) {
return $returnArray[0];
} else {
return $returnArray;
}
}
/**
* Creates an E-record (footer). This contains the number of C-records and the checksums for
* account numbers, bank codes and amounts.
*
* @return string
*/
protected function _footer()
{
$tmp = '0128';
$tmp .= 'E';
$tmp .= ' ';
$tmp .= $this->_prepString(
count($this->_entries),
array(
'length' => 7,
'fill' => true,
'char' => '0',
'align' => 'right'
)
);
$tmp .= '0000000000000';
$tmp .= $this->_prepString(
$this->_checksums['accountNumbers'],
array(
'length' => 17,
'fill' => true,
'char' => '0',
'align' => 'right'
)
);
$tmp .= $this->_prepString(
$this->_checksums['bankCodes'],
array(
'length' => 17,
'fill' => true,
'char' => '0',
'align' => 'right'
)
);
$tmp .= $this->_prepString(
number_format($this->_checksums['amounts'], 2, '', ''),
array(
'length' => 13,
'fill' => true,
'char' => '0',
'align' => 'right'
)
);
$tmp .= ' ';
return $tmp;
}
/**
* Creates the A-record (header).
*
* @return string
* @throws InvalidArgumentException
* @throws LogicException
* @param string $type $type Type. Either L for debit (Lastschrift) or G for credit note (Gutschrift)
* @param string $ref Collective reference number of the client
* @param string $execDate Alternative execution date (ddmmyyyy)
*/
protected function _header($type, $ref = "0", $execDate='')
{
if ($type != 'L' && $type != 'G') {
throw new InvalidArgumentException('Invalid type. Type must be either \'L\' for debits or \'G\' for credit notes.');
}
if (strlen($ref) > 10) {
throw new InvalidArgumentException('The collective reference number must not be longer than 10 digits.');
}
if (strlen($execDate) > 0 && strlen($execDate) != 8) {
throw new InvalidArgumentException('Please enter the execution date in the format \'ddmmyyyy\'.');
} elseif (strlen($execDate) == 8) {
$tmpDay = substr($execDate, 0, 2);
$tmpMonth = substr($execDate, 2, 2);
$tmpYear = substr($execDate, 4, 4);
$nowTs = mktime(12, 0, 0);
$thenTs = mktime(23, 59, 59, $tmpMonth, $tmpDay, $tmpYear);
$fifteenDays = 60 * 60 * 24 * 15;
if ($thenTs > ($nowTs + $fifteenDays)) {
throw new LogicException('The alternative execution date can be no more than fifteen days in the future.');
}
}
$tmp = '';
$tmp .= '0128';
$tmp .= 'A';
$tmp .= $type . 'K';
$tmp .= $this->_originatorBankCode;
$tmp .= '00000000';
$tmpExt = $this->_prepString(
$this->_originatorName, array(
'length' => 27,
'fill' => true,
'char' => ' ',
'align' => 'left',
'transform' => 'upper',
'replaceUmlauts' => true,
'truncate' => true,
'mutliline' => true,
'maxLines' => 2
)
);
if (is_array($tmpExt)) {
$this->_extensions[] = array('01', $tmpExt[1]);
$tmp .= $tmpExt[0];
} else {
$tmp .= $tmpExt;
}
$tmp .= date('dmy');
$tmp .= ' ';
$tmp .= $this->_prepString(
$this->_originatorAccount,
array(
'length' => 10,
'fill' => true,
'char' => '0',
'align' => 'right'
)
);
$tmp .= $this->_prepString($ref, array('length' => 10, 'fill' => true, 'char' => '0'));
$tmp .= ' ';
if (strlen($execDate) == 8) {
$tmp .= $execDate;
} else {
$tmp .= ' ';
}
$tmp .= ' ';
$tmp .= '1';
return $tmp;
}
}