<?php

class Contact_Form {
    

    private $securekey, $iv;

    function __construct($textkey) {
        $this->securekey = hash('sha256',$textkey,TRUE);
       // $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB); 
       // $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND); 
        $this->iv = mcrypt_create_iv(32, MCRYPT_RAND);
    }

	public function submit() {

        $plugin_settings["recipient_name"] = "mivita.care";
        //$plugin_settings["recipient_email"] = "info@mivita.care";
        $plugin_settings["recipient_email"] = "kevin.adametz@me.com";
        $plugin_settings["email_subject"] = "Mail von mivita.care";


        $errors = array();

        if ( empty( $plugin_settings['recipient_email'] ) ) {
            $errors['general'] = 'The recipient email is not set.';
            return array("errors"=>$errors);
            exit;
        }

        if( empty($_POST['required']) ){
            $errors['general'] = 'Pflichtfelder nicht definiert.';
            return array("errors"=>$errors);
            exit;
        }

          //check token
        if(!$this->checkSpamAutoSend($_POST['sender_token'])){
            $errors['general'] = 'Konnte nicht gesendet werden. Bitte nur alle 10 sec. senden.';
            return array("errors"=>$errors);
            exit;
        }

        if ( empty( $_POST['sender_email_repeat'] ) ) {
            //$errors['sender_email_repeat'] = 'invalid';
            $errors['general'] = 'Konnte nicht gesendet werden. Bitte alle Felder ausfüllen.'.$_POST['sender_email_repeat'];
            return array("errors"=>$errors);
            exit;
        }

        $required = explode(",", trim($_REQUEST['required']));
        $required = array_merge($required,  array( 'sender_email', 'sender_name' ) );

        $key = array_search("sender_email_repeat",$required);
        if($key!==false){
            unset($required[$key]);
        }
        foreach ( $required as $req ) {
            if ( empty( $_POST[$req] ) ) {
                $errors[$req] = 'required';
            }
        }

        if ( !isset( $errors['sender_email'] ) && !strpos($_POST['sender_email'], "@")  ) {
            $errors['sender_email'] = 'invalid';
        }

        if ( !empty( $errors ) ) {
            return array("errors"=>$errors);
            exit;
        }

        $malicious = array( 'sender_name', 'sender_email' );
        foreach ( $malicious as $mal ) {
            if ( $this->is_malicious( $_POST[$mal] ) ) {
                $errors[$mal] = 'malicious';
            }
        }


        if ( !empty( $errors ) ) {
            return array("errors"=>$errors);
            exit;
        }

        //remove POST

        unset($_POST['sender_token']);
        unset($_POST['sender_email_repeat']);

        $to = trim( $plugin_settings['recipient_name'] . ' <' . $plugin_settings['recipient_email'] . '>' );
        $from = $_POST['sender_name'] . ' <' . $_POST['sender_email'] . '>';
        $subject = $plugin_settings['email_subject'];

        $message = '';

        foreach ( $_POST as $name => $value ) {
            if(strpos($name, 'sender_') !== false) {
                $nicename = ucwords( str_replace( '_', ' ', str_replace('sender_', '', $name) ) );
                $message .= $nicename . ': ';
                if ( !empty( $_POST[$name] ) ) {
                    $message .= ( strpos( $_POST[$name], "\n" ) !== false ) ? "\r\n" : '';
                    $message .= $_POST[$name];
                }
                $message .= "\r\n\r\n-----------------------------------------------------------\r\n\r\n";
            }
        }
        $message .= "\r\n";

        $message .= $_POST['message'];

        $message .= "\r\n\r\n-----------------------------------------------------------\r\n".
                    "Datum: ". date("H:i - d.m.y", time()). "\r\n".
                    "Onlinenummer: " .time(). "\r\n".
                    "-----------------------------------------------------------\r\n".
                    "\r\n\r\n".
                    "Abgesendet von:\r\n".
                    "IP-Adresse: " . $_SERVER['REMOTE_ADDR'] . "\r\n".
                    "Benutzer Browser: ". $_SERVER['HTTP_USER_AGENT'] . "\r\n".
                    "Server Zeit: ". date("H:i - d.m.y", time()). "\r\n\r\n";

        $message = wordwrap( $message, 80, "\r\n");

        $headers = "MIME-Version: 1.0\r\n";
        $headers .= "From: $from\r\n";
        $headers .= "Content-Type: text/plain; charset=\"UTF-8\"\r\n";

        //header( 'Content-Type: text/plain' ); print_r( compact( 'to', 'subject', 'message', 'headers' ) ); exit;
        
        if ( !mail( $to, $subject, $message, $headers ) ) {
            $errors['general'] = 'For some reason the call to mail() failed. Best to contact the web host.';
            return array("errors"=>$errors);
            exit;
        }

        return array( 'success' => true );
        exit;
	}


    private function checkSpamAutoSend($token) { 
    
        //var_dump($this->language);
        $time = $this->decrypt($token);
        $time_now = time();

        if(!empty($time)){
                            
            if (!isset($time)) { return false; /* Feld fehlt ->Spam */ }
            elseif (!is_numeric($time)) { return false; /* Manipulierung ->Spam */ }
            elseif (intval($time) > $time_now-5) { return false; /* zu schnell */ }
            elseif (intval($time) < $time_now-10*3600) { return false; /* altes Formular ->Spam */ }
            else { return true; /* weitere Überprüfungen */ }

        }

        return false;
    }
    

    private function is_malicious( $input ) {
        $bad_inputs = array( "\r", "\n", "%0a", "%0d", "Content-Type:", "bcc:","to:","cc:" );
        foreach ( $bad_inputs as $bad_input ) {
            if ( stripos( strtolower( $input ), strtolower( $bad_input ) ) !== false ) {
                return true;
            }
        }
        return false;
    }

    public function encrypt($input) {
        return base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $this->securekey, $input, MCRYPT_MODE_ECB, $this->iv));
    }
    public function decrypt($input) {
        return trim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $this->securekey, base64_decode($input), MCRYPT_MODE_ECB, $this->iv));
    }

}

