Completed
Push — feature/refactor-app-design ( d959a3 )
by Avtandil
03:51
created

Client::send()   B

Complexity

Conditions 3
Paths 3

Size

Total Lines 25
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
dl 0
loc 25
ccs 0
cts 13
cp 0
rs 8.8571
c 0
b 0
f 0
cc 3
eloc 13
nc 3
nop 2
crap 12
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 Request
23
 *
24
 * @method static ServerResponse 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 ServerResponse 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 ServerResponse 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 ServerResponse 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 ServerResponse 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 ServerResponse forwardMessage(array $data)          Use this method to forward messages of any kind. On success, the sent Message is
36
 *     returned.
37
 * @method static ServerResponse sendPhoto(array $data)               Use this method to send photos. On success, the sent Message is returned.
38
 * @method static ServerResponse 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 ServerResponse 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 ServerResponse sendSticker(array $data)             Use this method to send .webp stickers. On success, the sent Message is returned.
44
 * @method static ServerResponse 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 ServerResponse 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 ServerResponse sendVideoNote(array $data)           Use this method to send video messages. On success, the sent Message is returned.
51
 * @method static ServerResponse 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 ServerResponse sendLocation(array $data)            Use this method to send point on the map. On success, the sent Message is returned.
54
 * @method static ServerResponse 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 ServerResponse 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 ServerResponse sendVenue(array $data)               Use this method to send information about a venue. On success, the sent Message is
60
 *     returned.
61
 * @method static ServerResponse sendContact(array $data)             Use this method to send phone contacts. On success, the sent Message is returned.
62
 * @method static ServerResponse 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 ServerResponse getUserProfilePhotos(array $data)    Use this method to get a list of profile pictures for a user. Returns a UserProfilePhotos
65
 *     object.
66
 * @method static ServerResponse 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 ServerResponse 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 ServerResponse 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 ServerResponse 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 ServerResponse 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 ServerResponse 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 ServerResponse 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 ServerResponse 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 ServerResponse 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 ServerResponse 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 ServerResponse 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 ServerResponse 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 ServerResponse leaveChat(array $data)               Use this method for your bot to leave a group, supergroup or channel. Returns True on
99
 *     success.
100
 * @method static ServerResponse 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 ServerResponse 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 ServerResponse getChatMembersCount(array $data)     Use this method to get the number of members in a chat. Returns Int on success.
106
 * @method static ServerResponse 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 ServerResponse 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 ServerResponse 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 ServerResponse 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 ServerResponse answerInlineQuery(array $data)       Use this method to send answers to an inline query. On success, True is returned.
117
 * @method static ServerResponse 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 ServerResponse 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 ServerResponse 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 ServerResponse deleteMessage(array $data)           Use this method to delete a message, including service messages, with certain
124
 *     limitations. Returns True on success.
125
 * @method static ServerResponse getStickerSet(array $data)           Use this method to get a sticker set. On success, a StickerSet object is returned.
126
 * @method static ServerResponse 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 ServerResponse 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 ServerResponse 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 ServerResponse 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 ServerResponse 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 ServerResponse sendInvoice(array $data)             Use this method to send invoices. On success, the sent Message is returned.
137
 * @method static ServerResponse 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 ServerResponse 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
     * Input value of the request
169
     *
170
     * @var string
171
     */
172
    private static $input;
173
174
    /**
175
     * Request limiter
176
     *
177
     * @var boolean
178
     */
179
    private static $limiter_enabled;
180
181
    /**
182
     * Request limiter's interval between checks
183
     *
184
     * @var float
185
     */
186
    private static $limiter_interval;
187
188
    /**
189
     * Available actions to send
190
     *
191
     * This is basically the list of all methods listed on the official API documentation.
192
     *
193
     * @link https://core.telegram.org/bots/api
194
     *
195
     * @var array
196
     */
