<?php

class abusers {
	private $file = 'abusers.sqlite3';
	private $salt = 'sf476asedfasd';
	private $algo = 'sha256';
	private $dbh;

	function __construct () {
		try {
			$this->dbh = new PDO(
				'sqlite:' . $this->file,
				null,
				null,
				array( PDO::ATTR_PERSISTENT => true )
				
			);
		} catch (PDOException $e) {
			trigger_error ( 'Verbindung fehlgeschlagen: ' . $e->getMessage(), E_USER_ERROR );
		}
	}
	
	public function check( $name ) {
		$entry = $this->hashName ( $name );
		$sth = $this->dbh->prepare( 'SELECT COUNT(hash) AS count FROM abusers WHERE hash = :entry' );
		$sth->bindValue( ':entry', $entry, PDO::PARAM_STR );
        $sth->execute();
		$res = $sth->fetchAll();
		return 0 < $res[0]['count'];
	}
	
	public function add ( $name ) {
		$entry =  $this->hashName ( $name );
		$sql = 'INSERT INTO abusers ( hash ) VALUES ( ' . $this->dbh->quote( $entry ) . ' );';
		return 1 == $this->dbh->exec( $sql ) ;
	}
	
	public function remove( $name ) {
		$entry =  $this->hashName ( $name );
		$sql = 'DELETE FROM abusers WHERE hash = ' . $this->dbh->quote( $entry );
		return 0 < $this->dbh->exec( $sql );
	}
	
	private function hashName ( $name ) {

		$hashes = [];
		$name   = strtolower( trim( $name ) );

		if ( '' == $name ) {
			return false;
		}
		$name = preg_replace ( '/\s+/', '_', strtolower( $name ) );
		$arr = explode( '_', $name );
		foreach ( $arr as $part ) {
			$part = filter_var( $part, FILTER_SANITIZE_EMAIL );
			$part = str_replace( str_split( '^°!#$§%&*"\'*+-=?^`´:;<>(){|}~@.[].' ) , '', $part );
			$hashes[] = hash( $this->algo, $this->salt . $part, false );
		}

		sort( $hashes, SORT_STRING );
		return ( implode(':', $hashes ) );
	}
}