Passed
Push — master ( b5fef0...47a2b4 )
by Shahrad
02:38
created
src/lib/Util/Common.php 1 patch
Indentation   +49 added lines, -49 removed lines patch added patch discarded remove patch
@@ -12,63 +12,63 @@
 block discarded – undo
12 12
 class Common
13 13
 {
14 14
 
15
-	/**
16
-	 * Validate the given string is JSON or not
17
-	 *
18
-	 * @param ?string $string
19
-	 * @return bool
20
-	 */
21
-	public static function isJson(?string $string): bool
22
-	{
23
-		if (!is_string($string)) {
24
-			return false;
25
-		}
15
+    /**
16
+     * Validate the given string is JSON or not
17
+     *
18
+     * @param ?string $string
19
+     * @return bool
20
+     */
21
+    public static function isJson(?string $string): bool
22
+    {
23
+        if (!is_string($string)) {
24
+            return false;
25
+        }
26 26
 
27
-		json_decode($string);
27
+        json_decode($string);
28 28
 
29
-		return json_last_error() === JSON_ERROR_NONE;
30
-	}
29
+        return json_last_error() === JSON_ERROR_NONE;
30
+    }
31 31
 
32
-	/**
33
-	 * Check string is a url encoded string or not
34
-	 *
35
-	 * @param ?string $string
36
-	 * @return bool
37
-	 */
38
-	public static function isUrlEncode(?string $string): bool
39
-	{
40
-		if (!is_string($string)) {
41
-			return false;
42
-		}
32
+    /**
33
+     * Check string is a url encoded string or not
34
+     *
35
+     * @param ?string $string
36
+     * @return bool
37
+     */
38
+    public static function isUrlEncode(?string $string): bool
39
+    {
40
+        if (!is_string($string)) {
41
+            return false;
42
+        }
43 43
 
44
-		return preg_match('/%[0-9A-F]{2}/i', $string);
45
-	}
44
+        return preg_match('/%[0-9A-F]{2}/i', $string);
45
+    }
46 46
 
47
-	/**
48
-	 * Convert url encoded string to array
49
-	 *
50
-	 * @param string $string
51
-	 * @return array
52
-	 */
53
-	public static function urlDecode(string $string): array
54
-	{
55
-		$raw_data = explode('&', urldecode($string));
56
-		$data = [];
47
+    /**
48
+     * Convert url encoded string to array
49
+     *
50
+     * @param string $string
51
+     * @return array
52
+     */
53
+    public static function urlDecode(string $string): array
54
+    {
55
+        $raw_data = explode('&', urldecode($string));
56
+        $data = [];
57 57
 
58
-		foreach ($raw_data as $row) {
59
-			[$key, $value] = explode('=', $row);
58
+        foreach ($raw_data as $row) {
59
+            [$key, $value] = explode('=', $row);
60 60
 
61
-			if (self::isUrlEncode($value)) {
62
-				$value = urldecode($value);
63
-				if (self::isJson($value)) {
64
-					$value = json_decode($value, true);
65
-				}
66
-			}
61
+            if (self::isUrlEncode($value)) {
62
+                $value = urldecode($value);
63
+                if (self::isJson($value)) {
64
+                    $value = json_decode($value, true);
65
+                }
66
+            }
67 67
 
68
-			$data[$key] = $value;
69
-		}
68
+            $data[$key] = $value;
69
+        }
70 70
 
71
-		return $data;
72
-	}
71
+        return $data;
72
+    }
73 73
 
74 74
 }
75 75
\ No newline at end of file
Please login to merge, or discard this patch.
src/lib/WebhookHandler.php 1 patch
Indentation   +216 added lines, -216 removed lines patch added patch discarded remove patch
@@ -17,221 +17,221 @@
 block discarded – undo
17 17
 abstract class WebhookHandler extends Telegram
