Passed
Push — master ( 163ca3...6d62ea )
by Armando
01:57
created

Request::getChatMembersCount()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 3
ccs 0
cts 2
cp 0
crap 2
rs 10
1
<?php
2
3
/**
4
 * This file is part of the TelegramBot package.
5
 *
6
 * (c) Avtandil Kikabidze aka LONGMAN <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Longman\TelegramBot;
13
14
use GuzzleHttp\Client;
15
use GuzzleHttp\ClientInterface;
16
use GuzzleHttp\Exception\RequestException;
17
use GuzzleHttp\Psr7\Stream;
18
use Longman\TelegramBot\Entities\File;
19
use Longman\TelegramBot\Entities\InputMedia\InputMedia;
20
use Longman\TelegramBot\Entities\Message;
21
use Longman\TelegramBot\Entities\ServerResponse;
22
use Longman\TelegramBot\Exception\InvalidBotTokenException;
23
use Longman\TelegramBot\Exception\TelegramException;
24
use Throwable;
25
26
/**
27
 * Class Request
28
 *
29
 * @method static ServerResponse getUpdates(array $data)                      Use this method to receive incoming updates using long polling (wiki). An Array of Update objects is returned.
30
 * @method static ServerResponse setWebhook(array $data)                      Use this method to specify a url and receive incoming updates via an outgoing webhook. 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 unsuccessful request, we will give up after a reasonable amount of attempts. Returns true.
31
 * @method static ServerResponse deleteWebhook(array $data)                   Use this method to remove webhook integration if you decide to switch back to getUpdates. Returns True on success.
32
 * @method static ServerResponse getWebhookInfo()                             Use this method to get current webhook status. Requires no parameters. On success, 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 information about the bot in form of a User object.
34
 * @method static ServerResponse logOut()                                     Use this method to log out from the cloud Bot API server before launching the bot locally. Requires no parameters. Returns True on success.
35
 * @method static ServerResponse close()                                      Use this method to close the bot instance before moving it from one local server to another. Requires no parameters. Returns True on success.
36
 * @method static ServerResponse forwardMessage(array $data)                  Use this method to forward messages of any kind. On success, the sent Message is returned.
37
 * @method static ServerResponse copyMessage(array $data)                     Use this method to copy messages of any kind. The method is analogous to the method forwardMessages, but the copied message doesn't have a link to the original message. Returns the MessageId of the sent message on success.
38
 * @method static ServerResponse sendPhoto(array $data)                       Use this method to send photos. On success, the sent Message is returned.
39
 * @method static ServerResponse sendAudio(array $data)                       Use this method to send audio files, if you want Telegram clients to display them in the 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 size, this limit may be changed in the future.
40
 * @method static ServerResponse sendDocument(array $data)                    Use this method to send general files. On success, the sent Message is returned. Bots can currently send files of any type of up to 50 MB in size, this limit may be changed in the future.
41
 * @method static ServerResponse sendSticker(array $data)                     Use this method to send .webp stickers. On success, the sent Message is returned.
42
 * @method static ServerResponse sendVideo(array $data)                       Use this method to send video files, Telegram clients support mp4 videos (other formats 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 changed in the future.
43
 * @method static ServerResponse sendAnimation(array $data)                   Use this method to send animation files (GIF or H.264/MPEG-4 AVC video without sound). On success, the sent Message is returned. Bots can currently send animation files of up to 50 MB in size, this limit may be changed in the future.
44
 * @method static ServerResponse sendVoice(array $data)                       Use this method to send audio files, if you want Telegram clients to display the file as 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 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.
45
 * @method static ServerResponse sendVideoNote(array $data)                   Use this method to send video messages. On success, the sent Message is returned.
46
 * @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 the sent Messages is returned.
47
 * @method static ServerResponse sendLocation(array $data)                    Use this method to send point on the map. On success, the sent Message is returned.
48
 * @method static ServerResponse editMessageLiveLocation(array $data)         Use this method to edit live location messages sent by the bot or via the bot (for inline 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 edited message was sent by the bot, the edited Message is returned, otherwise True is returned.
49
 * @method static ServerResponse stopMessageLiveLocation(array $data)         Use this method to stop updating a live location message sent by the bot or via the bot (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.
50
 * @method static ServerResponse sendVenue(array $data)                       Use this method to send information about a venue. On success, the sent Message is returned.
51
 * @method static ServerResponse sendContact(array $data)                     Use this method to send phone contacts. On success, the sent Message is returned.
52
 * @method static ServerResponse sendPoll(array $data)                        Use this method to send a native poll. A native poll can't be sent to a private chat. On success, the sent Message is returned.
53
 * @method static ServerResponse sendDice(array $data)                        Use this method to send a dice, which will have a random value from 1 to 6. On success, the sent Message is returned.
54
 * @method static ServerResponse sendChatAction(array $data)                  Use this method when you need to tell the user that something is happening on the bot's 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.
55
 * @method static ServerResponse getUserProfilePhotos(array $data)            Use this method to get a list of profile pictures for a user. Returns a UserProfilePhotos object.
56
 * @method static ServerResponse getFile(array $data)                         Use this method to get basic info about a file and prepare it for downloading. For the 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 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 least 1 hour. When the link expires, a new one can be requested by calling getFile again.
57
 * @method static ServerResponse banChatMember(array $data)                   Use this method to kick a user from a group, a supergroup or a channel. In the case of 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 an administrator in the chat for this to work and must have the appropriate admin rights. Returns True on success.
58
 * @method static ServerResponse unbanChatMember(array $data)                 Use this method to unban a previously kicked user in a supergroup or channel. The user 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. Returns True on success.
59
 * @method static ServerResponse restrictChatMember(array $data)              Use this method to restrict a user in a supergroup. The bot must be an administrator in the supergroup for this to work and must have the appropriate admin rights. Pass True for all permissions to lift restrictions from a user. Returns True on success.
60
 * @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 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. Returns True on success.
61
 * @method static ServerResponse setChatAdministratorCustomTitle(array $data) Use this method to set a custom title for an administrator in a supergroup promoted by the bot. Returns True on success.
62
 * @method static ServerResponse setChatPermissions(array $data)              Use this method to set default chat permissions for all members. The bot must be an administrator in the group or a supergroup for this to work and must have the can_restrict_members admin rights. Returns True on success.
63
 * @method static ServerResponse exportChatInviteLink(array $data)            Use this method to generate a new invite link for a chat. Any previously generated link is revoked. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Returns the new invite link as String on success.
64
 * @method static ServerResponse createChatInviteLink(array $data)            Use this method to create an additional invite link for a chat. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. The link can be revoked using the method revokeChatInviteLink. Returns the new invite link as ChatInviteLink object.
65
 * @method static ServerResponse editChatInviteLink(array $data)              Use this method to edit a non-primary invite link created by the bot. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Returns the edited invite link as a ChatInviteLink object.
66
 * @method static ServerResponse revokeChatInviteLink(array $data)            Use this method to revoke an invite link created by the bot. If the primary link is revoked, a new link is automatically generated. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Returns the revoked invite link as ChatInviteLink object.
67
 * @method static ServerResponse setChatPhoto(array $data)                    Use this method to set a new profile photo for the chat. Photos can't be changed for 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.
68
 * @method static ServerResponse deleteChatPhoto(array $data)                 Use this method to delete a chat photo. Photos can't be changed for 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.
69
 * @method static ServerResponse setChatTitle(array $data)                    Use this method to change the title of a chat. Titles can't be changed for 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.
70
 * @method static ServerResponse setChatDescription(array $data)              Use this method to change the description of a group, a supergroup or a channel. The bot must be an administrator in the chat for this to work and must have the appropriate admin rights. Returns True on success.
71
 * @method static ServerResponse pinChatMessage(array $data)                  Use this method to pin a message in a supergroup or a channel. The bot must be an 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 channel. Returns True on success.
72
 * @method static ServerResponse unpinChatMessage(array $data)                Use this method to unpin a message in a supergroup or a channel. The bot must be an 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 channel. Returns True on success.
73
 * @method static ServerResponse unpinAllChatMessages(array $data)            Use this method to clear the list of pinned messages in a chat. If the chat is not a private chat, the bot must be an administrator in the chat for this to work and must have the 'can_pin_messages' admin right in a supergroup or 'can_edit_messages' admin right in a channel. Returns True on success.
74
 * @method static ServerResponse leaveChat(array $data)                       Use this method for your bot to leave a group, supergroup or channel. Returns True on success.
75
 * @method static ServerResponse getChat(array $data)                         Use this method to get up to date information about the chat (current name of the user for one-on-one conversations, current username of a user, group or channel, etc.). Returns a Chat object on success.
76
 * @method static ServerResponse getChatAdministrators(array $data)           Use this method to get a list of administrators in a chat. On success, returns an Array of ChatMember objects that contains information about all chat administrators except other bots. If the chat is a group or a supergroup and no administrators were appointed, only the creator will be returned.
77
 * @method static ServerResponse getChatMemberCount(array $data)              Use this method to get the number of members in a chat. Returns Int on success.
78
 * @method static ServerResponse getChatMember(array $data)                   Use this method to get information about a member of a chat. Returns a ChatMember object on success.
79
 * @method static ServerResponse setChatStickerSet(array $data)               Use this method to set a new group sticker set for a supergroup. The bot must be an 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 requests to check if the bot can use this method. Returns True on success.
80
 * @method static ServerResponse deleteChatStickerSet(array $data)            Use this method to delete a group sticker set from a supergroup. The bot must be an 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 requests to check if the bot can use this method. Returns True on success.
81
 * @method static ServerResponse answerCallbackQuery(array $data)             Use this method to send answers to callback queries sent from inline keyboards. The 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.
82
 * @method static ServerResponse answerInlineQuery(array $data)               Use this method to send answers to an inline query. On success, True is returned.
83
 * @method static ServerResponse setMyCommands(array $data)                   Use this method to change the list of the bot's commands. Returns True on success.
84
 * @method static ServerResponse deleteMyCommands(array $data)                Use this method to delete the list of the bot's commands for the given scope and user language. After deletion, higher level commands will be shown to affected users. Returns True on success.
85
 * @method static ServerResponse getMyCommands()                              Use this method to get the current list of the bot's commands. Requires no parameters. Returns Array of BotCommand on success.
86
 * @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 bots). On success, if edited message is sent by the bot, the edited Message is returned, otherwise True is returned.
87
 * @method static ServerResponse editMessageCaption(array $data)              Use this method to edit captions of messages sent by the bot or via the bot (for inline bots). On success, if edited message is sent by the bot, the edited Message is returned, otherwise True is returned.
88
 * @method static ServerResponse editMessageMedia(array $data)                Use this method to edit audio, document, photo, or video messages. On success, if the edited message was sent by the bot, the edited Message is returned, otherwise True is returned.
89
 * @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 (for inline bots). On success, if edited message is sent by the bot, the edited Message is returned, otherwise True is returned.
90
 * @method static ServerResponse stopPoll(array $data)                        Use this method to stop a poll which was sent by the bot. On success, the stopped Poll with the final results is returned.
91
 * @method static ServerResponse deleteMessage(array $data)                   Use this method to delete a message, including service messages, with certain limitations. Returns True on success.
92
 * @method static ServerResponse getStickerSet(array $data)                   Use this method to get a sticker set. On success, a StickerSet object is returned.
93
 * @method static ServerResponse uploadStickerFile(array $data)               Use this method to upload a .png file with a sticker for later use in createNewStickerSet and addStickerToSet methods (can be used multiple times). Returns the uploaded File on success.
94
 * @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 the created sticker set. Returns True on success.
95
 * @method static ServerResponse addStickerToSet(array $data)                 Use this method to add a new sticker to a set created by the bot. Returns True on success.
96
 * @method static ServerResponse setStickerPositionInSet(array $data)         Use this method to move a sticker in a set created by the bot to a specific position. Returns True on success.
97
 * @method static ServerResponse deleteStickerFromSet(array $data)            Use this method to delete a sticker from a set created by the bot. Returns True on success.
98
 * @method static ServerResponse setStickerSetThumb(array $data)              Use this method to set the thumbnail of a sticker set. Animated thumbnails can be set for animated sticker sets only. Returns True on success.
99
 * @method static ServerResponse sendInvoice(array $data)                     Use this method to send invoices. On success, the sent Message is returned.
100
 * @method static ServerResponse answerShippingQuery(array $data)             If you sent an invoice requesting a shipping address and the parameter is_flexible was 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 returned.
101
 * @method static ServerResponse answerPreCheckoutQuery(array $data)          Once the user has confirmed their payment and shipping details, the Bot API sends the 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 is returned.
102
 * @method static ServerResponse setPassportDataErrors(array $data)           Informs a user that some of the Telegram Passport elements they provided contains errors. The user will not be able to re-submit their Passport to you until the errors are fixed (the contents of the field for which you returned the error must change). Returns True on success. Use this if the data submitted by the user doesn't satisfy the standards your service requires for any reason. For example, if a birthday date seems invalid, a submitted document is blurry, a scan shows evidence of tampering, etc. Supply some details in the error message to make sure the user knows how to correct the issues.
103
 * @method static ServerResponse sendGame(array $data)                        Use this method to send a game. On success, the sent Message is returned.
104
 * @method static ServerResponse setGameScore(array $data)                    Use this method to set the score of the specified user in a game. On success, if the message was sent by the bot, returns the edited Message, otherwise returns True. Returns an error, if the new score is not greater than the user's current score in the chat and force is False.
105
 * @method static ServerResponse getGameHighScores(array $data)               Use this method to get data for high score tables. Will return the score of the specified user and several of his neighbors in a game. On success, returns an Array of GameHighScore objects.
106
 */
