1<?php
2class helper_plugin_twofactortelegram extends Twofactor_Auth_Module {
3
4    public function canUse($user = null){
5		return ($this->_settingExists("verified", $user));
6	}
7
8    public function canAuthLogin() {
9		return false;
10	}
11
12    public function renderProfileForm(){
13		$elements = array();
14			$id = $this->_settingGet("id", '');
15			$elements[] = form_makeTextField('telegram_id', $id, $this->getLang('id'), '', 'block', array('size'=>'50'));
16
17			if ($id) {
18				if (!$this->_settingExists("verified")) {
19					$elements[] = '<span>'.$this->getLang('verifynotice').'</span>';
20					$elements[] = form_makeTextField('telegram_verify', '', $this->getLang('verifymodule'), '', 'block', array('size'=>'50', 'autocomplete'=>'off'));
21					$elements[] = form_makeCheckboxField('telegram_send', '1', $this->getLang('resendcode'),'','block');
22				}
23				$elements[] = form_makeCheckboxField('telegram_disable', '1', $this->getLang('killmodule'), '', 'block');
24			}
25		return $elements;
26	}
27
28    public function processProfileForm(){
29		global $INPUT;
30		$id = $INPUT->str('telegram_id', '');
31		if ($INPUT->bool('telegram_disable', false) || $id === '') {
32			$this->_settingDelete("id");
33			$this->_settingDelete("verified");
34			return true;
35		}
36		$oldid = $this->_settingGet("id", '');
37		if ($oldid) {
38			if ($INPUT->bool('telegram_send', false)) {
39				return 'otp';
40			}
41			$otp = $INPUT->str('telegram_verify', '');
42			if ($otp) {
43				$checkResult = $this->processLogin($otp);
44				if ($checkResult == false) {
45					return 'failed';
46				}
47				else {
48					$this->_settingSet("verified", true);
49					return 'verified';
50				}
51			}
52		}
53
54		$changed = null;
55		if (preg_match('/^[0-9]{5,}$/',$id) != false) {
56			if ($id != $oldid) {
57				if ($this->_settingSet("id", $id)== false) {
58					msg("TwoFactor: Error setting id.", -1);
59				}
60				$this->_settingDelete("verified");
61				return 'deleted';
62			}
63		}
64		if ($changed === true && $this->_settingExists("id")) {
65			$changed = 'otp';
66		}
67		return $changed;
68	}
69	public function canTransmitMessage(){
70		return true;
71	}
72
73	public function transmitMessage($subject, $message, $force = false){
74		if (!$this->canUse()  && !$force) { return false; }
75		$id = $this->_settingGet("id", null);
76		if (!$id) {
77			return false;
78		}
79		$token = $this->getConf('token');
80		$text = rawurlencode($this->getLang('msgtext'));
81		$code = rawurlencode($message);
82		$url = "https://api.telegram.org/bot{$token}/sendMessage?chat_id={$id}&text={$text}{$code}";
83		$result = file_get_contents($url);
84		return true;
85		}
86}