database );
		if (!$db) die ($error);
		return $db;
	}
	public function query_code($code) {
		$db = $this->db_connect();
		$c = SQLite3::escapeString ( $code ) ;
		$q = "SELECT * FROM '" .  self::TABLE . "' WHERE code='" . $c . "'" ;
		$result = @$db->query( $q );
		$row = @$result->fetchArray();
		$db->close();
		/* row == false when no row was found */
		return $row;
	}
	private function increase_count_in_db() {
		$db = @$this->db_connect();
		$db->exec( "UPDATE '" .  self::TABLE . "' SET count = count + 1 WHERE code='" . $this->code . "'" );
		$db->close();
	}
	public function reached_max_dl( $count ) {
		$max = false;
		$count += 1;
		if ( $count > self::MAXDOWNLOADS ) $max = true;
		return $max;
	}
	public function gen_response( $c , $f ){
		$this->code = $c;
		$content = "Code ungültig oder abgelaufen.";
		/* row == false when no row was found */
		if ( $row = $this->query_code($this->code) ) {
			// max count not reached
			if ( false === $this->reached_max_dl( $row['count'] ) ) {
				$content ='
                                  
Du hast noch ' .  ( self::MAXDOWNLOADS - $row['count'] - 1 ) .' Downloads zur Verfügung bis der Code ungültig wird.
                                  
				';
			}
		}
		return $content;
	}
	public function dl_trigger($format) {
		// Start Download
		switch ($format) {
			case 'mp3':
				$file = $this->mp3_file;
                                $filename = "Rainer_von_Vielen-Überall_Chaos_2017-MP3.zip";
				break;
			case 'wav':
				$file = $this->wav_file;
                                $filename = "Rainer_von_Vielen-Überall_Chaos_2017-WAV.zip";
				break;
		}
		$this->downloader( $file, $filename );
		$this->increase_count_in_db();
        }
	private function downloader( $file, $filename ){
		// Force the browser to start the download automatically
		//  Variables:
		//  $file = real name of actual download file on the server
		//  $filename = new name of local download file - this is what the visitor's file will actually be called when he/she saves it
		ob_start();
		header("Content-Type: application/octet-stream");
		header("Content-Disposition: attachment; filename=".$filename."");
		header("Content-Description: File Transfer");
		header("Content-Length: " .(string)(filesize($file)) );
		header("Cache-Control: public, must-revalidate");
		header("Pragma: public");
		header("Content-Transfer-Encoding: binary\n");
		ob_end_clean();
		readfile($file);
	}
}
?>