<?php
error_reporting(E_ALL & ~E_WARNING & ~E_NOTICE & ~E_DEPRECATED);
ob_start();
session_start();
if($_SESSION['sml_si_l']!=session_id() && $_SESSION['sml_si']!=session_id()) { die('Invalid request'); }
define('AJAX_REQUEST', isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');
if(!AJAX_REQUEST) { die('Invalid request'); }
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require_once('../vendor/PHPMailer/Exception.php');
require_once('../vendor/PHPMailer/PHPMailer.php');
require_once('../vendor/PHPMailer/SMTP.php');
require_once('../functions.php');
require_once("../../db/connection.php");
if(isset($_POST['language'])) {
    $language = strip_tags($_POST['language']);
}
$settings = get_settings();
if(isset($language)) {
    set_language($language,$settings['language_domain']);
} else {
    set_language($settings['language'],$settings['language_domain']);
}
$type = strip_tags($_POST['type']);
$name = $settings['name'];
$smtp_server = $settings['smtp_server'];
$smtp_auth = $settings['smtp_auth'];
$smtp_username = $settings['smtp_username'];
$smtp_password = $settings['smtp_password'];
$smtp_secure = $settings['smtp_secure'];
$smtp_port = $settings['smtp_port'];
$smtp_from_email = $settings['smtp_from_email'];
$smtp_from_name = $settings['smtp_from_name'];
$mail_forgot_subject = $settings['mail_forgot_subject'];
$mail_forgot_body = $settings['mail_forgot_body'];
$email = isset($_POST['email']) ? trim(strip_tags($_POST['email'])) : '';
$subject = '';
$body = '';
$verification_code = '';
$id_user = 0;

switch ($type) {
    case 'validate':
        if(empty($email)) $email = $smtp_from_email;
        $subject = $name . ' - Test email';
        $body = 'This is a test e-mail for validating mail server settings.';
        break;
    case 'forgot':
        $username = '';
        $query = "SELECT id,username FROM sml_users WHERE email=? LIMIT 1;";
        if($smt = $mysqli->prepare($query)) {
            $smt->bind_param('s', $email);
            $result = $smt->execute();
            if($result) {
                $result = get_result($smt);
                if(count($result)==1) {
                    $row = array_shift($result);
                    $id_user = $row['id'];
                    $username = $row['username'];
                } else {
                    ob_end_clean();
                    echo json_encode(array("status"=>"error","msg"=>_("Invalid e-mail")));
                    exit;
                }
            } else {
                ob_end_clean();
                echo json_encode(array("status"=>"error","msg"=>_("Invalid e-mail")));
                exit;
            }
        } else {
            ob_end_clean();
            echo json_encode(array("status"=>"error","msg"=>_("Invalid e-mail")));
            exit;
        }
        $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        for($i=0;$i<16;$i++) {
            $verification_code .= $characters[random_int(0, strlen($characters) - 1)];
        }
        $currentPath = $_SERVER['PHP_SELF'];
        $pathInfo = pathinfo($currentPath);
        $hostName = $_SERVER['HTTP_HOST'];
        if (is_ssl()) { $protocol = 'https'; } else { $protocol = 'http'; }
        $url = $protocol."://".$hostName.$pathInfo['dirname'];
        $url = str_replace("/ajax","",$url)."/login.php?forgot=1&email=".urlencode($email)."&verification_code=".urlencode($verification_code);
        $subject = $mail_forgot_subject;
        $mail_forgot_body = str_replace("%LINK%","<a href='$url'>$url</a>",$mail_forgot_body);
        $mail_forgot_body = str_replace("%VERIFICATION_CODE%",$verification_code,$mail_forgot_body);
        $mail_forgot_body = str_replace("%USER_NAME%",$username,$mail_forgot_body);
        $body = $mail_forgot_body;
        break;
    default:
        ob_end_clean();
        echo json_encode(array("status"=>"error","msg"=>_("Error, retry later")));
        exit;
}

$mail = new PHPMailer(true);
$body = str_replace('<p><br></p>','<br>',$body);
$body = str_replace('<p>','<p style="padding:0;margin:0;">',$body);
try {
    $mail->isSMTP();
    $mail->CharSet = 'UTF-8';
    $mail->Timeout = 10;
    $mail->Host = $smtp_server;
    $mail->SMTPAuth = $smtp_auth;
    $mail->SMTPOptions = array(
        'ssl' => array(
            'verify_peer' => false,
            'verify_peer_name' => false,
            'allow_self_signed' => true
        )
    );
    $mail->Username = $smtp_username;
    $mail->Password = $smtp_password;
    switch($smtp_secure) {
        case 'ssl':
            $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
            break;
        case 'tls':
            $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
            break;
    }
    $mail->Port = $smtp_port;
    $mail->setFrom($smtp_from_email, $smtp_from_name);
    $mail->addAddress($email);
    $mail->isHTML(true);
    $mail->Subject = $subject;
    $mail->Body = $body;
    $mail->send();
    switch ($type) {
        case 'validate':
            $mysqli->query("UPDATE sml_settings SET smtp_valid=1;");
            break;
        case 'forgot':
            $query = "UPDATE sml_users SET forgot_code=? WHERE id=?;";
            if($smt = $mysqli->prepare($query)) {
                $smt->bind_param('si',$verification_code,$id_user);
                $smt->execute();
            }
            break;
    }
    ob_end_clean();
    echo json_encode(array("status"=>"ok"));
} catch (Exception $e) {
    if($type=='validate') {
        $mysqli->query("UPDATE sml_settings SET smtp_valid=0;");
    }
    ob_end_clean();
    echo json_encode(array("status"=>"error","msg"=>$mail->ErrorInfo));
}
