<?
function setLogEmail($from , $to, $subj, $text, $rez,$msg){
    //ЛОгирование отправки формы на почту
    $message = date("d-m-Y H:i:s",  time())." : ".$msg."\r\n";
    $message .= "Результат: ".$rez."\r\n";
    $message .= "Исходные данные: \r\n";
    $message .= "От: ".$from."\r\n";
    $message .= "Куда: ".$to."\r\n";
    $message .= "Тема: ".$subj."\r\n";
    $message .= "Текст: ".$text."\r\n";
    $message .= "-----------------------------------------------------\r\n\r\n\r\n\r\n";
    file_put_contents($_SERVER['DOCUMENT_ROOT']."/baform/showrezulthtml/log_email.txt", $message);
}
$ms = $_REQUEST;
if(!empty($ms['main_message'])){
    setLogEmail($from , $toUser, $subjUser, $text, $rez,"Отправлено SPAM1");
    echo "SPAM1";
    die;
}
$isSpam = 1;
if(!empty($ms['fromEmail'])){
    if($ms['fromEmail'] == "-DATA_EMAIL_FROM-"){
        $isSpam = 0;
    }
}
if($isSpam == 1 ){
    setLogEmail($from , $toUser, $subjUser, $text, $rez,"Отправлено SPAM2");
    echo "SPAM2";
    die;
}

$max = 100;

$bodyHtml = "";
$bodyText = "";
$iz=1;
$arrFiles=Array();
for($iz = 1;$iz<=$max; $iz++){
    if(!empty($ms['rezult-question-'.$iz])){
        $strStep = "Шаг №".$iz." ";
        if(strlen($bodyHtml) === 0){
            $bodyHtml = $strStep.$ms['question_'.$iz]."<br>".$ms['rezult-question-'.$iz];
            $bodyText = $strStep.$ms['question_'.$iz]."\r\n".$ms['rezult-question-'.$iz];
        }else{
            $bodyHtml .= "<br><br>".$strStep.$ms['question_'.$iz]."<br>".$ms['rezult-question-'.$iz];
            $bodyText .= "\r\n\r\n".$strStep.$ms['question_'.$iz]."\r\n".$ms['rezult-question-'.$iz];
        }
    }
    $izInput = 1;
    for($izInput = 1;$izInput<=20; $izInput++){
        if(!empty($ms['question-'.$iz.'-input-'.$izInput])){
            if(strlen($bodyHtml) === 0){
                $bodyHtml = $ms['label-question-'.$iz.'-input-'.$izInput]."<br>".$ms['question-'.$iz.'-input-'.$izInput];
                $bodyText = $ms['label-question-'.$iz.'-input-'.$izInput]."\r\n".$ms['question-'.$iz.'-input-'.$izInput];
            }else{
                $bodyHtml .= "<br><br>".$ms['label-question-'.$iz.'-input-'.$izInput]."<br>".$ms['question-'.$iz.'-input-'.$izInput];
                $bodyText .= "\r\n\r\n".$ms['label-question-'.$iz.'-input-'.$izInput]."\r\n".$ms['question-'.$iz.'-input-'.$izInput];
            }
        }
        if(!empty($_FILES)){
            foreach($_FILES as $key=>$val){
                if($key == 'file_'.$iz.'_file_'.$izInput){
                    if(!empty($val['tmp_name'])){
                        $path_parts = pathinfo($val['full_path']);
                        if(!empty($path_parts['extension'])){
                            $newNameFile = $key.".".$path_parts['extension'];
                        }else{
                            $newNameFile = $key;
                        }
                        $arrFiles[] = array(
                            "full_tmp_puth" => $val['tmp_name'],
                            "name" => $newNameFile,
                            "content"=>file_get_contents($val['tmp_name']),
                        );
                    }
                }
            }
        }
    }
}

function XMail( $from, $to, $subj, $text, $files, $arrFiles, $formatTYpe){
    $un = strtoupper(uniqid(time()));
    $head = "From: ".$from."\n";
    //$head .= "To: ".$to."\n";

    $encoded_subject = mb_encode_mimeheader($subj, 'UTF-8', 'Q');

    $head .= "Subject: ".$encoded_subject."\n";
    $head .= "X-Mailer: PHPMail Tool\n";
    $head .= "Reply-To: ".$from."\n";
    $head .= "Mime-Version: 1.0\n";
    $head .= "Content-Type:multipart/mixed;";
    $head .= "boundary=\"----------".$un."\"\n\n";
    $zag = "------------".$un."\nContent-Type:".$formatTYpe.";\n";
    $zag .= "Content-Transfer-Encoding: 8bit\n\n".$text."\n\n";
    foreach($arrFiles as $key=>$value) {
        if(!empty($value['content'])){
            $zag .= "------------".$un."\n";
            $zag .= "Content-Type: application/octet-stream;";
            $zag .= "name=\"".$value['name']."\"\n";
            $zag .= "Content-Transfer-Encoding:base64\n";
            $zag .= "Content-Disposition:attachment;";
            $zag .= "filename=\"".$value['name']."\"\n\n";
            $zag .= chunk_split(base64_encode($value['content']))."\n";
        }
    }

    if (mail($to, $subj, $zag, $head)){
        return 1;
    }else{
        return 0;
    }
}

$from = "duha2@yandex.ru";
$to = "duha3740@mail.ru";
//$subj = "Ответ на опросник/квиз";
$subj = "Ответ на опросник/ квиз";
$subjUser = "Вы ответили на  вопросы";
$sendToUser = "N";

$flHtml = 0;//0-В текстовом Формате, 1-в html формате

If($flHtml === 0){
    $text = $bodyText;
    $formatTYpe = "text/plain";
}else{
    $text = $bodyHtml;
    $formatTYpe = "text/html";
}

$rez =false;
if(!empty($ms['main_message'])){
    setLogEmail($from , $to, $subj, $text, "Spam","Попытка отправить админу");
    echo "SPAM";
}else{
    $rez = XMail($from, $to, $subj, $text, array(), $arrFiles, $formatTYpe);
    setLogEmail($from, $to, $subj, $text, $rez, "Отправлено Админу");//Логирование отправки формы админу
    if($sendToUser == "Y"){//Дополнительное письмо пользователю, если это необходимо
        $userEmailKeyField = "question-1-input-3";
        $userPhoneKeyField = "question-1-input-4";
        //file_put_contents($_SERVER['DOCUMENT_ROOT']."/baform/showrezulthtml/1.txt", print_r($userPhoneKeyField, true));
        //file_put_contents($_SERVER['DOCUMENT_ROOT']."/baform/showrezulthtml/1.txt", print_r($ms, true), FILE_APPEND);
        if(!empty($userEmailKeyField)){
            if(!empty($ms[$userEmailKeyField])){
                $toUser = $ms[$userEmailKeyField];
                $rez = false;
                $rez = XMail($from, $toUser, $subjUser, $text, array(), $arrFiles, $formatTYpe);
                setLogEmail($from, $toUser, $subjUser, $text, $rez, "Отправлено посетителю");//Логирование отправки формы посетителю
            }
        }
    }
    if($rez){
        echo "OK";
    }else{
        echo "ERROR";
    }
}





?>