18 18
 {
19 19
 
20
-	/**
21
-	 * @var ?Update
22
-	 */
23
-	protected ?Update $update;
24
-
25
-	/**
26
-	 * @var array<Plugin>
27
-	 */
28
-	private array $plugins = [];
29
-
30
-	/**
31
-	 * @var bool
32
-	 */
33
-	private bool $isActive = false;
34
-
35
-	/**
36
-	 * The default configuration of the webhook.
37
-	 *
38
-	 * @var array
39
-	 */
40
-	private array $config = [
41
-		'autoload_env_file' => false,
42
-		'env_file_path' => null,
43
-	];
44
-
45
-	/**
46
-	 * Webhook constructor.
47
-	 *
48
-	 * @param string $api_key The API key of the bot. Leave it blank for autoload from .env file.
49
-	 */
50
-	public function __construct(string $api_key = '')
51
-	{
52
-		parent::__construct($api_key);
53
-
54
-		if (!Telegram::validateToken(self::getApiKey())) {
55
-			throw new InvalidBotTokenException();
56
-		}
57
-	}
58
-
59
-	/**
60
-	 * Initialize the receiver.
61
-	 *
62
-	 * @return void
63
-	 */
64
-	public function init(): void
65
-	{
66
-		$this->config['env_file_path'] = $_SERVER['DOCUMENT_ROOT'] . '/.env';
67
-	}
68
-
69
-	/**
70
-	 * Add a plugin to the receiver
71
-	 *
72
-	 * @param array<Plugin> $plugins
73
-	 */
74
-	public function addPlugin(array $plugins): void
75
-	{
76
-		foreach ($plugins as $plugin) {
77
-			if (!is_subclass_of($plugin, Plugin::class)) {
78
-				throw new \RuntimeException(
79
-					sprintf('The plugin %s must be an instance of %s', get_class($plugin), Plugin::class)
80
-				);
81
-			}
82
-			$this->plugins[] = $plugin;
83
-		}
84
-	}
85
-
86
-	/**
87
-	 * Match the update with the given plugins
88
-	 *
89
-	 * @param array<Plugin> $plugins
90
-	 * @param ?Update $update The update to match
91
-	 * @return void
92
-	 */
93
-	public function loadPluginsWith(array $plugins, Update $update = null): void
94
-	{
95
-		$update = $update ?? ($this->update ?? Telegram::getUpdate());
96
-
97
-		foreach ($plugins as $plugin) {
98
-			if (!is_subclass_of($plugin, Plugin::class)) {
99
-				throw new \InvalidArgumentException(
100
-					sprintf('The plugin %s must be an instance of %s', get_class($plugin), Plugin::class)
101
-				);
102
-			}
103
-		}
104
-
105
-		if ($update instanceof Update) {
106
-			$this->spreadUpdateWith($update, $plugins);
107
-		}
108
-	}
109
-
110
-	/**
111
-	 * Match the message to the plugins
112
-	 *
113
-	 * @param ?Update $update The update to match
114
-	 * @return void
115
-	 */
116
-	public function loadPlugins(Update $update = null): void
117
-	{
118
-		$update = $update ?? ($this->update ?? Telegram::getUpdate());
119
-		$this->loadPluginsWith($this->plugins, $update);
120
-	}
121
-
122
-	/**
123
-	 * Load the environment's
124
-	 *
125
-	 * @param string $path
126
-	 * @retrun void
127
-	 */
128
-	public function loadFileOfEnv(string $path): void
129
-	{
130
-		DotEnv::load($path);
131
-	}
132
-
133
-	/**
134
-	 * Update the configuration
135
-	 *
136
-	 * @param array $configuration
137
-	 * @return void
138
-	 */
139
-	public function updateConfiguration(array $configuration): void
140
-	{
141
-		$this->config = array_merge($this->config, $configuration);
142
-	}
143
-
144
-	/**
145
-	 * Resolve the request.
146
-	 *
147
-	 * @param ?Update $update The custom to work with
148
-	 * @param array $config The configuration of the receiver
149
-	 *
150
-	 * @retrun void
151
-	 */
152
-	public function resolve(Update $update = null, array $config = []): void
153
-	{
154
-		$method = '__process';
155
-		if (!method_exists($this, $method)) {
156
-			throw new \RuntimeException(sprintf('The method %s does not exist', $method));
157
-		}
158
-
159
-		if (is_array($config)) $this->updateConfiguration($config);
160
-
161
-		if (!empty($update)) $this->update = $update;
162
-		else $this->update = Telegram::getUpdate() !== false ? Telegram::getUpdate() : null;
163
-
164
-		if (empty($this->update)) {
165
-			TelegramLog::error(
166
-				'The update is empty, the request is not processed'
167
-			);
168
-			return;
169
-		}
170
-
171
-		putenv('TG_CURRENT_UPDATE=' . $this->update->getRawData(false));
172
-
173
-		$this->$method($update);
174
-	}
175
-
176
-	/**
177
-	 * This function will get update and spread it to the plugins
178
-	 *
179
-	 * @param Update $update
180
-	 * @param array<Plugin> $plugins
181
-	 * @return void
182
-	 */
183
-	private function spreadUpdateWith(Update $update, array $plugins): void
184
-	{
185
-		$this->isActive = true;
186
-
187
-		foreach ($plugins as $plugin) {
188
-			/** @var Plugin $plugin */
189
-			(new $plugin())->__execute($this, $update);
190
-			if ($this->isActive === false) break;
191
-		}
192
-
193
-		$this->isActive = false;
194
-	}
195
-
196
-	/**
197
-	 * Kill the speeding process
198
-	 *
199
-	 * @return void
200
-	 */
201
-	public function kill(): void
202
-	{
203
-		$this->isActive = false;
204
-	}
205
-
206
-	/**
207
-	 * Use this method on the webhook class to get the updates
208
-	 *
209
-	 * @param Update $update
210
-	 * @return void
211
-	 */
212
-	abstract public function __process(Update $update): void;
213
-
214
-	/**
215
-	 * put CrossData into the plugins
216
-	 *
217
-	 * @param string $key
218
-	 * @param mixed $value
219
-	 * @return void
220
-	 */
221
-	public function putCrossData(string $key, mixed $value): void
222
-	{
223
-		CrossData::put($key, $value);
224
-	}
225
-
226
-	/**
227
-	 * get CrossData from the plugins
228
-	 *
229
-	 * @param string $key
230
-	 * @return string|array|bool|null
231
-	 */
232
-	public function getCrossData(string $key): string|array|bool|null
233
-	{
234
-		return CrossData::get($key);
235
-	}
20
+    /**
21
+     * @var ?Update
22
+     */
23
+    protected ?Update $update;
24
+
25
+    /**
26
+     * @var array<Plugin>
27
+     */
28
+    private array $plugins = [];
29
+
30
+    /**
31
+     * @var bool
32
+     */
33
+    private bool $isActive = false;
34
+
35
+    /**
36
+     * The default configuration of the webhook.
37
+     *
38
+     * @var array
39
+     */
40
+    private array $config = [
41
+        'autoload_env_file' => false,
42
+        'env_file_path' => null,
43
+    ];
44
+
45
+    /**
46
+     * Webhook constructor.
47
+     *
48
+     * @param string $api_key The API key of the bot. Leave it blank for autoload from .env file.
49
+     */
50
+    public function __construct(string $api_key = '')
51
+    {
52
+        parent::__construct($api_key);
53
+
54
+        if (!Telegram::validateToken(self::getApiKey())) {
55
+            throw new InvalidBotTokenException();
56
+        }
57
+    }
58
+
59
+    /**
60
+     * Initialize the receiver.
61
+     *
62
+     * @return void
63
+     */
64
+    public function init(): void
65
+    {
66
+        $this->config['env_file_path'] = $_SERVER['DOCUMENT_ROOT'] . '/.env';
67
+    }
68
+
69
+    /**
70
+     * Add a plugin to the receiver
71
+     *
72
+     * @param array<Plugin> $plugins
73
+     */
74
+    public function addPlugin(array $plugins): void
75
+    {
76
+        foreach ($plugins as $plugin) {
77
+            if (!is_subclass_of($plugin, Plugin::class)) {
78
+                throw new \RuntimeException(
79
+                    sprintf('The plugin %s must be an instance of %s', get_class($plugin), Plugin::class)
80
+                );
81
+            }
82
+            $this->plugins[] = $plugin;
83
+        }
84
+    }
85
+
86
+    /**
87
+     * Match the update with the given plugins
88
+     *
89
+     * @param array<Plugin> $plugins
90
+     * @param ?Update $update The update to match
91
+     * @return void
92
+     */
93
+    public function loadPluginsWith(array $plugins, Update $update = null): void
94
+    {
95
+        $update = $update ?? ($this->update ?? Telegram::getUpdate());
96
+
97
+        foreach ($plugins as $plugin) {
98
+            if (!is_subclass_of($plugin, Plugin::class)) {
99
+                throw new \InvalidArgumentException(
100
+                    sprintf('The plugin %s must be an instance of %s', get_class($plugin), Plugin::class)
101
+                );
102
+            }
103
+        }
104
+
105
+        if ($update instanceof Update) {
106
+            $this->spreadUpdateWith($update, $plugins);
107
+        }
108
+    }
109
+
110
+    /**
111
+     * Match the message to the plugins
112
+     *
113
+     * @param ?Update $update The update to match
114
+     * @return void
115
+     */
116
+    public function loadPlugins(Update $update = null): void
117
+    {
118
+        $update = $update ?? ($this->update ?? Telegram::getUpdate());
119
+        $this->loadPluginsWith($this->plugins, $update);
120
+    }
121
+
122
+    /**
123
+     * Load the environment's
124
+     *
125
+     * @param string $path
126
+     * @retrun void
127
+     */
128
+    public function loadFileOfEnv(string $path): void
129
+    {
130
+        DotEnv::load($path);
131
+    }
132
+
133
+    /**
134
+     * Update the configuration
135
+     *
136
+     * @param array $configuration
137
+     * @return void
138
+     */
139
+    public function updateConfiguration(array $configuration): void
140
+    {
141
+        $this->config = array_merge($this->config, $configuration);
142
+    }
143
+
144
+    /**
145
+     * Resolve the request.
146
+     *
147
+     * @param ?Update $update The custom to work with
148
+     * @param array $config The configuration of the receiver
149
+     *
150
+     * @retrun void
151
+     */
152
+    public function resolve(Update $update = null, array $config = []): void
153
+    {
154
+        $method = '__process';
155
+        if (!method_exists($this, $method)) {
156
+            throw new \RuntimeException(sprintf('The method %s does not exist', $method));
157
+        }
158
+
159
+        if (is_array($config)) $this->updateConfiguration($config);
160
+
161
+        if (!empty($update)) $this->update = $update;
162
+        else $this->update = Telegram::getUpdate() !== false ? Telegram::getUpdate() : null;
163
+
164
+        if (empty($this->update)) {
165
+            TelegramLog::error(
166
+                'The update is empty, the request is not processed'
167
+            );
168
+            return;
169
+        }
170
+
171
+        putenv('TG_CURRENT_UPDATE=' . $this->update->getRawData(false));
172
+
173
+        $this->$method($update);
174
+    }
175
+
176
+    /**
177
+     * This function will get update and spread it to the plugins
178
+     *
179
+     * @param Update $update
180
+     * @param array<Plugin> $plugins
181
+     * @return void
182
+     */
183
+    private function spreadUpdateWith(Update $update, array $plugins): void
184
+    {
185
+        $this->isActive = true;
186
+
187
+        foreach ($plugins as $plugin) {
188
+            /** @var Plugin $plugin */
189
+            (new $plugin())->__execute($this, $update);
190
+            if ($this->isActive === false) break;
191
+        }
192
+
193
+        $this->isActive = false;
194
+    }
195
+
196
+    /**
197
+     * Kill the speeding process
198
+     *
199
+     * @return void
200
+     */
201
+    public function kill(): void
202
+    {
203
+        $this->isActive = false;
204
+    }
205
+
206
+    /**
207
+     * Use this method on the webhook class to get the updates
208
+     *
209
+     * @param Update $update
210
+     * @return void
211
+     */
212
+    abstract public function __process(Update $update): void;
213
+
214
+    /**
215
+     * put CrossData into the plugins
216
+     *
217
+     * @param string $key
218
+     * @param mixed $value
219
+     * @return void
220
+     */
221
+    public function putCrossData(string $key, mixed $value): void
222
+    {
223
+        CrossData::put($key, $value);
224
+    }
225
+
226
+    /**
227
+     * get CrossData from the plugins
228
+     *
229
+     * @param string $key
230
+     * @return string|array|bool|null
231
+     */
232
+    public function getCrossData(string $key): string|array|bool|null
233
+    {
234
+        return CrossData::get($key);
235
+    }
236 236
 
237 237
 }