107
class Request
108
{
109
    /**
110
     * Telegram object
111
     *
112
     * @var Telegram
113
     */
114
    private static $telegram;
115
116
    /**
117
     * URI of the Telegram API
118
     *
119
     * @var string
120
     */
121
    private static $api_base_uri = 'https://api.telegram.org';
122
123
    /**
124
     * URI of the Telegram API for downloading files (relative to $api_base_url or absolute)
125
     *
126
     * @var string
127
     */
128
    private static $api_base_download_uri = '/file/bot{API_KEY}';
129
130
    /**
131
     * Guzzle Client object
132
     *
133
     * @var ClientInterface
134
     */
135
    private static $client;
136
137
    /**
138
     * Request limiter
139
     *
140
     * @var bool
141
     */
142
    private static $limiter_enabled;
143
144
    /**
145
     * Request limiter's interval between checks
146
     *
147
     * @var float
148
     */
149
    private static $limiter_interval;
150
151
    /**
152
     * The current action that is being executed
153
     *
154
     * @var string
155
     */
156
    private static $current_action = '';
157
158
    /**
159
     * Available actions to send
160
     *
161
     * This is basically the list of all methods listed on the official API documentation.
162
     *
163
     * @link https://core.telegram.org/bots/api
164
     *
165
     * @var array
166
     */
167
    private static $actions = [
168
        'getUpdates',
169
        'setWebhook',
170
        'deleteWebhook',
171
        'getWebhookInfo',
172
        'getMe',
173
        'logOut',
174
        'close',
175
        'sendMessage',
176
        'forwardMessage',
177
        'copyMessage',
178
        'sendPhoto',
179
        'sendAudio',
180
        'sendDocument',
181
        'sendSticker',
182
        'sendVideo',
183
        'sendAnimation',
184
        'sendVoice',
185
        'sendVideoNote',
186
        'sendMediaGroup',
187
        'sendLocation',
188
        'editMessageLiveLocation',
189
        'stopMessageLiveLocation',
190
        'sendVenue',
191
        'sendContact',
192
        'sendPoll',
193
        'sendDice',
194
        'sendChatAction',
195
        'getUserProfilePhotos',
196
        'getFile',
197
        'banChatMember',
198
        'unbanChatMember',
199
        'restrictChatMember',
200
        'promoteChatMember',
201
        'setChatAdministratorCustomTitle',
202
        'setChatPermissions',
203
        'exportChatInviteLink',
204
        'createChatInviteLink',
205
        'editChatInviteLink',
206
        'revokeChatInviteLink',
207
        'setChatPhoto',
208
        'deleteChatPhoto',
209
        'setChatTitle',
210
        'setChatDescription',
211
        'pinChatMessage',
212
        'unpinChatMessage',
213
        'unpinAllChatMessages',
214
        'leaveChat',
215
        'getChat',
216
        'getChatAdministrators',
217
        'getChatMemberCount',
218
        'getChatMember',
219
        'setChatStickerSet',
220
        'deleteChatStickerSet',
221
        'answerCallbackQuery',
222
        'answerInlineQuery',
223
        'setMyCommands',
224
        'deleteMyCommands',
225
        'getMyCommands',
226
        'editMessageText',
227
        'editMessageCaption',
228
        'editMessageMedia',
229
        'editMessageReplyMarkup',
230
        'stopPoll',
231
        'deleteMessage',
232
        'getStickerSet',
233
        'uploadStickerFile',
234
        'createNewStickerSet',
235
        'addStickerToSet',
236
        'setStickerPositionInSet',
237
        'deleteStickerFromSet',
238
        'setStickerSetThumb',
239
        'sendInvoice',
240
        'answerShippingQuery',
241
        'answerPreCheckoutQuery',
242
        'setPassportDataErrors',
243
        'sendGame',
244
        'setGameScore',
245
        'getGameHighScores',
246
    ];
247
248
    /**
249
     * Some methods need a dummy param due to certain cURL issues.
250
     *
251
     * @see Request::addDummyParamIfNecessary()
252
     *
253
     * @var array
254
     */
255
    private static $actions_need_dummy_param = [
256
        'deleteWebhook',
257
        'getWebhookInfo',
258
        'getMe',
259
        'logOut',
260
        'close',
261
        'getMyCommands',
262
    ];
263
264
    /**
265
     * Available fields for InputFile helper
266
     *
267
     * This is basically the list of all fields that allow InputFile objects
268
     * for which input can be simplified by providing local path directly  as string.
269
     *
270
     * @var array
271
     */
272
    private static $input_file_fields = [
273
        'setWebhook'          => ['certificate'],
274
        'sendPhoto'           => ['photo'],
275
        'sendAudio'           => ['audio', 'thumb'],
276
        'sendDocument'        => ['document', 'thumb'],
277
        'sendVideo'           => ['video', 'thumb'],
278
        'sendAnimation'       => ['animation', 'thumb'],
279
        'sendVoice'           => ['voice', 'thumb'],
280
        'sendVideoNote'       => ['video_note', 'thumb'],
281
        'setChatPhoto'        => ['photo'],
282
        'sendSticker'         => ['sticker'],
283
        'uploadStickerFile'   => ['png_sticker'],
284
        'createNewStickerSet' => ['png_sticker', 'tgs_sticker'],
285
        'addStickerToSet'     => ['png_sticker', 'tgs_sticker'],
286
        'setStickerSetThumb'  => ['thumb'],
287
    ];
288
289
    /**
290
     * Initialize
291
     *
292
     * @param Telegram $telegram
293
     */
294 33
    public static function initialize(Telegram $telegram): void
295
    {
296 33
        self::$telegram = $telegram;
297 33
        self::setClient(self::$client ?: new Client(['base_uri' => self::$api_base_uri]));
298 33
    }
299
300
    /**
301
     * Set a custom Guzzle HTTP Client object
302
     *
303
     * @param ClientInterface $client
304
     */
305 33
    public static function setClient(ClientInterface $client): void
306
    {
307 33
        self::$client = $client;
308 33
    }
309
310
    /**
311
     * Set a custom Bot API URL
312
     *
313
     * @param string $api_base_uri
314
     * @param string $api_base_download_uri
315
     */
316
    public static function setCustomBotApiUri(string $api_base_uri, string $api_base_download_uri = ''): void
317
    {
318
        self::$api_base_uri = $api_base_uri;
319
        if ($api_base_download_uri !== '') {
320
            self::$api_base_download_uri = $api_base_download_uri;
321
        }
322
    }
323
324
    /**
325
     * Get input from custom input or stdin and return it
326
     *
327
     * @return string
328
     */
329
    public static function getInput(): string
330
    {
331
        // First check if a custom input has been set, else get the PHP input.
332
        return self::$telegram->getCustomInput()
333
            ?: file_get_contents('php://input');
334
    }
335
336
    /**
337
     * Generate general fake server response
338
     *
339
     * @param array $data Data to add to fake response
340
     *
341
     * @return array Fake response data
342
     */
343 1
    public static function generateGeneralFakeServerResponse(array $data = []): array
344
    {
345
        //PARAM BINDED IN PHPUNIT TEST FOR TestServerResponse.php
346
        //Maybe this is not the best possible implementation
347
348
        //No value set in $data ie testing setWebhook
349
        //Provided $data['chat_id'] ie testing sendMessage
350
351 1
        $fake_response = ['ok' => true]; // :)
352
353 1
        if ($data === []) {
354 1
            $fake_response['result'] = true;
355
        }
356
357
        //some data to initialize the class method SendMessage
358 1
        if (isset($data['chat_id'])) {
359 1
            $data['message_id'] = '1234';
360 1
            $data['date']       = '1441378360';
361 1
            $data['from']       = [
362
                'id'         => 123456789,
363
                'first_name' => 'botname',
364
                'username'   => 'namebot',
365
            ];
366 1
            $data['chat']       = ['id' => $data['chat_id']];
367
368 1
            $fake_response['result'] = $data;
369
        }
370
371 1
        return $fake_response;
372
    }
373
374
    /**
375
     * Properly set up the request params
376
     *
377
     * If any item of the array is a resource, reformat it to a multipart request.
378
     * Else, just return the passed data as form params.
379
     *
380
     * @param array $data
381
     *
382
     * @return array
383
     * @throws TelegramException
384
     */
385
    private static function setUpRequestParams(array $data): array
386
    {
387
        $has_resource = false;
388
        $multipart    = [];
389
390
        foreach ($data as $key => &$item) {
391
            if ($key === 'media') {
392
                // Magical media input helper.
393
                $item = self::mediaInputHelper($item, $has_resource, $multipart);
394
            } elseif (array_key_exists(self::$current_action, self::$input_file_fields) && in_array($key, self::$input_file_fields[self::$current_action], true)) {
395
                // Allow absolute paths to local files.
396
                if (is_string($item) && file_exists($item)) {
397
                    $item = new Stream(self::encodeFile($item));
398
                }
399
            } elseif (is_array($item) || is_object($item)) {
400
                // Convert any nested arrays or objects into JSON strings.
401
                $item = json_encode($item);
402
            }
403
404
            // Reformat data array in multipart way if it contains a resource
405
            $has_resource = $has_resource || is_resource($item) || $item instanceof Stream;
406
            $multipart[]  = ['name' => $key, 'contents' => $item];
407
        }
408
        unset($item);
409
410
        if ($has_resource) {
411
            return ['multipart' => $multipart];
412
        }
413
414
        return ['form_params' => $data];
415
    }
416
417
    /**
418
     * Magical input media helper to simplify passing media.
419
     *
420
     * This allows the following:
421
     * Request::editMessageMedia([
422
     *     ...
423
     *     'media' => new InputMediaPhoto([
424
     *         'caption' => 'Caption!',
425
     *         'media'   => Request::encodeFile($local_photo),
426
     *     ]),
427
     * ]);
428
     * and
429
     * Request::sendMediaGroup([
430
     *     'media'   => [
431
     *         new InputMediaPhoto(['media' => Request::encodeFile($local_photo_1)]),
432
     *         new InputMediaPhoto(['media' => Request::encodeFile($local_photo_2)]),
433
     *         new InputMediaVideo(['media' => Request::encodeFile($local_video_1)]),
434
     *     ],
435
     * ]);
436
     * and even
437
     * Request::sendMediaGroup([
438
     *     'media'   => [
439
     *         new InputMediaPhoto(['media' => $local_photo_1]),
440
     *         new InputMediaPhoto(['media' => $local_photo_2]),
441
     *         new InputMediaVideo(['media' => $local_video_1]),
442
     *     ],
443
     * ]);
444
     *
445
     * @param mixed $item
446
     * @param bool  $has_resource
447
     * @param array $multipart
448
     *
449
     * @return mixed
450
     * @throws TelegramException
451
     */
452
    private static function mediaInputHelper($item, bool &$has_resource, array &$multipart)
453
    {
454
        $was_array = is_array($item);
455
        $was_array || $item = [$item];
456
457
        /** @var InputMedia|null $media_item */
458
        foreach ($item as $media_item) {
459
            if (!($media_item instanceof InputMedia)) {
460
                continue;
461
            }
462
463
            // Make a list of all possible media that can be handled by the helper.
464
            $possible_medias = array_filter([
465
                'media' => $media_item->getMedia(),
0 ignored issues
show
Bug introduced by
The method getMedia() does not exist on Longman\TelegramBot\Entities\InputMedia\InputMedia. Since it exists in all sub-types, consider adding an abstract or default implementation to Longman\TelegramBot\Entities\InputMedia\InputMedia. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

465
                'media' => $media_item->/** @scrutinizer ignore-call */ getMedia(),
Loading history...
466
                'thumb' => $media_item->getThumb(),
0 ignored issues
show
Bug introduced by
The method getThumb() does not exist on Longman\TelegramBot\Entities\InputMedia\InputMedia. Since it exists in all sub-types, consider adding an abstract or default implementation to Longman\TelegramBot\Entities\InputMedia\InputMedia. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

466
                'thumb' => $media_item->/** @scrutinizer ignore-call */ getThumb(),
Loading history...
467
            ]);
468
469
            foreach ($possible_medias as $type => $media) {
470
                // Allow absolute paths to local files.
471
                if (is_string($media) && strpos($media, 'attach://') !== 0 && file_exists($media)) {
472
                    $media = new Stream(self::encodeFile($media));
473
                }
474
475
                if (is_resource($media) || $media instanceof Stream) {
476
                    $has_resource = true;
477
                    $unique_key   = uniqid($type . '_', false);
478
                    $multipart[]  = ['name' => $unique_key, 'contents' => $media];
479
480
                    // We're literally overwriting the passed media type data!
481
                    $media_item->$type           = 'attach://' . $unique_key;
482
                    $media_item->raw_data[$type] = 'attach://' . $unique_key;
483
                }
484
            }
485
        }
486
487
        $was_array || $item = reset($item);
488
489
        return json_encode($item);
490
    }
491
492
    /**
493
     * Get the current action that's being executed
494
     *
495
     * @return string
496
     */
497 7
    public static function getCurrentAction(): string
498
    {
499 7
        return self::$current_action;
500
    }
501
502
    /**
503
     * Execute HTTP Request
504
     *
505
     * @param string $action Action to execute
506
     * @param array  $data   Data to attach to the execution
507
     *
508
     * @return string Result of the HTTP Request
509
     * @throws TelegramException
510
     */
511
    public static function execute(string $action, array $data = []): string
512
    {
513
        $request_params          = self::setUpRequestParams($data);
514
        $request_params['debug'] = TelegramLog::getDebugLogTempStream();
515
516
        try {
517
            $response = self::$client->post(
518
                '/bot' . self::$telegram->getApiKey() . '/' . $action,
519
                $request_params
520
            );
521
            $result   = (string) $response->getBody();
522
        } catch (RequestException $e) {
523
            $response = null;
524
            $result   = $e->getResponse() ? (string) $e->getResponse()->getBody() : '';
525
        }
526
527
        //Logging verbose debug output
528
        if (TelegramLog::$always_log_request_and_response || $response === null) {
529
            TelegramLog::debug('Request data:' . PHP_EOL . print_r($data, true));
0 ignored issues
show
Bug introduced by
Are you sure print_r($data, true) of type string|true can be used in concatenation? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

529
            TelegramLog::debug('Request data:' . PHP_EOL . /** @scrutinizer ignore-type */ print_r($data, true));
Loading history...
530
            TelegramLog::debug('Response data:' . PHP_EOL . $result);
531
            TelegramLog::endDebugLogTempStream('Verbose HTTP Request output:' . PHP_EOL . '%s' . PHP_EOL);
532
        }
533
534
        return $result;
535
    }
536
537
    /**
538
     * Download file
539
     *
540
     * @param File $file
541
     *
542
     * @return bool
543
     * @throws TelegramException
544
     */
545
    public static function downloadFile(File $file): bool
546
    {
547
        if (empty($download_path = self::$telegram->getDownloadPath())) {
548
            throw new TelegramException('Download path not set!');
549
        }
550
551
        $tg_file_path = $file->getFilePath();
552
        $file_path    = $download_path . '/' . $tg_file_path;
553
554
        $file_dir = dirname($file_path);
555
        //For safety reasons, first try to create the directory, then check that it exists.
556
        //This is in case some other process has created the folder in the meantime.
557
        if (!@mkdir($file_dir, 0755, true) && !is_dir($file_dir)) {
558
            throw new TelegramException('Directory ' . $file_dir . ' can\'t be created');
559
        }
560
561
        $debug_handle = TelegramLog::getDebugLogTempStream();
562
563
        try {
564
            $base_download_uri = str_replace('{API_KEY}', self::$telegram->getApiKey(), self::$api_base_download_uri);
565
            self::$client->get(
566
                "{$base_download_uri}/{$tg_file_path}",
567
                ['debug' => $debug_handle, 'sink' => $file_path]
568
            );
569
570
            return filesize($file_path) > 0;
571
        } catch (Throwable $e) {
572
            return false;
573
        } finally {
574
            //Logging verbose debug output
575
            TelegramLog::endDebugLogTempStream('Verbose HTTP File Download Request output:' . PHP_EOL . '%s' . PHP_EOL);
576
        }
577
    }
578
579
    /**
580
     * Encode file
581
     *
582
     * @param string $file
583
     *
584
     * @return resource
585
     * @throws TelegramException
586
     */
587
    public static function encodeFile(string $file)
588
    {
589
        $fp = fopen($file, 'rb');
590
        if ($fp === false) {
591
            throw new TelegramException('Cannot open "' . $file . '" for reading');
592
        }
593
594
        return $fp;
595
    }
596
597
    /**
598
     * Send command
599
     *
600
     * @todo Fake response doesn't need json encoding?
601
     * @todo Write debug entry on failure
602
     *
603
     * @param string $action
604
     * @param array  $data
605
     *
606
     * @return ServerResponse
607
     * @throws TelegramException
608
     */
609
    public static function send(string $action, array $data = []): ServerResponse
610
    {
611
        self::ensureValidAction($action);
612
        self::addDummyParamIfNecessary($action, $data);
613
614
        $bot_username = self::$telegram->getBotUsername();
615
616
        if (defined('PHPUNIT_TESTSUITE')) {
617
            $fake_response = self::generateGeneralFakeServerResponse($data);
618
619
            return new ServerResponse($fake_response, $bot_username);
620
        }
621
622
        self::ensureNonEmptyData($data);
623
624
        self::limitTelegramRequests($action, $data);
625
626
        // Remember which action is currently being executed.
627
        self::$current_action = $action;
628
629
        $raw_response = self::execute($action, $data);
630
        $response     = json_decode($raw_response, true);
631
632
        if (null === $response) {
633
            TelegramLog::debug($raw_response);
634
            throw new TelegramException('Telegram returned an invalid response!');
635
        }
636
637
        $response = new ServerResponse($response, $bot_username);
638
639
        if (!$response->isOk() && $response->getErrorCode() === 401 && $response->getDescription() === 'Unauthorized') {
640
            throw new InvalidBotTokenException();
641
        }
642
643
        // Special case for sent polls, which need to be saved specially.
644
        // @todo Take into account if DB gets extracted into separate module.
645
        if ($response->isOk() && ($message = $response->getResult()) && ($message instanceof Message) && $poll = $message->getPoll()) {
646
            DB::insertPollRequest($poll);
647
        }
648
649
        // Reset current action after completion.
650
        self::$current_action = '';
651
652
        return $response;
653
    }
654
655
    /**
656
     * Add a dummy parameter if the passed action requires it.
657
     *
658
     * If a method doesn't require parameters, we need to add a dummy one anyway,
659
     * because of some cURL version failed POST request without parameters.
660
     *
661
     * @link https://github.com/php-telegram-bot/core/pull/228
662
     *
663
     * @todo Would be nice to find a better solution for this!
664
     *
665
     * @param string $action
666
     * @param array  $data
667
     */
668
    protected static function addDummyParamIfNecessary(string $action, array &$data): void
669
    {
670
        if (empty($data) && in_array($action, self::$actions_need_dummy_param, true)) {
671
            // Can be anything, using a single letter to minimise request size.
672
            $data = ['d'];
673
        }
674
    }
675
676
    /**
677
     * Make sure the data isn't empty, else throw an exception
678
     *
679
     * @param array $data
680
     *
681
     * @throws TelegramException
682
     */
683
    private static function ensureNonEmptyData(array $data): void
684
    {
685
        if (count($data) === 0) {
686
            throw new TelegramException('Data is empty!');
687
        }
688
    }
689
690
    /**
691
     * Make sure the action is valid, else throw an exception
692
     *
693
     * @param string $action
694
     *
695
     * @throws TelegramException
696
     */
697
    private static function ensureValidAction(string $action): void
698
    {
699
        if (!in_array($action, self::$actions, true)) {
700
            throw new TelegramException('The action "' . $action . '" doesn\'t exist!');
701
        }
702
    }
703
704
    /**
705
     * Use this method to send text messages. On success, the last sent Message is returned
706
     *
707
     * All message responses are saved in `$extras['responses']`.
708
     * Custom encoding can be defined in `$extras['encoding']` (default: `mb_internal_encoding()`)
709
     * Custom splitting can be defined in `$extras['split']` (default: 4096)
710
     *     `$extras['split'] = null;` // force to not split message at all!
711
     *     `$extras['split'] = 200;`  // split message into 200 character chunks
712
     *
713
     * @link https://core.telegram.org/bots/api#sendmessage
714
     *
715
     * @todo Splitting formatted text may break the message.
716
     *
717
     * @param array      $data
718
     * @param array|null $extras
719
     *
720
     * @return ServerResponse
721
     * @throws TelegramException
722
     */
723
    public static function sendMessage(array $data, ?array &$extras = []): ServerResponse
724
    {
725
        $extras = array_merge([
726
            'split'    => 4096,
727
            'encoding' => mb_internal_encoding(),
728
        ], (array) $extras);
729
730
        $text       = $data['text'];
731
        $encoding   = $extras['encoding'];
732
        $max_length = $extras['split'] ?: mb_strlen($text, $encoding);
733
734
        $responses = [];
735
736
        do {
737
            // Chop off and send the first message.
738
            $data['text'] = mb_substr($text, 0, $max_length, $encoding);
739
            $responses[]  = self::send('sendMessage', $data);
740
741
            // Prepare the next message.
742
            $text = mb_substr($text, $max_length, null, $encoding);
743
        } while ($text !== '');
744
745
        // Add all response objects to referenced variable.
746
        $extras['responses'] = $responses;
747
748
        return end($responses);
749
    }
750
751
    /**
752
     * Any statically called method should be relayed to the `send` method.
753
     *
754
     * @param string $action
755
     * @param array  $data
756
     *
757
     * @return ServerResponse
758
     * @throws TelegramException
759
     */
760
    public static function __callStatic(string $action, array $data): ServerResponse
761
    {
762
        // Only argument should be the data array, ignore any others.
763
        return static::send($action, reset($data) ?: []);
764
    }
765
766
    /**
767
     * Return an empty Server Response
768
     *
769
     * No request is sent to Telegram.
770
     * This function is used in commands that don't need to fire a message after execution
771
     *
772
     * @return ServerResponse
773
     */
774
    public static function emptyResponse(): ServerResponse
775
    {
776
        return new ServerResponse(['ok' => true, 'result' => true]);
777
    }
778
779
    /**
780
     * Send message to all active chats
781
     *
782
     * @param string $callback_function
783
     * @param array  $data
784
     * @param array  $select_chats_params
785
     *
786
     * @return array
787
     * @throws TelegramException
788
     */
789
    public static function sendToActiveChats(
790
        string $callback_function,
791
        array $data,
792
        array $select_chats_params
793
    ): array {
794
        self::ensureValidAction($callback_function);
795
796
        $chats = DB::selectChats($select_chats_params);
797
798
        $results = [];
799
        if (is_array($chats)) {
800
            foreach ($chats as $row) {
801
                $data['chat_id'] = $row['chat_id'];
802
                $results[]       = self::send($callback_function, $data);
803
            }
804
        }
805
806
        return $results;
807
    }
808
809
    /**
810
     * Enable request limiter
811
     *
812
     * @param bool  $enable
813
     * @param array $options
814
     *
815
     * @throws TelegramException
816
     */
817
    public static function setLimiter(bool $enable = true, array $options = []): void
818
    {
819
        if (DB::isDbConnected()) {
820
            $options_default = [
821
                'interval' => 1,
822
            ];
823
824
            $options = array_merge($options_default, $options);
825
826
            if (!is_numeric($options['interval']) || $options['interval'] <= 0) {
827
                throw new TelegramException('Interval must be a number and must be greater than zero!');
828
            }
829
830
            self::$limiter_interval = $options['interval'];
831
            self::$limiter_enabled  = $enable;
832
        }
833
    }
834
835
    /**
836
     * This functions delays API requests to prevent reaching Telegram API limits
837
     *  Can be disabled while in execution by 'Request::setLimiter(false)'
838
     *
839
     * @link https://core.telegram.org/bots/faq#my-bot-is-hitting-limits-how-do-i-avoid-this
840
     *
841
     * @param string $action
842
     * @param array  $data
843
     *
844
     * @throws TelegramException
845
     */
846
    private static function limitTelegramRequests(string $action, array $data = []): void
847
    {
848
        if (self::$limiter_enabled) {
849
            $limited_methods = [
850
                'sendMessage',
851
                'forwardMessage',
852
                'copyMessage',
853
                'sendPhoto',
854
                'sendAudio',
855
                'sendDocument',
856
                'sendSticker',
857
                'sendVideo',
858
                'sendAnimation',
859
                'sendVoice',
860
                'sendVideoNote',
861
                'sendMediaGroup',
862
                'sendLocation',
863
                'editMessageLiveLocation',
864
                'stopMessageLiveLocation',
865
                'sendVenue',
866
                'sendContact',
867
                'sendPoll',
868
                'sendDice',
869
                'sendInvoice',
870
                'sendGame',
871
                'setGameScore',
872
                'setMyCommands',
873
                'deleteMyCommands',
874
                'editMessageText',
875
                'editMessageCaption',
876
                'editMessageMedia',
877
                'editMessageReplyMarkup',
878
                'stopPoll',
879
                'setChatTitle',
880
                'setChatDescription',
881
                'setChatStickerSet',
882
                'deleteChatStickerSet',
883
                'setPassportDataErrors',
884
            ];
885
886
            $chat_id           = $data['chat_id'] ?? null;
887
            $inline_message_id = $data['inline_message_id'] ?? null;
888
889
            if (($chat_id || $inline_message_id) && in_array($action, $limited_methods, true)) {
890
                $timeout = 60;
891
892
                while (true) {
893
                    if ($timeout <= 0) {
894
                        throw new TelegramException('Timed out while waiting for a request spot!');
895
                    }
896
897
                    if (!($requests = DB::getTelegramRequestCount($chat_id, $inline_message_id))) {
898
                        break;
899
                    }
900
901
                    // Make sure we're handling integers here.
902
                    $requests = array_map('intval', $requests);
0 ignored issues
show
Bug introduced by
It seems like $requests can also be of type true; however, parameter $array of array_map() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

902
                    $requests = array_map('intval', /** @scrutinizer ignore-type */ $requests);
Loading history...
903
904
                    $chat_per_second   = ($requests['LIMIT_PER_SEC'] === 0);    // No more than one message per second inside a particular chat
905
                    $global_per_second = ($requests['LIMIT_PER_SEC_ALL'] < 30); // No more than 30 messages per second to different chats
906
                    $groups_per_minute = (((is_numeric($chat_id) && $chat_id > 0) || $inline_message_id !== null) || ((!is_numeric($chat_id) || $chat_id < 0) && $requests['LIMIT_PER_MINUTE'] < 20));    // No more than 20 messages per minute in groups and channels
907
908
                    if ($chat_per_second && $global_per_second && $groups_per_minute) {
909
                        break;
910
                    }
911
912
                    $timeout--;
913
                    usleep((int) (self::$limiter_interval * 1000000));
914
                }
915
916
                DB::insertTelegramRequest($action, $data);
917
            }
918
        }
919
    }
920
921
    /**
922
     * Use this method to kick a user from a group, a supergroup or a channel. In the case of 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 an administrator in the chat for this to work and must have the appropriate admin rights. Returns True on success.
923
     *
924
     * @deprecated
925
     * @see Request::banChatMember()
926
     *
927
     * @param  array  $data
928
     * @return ServerResponse
929
     */
930
    public static function kickChatMember(array $data = []): ServerResponse
931
    {
932
        return static::banChatMember($data);
933
    }
934
935
    /**
936
     * Use this method to get the number of members in a chat. Returns Int on success.
937
     *
938
     * @deprecated
939
     * @see Request::getChatMemberCount()
940
     *
941
     * @param  array  $data
942
     * @return ServerResponse
943
     */
944
    public static function getChatMembersCount(array $data = []): ServerResponse
945
    {
946
        return static::getChatMemberCount($data);
947
    }
948
}
949