Completed
Push — feature/refactor-app-design ( 84f9ff...b18d21 )
by Avtandil
04:09
created

Client::ensureValidAction()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2.0625

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 6
ccs 3
cts 4
cp 0.75
rs 9.4285
cc 2
eloc 3
nc 2
nop 1
crap 2.0625
1
<?php
2
/**
3
 * This file is part of the TelegramBot package.
4
 *
5
 * (c) Avtandil Kikabidze aka LONGMAN <[email protected]>
6
 *
7
 * For the full copyright and license information, please view the LICENSE
8
 * file that was distributed with this source code.
9
 */
10
11
namespace Longman\TelegramBot\Http;
12
13
use GuzzleHttp\Client as GuzzleClient;
14
use GuzzleHttp\Exception\RequestException;
15
use Longman\TelegramBot\DB;
16
use Longman\TelegramBot\Entities\File;
17
use Longman\TelegramBot\Exception\TelegramException;
18
use Longman\TelegramBot\Telegram;
19
use Longman\TelegramBot\TelegramLog;
20
21
/**
22
 * Class Client
23
 *
24
 * @method static Response getUpdates(array $data)              Use this method to receive incoming updates using long polling (wiki). An Array of Update
25
 *     objects is returned.
26
 * @method static Response setWebhook(array $data)              Use this method to specify a url and receive incoming updates via an outgoing webhook.
27
 *     Whenever there is an update for the bot, we will send an HTTPS POST request to the specified url, containing a JSON-serialized Update. In case of an
28
 *     unsuccessful request, we will give up after a reasonable amount of attempts. Returns true.
29
 * @method static Response deleteWebhook()                      Use this method to remove webhook integration if you decide to switch back to getUpdates.
30
 *     Returns True on success. Requires no parameters.
31
 * @method static Response getWebhookInfo()                     Use this method to get current webhook status. Requires no parameters. On success,
32
 *     returns a WebhookInfo object. If the bot is using getUpdates, will return an object with the url field empty.
33
 * @method static Response getMe()                              A simple method for testing your bot's auth token. Requires no parameters. Returns basic
34
 *     information about the bot in form of a User object.
35
 * @method static Response forwardMessage(array $data)          Use this method to forward messages of any kind. On success, the sent Message is
36
 *     returned.
37
 * @method static Response sendPhoto(array $data)               Use this method to send photos. On success, the sent Message is returned.
38
 * @method static Response sendAudio(array $data)               Use this method to send audio files, if you want Telegram clients to display them in the
39
 *     music player. Your audio must be in the .mp3 format. On success, the sent Message is returned. Bots can currently send audio files of up to 50 MB in
40
 *     size, this limit may be changed in the future.
41
 * @method static Response sendDocument(array $data)            Use this method to send general files. On success, the sent Message is returned. Bots can
42
 *     currently send files of any type of up to 50 MB in size, this limit may be changed in the future.
43
 * @method static Response sendSticker(array $data)             Use this method to send .webp stickers. On success, the sent Message is returned.
44
 * @method static Response sendVideo(array $data)               Use this method to send video files, Telegram clients support mp4 videos (other formats
45
 *     may be sent as Document). On success, the sent Message is returned. Bots can currently send video files of up to 50 MB in size, this limit may be
46
 *     changed in the future.
47
 * @method static Response sendVoice(array $data)               Use this method to send audio files, if you want Telegram clients to display the file as
48
 *     a playable voice message. For this to work, your audio must be in an .ogg file encoded with OPUS (other formats may be sent as Audio or Document). On
49
 *     success, the sent Message is returned. Bots can currently send voice messages of up to 50 MB in size, this limit may be changed in the future.
50
 * @method static Response sendVideoNote(array $data)           Use this method to send video messages. On success, the sent Message is returned.
51
 * @method static Response sendMediaGroup(array $data)          Use this method to send a group of photos or videos as an album. On success, an array of
52
 *     the sent Messages is returned.
53
 * @method static Response sendLocation(array $data)            Use this method to send point on the map. On success, the sent Message is returned.
54
 * @method static Response editMessageLiveLocation(array $data) Use this method to edit live location messages sent by the bot or via the bot (for inline
55
 *     bots). A location can be edited until its live_period expires or editing is explicitly disabled by a call to stopMessageLiveLocation. On success, if the
56
 *     edited message was sent by the bot, the edited Message is returned, otherwise True is returned.
57
 * @method static Response stopMessageLiveLocation(array $data) Use this method to stop updating a live location message sent by the bot or via the bot
58
 *     (for inline bots) before live_period expires. On success, if the message was sent by the bot, the sent Message is returned, otherwise True is returned.
59
 * @method static Response sendVenue(array $data)               Use this method to send information about a venue. On success, the sent Message is
60
 *     returned.
61
 * @method static Response sendContact(array $data)             Use this method to send phone contacts. On success, the sent Message is returned.
62
 * @method static Response sendChatAction(array $data)          Use this method when you need to tell the user that something is happening on the bot's
63
 *     side. The status is set for 5 seconds or less (when a message arrives from your bot, Telegram clients clear its typing status). Returns True on success.
64
 * @method static Response getUserProfilePhotos(array $data)    Use this method to get a list of profile pictures for a user. Returns a UserProfilePhotos
65
 *     object.
66
 * @method static Response getFile(array $data)                 Use this method to get basic info about a file and prepare it for downloading. For the
67
 *     moment, bots can download files of up to 20MB in size. On success, a File object is returned. The file can then be downloaded via the link
68
 *     https://api.telegram.org/file/bot<token>/<file_path>, where <file_path> is taken from the response. It is guaranteed that the link will be valid for at
69
 *     least 1 hour. When the link expires, a new one can be requested by calling getFile again.
70
 * @method static Response kickChatMember(array $data)          Use this method to kick a user from a group, a supergroup or a channel. In the case of
71
 *     supergroups and channels, the user will not be able to return to the group on their own using invite links, etc., unless unbanned first. The bot must be
72
 *     an administrator in the chat for this to work and must have the appropriate admin rights. Returns True on success.
73
 * @method static Response unbanChatMember(array $data)         Use this method to unban a previously kicked user in a supergroup or channel. The user
74
 *     will not return to the group or channel automatically, but will be able to join via link, etc. The bot must be an administrator for this to work.
75
 *     Returns True on success.
76
 * @method static Response restrictChatMember(array $data)      Use this method to restrict a user in a supergroup. The bot must be an administrator in
77
 *     the supergroup for this to work and must have the appropriate admin rights. Pass True for all boolean parameters to lift restrictions from a user.
78
 *     Returns True on success.
79
 * @method static Response promoteChatMember(array $data)       Use this method to promote or demote a user in a supergroup or a channel. The bot must be
80
 *     an administrator in the chat for this to work and must have the appropriate admin rights. Pass False for all boolean parameters to demote a user.
81
 *     Returns True on success.
82
 * @method static Response exportChatInviteLink(array $data)    Use this method to export an invite link to a supergroup or a channel. The bot must be an
83
 *     administrator in the chat for this to work and must have the appropriate admin rights. Returns exported invite link as String on success.
84
 * @method static Response setChatPhoto(array $data)            Use this method to set a new profile photo for the chat. Photos can't be changed for
85
 *     private chats. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Returns True on success.
86
 * @method static Response deleteChatPhoto(array $data)         Use this method to delete a chat photo. Photos can't be changed for private chats. The
87
 *     bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Returns True on success.
88
 * @method static Response setChatTitle(array $data)            Use this method to change the title of a chat. Titles can't be changed for private chats.
89
 *     The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Returns True on success.
90
 * @method static Response setChatDescription(array $data)      Use this method to change the description of a supergroup or a channel. The bot must be
91
 *     an administrator in the chat for this to work and must have the appropriate admin rights. Returns True on success.
92
 * @method static Response pinChatMessage(array $data)          Use this method to pin a message in a supergroup or a channel. The bot must be an
93
 *     administrator in the chat for this to work and must have the ‘can_pin_messages’ admin right in the supergroup or ‘can_edit_messages’ admin right in the
94
 *     channel. Returns True on success.
95
 * @method static Response unpinChatMessage(array $data)        Use this method to unpin a message in a supergroup or a channel. The bot must be an
96
 *     administrator in the chat for this to work and must have the ‘can_pin_messages’ admin right in the supergroup or ‘can_edit_messages’ admin right in the
97
 *     channel. Returns True on success.
98
 * @method static Response leaveChat(array $data)               Use this method for your bot to leave a group, supergroup or channel. Returns True on
99
 *     success.
100
 * @method static Response getChat(array $data)                 Use this method to get up to date information about the chat (current name of the user
101
 *     for one-on-one conversations, current username of a user, group or channel, etc.). Returns a Chat object on success.
102
 * @method static Response getChatAdministrators(array $data)   Use this method to get a list of administrators in a chat. On success, returns an Array
103
 *     of ChatMember objects that contains information about all chat administrators except other bots. If the chat is a group or a supergroup and no
104
 *     administrators were appointed, only the creator will be returned.
105
 * @method static Response getChatMembersCount(array $data)     Use this method to get the number of members in a chat. Returns Int on success.
106
 * @method static Response getChatMember(array $data)           Use this method to get information about a member of a chat. Returns a ChatMember object
107
 *     on success.
108
 * @method static Response setChatStickerSet(array $data)       Use this method to set a new group sticker set for a supergroup. The bot must be an
109
 *     administrator in the chat for this to work and must have the appropriate admin rights. Use the field can_set_sticker_set optionally returned in getChat
110
 *     requests to check if the bot can use this method. Returns True on success.
111
 * @method static Response deleteChatStickerSet(array $data)    Use this method to delete a group sticker set from a supergroup. The bot must be an
112
 *     administrator in the chat for this to work and must have the appropriate admin rights. Use the field can_set_sticker_set optionally returned in getChat
113
 *     requests to check if the bot can use this method. Returns True on success.
114
 * @method static Response answerCallbackQuery(array $data)     Use this method to send answers to callback queries sent from inline keyboards. The
115
 *     answer will be displayed to the user as a notification at the top of the chat screen or as an alert. On success, True is returned.
116
 * @method static Response answerInlineQuery(array $data)       Use this method to send answers to an inline query. On success, True is returned.
117
 * @method static Response editMessageText(array $data)         Use this method to edit text and game messages sent by the bot or via the bot (for inline
118
 *     bots). On success, if edited message is sent by the bot, the edited Message is returned, otherwise True is returned.
119
 * @method static Response editMessageCaption(array $data)      Use this method to edit captions of messages sent by the bot or via the bot (for inline
120
 *     bots). On success, if edited message is sent by the bot, the edited Message is returned, otherwise True is returned.
121
 * @method static Response editMessageReplyMarkup(array $data)  Use this method to edit only the reply markup of messages sent by the bot or via the bot
122
 *     (for inline bots). On success, if edited message is sent by the bot, the edited Message is returned, otherwise True is returned.
123
 * @method static Response deleteMessage(array $data)           Use this method to delete a message, including service messages, with certain
124
 *     limitations. Returns True on success.
125
 * @method static Response getStickerSet(array $data)           Use this method to get a sticker set. On success, a StickerSet object is returned.
126
 * @method static Response uploadStickerFile(array $data)       Use this method to upload a .png file with a sticker for later use in createNewStickerSet
127
 *     and addStickerToSet methods (can be used multiple times). Returns the uploaded File on success.
128
 * @method static Response createNewStickerSet(array $data)     Use this method to create new sticker set owned by a user. The bot will be able to edit
129
 *     the created sticker set. Returns True on success.
130
 * @method static Response addStickerToSet(array $data)         Use this method to add a new sticker to a set created by the bot. Returns True on
131
 *     success.
132
 * @method static Response setStickerPositionInSet(array $data) Use this method to move a sticker in a set created by the bot to a specific position.
133
 *     Returns True on success.
134
 * @method static Response deleteStickerFromSet(array $data)    Use this method to delete a sticker from a set created by the bot. Returns True on
135
 *     success.
136
 * @method static Response sendInvoice(array $data)             Use this method to send invoices. On success, the sent Message is returned.
137
 * @method static Response answerShippingQuery(array $data)     If you sent an invoice requesting a shipping address and the parameter is_flexible was
138
 *     specified, the Bot API will send an Update with a shipping_query field to the bot. Use this method to reply to shipping queries. On success, True is
139
 *     returned.
140
 * @method static Response answerPreCheckoutQuery(array $data)  Once the user has confirmed their payment and shipping details, the Bot API sends the
141
 *     final confirmation in the form of an Update with the field pre_checkout_query. Use this method to respond to such pre-checkout queries. On success, True
142
 *     is returned.
143
 */
