-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathemail_processor.php
More file actions
202 lines (180 loc) · 7.81 KB
/
Copy pathemail_processor.php
File metadata and controls
202 lines (180 loc) · 7.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
<?php
require(SEEDROOT.'/vendor/autoload.php');
use Ddeboer\Imap\Server;
use Ddeboer\Imap\SearchExpression;
use Ddeboer\Imap\Search\Flag\Unseen;
use Ddeboer\Imap\MessageIterator;
class EmailProcessor {
//Constants
const HST = 1.13;
const FOLDER = CATSDIR_FILES."/acounting/attachments/";
//Potential proccessing error code constants
const DISCARDED_NO_AMOUNT = -1;
const DISCARDED_NO_DATE = -2;
const DISCARDED_ZERO_AMOUNT = -3;
//Body Entries Cutoff numbers
const EMPTY_LINE_CUTOFF = 2;
const DASH_CUTOFF = 8;
//Paterns used to pull information out of emails
private $PATTERNS = array(
"amount" => "/\\$\\-?[0-9]+\\.?[0-9]*H?($|[, ])/",
"income" => "/income/i",
"date" => "/(?<= )((Jan|Feb|Mar|Apr|May|Jun|June|Jul|July|Aug|Sept|Sep|Oct|Nov|Dec) [0-3]?[0-9]\/[0-9]{2,4})|(\\d{2}\\/\\d{2}\/\\d{2}(\\d{2})?)/i",
"companyCreditCard" => "/ccc/i"
);
private $connection;
public function __construct($email, $psw){
$server = new Server("catherapyservices.ca");
$this->connection = $server->authenticate($email,$psw);
if(!file_exists(self::FOLDER)){
@mkdir(self::FOLDER, 0777, true);
echo "Attachments Directiory Created<br />";
}
}
public function processEmails($box = 'INBOX'){
$mailbox = $this->connection->getMailbox($box);
$search = new SearchExpression();
$search->addCondition(new Unseen());
$this->processMessages($mailbox->getMessages($search));
}
private function processMessages(MessageIterator $messages){
foreach($messages as $message){
$attachment = microtime(TRUE);
echo $attachment."<br />";
$raAttachments = $message->getAttachments();
if(count($raAttachments) > 0){
$oAttachment = $raAttachments[0];
$attachmentFile = fopen(self::FOLDER.$attachment.".".pathinfo($oAttachment->getFilename(), PATHINFO_EXTENSION), "w");
fwrite($attachmentFile, $oAttachment->getDecodedContent());
fclose($attachmentFile);
}
else{
$attachment = NULL;
}
preg_match("/(?<=\\.)\w+(?=@)/i", $message->getTo()[0]->getAddress(), $matches);
$clinic = $matches[0];
$entries = array();
$errors = array();
$from = $message->getFrom();
$subject = $message->getSubject();
$date = $message->getDate();
$body = $message->getBodyText();
$subject = $message->getSubject();
//Pull the information out of subject
$result = $this->processString($subject, $attachment, $clinic);
if($result instanceof AccountingEntry){
array_push($entries, $result);
}
else{
$errors['subject'] = $result;
}
if($body){
$lines = explode("\n", $body);
$emptyLineCount = 0;
//For every line in the body
//Pull the information out
foreach ($lines as $key => $line){
if(!preg_match_all("/[$,-9A-Za-z]+/", $line)){
//The line is empty, don't try to process
$emptyLineCount++;
continue;
}
if($emptyLineCount >= self::EMPTY_LINE_CUTOFF || substr_count($line, "-") >= self::DASH_CUTOFF){
//Its safe to assume there won't be any entries after this point
break;
}
$emptyLineCount = 0;
$result = $this->processString($line, $attachment, $clinic);
if($result instanceof AccountingEntry){
array_push($entries, $result);
}
else{
$errors["line_".$key] = $result;
}
}
}
if($responce = $this->handleErrors($entries,$errors)){
echo str_replace("\n", "<br />", $responce);
echo "<br />";
}
var_dump($entries);
echo "<br />";
//TODO Link into accounting system
$message->markAsSeen();
}
}
private function processString(String $value, String $attachment, String $clinic){
preg_match($this->PATTERNS['amount'], $value, $matches);
if(count($matches) === 0){
return self::DISCARDED_NO_AMOUNT;
}
$amount = $matches[0];
$amount = substr($amount, 1, -1); //Extract amount from wrappers
if(substr_compare($amount, "H", -1, 1, TRUE) == 0){
$amount = substr($amount, 0, -1); //Remove the 'H' from the amount
$amount *= self::HST;
$amount = round($amount, 2);
}
$incomeOrExpense = NULL; // Start as not defined
if($amount < 0 || preg_match($this->PATTERNS["income"], $value)){
$incomeOrExpense = "Income";
if($amount < 0){
$amount *= -1;
}
}
elseif ($amount > 0){
$incomeOrExpense = "Expense";
}
if($incomeOrExpense){
preg_match($this->PATTERNS["date"], $value, $matches);
if(count($matches) === 0){
return self::DISCARDED_NO_DATE;
}
$date = $matches[0];
$category = preg_replace($this->PATTERNS, "", $value);
return new AccountingEntry($amount, $incomeOrExpense, $clinic, $date,$category, $attachment, (preg_match($this->PATTERNS['companyCreditCard'], $value) > 0));
}
return self::DISCARDED_ZERO_AMOUNT;
}
private function handleErrors(array $entries, array $errors){
$responce = "";
foreach($errors as $k => $v){
if($k == "subject" && $v == self::DISCARDED_NO_AMOUNT && count($entries) != 0){
continue;
}
switch ($v){
case self::DISCARDED_NO_AMOUNT:
$responce .= "Missing Amount ".($k == "subject"?"in ":"on ").str_replace("_", " ", $k)."\n"
."Please check that the amount begins with a $, ends with either a comma, a space or the end of the line/subject, and contains a maximum of one decimal\n";
break;
case self::DISCARDED_NO_DATE:
$responce .= "Missing Date ".($k == "subject"?"in ":"on ").str_replace("_", " ", $k)."\n"
."Accepted formats are MMM(M) DD?YY(YY) and MM/DD/YY(YY). Values in brackets are optional.\n";
break;
case self::DISCARDED_ZERO_AMOUNT:
$responce .= "Amount is zero ".($k == "subject"?"in ":"on ").str_replace("_", " ", $k)."\n"
."The amount was calulated as zero and the entry was discarded since it does not affect the balance\n";
break;
}
}
return $responce;
}
}
class AccountingEntry {
private $amount;
private $type;
private $clinic;
private $category;
private $date;
private $attachment;
private $ccc;
function __construct($amount, $type, $clinic, $date, $category, $attachment, $ccc){
$this->clinic = $clinic;
$this->amount = $amount;
$this->type = $type;
$this->category = $category;
$this->attachment = $attachment;
$this->ccc = $ccc;
}
}
?>