<?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_ulid($milliseconds = null,$lowercase = false) {
    if($milliseconds===null)
        $milliseconds = (int) (microtime(true) * 1000);
    $encodingChars = '0123456789ABCDEFGHJKMNPQRSTVWXYZ';
    $encodingLength = 32;
    $randomLength = 16;
    $lastRandChars = [];
    $timeLength = 10;

        $timeChars = '';
        $randChars = '';

        for ($i = $timeLength - 1; $i >= 0; $i--) {
            $mod = $milliseconds % $encodingLength;
            $timeChars = $encodingChars[$mod].$timeChars;
            $milliseconds = ($milliseconds - $mod) / $encodingLength;
        }

        for ($i = 0; $i < $randomLength; $i++) {
            $lastRandChars[$i] = random_int(0, 31);
        }

        for ($i = 0; $i < $randomLength; $i++) {
            $randChars .= $encodingChars[$lastRandChars[$i]];
        }

        return ($value = $timeChars . $randChars) && $lowercase ? strtolower($value) : strtoupper($value);
}

function ulid_to_timestamp($ulid)
{
    $encodingChars = '0123456789ABCDEFGHJKMNPQRSTVWXYZ';
    $encodingLength = 32;
    $timeLength = 10;

    $timeChars = substr($ulid,0,$timeLength);
    $time = 0;

    for ($i = 0; $i < $timeLength; $i++) {
        $time = $time * $encodingLength + strpos($encodingChars, $timeChars[$i]);
    }

    return $time;
}

function escape($str)
{
    return htmlspecialchars($str, ENT_QUOTES, 'UTF-8');
}

function uuid4($data = null) {
    // Generate 16 bytes (128 bits) of random data or use the data passed into the function.
    $data = $data ?? random_bytes(16);
    assert(strlen($data) == 16);

    // Set version to 0100
    $data[6] = chr(ord($data[6]) & 0x0f | 0x40);
    // Set bits 6-7 to 10
    $data[8] = chr(ord($data[8]) & 0x3f | 0x80);

    // Output the 36 character UUID.
    return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4));
}

/*
* @param $path string Path to the file that should be uploaded
* @param $hash string Optional. File name we want on pictshare for the file
*/
function pictshareUploadImage($path,$hash=false)
{
    if(!file_exists($path)) return false;
    $request = curl_init('https://i.haschek.at/api/upload.php');
    
    curl_setopt($request,CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($request, CURLOPT_POST, true);
    curl_setopt(
        $request,
        CURLOPT_POSTFIELDS,
        array(
        'file' => curl_file_create($path),
        'hash'=>$hash
        ));

    // output the response
    curl_setopt($request, CURLOPT_RETURNTRANSFER, true);
    $answer = curl_exec($request);
    if($answer === false) return ['status'=>'error','error'=>curl_error($request)];
    else
        $json = json_decode($answer.PHP_EOL,true);

    // close the session
    curl_close($request);

    return $json;
}

function partial($name,$variables=[])
{
    $templatefile = ROOT.DS.'templates'.DS.'partials'.DS.$name;
    return template($templatefile,$variables);
}

function template($templatefile,$variables=[])
{
    ob_start();
    if(is_array($variables))
        extract($variables);
    if(file_exists($templatefile))
        include($templatefile);
    $pagecontent = ob_get_contents();
    ob_end_clean();

    return $pagecontent;
}