<?php
namespace App;

class DovecotPw
{
    static private $rounds = 14;
    static private $method = "BLF-CRYPT";

    public static function Encrypt($password)
    {
        $fp = [];
        $m = static::$method;
        $r = static::$rounds;
        $proc = proc_open(  "'/usr/bin/doveadm' 'pw' '-s' '{$m}' '-r' '{$r}'",
                            [0 => ["pipe","r"], 1 => ["pipe", "w"], 2 => ["pipe", "w"]],
                            $fp);

        // write password
        fwrite($fp[0],$password . "\n");
        fwrite($fp[0],$password . "\n");

        // retrieve hash
        $s = fread($fp[1],512);

        // and only return the parts before the first line end
        $lines = preg_split("/\r\n|\n|\r/", $s);
        return $lines[0];
    }

    public static function Validate($user, $password)
    {
        $fp = [];
        $m = static::$method;
        $r = static::$rounds;
        $proc = proc_open(  "'/usr/bin/doveadm' 'auth' 'test' '-x' 'service=imap' '{$user}'",
                            [0 => ["pipe","r"], 1 => ["pipe", "w"], 2 => ["pipe", "w"]],
                            $fp);

        // write password
        fwrite($fp[0],$password . "\n");

        // retrieve hash
        $s = fread($fp[1],512);

        // and only return the parts before the first line end
        $lines = preg_split("/\r\n|\n|\r/", $s);
        if(preg_match('/(.*)auth succeeded$/',$lines[0]))
        {
           return true;
        }
        else 
        {
            return false;
        }

    }

}