<?php

function sendMail($rcpt,$subject,$markdown)
{
    $mail = new PHPMailer();
    $pd = new Parsedown();

    $html = $pd->text($markdown);

    ob_start();

    $mail->CharSet ="UTF-8";
    $mail->SMTPDebug = SMTP::DEBUG_SERVER;                      // Enable verbose debug output
    $mail->isSMTP();                                            // Send using SMTP
    $mail->Host       = SMTP_HOST;                              // Set the SMTP server to send through
    $mail->SMTPAuth   = (defined('SMTP_AUTH')?SMTP_AUTH:true);  // Enable SMTP authentication
    $mail->Username   = SMTP_USER;                              // SMTP username
    $mail->Password   = SMTP_PW;                                // SMTP password
    $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;         // Enable TLS encryption; `PHPMailer::ENCRYPTION_SMTPS` also accepted
    $mail->Port       = (defined('SMTP_PORT')?SMTP_PORT:587);   // TCP port to connect to
    if(defined('SMTP_EHLO_DOMAIN') && SMTP_EHLO_DOMAIN)
        $mail->Hostname = SMTP_EHLO_DOMAIN;
    
    //make sure we use ipv4
    $mail->SMTPOptions = [
        'socket' => [
            'bindto' => "0:0",
        ],
    ];

    //Recipients
    $mail->setFrom(EMAIL_FROM_EMAIL, EMAIL_FROM_NAME);
    $mail->addAddress($rcpt);     // Add a recipient

    // Content
    $mail->isHTML(true);                                  // Set email format to HTML
    $mail->Subject = $subject;
    $mail->Body    = $html;
    $mail->AltBody = $markdown;

    $mail->send();

    $output = ob_get_clean();

    addToMailLog($rcpt,$subject,$output);

    return $output;
}

// found on https://html-online.com/articles/php-get-ip-cloudflare-proxy/
function getUserIP() {
	if (isset($_SERVER["HTTP_CF_CONNECTING_IP"])) {
			  $_SERVER['REMOTE_ADDR'] = $_SERVER["HTTP_CF_CONNECTING_IP"];
			  $_SERVER['HTTP_CLIENT_IP'] = $_SERVER["HTTP_CF_CONNECTING_IP"];
	}
	$client  = @$_SERVER['HTTP_CLIENT_IP'];
	$forward = @$_SERVER['HTTP_X_FORWARDED_FOR'];
	$remote  = $_SERVER['REMOTE_ADDR'];

	if(filter_var($client, FILTER_VALIDATE_IP)) { $ip = $client; }
	elseif(filter_var($forward, FILTER_VALIDATE_IP)) { $ip = $forward; }
	else { $ip = $remote; }

	return $ip;
}


// from https://stackoverflow.com/a/834355/1174516
function startsWith( $haystack, $needle ) {
    $length = strlen( $needle );
    return substr( $haystack, 0, $length ) === $needle;
}
function endsWith( $haystack, $needle ) {
   $length = strlen( $needle );
   if( !$length ) {
       return true;
   }
   return substr( $haystack, -$length ) === $needle;
}

function is_cli()
{
    if ( defined('STDIN') )
        return true;
    if ( php_sapi_name() === 'cli' )
        return true;
    if ( array_key_exists('SHELL', $_ENV) )
        return true;
    if ( empty($_SERVER['REMOTE_ADDR']) and !isset($_SERVER['HTTP_USER_AGENT']) and count($_SERVER['argv']) > 0) 
        return true; 
    if ( !array_key_exists('REQUEST_METHOD', $_SERVER) )
        return true;
    return false;
}

function addToLog($text,$module='general')
{
    $fp = fopen(ROOT.DS.'..'.DS.'log'.DS.$module.'.log','a');
    fwrite($fp,'['.date("y.m.d H:i").']'.$text.PHP_EOL);
    fclose($fp);
}

function addToMailLog($rcpt,$subject,$response)
{
    $rcpt_esc = str_replace('@','_at_',$rcpt);
    $dir = ROOT.DS.'..'.DS.'log'.DS.'maillog';
    if(!is_dir($dir))
        mkdir($dir);
    $fp = fopen($dir.DS.$rcpt_esc.'.log','a');
    fwrite($fp,"========= NEW MAIL ========\n[".date("y.m.d H:i")."] To: $rcpt\nSubject: $subject\n\n$response\n\n");
    fclose($fp);
}

function translate($what)
{
    $what = trim($what);
    return ($GLOBALS['translations'][$what]?:$what);
}

function getFilesOfFolder($dir)
{
    return array_diff(scandir($dir), array('.', '..'));
}

function dbNeedsToBeUpgraded()
{
    if(DB_TYPE=='sqlite' && !file_exists(ROOT.DS.'..'.DS.'data'.DS.'db.sqlite3'))
        return true;
    else if(!file_exists(ROOT.DS.'..'.DS.'log'.DS.'db_version'))
        return true;
    else if($GLOBALS['db_version']<getHighestSQLVersion())
        return true;
    
    return false;
}

function getHighestSQLVersion()
{
    $dir = ROOT.DS.'..'.DS.'sql'.DS;
    $files = array_diff(scandir($dir), array('..', '.'));
    $files = array_map(function($e){
        return pathinfo($e, PATHINFO_FILENAME);
    }, $files);

    sort($files);

    return end($files);
}

function gen_uuid() {
    return sprintf( '%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
        // 32 bits for "time_low"
        mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ),

        // 16 bits for "time_mid"
        mt_rand( 0, 0xffff ),

        // 16 bits for "time_hi_and_version",
        // four most significant bits holds version number 4
        mt_rand( 0, 0x0fff ) | 0x4000,

        // 16 bits, 8 bits for "clk_seq_hi_res",
        // 8 bits for "clk_seq_low",
        // two most significant bits holds zero and one for variant DCE1.1
        mt_rand( 0, 0x3fff ) | 0x8000,

        // 48 bits for "node"
        mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff )
    );
}