238 238
\ No newline at end of file
Please login to merge, or discard this patch.
src/lib/Telegram.php 2 patches
Indentation   +361 added lines, -361 removed lines patch added patch discarded remove patch
@@ -18,366 +18,366 @@
 block discarded – undo
18 18
 class Telegram
19 19
 {
20 20
 
21
-	/**
22
-	 * @var string
23
-	 */
24
-	private string $api_key;
25
-
26
-	/**
27
-	 * @var string
28
-	 */
29
-	public static string $VERSION = 'v1.0.0';
30
-
31
-	/**
32
-	 * Telegram constructor.
33
-	 *
34
-	 * @param string $api_key
35
-	 */
36
-	public function __construct(string $api_key = '')
37
-	{
38
-		if ($api_key === '') {
39
-			$env_file = $this->getEnvFilePath();
40
-			$api_key = DotEnv::load($env_file)->get('TELEGRAM_API_KEY');
41
-		}
42
-
43
-		if (empty($api_key) || !is_string($api_key)) {
44
-			throw new TelegramException('API Key is required');
45
-		}
46
-
47
-		DotEnv::put('TG_CURRENT_KEY', ($this->api_key = $api_key));
48
-		DotEnv::put('TELEGRAM_API_KEY', ($this->api_key = $api_key));
49
-	}
50
-
51
-	/**
52
-	 * Get env file path and return it
53
-	 *
54
-	 * @return string
55
-	 */
56
-	private function getEnvFilePath(): string
57
-	{
58
-		$defaultEnvPaths = [
59
-			$_SERVER['DOCUMENT_ROOT'] . '/.env',
60
-			getcwd() . '/../.env',
61
-			getcwd() . '/.env',
62
-		];
63
-
64
-		foreach ($defaultEnvPaths as $path) {
65
-			if (file_exists($path)) {
66
-				return $path;
67
-			}
68
-		}
69
-
70
-		return '';
71
-	}
72
-
73
-	/**
74
-	 * Get API key from temporary ENV variable
75
-	 *
76
-	 * @return ?string
77
-	 */
78
-	public static function getApiKey(): ?string
79
-	{
80
-		return DotEnv::get('TG_CURRENT_KEY');
81
-	}
82
-
83
-	/**
84
-	 * Get bot info from given API key
85
-	 *
86
-	 * @return Response
87
-	 * @throws TelegramException
88
-	 */
89
-	public function getInfo(): Response
90
-	{
91
-		$result = Request::getMe();
92
-
93
-		if (!$result->isOk()) {
94
-			throw new TelegramException($result->getErrorCode() . ': ' . $result->getDescription());
95
-		}
96
-
97
-		return $result;
98
-	}
99
-
100
-	/**
101
-	 * Set Webhook for bot
102
-	 *
103
-	 * @param string $url
104
-	 * @param array $data Optional parameters.
105
-	 * @return Response
106
-	 * @throws TelegramException
107
-	 */
108
-	public function setWebhook(string $url, array $data = []): Response
109
-	{
110
-		if ($url === '') {
111
-			throw new TelegramException('Hook url is empty!');
112
-		}
113
-
114
-		if (!str_starts_with($url, 'https://')) {
115
-			throw new TelegramException('Hook url must start with https://');
116
-		}
117
-
118
-		$data = array_intersect_key($data, array_flip([
119
-			'certificate',
120
-			'ip_address',
121
-			'max_connections',
122
-			'allowed_updates',
123
-			'drop_pending_updates',
124
-		]));
125
-		$data['url'] = $url;
126
-
127
-		$result = Request::setWebhook($data);
128
-
129
-		if (!$result->isOk()) {
130
-			throw new TelegramException(
131
-				'Webhook was not set! Error: ' . $result->getErrorCode() . ' ' . $result->getDescription()
132
-			);
133
-		}
134
-
135
-		return $result;
136
-	}
137
-
138
-	/**
139
-	 * Delete any assigned webhook
140
-	 *
141
-	 * @param array $data
142
-	 * @return Response
143
-	 * @throws TelegramException
144
-	 */
145
-	public function deleteWebhook(array $data = []): Response
146
-	{
147
-		$result = Request::deleteWebhook($data);
148
-
149
-		if (!$result->isOk()) {
150
-			throw new TelegramException(
151
-				'Webhook was not deleted! Error: ' . $result->getErrorCode() . ' ' . $result->getDescription()
152
-			);
153
-		}
154
-
155
-		return $result;
156
-	}
157
-
158
-	/**
159
-	 * This method sets the admin username. and will be used to send you a message if the bot is not working.
160
-	 *
161
-	 * @param int $chat_id
162
-	 * @return void
163
-	 */
164
-	public function setAdmin(int $chat_id): void
165
-	{
166
-		defined('TG_ADMIN_ID') or define('TG_ADMIN_ID', $chat_id);
167
-	}
168
-
169
-	/**
170
-	 * Get input from stdin and return it
171
-	 *
172
-	 * @return ?string
173
-	 */
174
-	public static function getInput(): ?string
175
-	{
176
-		return file_get_contents('php://input') ?? null;
177
-	}
178
-
179
-	/**
180
-	 * This method will convert a string to an update object
181
-	 *
182
-	 * @param string $input The input string
183
-	 * @param string $apiKey The API key
184
-	 * @return Update|false
185
-	 */
186
-	public static function processUpdate(string $input, string $apiKey): Update|false
187
-	{
188
-		if (empty($input)) {
189
-			throw new TelegramException(
190
-				'Input is empty! Please check your code and try again.'
191
-			);
192
-		}
193
-
194
-		if (!self::validateToken($apiKey)) {
195
-			throw new TelegramException(
196
-				'Invalid token! Please check your code and try again.'
197
-			);
198
-		}
199
-
200
-		if (self::validateWebData($apiKey, $input)) {
201
-			if (Common::isUrlEncode($input)) {
202
-				$web_data = Common::urlDecode($input);
203
-			}
204
-
205
-			if (Common::isJson($input)) {
206
-				$web_data = json_decode($input, true);
207
-			}
208
-
209
-			$input = json_encode([
210
-				'web_data' => $web_data,
211
-			]);
212
-		}
213
-
214
-		if (!Common::isJson($input)) {
215
-			throw new TelegramException(
216
-				'Input is not a valid JSON string! Please check your code and try again.'
217
-			);
218
-		}
219
-
220
-		$input = json_decode($input, true);
221
-
222
-		return new Update($input);
223
-	}
224
-
225
-	/**
226
-	 * Validate webapp data from is from Telegram
227
-	 *
228
-	 * @link https://core.telegram.org/bots/webapps#validating-data-received-via-the-web-app
229
-	 *
230
-	 * @param string $token The bot token
231
-	 * @param string $body The message body from getInput()
232
-	 * @return bool
233
-	 */
234
-	public static function validateWebData(string $token, string $body): bool
235
-	{
236
-		if (!Common::isJson($body)) {
237
-			$raw_data = rawurldecode(str_replace('_auth=', '', $body));
238
-			$data = Common::urlDecode($raw_data);
239
-
240
-			if (empty($data['user'])) {
241
-				return false;
242
-			}
243
-
244
-			$data['user'] = urldecode($data['user']);
245
-
246
-		} else {
247
-			$data = json_decode($body, true);
248
-
249
-			if (empty($data['user'])) {
250
-				return false;
251
-			}
252
-
253
-			$data['user'] = json_encode($data['user']);
254
-		}
255
-
256
-		$data_check_string = "auth_date={$data['auth_date']}\nquery_id={$data['query_id']}\nuser={$data['user']}";
257
-		$secret_key = hash_hmac('sha256', $token, "WebAppData", true);
258
-
259
-		return hash_hmac('sha256', $data_check_string, $secret_key) == $data['hash'];
260
-	}
261
-
262
-	/**
263
-	 * Get the update from input
264
-	 *
265
-	 * @return Update|false
266
-	 */
267
-	public static function getUpdate(): Update|false
268
-	{
269
-		$input = self::getInput();
270
-		if (empty($input)) return false;
271
-		return Telegram::processUpdate($input, self::getApiKey());
272
-	}
273
-
274
-	/**
275
-	 * Validate the token
276
-	 *
277
-	 * @param string $token (e.g. 123456789:ABC-DEF1234ghIkl-zyx57W2v1u123ew11) {digit}:{alphanumeric[34]}
278
-	 * @return bool
279
-	 */
280
-	public static function validateToken(string $token): bool
281
-	{
282
-		preg_match_all('/([0-9]+:[a-zA-Z0-9-_]+)/', $token, $matches);
283
-		return count($matches[0]) == 1;
284
-	}
285
-
286
-	/**
287
-	 * Pass the update to the given webhook handler
288
-	 *
289
-	 * @param WebhookHandler $webhook_handler The webhook handler
290
-	 * @param ?Update $update By default, it will get the update from input
291
-	 * @return void
292
-	 */
293
-	public function fetchWith(WebhookHandler $webhook_handler, ?Update $update = null): void
294
-	{
295
-		if (is_subclass_of($webhook_handler, WebhookHandler::class)) {
296
-			if ($update === null) $update = self::getUpdate();
297
-			$webhook_handler->resolve($update);
298
-		}
299
-	}
300
-
301
-	/**
302
-	 * Get token from env file.
303
-	 *
304
-	 * @param string $file
305
-	 * @return ?string
306
-	 */
307
-	protected function getTokenFromEnvFile(string $file): ?string
308
-	{
309
-		if (!file_exists($file)) return null;
310
-		return DotEnv::load($file)::get('TELEGRAM_API_KEY');
311
-	}
312
-
313
-	/**
314
-	 * Debug mode
315
-	 *
316
-	 * @param ?int $admin_id Fill this or use setAdmin()
317
-	 * @return void
318
-	 */
319
-	public static function setDebugMode(?int $admin_id = null): void
320
-	{
321
-		error_reporting(E_ALL);
322
-		ini_set('display_errors', 1);
323
-
324
-		defined('DEBUG_MODE') or define('DEBUG_MODE', true);
325
-		if ($admin_id) {
326
-			defined('TG_ADMIN_ID') or define('TG_ADMIN_ID', $admin_id);
327
-		}
328
-
329
-		set_exception_handler(function ($exception) {
330
-
331
-			if (defined('DEBUG_MODE') && DEBUG_MODE) {
332
-
333
-				TelegramLog::error(($message = sprintf(
334
-					'%s(%d): %s\n%s',
335
-					$exception->getFile(),
336
-					$exception->getLine(),
337
-					$exception->getMessage(),
338
-					$exception->getTraceAsString()
339
-				)));
340
-
341
-				echo '<b>TelegramError:</b> ' . $message;
342
-
343
-				if (defined('TG_ADMIN_ID') && TG_ADMIN_ID) {
344
-					$input = getenv('TG_CURRENT_UPDATE') ?? self::getInput();
345
-					$update = self::processUpdate($input, self::getApiKey());
346
-
347
-					file_put_contents(
348
-						($file = getcwd() . '/' . uniqid('error_') . '.log'),
349
-						$message . PHP_EOL . PHP_EOL . $update->getRawData(false)
350
-					);
351
-
352
-					Request::sendMessage([
353
-						'chat_id' => TG_ADMIN_ID,
354
-						'text' => $message,
355
-					]);
356
-
357
-					Request::sendDocument([
358
-						'chat_id' => TG_ADMIN_ID,
359
-						'document' => $file,
360
-					]);
361
-
362
-					unlink($file);
363
-				}
364
-
365
-			} else {
366
-				throw $exception;
367
-			}
368
-
369
-		});
370
-	}
371
-
372
-	/**
373
-	 * Just another echo
374
-	 *
375
-	 * @param string $text
376
-	 * @return void
377
-	 */
378
-	public static function echo(string $text): void
379
-	{
380
-		echo $text;
381
-	}
21
+    /**
22
+     * @var string
23
+     */
24
+    private string $api_key;
25
+
26
+    /**
27
+     * @var string
28
+     */
29
+    public static string $VERSION = 'v1.0.0';
30
+
31
+    /**
32
+     * Telegram constructor.
33
+     *
34
+     * @param string $api_key
35
+     */
36
+    public function __construct(string $api_key = '')
37
+    {
38
+        if ($api_key === '') {
39
+            $env_file = $this->getEnvFilePath();
40
+            $api_key = DotEnv::load($env_file)->get('TELEGRAM_API_KEY');
41
+        }
42
+
43
+        if (empty($api_key) || !is_string($api_key)) {
44
+            throw new TelegramException('API Key is required');
45
+        }
46
+
47
+        DotEnv::put('TG_CURRENT_KEY', ($this->api_key = $api_key));
48
+        DotEnv::put('TELEGRAM_API_KEY', ($this->api_key = $api_key));
49
+    }
50
+
51
+    /**
52
+     * Get env file path and return it
53
+     *
54
+     * @return string
55
+     */
56
+    private function getEnvFilePath(): string
57
+    {
58
+        $defaultEnvPaths = [
59
+            $_SERVER['DOCUMENT_ROOT'] . '/.env',
60
+            getcwd() . '/../.env',
61
+            getcwd() . '/.env',
62
+        ];
63
+
64
+        foreach ($defaultEnvPaths as $path) {
65
+            if (file_exists($path)) {
66
+                return $path;
67
+            }
68
+        }
69
+
70
+        return '';
71
+    }
72
+
73
+    /**
74
+     * Get API key from temporary ENV variable
75
+     *
76
+     * @return ?string
77
+     */
78
+    public static function getApiKey(): ?string
79
+    {
80
+        return DotEnv::get('TG_CURRENT_KEY');
81
+    }
82
+
83
+    /**
84
+     * Get bot info from given API key
85
+     *
86
+     * @return Response
87
+     * @throws TelegramException
88
+     */
89
+    public function getInfo(): Response
90
+    {
91
+        $result = Request::getMe();
92
+
93
+        if (!$result->isOk()) {
94
+            throw new TelegramException($result->getErrorCode() . ': ' . $result->getDescription());
95
+        }
96
+
97
+        return $result;
98
+    }
99
+
100
+    /**
101
+     * Set Webhook for bot
102
+     *
103
+     * @param string $url
104
+     * @param array $data Optional parameters.
105
+     * @return Response
106
+     * @throws TelegramException
107
+     */
108
+    public function setWebhook(string $url, array $data = []): Response
109
+    {
110
+        if ($url === '') {
111
+            throw new TelegramException('Hook url is empty!');
112
+        }
113
+
114
+        if (!str_starts_with($url, 'https://')) {
115
+            throw new TelegramException('Hook url must start with https://');
116
+        }
117
+
118
+        $data = array_intersect_key($data, array_flip([
119
+            'certificate',
120
+            'ip_address',
121
+            'max_connections',
122
+            'allowed_updates',
123
+            'drop_pending_updates',
124
+        ]));
125
+        $data['url'] = $url;
126
+
127
+        $result = Request::setWebhook($data);
128
+
129
+        if (!$result->isOk()) {
130
+            throw new TelegramException(
131
+                'Webhook was not set! Error: ' . $result->getErrorCode() . ' ' . $result->getDescription()
132
+            );
133
+        }
134
+
135
+        return $result;
136
+    }
137
+
138
+    /**
139
+     * Delete any assigned webhook
140
+     *
141
+     * @param array $data
142
+     * @return Response
143
+     * @throws TelegramException
144
+     */
145
+    public function deleteWebhook(array $data = []): Response
146
+    {
147
+        $result = Request::deleteWebhook($data);
148
+
149
+        if (!$result->isOk()) {
150
+            throw new TelegramException(
151
+                'Webhook was not deleted! Error: ' . $result->getErrorCode() . ' ' . $result->getDescription()
152
+            );
153
+        }
154
+
155
+        return $result;
156
+    }
157
+
158
+    /**
159
+     * This method sets the admin username. and will be used to send you a message if the bot is not working.
160
+     *
161
+     * @param int $chat_id
162
+     * @return void
163
+     */
164
+    public function setAdmin(int $chat_id): void
165
+    {
166
+        defined('TG_ADMIN_ID') or define('TG_ADMIN_ID', $chat_id);
167
+    }
168
+
169
+    /**
170
+     * Get input from stdin and return it
171
+     *
172
+     * @return ?string
173
+     */
174
+    public static function getInput(): ?string
175
+    {
176
+        return file_get_contents('php://input') ?? null;
177
+    }
178
+
179
+    /**
180
+     * This method will convert a string to an update object
181
+     *
182
+     * @param string $input The input string
183
+     * @param string $apiKey The API key
184
+     * @return Update|false
185
+     */
186
+    public static function processUpdate(string $input, string $apiKey): Update|false
187
+    {
188
+        if (empty($input)) {
189
+            throw new TelegramException(
190
+                'Input is empty! Please check your code and try again.'
191
+            );
192
+        }
193
+
194
+        if (!self::validateToken($apiKey)) {
195
+            throw new TelegramException(
196
+                'Invalid token! Please check your code and try again.'
197
+            );
198
+        }
199
+
200
+        if (self::validateWebData($apiKey, $input)) {
201
+            if (Common::isUrlEncode($input)) {
202
+                $web_data = Common::urlDecode($input);
203
+            }
204
+
205
+            if (Common::isJson($input)) {
206
+                $web_data = json_decode($input, true);
207
+            }
208
+
209
+            $input = json_encode([
210
+                'web_data' => $web_data,
211
+            ]);
212
+        }
213
+
214
+        if (!Common::isJson($input)) {
215
+            throw new TelegramException(
216
+                'Input is not a valid JSON string! Please check your code and try again.'
217
+            );
218
+        }
219
+
220
+        $input = json_decode($input, true);
221
+
222
+        return new Update($input);
223
+    }
224
+
225
+    /**
226
+     * Validate webapp data from is from Telegram
227
+     *
228
+     * @link https://core.telegram.org/bots/webapps#validating-data-received-via-the-web-app
229
+     *
230
+     * @param string $token The bot token
231
+     * @param string $body The message body from getInput()
232
+     * @return bool
233
+     */
234
+    public static function validateWebData(string $token, string $body): bool
235
+    {
236
+        if (!Common::isJson($body)) {
237
+            $raw_data = rawurldecode(str_replace('_auth=', '', $body));
238
+            $data = Common::urlDecode($raw_data);
239
+
240
+            if (empty($data['user'])) {
241
+                return false;
242
+            }
243
+
244
+            $data['user'] = urldecode($data['user']);
245
+
246
+        } else {
247
+            $data = json_decode($body, true);
248
+
249
+            if (empty($data['user'])) {
250
+                return false;
251
+            }
252
+
253
+            $data['user'] = json_encode($data['user']);
254
+        }
255
+
256
+        $data_check_string = "auth_date={$data['auth_date']}\nquery_id={$data['query_id']}\nuser={$data['user']}";
257
+        $secret_key = hash_hmac('sha256', $token, "WebAppData", true);
258
+
259
+        return hash_hmac('sha256', $data_check_string, $secret_key) == $data['hash'];
260
+    }
261
+
262
+    /**
263
+     * Get the update from input
264
+     *
265
+     * @return Update|false
266
+     */
267
+    public static function getUpdate(): Update|false
268
+    {
269
+        $input = self::getInput();
270
+        if (empty($input)) return false;
271
+        return Telegram::processUpdate($input, self::getApiKey());
272
+    }
273
+
274
+    /**
275
+     * Validate the token
276
+     *
277
+     * @param string $token (e.g. 123456789:ABC-DEF1234ghIkl-zyx57W2v1u123ew11) {digit}:{alphanumeric[34]}
278
+     * @return bool
279
+     */
280
+    public static function validateToken(string $token): bool
281
+    {
282
+        preg_match_all('/([0-9]+:[a-zA-Z0-9-_]+)/', $token, $matches);
283
+        return count($matches[0]) == 1;
284
+    }
285
+
286
+    /**
287
+     * Pass the update to the given webhook handler
288
+     *
289
+     * @param WebhookHandler $webhook_handler The webhook handler
290
+     * @param ?Update $update By default, it will get the update from input
291
+     * @return void
292
+     */
293
+    public function fetchWith(WebhookHandler $webhook_handler, ?Update $update = null): void
294
+    {
295
+        if (is_subclass_of($webhook_handler, WebhookHandler::class)) {
296
+            if ($update === null) $update = self::getUpdate();
297
+            $webhook_handler->resolve($update);
298
+        }
299
+    }
300
+
301
+    /**
302
+     * Get token from env file.
303
+     *
304
+     * @param string $file
305
+     * @return ?string
306
+     */
307
+    protected function getTokenFromEnvFile(string $file): ?string
308
+    {
309
+        if (!file_exists($file)) return null;
310
+        return DotEnv::load($file)::get('TELEGRAM_API_KEY');
311
+    }
312
+
313
+    /**
314
+     * Debug mode
315
+     *
316
+     * @param ?int $admin_id Fill this or use setAdmin()
317
+     * @return void
318
+     */
319
+    public static function setDebugMode(?int $admin_id = null): void
320
+    {
321
+        error_reporting(E_ALL);
322
+        ini_set('display_errors', 1);
323
+
324
+        defined('DEBUG_MODE') or define('DEBUG_MODE', true);
325
+        if ($admin_id) {
326
+            defined('TG_ADMIN_ID') or define('TG_ADMIN_ID', $admin_id);
327
+        }
328
+
329
+        set_exception_handler(function ($exception) {
330
+
331
+            if (defined('DEBUG_MODE') && DEBUG_MODE) {
332
+
333
+                TelegramLog::error(($message = sprintf(
334
+                    '%s(%d): %s\n%s',
335
+                    $exception->getFile(),
336
+                    $exception->getLine(),
337
+                    $exception->getMessage(),
338
+                    $exception->getTraceAsString()
339
+                )));
340
+
341
+                echo '<b>TelegramError:</b> ' . $message;
342
+
343
+                if (defined('TG_ADMIN_ID') && TG_ADMIN_ID) {
344
+                    $input = getenv('TG_CURRENT_UPDATE') ?? self::getInput();
345
+                    $update = self::processUpdate($input, self::getApiKey());
346
+
347
+                    file_put_contents(
348
+                        ($file = getcwd() . '/' . uniqid('error_') . '.log'),
349
+                        $message . PHP_EOL . PHP_EOL . $update->getRawData(false)
350
+                    );
351
+
352
+                    Request::sendMessage([
353
+                        'chat_id' => TG_ADMIN_ID,
354
+                        'text' => $message,
355
+                    ]);
356
+
357
+                    Request::sendDocument([
358
+                        'chat_id' => TG_ADMIN_ID,
359
+                        'document' => $file,
360
+                    ]);
361
+
362
+                    unlink($file);
363
+                }
364
+
365
+            } else {
366
+                throw $exception;
367
+            }
368
+
369
+        });
370
+    }
371
+
372
+    /**
373
+     * Just another echo
374
+     *
375
+     * @param string $text
376
+     * @return void
377
+     */
378
+    public static function echo(string $text): void
379
+    {
380
+        echo $text;
381
+    }
382 382
 
383 383
 }
384 384
\ No newline at end of file
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -326,7 +326,7 @@
 block discarded – undo
326 326
 			defined('TG_ADMIN_ID') or define('TG_ADMIN_ID', $admin_id);
327 327
 		}
328 328
 
329
-		set_exception_handler(function ($exception) {
329
+		set_exception_handler(function($exception) {
330 330
 
331 331
 			if (defined('DEBUG_MODE') && DEBUG_MODE) {
332 332
 
Please login to merge, or discard this patch.