1<?php
2
3/**
4 * Class helper_plugin_logindelay_log
5 */
6class helper_plugin_logindelay_log extends DokuWiki_Plugin
7{
8    /**
9     * @var string Absolute path to a user's stat file
10     */
11    protected $statFile;
12
13    /**
14     * helper_plugin_logindelay_log constructor
15     * @param string $user
16     */
17    public function __construct($user)
18    {
19        global $conf;
20        $this->statFile = $conf['cachedir'] . '/logindelay_' . $user . '.log';
21    }
22
23    /**
24     * Remove user's fail stats
25     */
26    public function clearFailStrikes()
27    {
28        @unlink($this->statFile);
29    }
30
31    /**
32     * Increment user's fail stats
33     * @return int
34     */
35    public function putFailStrike()
36    {
37        $strikes = $this->readStrikes() + 1;
38        file_put_contents($this->statFile, $strikes);
39        return $strikes;
40    }
41
42    /**
43     * Return the number of failed logins as recorded in user's
44     * stat file, or 0 if the file does not exist.
45     *
46     * @return int
47     */
48    public function readStrikes()
49    {
50        return (int) file_get_contents($this->statFile);
51    }
52
53    /**
54     * Calculates in how many minutes a login retry will be allowed,
55     * based on configuration and the stat file's timestamp
56     *
57     * @return int
58     */
59    public function calculateDelay()
60    {
61        if (!is_file($this->statFile)) return 0;
62
63        $strikes = $this->readStrikes();
64        if ($strikes < $this->getConf('maxFailures')) return 0;
65
66        $delay = $this->getConf('initialDelay') * pow(2, ($strikes - $this->getConf('maxFailures')));
67        $remainingDelay = $delay - (time() - filemtime($this->statFile)) / 60;
68        return (int) $remainingDelay >= 0 ? ceil($remainingDelay) : 0;
69    }
70}
71