197
    private static $actions = [
198
        'getUpdates',
199
        'setWebhook',
200
        'deleteWebhook',
201
        'getWebhookInfo',
202
        'getMe',
203
        'sendMessage',
204
        'forwardMessage',
205
        'sendPhoto',
206
        'sendAudio',
207
        'sendDocument',
208
        'sendSticker',
209
        'sendVideo',
210
        'sendVoice',
211
        'sendVideoNote',
212
        'sendMediaGroup',
213
        'sendLocation',
214
        'editMessageLiveLocation',
215
        'stopMessageLiveLocation',
216
        'sendVenue',
217
        'sendContact',
218
        'sendChatAction',
219
        'getUserProfilePhotos',
220
        'getFile',
221
        'kickChatMember',
222
        'unbanChatMember',
223
        'restrictChatMember',
224
        'promoteChatMember',
225
        'exportChatInviteLink',
226
        'setChatPhoto',
227
        'deleteChatPhoto',
228
        'setChatTitle',
229
        'setChatDescription',
230
        'pinChatMessage',
231
        'unpinChatMessage',
232
        'leaveChat',
233
        'getChat',
234
        'getChatAdministrators',
235
        'getChatMembersCount',
236
        'getChatMember',
237
        'setChatStickerSet',
238
        'deleteChatStickerSet',
239
        'answerCallbackQuery',
240
        'answerInlineQuery',
241
        'editMessageText',
242
        'editMessageCaption',
243
        'editMessageReplyMarkup',
244
        'deleteMessage',
245
        'getStickerSet',
246
        'uploadStickerFile',
247
        'createNewStickerSet',
248
        'addStickerToSet',
249
        'setStickerPositionInSet',
250
        'deleteStickerFromSet',
251
        'sendInvoice',
252
        'answerShippingQuery',
253
        'answerPreCheckoutQuery',
254
    ];
255
256
    /**
257
     * Some methods need a dummy param due to certain cURL issues.
258
     *
259
     * @see Client::addDummyParamIfNecessary()
260
     *
261
     * @var array
262
     */
263
    private static $actions_need_dummy_param = [
264
        'deleteWebhook',
265
        'getWebhookInfo',
266
        'getMe',
267
    ];
268
269
    /**
270
     * Initialize
271
     *
272
     * @param \Longman\TelegramBot\Telegram $telegram
273
     *
274
     * @throws TelegramException
275
     */
276 32
    public static function initialize(Telegram $telegram)
277
    {
278 32
        if (! ($telegram instanceof Telegram)) {
279
            throw new TelegramException('Invalid Telegram pointer!');
280
        }
281
282 32
        self::$telegram = $telegram;
283 32
        self::setClient(new GuzzleClient(['base_uri' => self::$api_base_uri]));
284 32
    }
285
286
    /**
287
     * Set a custom Guzzle HTTP Client object
288
     *
289
     * @param Client $client
290
     *
291
     * @throws TelegramException
292
     */
293 32
    public static function setClient(GuzzleClient $client)
294
    {
295 32
        if (! ($client instanceof GuzzleClient)) {
296
            throw new TelegramException('Invalid GuzzleHttp\Client pointer!');
297
        }
298
299 32
        self::$client = $client;
300 32
    }
301
302
    /**
303
     * Set input from custom input or stdin and return it
304
     *
305
     * @return string
306
     * @throws \Longman\TelegramBot\Exception\TelegramException
307
     */
308
    public static function getInput()
309
    {
310
        // First check if a custom input has been set, else get the PHP input.
311
        if (! ($input = self::$telegram->getCustomInput())) {
312
            $input = file_get_contents('php://input');
313
        }
314
315
        // Make sure we have a string to work with.
316
        if (! is_string($input)) {
317
            throw new TelegramException('Input must be a string!');
318
        }
319
320
        self::$input = $input;
321
322
        TelegramLog::update(self::$input);
323
324
        return self::$input;
325
    }
326
327
    /**
328
     * Generate general fake server response
329
     *
330
     * @param array $data Data to add to fake response
331
     *
332
     * @return array Fake response data
333
     */
334 1
    public static function generateGeneralFakeServerResponse(array $data = [])
335
    {
336
        //PARAM BINDED IN PHPUNIT TEST FOR TestServerResponse.php
337
        //Maybe this is not the best possible implementation
338
339
        //No value set in $data ie testing setWebhook
340
        //Provided $data['chat_id'] ie testing sendMessage
341
342 1
        $fake_response = ['ok' => true]; // :)
343
344 1
        if ($data === []) {
345 1
            $fake_response['result'] = true;
346
        }
347
348
        //some data to let iniatilize the class method SendMessage
349 1
        if (isset($data['chat_id'])) {
350 1
            $data['message_id'] = '1234';
351 1
            $data['date'] = '1441378360';
352 1
            $data['from'] = [
353
                'id'         => 123456789,
354
                'first_name' => 'botname',
355
                'username'   => 'namebot',
356
            ];
357 1
            $data['chat'] = ['id' => $data['chat_id']];
358
359 1
            $fake_response['result'] = $data;
360
        }
361
362 1
        return $fake_response;
363
    }
