Created
January 28, 2015 09:59
-
-
Save eightyeight/c3005c81218de8ad71f3 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$streamStr = parseStream(); | |
$dataArray = stringToArray($streamStr); | |
$from = getFromHeader($dataArray); | |
if($from == '<[email protected]>'){ | |
$attachmentStr = getAttachment($dataArray); | |
$attachmentData = getAttachmentData($attachmentStr); | |
insertData($attachmentData); | |
} | |
/* | |
* Парсим поток Ввода, собираем в строку. | |
* @return srting | |
*/ | |
function parseStream(){ | |
$stream = fopen("php://stdin", "r"); | |
$emailStr = ""; | |
while (!feof($stream)) { | |
$emailStr .= fread($stream, 2048); | |
} | |
fclose($stream); | |
return $emailStr; | |
} | |
/* | |
* @return array. | |
* Возвращает массив строк разделенный сиволом перевода строки. | |
*/ | |
function stringToArray($string){ | |
return $arrayStr = explode('\n', $string); | |
} | |
/* | |
* Извлекаем параметр From | |
*/ | |
function getFromHeader($array){ | |
for ($i=0; $i < count($array); $i++) { | |
if (preg_match("/^From: (.*)/", $array[$i], $matches)) { | |
$from = $matches[1]; | |
return $from; | |
} | |
} | |
} | |
/* | |
* Извлекаем элемент массива в котором содержится данные attachment | |
*/ | |
function getAttachment($array){ | |
$attachment = $array[count($array) - 1]; | |
return base64_decode($attachment); | |
} | |
/* | |
* Собираем данные из строки в двухмерный массив, удаляем ненужную информацию; | |
* @return array | |
*/ | |
function getAttachmentData($string){ | |
$prepareStr = preg_replace('/[\n]/', '|', $string); | |
$dataItems = explode('|', $prepareStr); | |
array_pop($dataItems); | |
$resArray = array(); | |
foreach ($dataItems as $dataStr) { | |
$str = preg_replace('/[\s]+/', '|', $dataStr); | |
$resArray[] = explode('|', $str); | |
} | |
return $resArray; | |
} | |
/* | |
* Пишем в базу, запросы в цикле - не хорошо... | |
*/ | |
function insertData($dataArray){ | |
$db = new PDO("mysql:host=localhost;dbname=test", 'username', ''); | |
$stmt = $db->prepare('INSERT INTO info (`date`, `fs_id`, `sum`) VALUES(:datetime, :fs_id, :sum)'); | |
foreach($dataArray as $item) | |
{ | |
$date = DateTime::createFromFormat("d.m.Y H:i:s", $item[1] . ' ' . $item[2]); | |
$stmt->bindValue(':datetime', $date->format("Y-m-d H:i:s")); | |
$stmt->bindValue(':fs_id', $item[0]); | |
$stmt->bindValue(':sum', $item[4]); | |
$stmt->execute(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment