1<?php
2
3use dokuwiki\Form\Form;
4use dokuwiki\plugin\twofactor\OtpField;
5use dokuwiki\plugin\twofactor\Provider;
6
7/**
8 * Twofactor Provider that sends codes by email
9 */
10class action_plugin_twofactoremail extends Provider
11{
12
13    /** @inheritdoc */
14    public function getLabel()
15    {
16        global $USERINFO;
17        return $this->getLang('name') . ' ' . $USERINFO['mail'];
18    }
19
20    /** @inheritdoc */
21    public function isConfigured()
22    {
23        return $this->settings->get('verified');
24    }
25
26    /** @inheritdoc */
27    public function renderProfileForm(Form $form)
28    {
29        $form->addHTML('<p>' . $this->getLang('verifynotice') . '</p>');
30        $form->addElement(new OtpField('verify'));
31        return $form;
32    }
33
34    /** @inheritdoc */
35    public function handleProfileForm()
36    {
37        global $INPUT;
38
39        if($INPUT->bool('init')) {
40            $this->initSecret();
41            $code = $this->generateCode();
42            $this->transmitMessage($code);
43        }
44
45        if ($INPUT->has('verify')) {
46            if ($this->checkCode($INPUT->str('verify'))) {
47                $this->settings->set('verified', true);
48            } else {
49                // send a new code
50                $code = $this->generateCode();
51                $this->transmitMessage($code);
52            }
53        }
54    }
55
56    /** @inheritdoc */
57    public function transmitMessage($code)
58    {
59        global $USERINFO;
60        $to = $USERINFO['mail'];
61        if (!$to) throw new \Exception($this->getLang('codesentfail'));
62
63        // Create the email object.
64        $body = io_readFile($this->localFN('mail'));
65        $mail = new Mailer();
66        $mail->to($to);
67        $mail->subject($this->getLang('subject'));
68        $mail->setBody($body, ['CODE' => $code]);
69        $result = $mail->send();
70        if (!$result) throw new \Exception($this->getLang('codesentfail'));
71
72        return $this->getLang('codesent');
73    }
74
75}
76