364
365
    /**
366
     * Properly set up the request params
367
     *
368
     * If any item of the array is a resource, reformat it to a multipart request.
369
     * Else, just return the passed data as form params.
370
     *
371
     * @param array $data
372
     *
373
     * @return array
374
     */
375
    private static function setUpRequestParams(array $data)
376
    {
377
        $has_resource = false;
378
        $multipart = [];
379
380
        // Convert any nested arrays into JSON strings.
381
        array_walk($data, function (&$item) {
382
            is_array($item) && $item = json_encode($item);
383
        });
384
385
        //Reformat data array in multipart way if it contains a resource
386
        foreach ($data as $key => $item) {
387
            $has_resource |= (is_resource($item) || $item instanceof \GuzzleHttp\Psr7\Stream);
388
            $multipart[] = ['name' => $key, 'contents' => $item];
389
        }
390
        if ($has_resource) {
391
            return ['multipart' => $multipart];
392
        }
393
394
        return ['form_params' => $data];
395
    }
396
397
    /**
398
     * Execute HTTP Request
399
     *
400
     * @param string $action Action to execute
401
     * @param array $data Data to attach to the execution
402
     *
403
     * @return string Result of the HTTP Request
404
     * @throws \Longman\TelegramBot\Exception\TelegramException
405
     */
406
    public static function execute($action, array $data = [])
407
    {
408
        //Fix so that the keyboard markup is a string, not an object
409
        if (isset($data['reply_markup'])) {
410
            $data['reply_markup'] = json_encode($data['reply_markup']);
411
        }
412
413
        $result = null;
414
        $request_params = self::setUpRequestParams($data);
415
        $request_params['debug'] = TelegramLog::getDebugLogTempStream();
416
417
        try {
418
            $response = self::$client->post(
419
                '/bot' . self::$telegram->getApiKey() . '/' . $action,
420
                $request_params
421
            );
422
            $result = (string) $response->getBody();
423
424
            //Logging getUpdates Update
425
            if ($action === 'getUpdates') {
426
                TelegramLog::update($result);
427
            }
428
        } catch (RequestException $e) {
429
            $result = ($e->getResponse()) ? (string) $e->getResponse()->getBody() : '';
430
        } finally {
431
            //Logging verbose debug output
432
            TelegramLog::endDebugLogTempStream('Verbose HTTP Request output:' . PHP_EOL . '%s' . PHP_EOL);
433
        }
434
435
        return $result;
436
    }
437
438
    /**
439
     * Download file
440
     *
441
     * @param \Longman\TelegramBot\Entities\File $file
442
     *
443
     * @return boolean
444
     * @throws \Longman\TelegramBot\Exception\TelegramException
445
     */
446
    public static function downloadFile(File $file)
447
    {
448
        if (empty($download_path = self::$telegram->getDownloadPath())) {
449
            throw new TelegramException('Download path not set!');
450
        }
451
452
        $tg_file_path = $file->getFilePath();
453
        $file_path = $download_path . '/' . $tg_file_path;
454
455
        $file_dir = dirname($file_path);
456
        //For safety reasons, first try to create the directory, then check that it exists.
457
        //This is in case some other process has created the folder in the meantime.
458
        if (! @mkdir($file_dir, 0755, true) && ! is_dir($file_dir)) {
459
            throw new TelegramException('Directory ' . $file_dir . ' can\'t be created');
460
        }
461
462
        $debug_handle = TelegramLog::getDebugLogTempStream();
463
464
        try {
465
            self::$client->get(
466
                '/file/bot' . self::$telegram->getApiKey() . '/' . $tg_file_path,
467
                ['debug' => $debug_handle, 'sink' => $file_path]
468
            );
469
470
            return filesize($file_path) > 0;
471
        } catch (RequestException $e) {
472
            return ($e->getResponse()) ? (string) $e->getResponse()->getBody() : '';
473
        } finally {
474
            //Logging verbose debug output
475
            TelegramLog::endDebugLogTempStream('Verbose HTTP File Download Request output:' . PHP_EOL . '%s' . PHP_EOL);
476
        }
477
    }
478
479
    /**
480
     * Encode file
481
     *
482
     * @param string $file
483
     *
484
     * @return resource
485
     * @throws \Longman\TelegramBot\Exception\TelegramException
486
     */
487
    public static function encodeFile($file)
488
    {
489
        $fp = fopen($file, 'rb');
490
        if ($fp === false) {
491
            throw new TelegramException('Cannot open "' . $file . '" for reading');
492
        }
493
494
        return $fp;
495
    }
