<?php

if(!defined('DOKU_INC')) die();
require_once(dirname(__FILE__).'/GoogleAuthenticator.php');

class TokenHelper {

    protected $_g2fafile = "";

    public function TokenHelper() {
        global $conf;

        $this->_g2fafile = $conf['metadir'].'/g2fa_secrets.php';
    }

    public function getTokens() {
        $ret = array();

        if(!@file_exists($this->_g2fafile))
            return $ret;

        $lines = file($this->_g2fafile);
        foreach($lines as $line) {
            $line = preg_replace('/#.*$/', '', $line); //ignore comments
            $line = trim($line);
            if(empty($line)) continue;

            $row    = explode(":", $line, 2);
            $user = $row[0];
            $secret = $row[1];
            $ret[$user] = $secret;
        }
        return $ret;
    }

    public function saveToken($user, $token)
    {
        $content = $user.":".$token."\n";

        if(!io_deleteFromFile($this->_g2fafile, '/^'.preg_quote($user).':/', true)) {
            msg('Unable to modify content data. Notify the Admin!');
            return false;
        }

        if(!@file_exists($this->_g2fafile)) {
            $header = "# g2fa_secrets.php\n# <?php exit()?>\n# Don't modify the lines above";
            $header .= "#\n# Userfile\n#\n# Format:\n#\n# login:secret\n\n";
            if(!io_saveFile($this->_g2fafile, $header, false)) {
              msg('There was an error saving to the file. Notify the Admin!');
              return false;
            }
        }


        if(!io_saveFile($this->_g2fafile, $content, true)) {
            msg('There was an error saving to the file. Notify the Admin!');
            return false;
        }

        return true;
    }

    public function deleteTokenForUser($user) {
        if(!io_deleteFromFile($this->_g2fafile, '/^'.preg_quote($user).':/', true)) {
           msg('Unable to modify the content data. Notify the Admin!');
           return false;
        }
        return true;
    }

    public function createTokenForUser($user) {
        $ga = new PHPGangsta_GoogleAuthenticator();
        $token = $ga->createSecret();
        return $this->saveToken($user, $token);
    }

    function getSecret($user) {
        $tokens = $this->getTokens();
        if(isset($tokens[$user]))
          return $tokens[$user];
        else
          return "";

    }

}