144
class Client
145
{
146
    /**
147
     * Telegram object
148
     *
149
     * @var \Longman\TelegramBot\Telegram
150
     */
151
    private static $telegram;
152
153
    /**
154
     * URI of the Telegram API
155
     *
156
     * @var string
157
     */
158
    private static $api_base_uri = 'https://api.telegram.org';
159
160
    /**
161
     * Guzzle Client object
162
     *
163
     * @var \GuzzleHttp\Client
164
     */
165
    private static $client;
166
167
    /**
168
     * Request limiter
169
     *
170
     * @var boolean
171
     */
172
    private static $limiter_enabled;
173
174
    /**
175
     * Request limiter's interval between checks
176
     *
177
     * @var float
178
     */
179
    private static $limiter_interval;
180
181
    /**
182
     * Available actions to send
183
     *
184
     * This is basically the list of all methods listed on the official API documentation.
185
     *
186
     * @link https://core.telegram.org/bots/api
187
     *
188
     * @var array
189
     */
190
    private static $actions = [
191
        'getUpdates',
192
        'setWebhook',
193
        'deleteWebhook',
194
        'getWebhookInfo',
195
        'getMe',
196
        'sendMessage',
197
        'forwardMessage',
198
        'sendPhoto',
199
        'sendAudio',
200
        'sendDocument',
201
        'sendSticker',
202
        'sendVideo',
203
        'sendVoice',
204
        'sendVideoNote',
205
        'sendMediaGroup',
206
        'sendLocation',
207
        'editMessageLiveLocation',
208
        'stopMessageLiveLocation',
209
        'sendVenue',
210
        'sendContact',
211
        'sendChatAction',
212
        'getUserProfilePhotos',
213
        'getFile',
214
        'kickChatMember',
215
        'unbanChatMember',
216
        'restrictChatMember',
217
        'promoteChatMember',
218
        'exportChatInviteLink',
219
        'setChatPhoto',
220
        'deleteChatPhoto',
221
        'setChatTitle',
222
        'setChatDescription',
223
        'pinChatMessage',
224
        'unpinChatMessage',
225
        'leaveChat',
226
        'getChat',
227
        'getChatAdministrators',
228
        'getChatMembersCount',
229
        'getChatMember',
230
        'setChatStickerSet',
231
        'deleteChatStickerSet',
232
        'answerCallbackQuery',
233
        'answerInlineQuery',
234
        'editMessageText',
235
        'editMessageCaption',
236
        'editMessageReplyMarkup',
237
        'deleteMessage',
238
        'getStickerSet',
239
        'uploadStickerFile',
240
        'createNewStickerSet',
241
        'addStickerToSet',
242
        'setStickerPositionInSet',
243
        'deleteStickerFromSet',
244
        'sendInvoice',
245
        'answerShippingQuery',
246
        'answerPreCheckoutQuery',
247
    ];
248
249
    /**
250
     * Some methods need a dummy param due to certain cURL issues.
251
     *
252
     * @see Client::addDummyParamIfNecessary()
253
     *
254
     * @var array
255
     */
256
    private static $actions_need_dummy_param = [
257
        'deleteWebhook',
258
        'getWebhookInfo',
259
        'getMe',
260
    ];
261
262
    /**
263
     * Initialize
264
     *
265
     * @param \Longman\TelegramBot\Telegram $telegram
266
     *
267
     * @throws TelegramException
268
     */
269 34
    public static function initialize(Telegram $telegram)
270
    {
271 34
        if (! ($telegram instanceof Telegram)) {
272
            throw new TelegramException('Invalid Telegram pointer!');
273
        }
274
275 34
        self::$telegram = $telegram;
276 34
        self::setClient(new GuzzleClient(['base_uri' => self::$api_base_uri]));
277 34
    }
278
279
    /**
280
     * Set a custom Guzzle HTTP Client object
281
     *
282
     * @param Client $client
283
     *
284
     * @throws TelegramException
285
     */
286 34
    public static function setClient(GuzzleClient $client)
287
    {
288 34
        if (! ($client instanceof GuzzleClient)) {
289
            throw new TelegramException('Invalid GuzzleHttp\Client pointer!');
290
        }
291
292 34
        self::$client = $client;
293 34
    }
294
295
    /**
296
     * Generate general fake server response
297
     *
298
     * @param array $data Data to add to fake response
299
     *
300
     * @return array Fake response data
301
     */
302 2
    public static function generateGeneralFakeServerResponse(array $data = [])
303
    {
304
        // PARAM BINDED IN PHPUNIT TEST FOR TestServerResponse.php
305
        // Maybe this is not the best possible implementation
306
307
        // No value set in $data ie testing setWebhook
308
        // Provided $data['chat_id'] ie testing sendMessage
309
310 2
        $fake_response = ['ok' => true]; // :)
311
312 2
        if ($data === []) {
313 1
            $fake_response['result'] = true;
314
        }
315
316
        //some data to let iniatilize the class method SendMessage
317 2
        if (isset($data['chat_id'])) {
318 1
            $data['message_id'] = '1234';
319 1
            $data['date'] = '1441378360';
320 1
            $data['from'] = [
321
                'id'         => 123456789,
322
                'first_name' => 'botname',
323
                'username'   => 'namebot',
324
            ];
325 1
            $data['chat'] = ['id' => $data['chat_id']];
326
327 1
            $fake_response['result'] = $data;
328
        }
329
330 2
        return $fake_response;
331
    }
332
333
    /**
334
     * Properly set up the request params
335
     *
336
     * If any item of the array is a resource, reformat it to a multipart request.
337
     * Else, just return the passed data as form params.
338
     *
339
     * @param array $data
340
     *
341
     * @return array
342
     */
343
    private static function setUpRequestParams(array $data)
344
    {
345
        $has_resource = false;
346
        $multipart = [];
347
348
        // Convert any nested arrays into JSON strings.
349
        array_walk($data, function (&$item) {
350
            is_array($item) && $item = json_encode($item);
351
        });
352
353
        //Reformat data array in multipart way if it contains a resource
354
        foreach ($data as $key => $item) {
355
            $has_resource |= (is_resource($item) || $item instanceof \GuzzleHttp\Psr7\Stream);
356
            $multipart[] = ['name' => $key, 'contents' => $item];
357
        }
358
        if ($has_resource) {
359
            return ['multipart' => $multipart];
360
        }
361
362
        return ['form_params' => $data];
363
    }
364
365
    /**
366
     * Execute HTTP Request
367
     *
368
     * @param string $action Action to execute
369
     * @param array $data Data to attach to the execution
370
     *
371
     * @return string Result of the HTTP Request
372
     * @throws \Longman\TelegramBot\Exception\TelegramException
373
     */
374
    public static function execute($action, array $data = [])
375
    {
376
        //Fix so that the keyboard markup is a string, not an object
377
        if (isset($data['reply_markup'])) {
378
            $data['reply_markup'] = json_encode($data['reply_markup']);
379
        }
380
381
        $result = null;
382
        $request_params = self::setUpRequestParams($data);
383
        $request_params['debug'] = TelegramLog::getDebugLogTempStream();
384
385
        try {
386
            $response = self::$client->post(
387
                '/bot' . self::$telegram->getApiKey() . '/' . $action,
388
                $request_params
389
            );
390
            $result = (string) $response->getBody();
391
392
            // Logging getUpdates Update
393
            if ($action === 'getUpdates') {
394
                TelegramLog::update($result);
395
            }
396
        } catch (RequestException $e) {
397
            $result = ($e->getResponse()) ? (string) $e->getResponse()->getBody() : '';
398
        } finally {
399
            // Logging verbose debug output
400
            TelegramLog::endDebugLogTempStream('Verbose HTTP Request output:' . PHP_EOL . '%s' . PHP_EOL);
401
        }
402
403
        return $result;
404
    }
405
406
    /**
407
     * Download file
408
     *
409
     * @param \Longman\TelegramBot\Entities\File $file
410
     *
411
     * @return boolean
412
     * @throws \Longman\TelegramBot\Exception\TelegramException
413
     */
414
    public static function downloadFile(File $file)
415
    {
416
        if (empty($download_path = self::$telegram->getDownloadPath())) {
417
            throw new TelegramException('Download path not set!');
418
        }
419
420
        $tg_file_path = $file->getFilePath();
421
        $file_path = $download_path . '/' . $tg_file_path;
422
423
        $file_dir = dirname($file_path);
424
        //For safety reasons, first try to create the directory, then check that it exists.
425
        //This is in case some other process has created the folder in the meantime.
426
        if (! @mkdir($file_dir, 0755, true) && ! is_dir($file_dir)) {
427
            throw new TelegramException('Directory ' . $file_dir . ' can\'t be created');
428
        }
429
430
        $debug_handle = TelegramLog::getDebugLogTempStream();
431
432
        try {
433
            self::$client->get(
434
                '/file/bot' . self::$telegram->getApiKey() . '/' . $tg_file_path,
435
                ['debug' => $debug_handle, 'sink' => $file_path]
436
            );
437
438
            return filesize($file_path) > 0;
439
        } catch (RequestException $e) {
440
            return ($e->getResponse()) ? (string) $e->getResponse()->getBody() : '';
441
        } finally {
442
            //Logging verbose debug output
443
            TelegramLog::endDebugLogTempStream('Verbose HTTP File Download Request output:' . PHP_EOL . '%s' . PHP_EOL);
444
        }
445
    }
446
447
    /**
448
     * Encode file
449
     *
450
     * @param string $file
451
     *
452
     * @return resource
453
     * @throws \Longman\TelegramBot\Exception\TelegramException
454
     */
455
    public static function encodeFile($file)
456
    {
457
        $fp = fopen($file, 'rb');
458
        if ($fp === false) {
459
            throw new TelegramException('Cannot open "' . $file . '" for reading');
460
        }
461
462
        return $fp;
463
    }
464
465
    /**
466
     * Send command
467
     *
468
     * @todo Fake response doesn't need json encoding?
469
     * @todo Write debug entry on failure
470
     *
471
     * @param string $action
472
     * @param array $data
473
     *
474
     * @return \Longman\TelegramBot\Http\Response
475
     * @throws \Longman\TelegramBot\Exception\TelegramException
476
     */
477 1
    public static function send($action, array $data = [])
478
    {
479 1
        self::ensureValidAction($action);
480 1
        self::addDummyParamIfNecessary($action, $data);
481
482 1
        $bot_username = self::$telegram->getBotUsername();
483
484
        // @TODO: Refactor testing and remove this
485 1
        if (defined('PHPUNIT_TESTSUITE')) {
486 1
            $fake_response = self::generateGeneralFakeServerResponse($data);
487
488 1
            return new Response($fake_response, $bot_username);
489
        }
490
491
        self::ensureNonEmptyData($data);
492
493
        self::limitTelegramRequests($action, $data);
494
495
        $result = self::execute($action, $data);
496
497
        $response = json_decode($result, true);
498
499
        if (null === $response) {
500
            throw new TelegramException('Telegram returned an invalid response! Please review your bot name and API key.');
501
        }
502
503
        return new Response($response, $bot_username);
504
    }
505
506
    /**
507
     * Add a dummy parameter if the passed action requires it.
508
     *
509
     * If a method doesn't require parameters, we need to add a dummy one anyway,
510
     * because of some cURL version failed POST request without parameters.
511
     *
512
     * @link https://github.com/php-telegram-bot/core/pull/228
513
     *
514
     * @todo Would be nice to find a better solution for this!
515
     *
516
     * @param string $action
517
     * @param array $data
518
     */
519 1
    protected static function addDummyParamIfNecessary($action, array &$data)
520
    {
521 1
        if (in_array($action, self::$actions_need_dummy_param, true)) {
522
            // Can be anything, using a single letter to minimise request size.
523
            $data = ['d'];
524
        }
525 1
    }
526
527
    /**
528
     * Make sure the data isn't empty, else throw an exception
529
     *
530
     * @param array $data
531
     *
532
     * @throws \Longman\TelegramBot\Exception\TelegramException
533
     */
534
    private static function ensureNonEmptyData(array $data)
535
    {
536
        if (count($data) === 0) {
537
            throw new TelegramException('Data is empty!');
538
        }
539
    }
540
541
    /**
542
     * Make sure the action is valid, else throw an exception
543
     *
544
     * @param string $action
545
     *
546
     * @throws \Longman\TelegramBot\Exception\TelegramException
547
     */
548 1
    private static function ensureValidAction($action)
549
    {
550 1
        if (! in_array($action, self::$actions, true)) {
551
            throw new TelegramException('The action "' . $action . '" doesn\'t exist!');
552
        }
553 1
    }
554
555
    /**
556
     * Use this method to send text messages. On success, the sent Message is returned
557
     *
558
     * @link https://core.telegram.org/bots/api#sendmessage
559
     *
560
     * @param array $data
561
     *
562
     * @return \Longman\TelegramBot\Http\Response
563
     * @throws \Longman\TelegramBot\Exception\TelegramException
564
     */
565
    public static function sendMessage(array $data)
566
    {
567
        $text = $data['text'];
568
569
        do {
570
            // Chop off and send the first message
571
            $data['text'] = mb_substr($text, 0, 4096);
572
            $response = self::send('sendMessage', $data);
573
574
            // Prepare the next message
575
            $text = mb_substr($text, 4096);
576
        } while (mb_strlen($text, 'UTF-8') > 0);
577
578
        return $response;
579
    }
580
581
    /**
582
     * Any statically called method should be relayed to the `send` method.
583
     *
584
     * @param string $action
585
     * @param array $data
586
     *
587
     * @return \Longman\TelegramBot\Http\Response
588
     * @throws \Longman\TelegramBot\Exception\TelegramException
589
     */
590 1
    public static function __callStatic($action, array $data)
591
    {
592
        // Make sure to add the action being called as the first parameter to be passed.
593 1
        array_unshift($data, $action);
594
595
        // @todo Use splat operator for unpacking when we move to PHP 5.6+
596 1
        return call_user_func_array('static::send', $data);
597
    }
598
599
    /**
600
     * Send message to all active chats
601
     *
602
     * @param string $callback_function
603
     * @param array $data
604
     * @param array $select_chats_params
605
     *
606
     * @return array
607
     * @throws TelegramException
608
     */
609
    public static function sendToActiveChats(
610
        $callback_function,
611
        array $data,
612
        array $select_chats_params
613
    ) {
614
        if (! method_exists(Client::class, $callback_function)) {
615
            throw new TelegramException('Method "' . $callback_function . '" not found in class Request.');
616
        }
617
618
        $chats = DB::selectChats($select_chats_params);
619
620
        $results = [];
621
        if (is_array($chats)) {
622
            foreach ($chats as $row) {
623
                $data['chat_id'] = $row['chat_id'];
624
                $results[] = call_user_func(Client::class . '::' . $callback_function, $data);
625
            }
626
        }
627
628
        return $results;
629
    }
630
631
    /**
632
     * Enable request limiter
633
     *
634
     * @param boolean $enable
635
     * @param array $options
636
     *
637
     * @throws \Longman\TelegramBot\Exception\TelegramException
638
     */
639
    public static function setLimiter($enable = true, array $options = [])
640
    {
641
        if (DB::isDbConnected()) {
642
            $options_default = [
643
                'interval' => 1,
644
            ];
645
646
            $options = array_merge($options_default, $options);
647
648
            if (! is_numeric($options['interval']) || $options['interval'] <= 0) {
649
                throw new TelegramException('Interval must be a number and must be greater than zero!');
650
            }
651
652
            self::$limiter_interval = $options['interval'];
0 ignored issues
show
Documentation Bug introduced by
It seems like $options['interval'] can also be of type integer or string. However, the property $limiter_interval is declared as type double. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
653
            self::$limiter_enabled = $enable;
654
        }
655
    }
656
657
    /**
658
     * This functions delays API requests to prevent reaching Telegram API limits
659
     *  Can be disabled while in execution by 'Request::setLimiter(false)'
660
     *
661
     * @link https://core.telegram.org/bots/faq#my-bot-is-hitting-limits-how-do-i-avoid-this
662
     *
663
     * @param string $action
664
     * @param array $data
665
     *
666
     * @throws \Longman\TelegramBot\Exception\TelegramException
667
     */
668
    private static function limitTelegramRequests($action, array $data = [])
669
    {
670
        if (self::$limiter_enabled) {
671
            $limited_methods = [
672
                'sendMessage',
673
                'forwardMessage',
674
                'sendPhoto',
675
                'sendAudio',
676
                'sendDocument',
677
                'sendSticker',
678
                'sendVideo',
679
                'sendVoice',
680
                'sendVideoNote',
681
                'sendMediaGroup',
682
                'sendLocation',
683
                'editMessageLiveLocation',
684
                'stopMessageLiveLocation',
685
                'sendVenue',
686
                'sendContact',
687
                'sendInvoice',
688
                'editMessageText',
689
                'editMessageCaption',
690
                'editMessageReplyMarkup',
691
                'setChatTitle',
692
                'setChatDescription',
693
                'setChatStickerSet',
694
                'deleteChatStickerSet',
695
            ];
696
697
            $chat_id = isset($data['chat_id']) ? $data['chat_id'] : null;
698
            $inline_message_id = isset($data['inline_message_id']) ? $data['inline_message_id'] : null;
699
700
            if (($chat_id || $inline_message_id) && in_array($action, $limited_methods)) {
701
                $timeout = 60;
702
703
                while (true) {
704
                    if ($timeout <= 0) {
705
                        throw new TelegramException('Timed out while waiting for a request spot!');
706
                    }
707
708
                    $requests = DB::getTelegramRequestCount($chat_id, $inline_message_id);
709
710
                    $chat_per_second = ($requests['LIMIT_PER_SEC'] == 0); // No more than one message per second inside a particular chat
711
                    $global_per_second = ($requests['LIMIT_PER_SEC_ALL'] < 30);    // No more than 30 messages per second to different chats
712
                    $groups_per_minute = (((is_numeric($chat_id) && $chat_id > 0) || ! is_null($inline_message_id)) || ((! is_numeric($chat_id) || $chat_id < 0) && $requests['LIMIT_PER_MINUTE'] < 20));    // No more than 20 messages per minute in groups and channels
713
714
                    if ($chat_per_second && $global_per_second && $groups_per_minute) {
715
                        break;
716
                    }
717
718
                    $timeout--;
719
                    usleep(self::$limiter_interval * 1000000);
720
                }
721
722
                DB::insertTelegramRequest($action, $data);
723
            }
724
        }
725
    }
726
}
727