496
497
    /**
498
     * Send command
499
     *
500
     * @todo Fake response doesn't need json encoding?
501
     * @todo Write debug entry on failure
502
     *
503
     * @param string $action
504
     * @param array $data
505
     *
506
     * @return \Longman\TelegramBot\Http\ServerResponse
507
     * @throws \Longman\TelegramBot\Exception\TelegramException
508
     */
509
    public static function send($action, array $data = [])
510
    {
511
        self::ensureValidAction($action);
512
        self::addDummyParamIfNecessary($action, $data);
513
514
        $bot_username = self::$telegram->getBotUsername();
515
516
        if (defined('PHPUNIT_TESTSUITE')) {
517
            $fake_response = self::generateGeneralFakeServerResponse($data);
518
519
            return new ServerResponse($fake_response, $bot_username);
520
        }
521
522
        self::ensureNonEmptyData($data);
523
524
        self::limitTelegramRequests($action, $data);
525
526
        $response = json_decode(self::execute($action, $data), true);
527
528
        if (null === $response) {
529
            throw new TelegramException('Telegram returned an invalid response! Please review your bot name and API key.');
530
        }
531
532
        return new ServerResponse($response, $bot_username);
533
    }
534
535
    /**
536
     * Add a dummy parameter if the passed action requires it.
537
     *
538
     * If a method doesn't require parameters, we need to add a dummy one anyway,
539
     * because of some cURL version failed POST request without parameters.
540
     *
541
     * @link https://github.com/php-telegram-bot/core/pull/228
542
     *
543
     * @todo Would be nice to find a better solution for this!
544
     *
545
     * @param string $action
546
     * @param array $data
547
     */
548
    protected static function addDummyParamIfNecessary($action, array &$data)
549
    {
550
        if (in_array($action, self::$actions_need_dummy_param, true)) {
551
            // Can be anything, using a single letter to minimise request size.
552
            $data = ['d'];
553
        }
554
    }
555
556
    /**
557
     * Make sure the data isn't empty, else throw an exception
558
     *
559
     * @param array $data
560
     *
561
     * @throws \Longman\TelegramBot\Exception\TelegramException
562
     */
563
    private static function ensureNonEmptyData(array $data)
564
    {
565
        if (count($data) === 0) {
566
            throw new TelegramException('Data is empty!');
567
        }
568
    }
569
570
    /**
571
     * Make sure the action is valid, else throw an exception
572
     *
573
     * @param string $action
574
     *
575
     * @throws \Longman\TelegramBot\Exception\TelegramException
576
     */
577
    private static function ensureValidAction($action)
578
    {
579
        if (! in_array($action, self::$actions, true)) {
580
            throw new TelegramException('The action "' . $action . '" doesn\'t exist!');
581
        }
582
    }
583
584
    /**
585
     * Use this method to send text messages. On success, the sent Message is returned
586
     *
587
     * @link https://core.telegram.org/bots/api#sendmessage
588
     *
589
     * @param array $data
590
     *
591
     * @return \Longman\TelegramBot\Http\ServerResponse
592
     * @throws \Longman\TelegramBot\Exception\TelegramException
593
     */
594
    public static function sendMessage(array $data)
595
    {
596
        $text = $data['text'];
597
598
        do {
599
            //Chop off and send the first message
600
            $data['text'] = mb_substr($text, 0, 4096);
601
            $response = self::send('sendMessage', $data);
602
603
            //Prepare the next message
604
            $text = mb_substr($text, 4096);
605
        } while (mb_strlen($text, 'UTF-8') > 0);
606
607
        return $response;
608
    }
609
610
    /**
611
     * Any statically called method should be relayed to the `send` method.
612
     *
613
     * @param string $action
614
     * @param array $data
615
     *
616
     * @return \Longman\TelegramBot\Http\ServerResponse
617
     * @throws \Longman\TelegramBot\Exception\TelegramException
618
     */
619
    public static function __callStatic($action, array $data)
620
    {
621
        // Make sure to add the action being called as the first parameter to be passed.
622
        array_unshift($data, $action);
623
624
        // @todo Use splat operator for unpacking when we move to PHP 5.6+
625
        return call_user_func_array('static::send', $data);
626
    }
627
628
    /**
629
     * Return an empty Server Response
630
     *
631
     * No request to telegram are sent, this function is used in commands that
632
     * don't need to fire a message after execution
633
     *
634
     * @return \Longman\TelegramBot\Http\ServerResponse
635
     * @throws \Longman\TelegramBot\Exception\TelegramException
636
     */
