forked from kinlane/email-xlsx-to-csv-json-xml
-
Notifications
You must be signed in to change notification settings - Fork 0
/
job.php
executable file
·373 lines (301 loc) · 12.2 KB
/
job.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
<?php
set_time_limit(3000);
ini_set('display_errors', true);
ini_set('auto_detect_line_endings', true);
function PrepareXMLName($PrepareString)
{
$PrepareString = str_replace(" ","",$PrepareString);
$PrepareString = preg_replace('#\W#', '', $PrepareString);
$PrepareString = str_replace("ZSPAZESZ","",$PrepareString);
$PrepareString = strtolower($PrepareString);
return $PrepareString;
}
// Function to convert CSV into associative array
function csvToArray($file, $delimiter) {
if (($handle = fopen($file, 'r')) !== FALSE) {
$i = 0;
while (($lineArray = fgetcsv($handle, 4000, $delimiter, '"')) !== FALSE) {
for ($j = 0; $j < count($lineArray); $j++) {
$arr[$i][$j] = $lineArray[$j];
}
$i++;
}
fclose($handle);
}
return $arr;
}
require_once 'classes/PHPExcel/IOFactory.php';
require_once 'libraries/class.phpmailer.php';
// Open Manifest
$ManifestPath = "data/manifest.json";
$ManifestString = file_get_contents($ManifestPath);
$Manifest = json_decode($ManifestString,true);
// Open Access
$AccessPath = "data/access.json";
$AccessString = file_get_contents($AccessPath);
$Access = json_decode($AccessString,true);
/* connect to gmail with your credentials */
$hostname = '{imap.gmail.com:993/imap/ssl}INBOX';
$username = '[google email]';
$password = '[google password]';
/* try to connect */
$inbox = imap_open($hostname,$username,$password) or die('Cannot connect to Gmail: ' . imap_last_error());
/* get all new emails. If set to 'ALL' instead
* of 'NEW' retrieves all the emails, but can be
* resource intensive, so the following variable,
* $max_emails, puts the limit on the number of emails downloaded.
*
*/
$emails = imap_search($inbox,'ALL');
/* useful only if the above search is set to 'ALL' */
$max_emails = 16;
/* if any emails found, iterate through each email */
if($emails) {
$count = 1;
/* put the newest emails on top */
rsort($emails);
$output = '';
/* for every email... */
foreach($emails as $email_number)
{
/* get information specific to this email */
$overview = imap_fetch_overview($inbox,$email_number,0);
/* get mail message */
$message = imap_fetchbody($inbox,$email_number,2);
/* output the email header information */
$Seen = $overview[0]->seen;
$Subject = $overview[0]->subject;
$From = $overview[0]->from;
$FromArray = explode("<",$From);
$From_Name = trim($FromArray[0]);
$From_Email = $FromArray[1];
$From_Email = trim(str_replace(">","",$From_Email));
$Email_Date = $overview[0]->date;
$SenderArray = array();
$SenderArray['name'] = $From_Name;
$SenderArray['email'] = $From_Email;
// If this user has name email in accesss.json
if(array_search($SenderArray,$Access)==false)
{
/* get mail structure */
$structure = imap_fetchstructure($inbox, $email_number);
$attachments = array();
/* if any attachments found... */
if(isset($structure->parts) && count($structure->parts))
{
for($i = 0; $i < count($structure->parts); $i++)
{
$attachments[$i] = array(
'is_attachment' => false,
'filename' => '',
'name' => '',
'attachment' => ''
);
if($structure->parts[$i]->ifdparameters)
{
foreach($structure->parts[$i]->dparameters as $object)
{
if(strtolower($object->attribute) == 'filename')
{
$attachments[$i]['is_attachment'] = true;
$attachments[$i]['filename'] = $object->value;
}
}
}
if($structure->parts[$i]->ifparameters)
{
foreach($structure->parts[$i]->parameters as $object)
{
if(strtolower($object->attribute) == 'name')
{
$attachments[$i]['is_attachment'] = true;
$attachments[$i]['name'] = $object->value;
}
}
}
if($attachments[$i]['is_attachment'])
{
$attachments[$i]['attachment'] = imap_fetchbody($inbox, $email_number, $i+1);
/* 4 = QUOTED-PRINTABLE encoding */
if($structure->parts[$i]->encoding == 3)
{
$attachments[$i]['attachment'] = base64_decode($attachments[$i]['attachment']);
}
/* 3 = BASE64 encoding */
elseif($structure->parts[$i]->encoding == 4)
{
$attachments[$i]['attachment'] = quoted_printable_decode($attachments[$i]['attachment']);
}
}
}
}
$AttachmentCount = 0;
/* iterate through each attachment and save it */
foreach($attachments as $attachment)
{
if($attachment['is_attachment'] == 1)
{
$filename = $attachment['name'];
$FileNameArray = explode(".",$filename);
$extension = $FileNameArray[1];
if($extension=="xlsx")
{
$filename = 'excel/'. $email_number . "-" . $filename;
}
else
{
$filename = 'files/'. $email_number . "-" . $filename;
}
if(empty($filename)) $filename = $attachment['filename'];
if(empty($filename)) $filename = time() . ".dat";
$fp = fopen($filename, "w+");
fwrite($fp, $attachment['attachment']);
fclose($fp);
$AttachmentCount++;
}
}
$ExcelFileName = $filename;
$ExcelFileName = str_replace("excel/","",$filename);
echo "Seen: " . $Seen . "<br />";
echo "Subject: " . $Subject . "<br />";
echo "Name: " . $From_Name . "<br />";
echo "Email: " . $From_Email . "<br />";
echo "Date: " . $Email_Date . "<br />";
echo "FileName: " . $filename . "<br />";
$ManifestEntry = array();
$ManifestEntry['name'] = $From_Name;
$ManifestEntry['email'] = $From_Email;
$ManifestEntry['filename'] = $From_Name;
$ManifestEntry['date'] = str_replace(".xlsx","",$filename);
$ManifestEntry['processed'] = '0';
if(array_search($ManifestEntry,$Manifest)==false)
{
array_push($Manifest, $ManifestEntry);
}
$ManifestJSON = json_encode($Manifest);
$fp = fopen($ManifestPath, "w+");
fwrite($fp, $ManifestJSON);
fclose($fp);
// Go ahead and delete we have everything we need if next process is killed
imap_delete($inbox, $email_number);
//Send Email
$mail = new PHPMailer();
$mail->IsSMTP();
//GMAIL config
$mail->SMTPAuth = true; // enable SMTP authentication
$mail->SMTPSecure = "ssl"; // sets the prefix to the server
$mail->Host = "smtp.gmail.com"; // sets GMAIL as the SMTP server
$mail->Port = 465; // set the SMTP port for the GMAIL server
$mail->Username = "[google email]"; // GMAIL username
$mail->Password = "[google password]"; // GMAIL password
//End Gmail
$Body = $ExcelFileName . ' is being processed, if its not too large you will receive links in a few minutes, if it was too large or had errors it will be processed as part of nightly queue, and you will receive email when done.';
$mail->From = "[google email]";
$mail->FromName = "Conversion - Processing";
$mail->Subject = "The Excel File (" . $ExcelFileName . ") Is Being Processed";
$mail->MsgHTML($Body);
//$mail->AddReplyTo("reply@email.com","reply name");//they answer here, optional
$mail->AddAddress($From_Email,$From_Name);
$mail->IsHTML(true); // send as HTML
if(!$mail->Send()) {//to see if we return a message or a value bolean
echo "Mailer Error: " . $mail->ErrorInfo;
} else echo "Message sent!";
// Generate CSV
$CSVFileName = str_replace(".xlsx",".csv",$filename);
$CSVFileName = str_replace("excel/","csv/",$CSVFileName);
$excel = PHPExcel_IOFactory::load($filename);
$writer = PHPExcel_IOFactory::createWriter($excel, 'CSV');
$writer->setDelimiter(",");
//$writer->setEnclosure("");
//$writer->setLineEnding("\r\n");
$writer->setSheetIndex(0);
$writer->save($CSVFileName);
// Generate JSON
$JSONFileName = str_replace(".csv",".json",$CSVFileName);
$JSONFileName = str_replace("csv/","json/",$JSONFileName);
$keys = array();
$newArray = array();
$data = csvToArray($CSVFileName, ',');
$count = count($data) - 1;
$labels = array_shift($data);
foreach ($labels as $label) { $keys[] = $label; }
$keys[] = 'id';
for ($i = 0; $i < $count; $i++) {
$data[$i][] = $i;
}
for ($j = 0; $j < $count; $j++) {
$d = array_combine($keys, $data[$j]);
$newArray[$j] = $d;
}
$JSONVersion = json_encode($newArray);
$fp = fopen($JSONFileName, "w+");
fwrite($fp, $JSONVersion);
fclose($fp);
// Generate XML
$XMLFileName = str_replace(".csv",".xml",$CSVFileName);
$XMLFileName = str_replace("csv/","xml/",$XMLFileName);
// Open csv to read
$inputFile = fopen($CSVFileName, 'rt');
// Get the headers of the file
$headers = fgetcsv($inputFile);
// Create a new dom document with pretty formatting
$doc = new DomDocument();
$doc->formatOutput = true;
// Add a root node to the document
$root = $doc->createElement('rows');
$root = $doc->appendChild($root);
// Loop through each row creating a <row> node with the correct data
while (($row = fgetcsv($inputFile)) !== FALSE)
{
$container = $doc->createElement('row');
foreach ($headers as $i => $header)
{
$header = str_replace(chr(32),"_",trim($header));
$header = strtolower($header);
if($header==''){ $header = 'empty';}
$header = PrepareXMLName($header);
if(is_numeric($header)) { $header = "number-". $header; }
//echo "HERE: " . $header . "<br />";
$child = $doc->createElement($header);
$child = $container->appendChild($child);
$value = $doc->createTextNode($row[$i]);
$value = $child->appendChild($value);
}
$root->appendChild($container);
}
$XMLVersion = $doc->saveXML();
$fp = fopen($XMLFileName, "w+");
fwrite($fp, $XMLVersion);
fclose($fp);
//Send Email
$mail = new PHPMailer();
$mail->IsSMTP();
//GMAIL config
$mail->SMTPAuth = true; // enable SMTP authentication
$mail->SMTPSecure = "ssl"; // sets the prefix to the server
$mail->Host = "smtp.gmail.com"; // sets GMAIL as the SMTP server
$mail->Port = 465; // set the SMTP port for the GMAIL server
$mail->Username = "[google email]"; // GMAIL username
$mail->Password = "[google password]"; // GMAIL password
//End Gmail
$Body = '<a href="http://conversion.laneworks.net/' . $CSVFileName . '">CSV File</a><br />';
$Body .= '<a href="http://conversion.laneworks.net/' . $JSONFileName . '">JSON File</a><br />';
$Body .= '<a href="http://conversion.laneworks.net/' . $XMLFileName . '">XML File</a><br />';
$mail->From = "[google email]";
$mail->FromName = "Conversion - Complete";
$mail->Subject = "The Excel File Has Been Converted";
$mail->MsgHTML($Body);
//$mail->AddReplyTo("reply@email.com","reply name");//they answer here, optional
$mail->AddAddress($From_Email,$From_Name);
$mail->IsHTML(true); // send as HTML
if(!$mail->Send()) {//to see if we return a message or a value bolean
echo "Mailer Error: " . $mail->ErrorInfo;
} else echo "Message sent!";
if($count++ >= $max_emails) break;
}
}
}
/* close the connection */
imap_close($inbox);
echo "<br />Done";
?>