637 1
    public static function emptyResponse()
638
    {
639 1
        return new ServerResponse(['ok' => true, 'result' => true], null);
640
    }
641
642
    /**
643
     * Send message to all active chats
644
     *
645
     * @param string $callback_function
646
     * @param array $data
647
     * @param array $select_chats_params
648
     *
649
     * @return array
650
     * @throws TelegramException
651
     */
652
    public static function sendToActiveChats(
653
        $callback_function,
654
        array $data,
655
        array $select_chats_params
656
    ) {
657
        if (! method_exists(Client::class, $callback_function)) {
658
            throw new TelegramException('Method "' . $callback_function . '" not found in class Request.');
659
        }
660
661
        $chats = DB::selectChats($select_chats_params);
662
663
        $results = [];
664
        if (is_array($chats)) {
665
            foreach ($chats as $row) {
666
                $data['chat_id'] = $row['chat_id'];
667
                $results[] = call_user_func(Client::class . '::' . $callback_function, $data);
668
            }
669
        }
670
671
        return $results;
672
    }
673
674
    /**
675
     * Enable request limiter
676
     *
677
     * @param boolean $enable
678
     * @param array $options
679
     *
680
     * @throws \Longman\TelegramBot\Exception\TelegramException
681
     */
682
    public static function setLimiter($enable = true, array $options = [])
683
    {
684
        if (DB::isDbConnected()) {
685
            $options_default = [
686
                'interval' => 1,
687
            ];
688
689
            $options = array_merge($options_default, $options);
690
691
            if (! is_numeric($options['interval']) || $options['interval'] <= 0) {
692
                throw new TelegramException('Interval must be a number and must be greater than zero!');
693
            }
694
695
            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...
696
            self::$limiter_enabled = $enable;
697
        }
698
    }
699
700
    /**
701
     * This functions delays API requests to prevent reaching Telegram API limits
702
     *  Can be disabled while in execution by 'Request::setLimiter(false)'
703
     *
704
     * @link https://core.telegram.org/bots/faq#my-bot-is-hitting-limits-how-do-i-avoid-this
705
     *
706
     * @param string $action
707
     * @param array $data
708
     *
709
     * @throws \Longman\TelegramBot\Exception\TelegramException
710
     */
711
    private static function limitTelegramRequests($action, array $data = [])
712
    {
713
        if (self::$limiter_enabled) {
714
            $limited_methods = [
715
                'sendMessage',
716
                'forwardMessage',
717
                'sendPhoto',
718
                'sendAudio',
719
                'sendDocument',
720
                'sendSticker',
721
                'sendVideo',
722
                'sendVoice',
723
                'sendVideoNote',
724
                'sendMediaGroup',
725
                'sendLocation',
726
                'editMessageLiveLocation',
727
                'stopMessageLiveLocation',
728
                'sendVenue',
729
                'sendContact',
730
                'sendInvoice',
731
                'editMessageText',
732
                'editMessageCaption',
733
                'editMessageReplyMarkup',
734
                'setChatTitle',
735
                'setChatDescription',
736
                'setChatStickerSet',
737
                'deleteChatStickerSet',
738
            ];
739
740
            $chat_id = isset($data['chat_id']) ? $data['chat_id'] : null;
741
            $inline_message_id = isset($data['inline_message_id']) ? $data['inline_message_id'] : null;
742
743
            if (($chat_id || $inline_message_id) && in_array($action, $limited_methods)) {
744
                $timeout = 60;
745
746
                while (true) {
747
                    if ($timeout <= 0) {
748
                        throw new TelegramException('Timed out while waiting for a request spot!');
749
                    }
750
751
                    $requests = DB::getTelegramRequestCount($chat_id, $inline_message_id);
752
753
                    $chat_per_second = ($requests['LIMIT_PER_SEC'] == 0); // No more than one message per second inside a particular chat
754
                    $global_per_second = ($requests['LIMIT_PER_SEC_ALL'] < 30);    // No more than 30 messages per second to different chats
755
                    $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
756
757
                    if ($chat_per_second && $global_per_second && $groups_per_minute) {
758
                        break;
759
                    }
760
761
                    $timeout--;
762
                    usleep(self::$limiter_interval * 1000000);
763
                }
764
765
                DB::insertTelegramRequest($action, $data);
766
            }
767
        }
768
    }
769
}
770