Passed
Push — master ( f3fe5e...097177 )
by Armando
05:18 queued 02:03
created

Request   F

Complexity

Total Complexity 93

Size/Duplication

Total Lines 843
Duplicated Lines 0 %

Test Coverage

Coverage 9.73%

Importance

Changes 41
Bugs 2 Features 1
Metric Value
eloc 334
c 41
b 2
f 1
dl 0
loc 843
ccs 18
cts 185
cp 0.0973
rs 2
wmc 93

22 Methods

Rating   Name   Duplication   Size   Complexity  
A setLimiter() 0 15 4
A getInput() 0 5 2
A setCustomBotApiUri() 0 5 2
A setClient() 0 3 1
A sendToActiveChats() 0 18 3
A downloadFile() 0 31 5
A ensureNonEmptyData() 0 4 2
A execute() 0 24 5
A ensureValidAction() 0 4 2
A initialize() 0 4 2
A __callStatic() 0 4 2
A sendMessage() 0 26 3
A generateGeneralFakeServerResponse() 0 29 3
C setUpRequestParams() 0 30 12
A getCurrentAction() 0 3 1
B send() 0 44 10
A encodeFile() 0 8 2
A kickChatMember() 0 3 1
A emptyResponse() 0 3 1
C limitTelegramRequests() 0 71 16
B mediaInputHelper() 0 38 11
A addDummyParamIfNecessary() 0 5 3

How to fix   Complexity   

Complex Class

Complex classes like Request often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Request, and based on these observations, apply Extract Interface, too.

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 banChatSenderChat(array $data)               Use this method to ban a channel chat in a supergroup or a channel. Until the chat is unbanned, the owner of the banned chat won't be able to send messages on behalf of any of their channels. The bot must be an administrator in the supergroup or channel for this to work and must have the appropriate administrator rights. Returns True on success.
63
 * @method static ServerResponse unbanChatSenderChat(array $data)             Use this method to unban a previously banned channel chat in a supergroup or channel. The bot must be an administrator for this to work and must have the appropriate administrator rights. Returns True on success.
64
 * @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.
65
 * @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.
66
 * @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.
67
 * @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.
68
 * @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.
69
 * @method static ServerResponse approveChatJoinRequest(array $data)          Use this method to approve a chat join request. The bot must be an administrator in the chat for this to work and must have the can_invite_users administrator right. Returns True on success.
70
 * @method static ServerResponse declineChatJoinRequest(array $data)          Use this method to decline a chat join request. The bot must be an administrator in the chat for this to work and must have the can_invite_users administrator right. Returns True on success.
71
 * @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.
72
 * @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.
73
 * @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.
74
 * @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.
75
 * @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.
76
 * @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.
77
 * @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.
78
 * @method static ServerResponse leaveChat(array $data)                       Use this method for your bot to leave a group, supergroup or channel. Returns True on success.
79
 * @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.
80
 * @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.
81
 * @method static ServerResponse getChatMemberCount(array $data)              Use this method to get the number of members in a chat. Returns Int on success.
82
 * @method static ServerResponse getChatMember(array $data)                   Use this method to get information about a member of a chat. Returns a ChatMember object on success.
83
 * @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.
84
 * @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.
85
 * @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.
86
 * @method static ServerResponse answerInlineQuery(array $data)               Use this method to send answers to an inline query. On success, True is returned.
87
 * @method static ServerResponse setMyCommands(array $data)                   Use this method to change the list of the bot's commands. Returns True on success.
88
 * @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.
89
 * @method static ServerResponse getMyCommands(array $data)                   Use this method to get the current list of the bot's commands. Requires no parameters. Returns Array of BotCommand on success.
90
 * @method static ServerResponse setChatMenuButton(array $data)               Use this method to change the bot's menu button in a private chat, or the default menu button. Returns True on success.
91
 * @method static ServerResponse getChatMenuButton(array $data)               Use this method to get the current value of the bot's menu button in a private chat, or the default menu button. Returns MenuButton on success.
92
 * @method static ServerResponse setMyDefaultAdministratorRights(array $data) Use this method to change the default administrator rights requested by the bot when it's added as an administrator to groups or channels. These rights will be suggested to users, but they are are free to modify the list before adding the bot. Returns True on success.
93
 * @method static ServerResponse getMyDefaultAdministratorRights(array $data) Use this method to get the current default administrator rights of the bot. Returns ChatAdministratorRights on success.
94
 * @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.
95
 * @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.
96
 * @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.
97
 * @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.
98
 * @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.
99
 * @method static ServerResponse deleteMessage(array $data)                   Use this method to delete a message, including service messages, with certain limitations. Returns True on success.
100
 * @method static ServerResponse getStickerSet(array $data)                   Use this method to get a sticker set. On success, a StickerSet object is returned.
101
 * @method static ServerResponse getCustomEmojiStickers(array $data)          Use this method to get information about custom emoji stickers by their identifiers. Returns an Array of Sticker objects.
102
 * @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.
103
 * @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.
104
 * @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.
105
 * @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.
106
 * @method static ServerResponse deleteStickerFromSet(array $data)            Use this method to delete a sticker from a set created by the bot. Returns True on success.
107
 * @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.
108
 * @method static ServerResponse answerWebAppQuery(array $data)               Use this method to set the result of an interaction with a Web App and send a corresponding message on behalf of the user to the chat from which the query originated. On success, a SentWebAppMessage object is returned.
109
 * @method static ServerResponse sendInvoice(array $data)                     Use this method to send invoices. On success, the sent Message is returned.
110
 * @method static ServerResponse createInvoiceLink(array $data)               Use this method to create a link for an invoice. Returns the created invoice link as String on success.
111
 * @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.
112
 * @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.
113
 * @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.
114
 * @method static ServerResponse sendGame(array $data)                        Use this method to send a game. On success, the sent Message is returned.
115
 * @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.
116
 * @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.
117
 */
118
class Request
119
{
120
    /**
121
     * Telegram object
122
     *
123
     * @var Telegram
124
     */
125
    private static $telegram;
126
127
    /**
128
     * URI of the Telegram API
129
     *
130
     * @var string
131
     */
132
    private static $api_base_uri = 'https://api.telegram.org';
133
134
    /**
135
     * URI of the Telegram API for downloading files (relative to $api_base_url or absolute)
136
     *
137
     * @var string
138
     */
139
    private static $api_base_download_uri = '/file/bot{API_KEY}';
140
141
    /**
142
     * Guzzle Client object
143
     *
144
     * @var ClientInterface
145
     */
146
    private static $client;
147
148
    /**
149
     * Request limiter
150
     *
151
     * @var bool
152
     */
153
    private static $limiter_enabled;
154
155
    /**
156
     * Request limiter's interval between checks
157
     *
158
     * @var float
159
     */
160
    private static $limiter_interval;
161
162
    /**
163
     * The current action that is being executed
164
     *
165
     * @var string
166
     */
167
    private static $current_action = '';
168
169
    /**
170
     * Available actions to send
171
     *
172
     * This is basically the list of all methods listed on the official API documentation.
173
     *
174
     * @link https://core.telegram.org/bots/api
175
     *
176
     * @var array
177
     */
178
    private static $actions = [
179
        'getUpdates',
180
        'setWebhook',
181
        'deleteWebhook',
182
        'getWebhookInfo',
183
        'getMe',
184
        'logOut',
185
        'close',
186
        'sendMessage',
187
        'forwardMessage',
188
        'copyMessage',
189
        'sendPhoto',
190
        'sendAudio',
191
        'sendDocument',
192
        'sendSticker',
193
        'sendVideo',
194
        'sendAnimation',
195
        'sendVoice',
196
        'sendVideoNote',
197
        'sendMediaGroup',
198
        'sendLocation',
199
        'editMessageLiveLocation',
200
        'stopMessageLiveLocation',
201
        'sendVenue',
202
        'sendContact',
203
        'sendPoll',
204
        'sendDice',
205
        'sendChatAction',
206
        'getUserProfilePhotos',
207
        'getFile',
208
        'banChatMember',
209
        'unbanChatMember',
210
        'restrictChatMember',
211
        'promoteChatMember',
212
        'setChatAdministratorCustomTitle',
213
        'banChatSenderChat',
214
        'unbanChatSenderChat',
215
        'setChatPermissions',
216
        'exportChatInviteLink',
217
        'createChatInviteLink',
218
        'editChatInviteLink',
219
        'revokeChatInviteLink',
220
        'approveChatJoinRequest',
221
        'declineChatJoinRequest',
222
        'setChatPhoto',
223
        'deleteChatPhoto',
224
        'setChatTitle',
225
        'setChatDescription',
226
        'pinChatMessage',
227
        'unpinChatMessage',
228
        'unpinAllChatMessages',
229
        'leaveChat',
230
        'getChat',
231
        'getChatAdministrators',
232
        'getChatMemberCount',
233
        'getChatMember',
234
        'setChatStickerSet',
235
        'deleteChatStickerSet',
236
        'answerCallbackQuery',
237
        'answerInlineQuery',
238
        'setMyCommands',
239
        'deleteMyCommands',
240
        'getMyCommands',
241
        'setChatMenuButton',
242
        'getChatMenuButton',
243
        'setMyDefaultAdministratorRights',
244
        'getMyDefaultAdministratorRights',
245
        'editMessageText',
246
        'editMessageCaption',
247
        'editMessageMedia',
248
        'editMessageReplyMarkup',
249
        'stopPoll',
250
        'deleteMessage',
251
        'getStickerSet',
252
        'getCustomEmojiStickers',
253
        'uploadStickerFile',
254
        'createNewStickerSet',
255
        'addStickerToSet',
256
        'setStickerPositionInSet',
257
        'deleteStickerFromSet',
258
        'setStickerSetThumb',
259
        'answerWebAppQuery',
260
        'sendInvoice',
261
        'createInvoiceLink',
262
        'answerShippingQuery',
263
        'answerPreCheckoutQuery',
264
        'setPassportDataErrors',
265
        'sendGame',
266
        'setGameScore',
267
        'getGameHighScores',
268
    ];
269
270
    /**
271
     * Some methods need a dummy param due to certain cURL issues.
272
     *
273
     * @see Request::addDummyParamIfNecessary()
274
     *
275
     * @var array
276
     */
277
    private static $actions_need_dummy_param = [
278
        'deleteWebhook',
279
        'getWebhookInfo',
280
        'getMe',
281
        'logOut',
282
        'close',
283
        'deleteMyCommands',
284
        'getMyCommands',
285
        'setChatMenuButton',
286
        'getChatMenuButton',
287
        'setMyDefaultAdministratorRights',
288
        'getMyDefaultAdministratorRights',
289
    ];
290
291
    /**
292
     * Available fields for InputFile helper
293
     *
294
     * This is basically the list of all fields that allow InputFile objects
295
     * for which input can be simplified by providing local path directly  as string.
296
     *
297
     * @var array
298
     */
299
    private static $input_file_fields = [
300
        'setWebhook'          => ['certificate'],
301
        'sendPhoto'           => ['photo'],
302
        'sendAudio'           => ['audio', 'thumb'],
303
        'sendDocument'        => ['document', 'thumb'],
304
        'sendVideo'           => ['video', 'thumb'],
305
        'sendAnimation'       => ['animation', 'thumb'],
306
        'sendVoice'           => ['voice', 'thumb'],
307
        'sendVideoNote'       => ['video_note', 'thumb'],
308
        'setChatPhoto'        => ['photo'],
309
        'sendSticker'         => ['sticker'],
310
        'uploadStickerFile'   => ['png_sticker'],
311
        'createNewStickerSet' => ['png_sticker', 'tgs_sticker', 'webm_sticker'],
312
        'addStickerToSet'     => ['png_sticker', 'tgs_sticker', 'webm_sticker'],
313
        'setStickerSetThumb'  => ['thumb'],
314
    ];
315
316
    /**
317
     * Initialize
318
     *
319
     * @param Telegram $telegram
320
     */
321 33
    public static function initialize(Telegram $telegram): void
322
    {
323 33
        self::$telegram = $telegram;
324 33
        self::setClient(self::$client ?: new Client(['base_uri' => self::$api_base_uri]));
325
    }
326
327
    /**
328
     * Set a custom Guzzle HTTP Client object
329
     *
330
     * @param ClientInterface $client
331
     */
332 33
    public static function setClient(ClientInterface $client): void
333
    {
334 33
        self::$client = $client;
335
    }
336
337
    /**
338
     * Set a custom Bot API URL
339
     *
340
     * @param string $api_base_uri
341
     * @param string $api_base_download_uri
342
     */
343
    public static function setCustomBotApiUri(string $api_base_uri, string $api_base_download_uri = ''): void
344
    {
345
        self::$api_base_uri = $api_base_uri;
346
        if ($api_base_download_uri !== '') {
347
            self::$api_base_download_uri = $api_base_download_uri;
348
        }
349
    }
350
351
    /**
352
     * Get input from custom input or stdin and return it
353
     *
354
     * @return string
355
     */
356
    public static function getInput(): string
357
    {
358
        // First check if a custom input has been set, else get the PHP input.
359
        return self::$telegram->getCustomInput()
360
            ?: file_get_contents('php://input');
361
    }
362
363
    /**
364
     * Generate general fake server response
365
     *
366
     * @param array $data Data to add to fake response
367
     *
368
     * @return array Fake response data
369
     */
370 1
    public static function generateGeneralFakeServerResponse(array $data = []): array
371
    {
372
        //PARAM BINDED IN PHPUNIT TEST FOR TestServerResponse.php
373
        //Maybe this is not the best possible implementation
374
375
        //No value set in $data ie testing setWebhook
376
        //Provided $data['chat_id'] ie testing sendMessage
377
378 1
        $fake_response = ['ok' => true]; // :)
379
380 1
        if ($data === []) {
381 1
            $fake_response['result'] = true;
382
        }
383
384
        //some data to initialize the class method SendMessage
385 1
        if (isset($data['chat_id'])) {
386 1
            $data['message_id'] = '1234';
387 1
            $data['date']       = '1441378360';
388 1
            $data['from']       = [
389
                'id'         => 123456789,
390
                'first_name' => 'botname',
391
                'username'   => 'namebot',
392
            ];
393 1
            $data['chat']       = ['id' => $data['chat_id']];
394
395 1
            $fake_response['result'] = $data;
396
        }
397
398 1
        return $fake_response;
399
    }
400
401
    /**
402
     * Properly set up the request params
403
     *
404
     * If any item of the array is a resource, reformat it to a multipart request.
405
     * Else, just return the passed data as form params.
406
     *
407
     * @param array $data
408
     *
409
     * @return array
410
     * @throws TelegramException
411
     */
412
    private static function setUpRequestParams(array $data): array
413
    {
414
        $has_resource = false;
415
        $multipart    = [];
416
417
        foreach ($data as $key => &$item) {
418
            if ($key === 'media') {
419
                // Magical media input helper.
420
                $item = self::mediaInputHelper($item, $has_resource, $multipart);
421
            } elseif (array_key_exists(self::$current_action, self::$input_file_fields) && in_array($key, self::$input_file_fields[self::$current_action], true)) {
422
                // Allow absolute paths to local files.
423
                if (is_string($item) && file_exists($item)) {
424
                    $item = new Stream(self::encodeFile($item));
425
                }
426
            } elseif (is_array($item) || is_object($item)) {
427
                // Convert any nested arrays or objects into JSON strings.
428
                $item = json_encode($item);
429
            }
430
431
            // Reformat data array in multipart way if it contains a resource
432
            $has_resource = $has_resource || is_resource($item) || $item instanceof Stream;
433
            $multipart[]  = ['name' => $key, 'contents' => $item];
434
        }
435
        unset($item);
436
437
        if ($has_resource) {
438
            return ['multipart' => $multipart];
439
        }
440
441
        return ['form_params' => $data];
442
    }
443
444
    /**
445
     * Magical input media helper to simplify passing media.
446
     *
447
     * This allows the following:
448
     * Request::editMessageMedia([
449
     *     ...
450
     *     'media' => new InputMediaPhoto([
451
     *         'caption' => 'Caption!',
452
     *         'media'   => Request::encodeFile($local_photo),
453
     *     ]),
454
     * ]);
455
     * and
456
     * Request::sendMediaGroup([
457
     *     'media'   => [
458
     *         new InputMediaPhoto(['media' => Request::encodeFile($local_photo_1)]),
459
     *         new InputMediaPhoto(['media' => Request::encodeFile($local_photo_2)]),
460
     *         new InputMediaVideo(['media' => Request::encodeFile($local_video_1)]),
461
     *     ],
462
     * ]);
463
     * and even
464
     * Request::sendMediaGroup([
465
     *     'media'   => [
466
     *         new InputMediaPhoto(['media' => $local_photo_1]),
467
     *         new InputMediaPhoto(['media' => $local_photo_2]),
468
     *         new InputMediaVideo(['media' => $local_video_1]),
469
     *     ],
470
     * ]);
471
     *
472
     * @param mixed $item
473
     * @param bool  $has_resource
474
     * @param array $multipart
475
     *
476
     * @return mixed
477
     * @throws TelegramException
478
     */
479
    private static function mediaInputHelper($item, bool &$has_resource, array &$multipart)
480
    {
481
        $was_array = is_array($item);
482
        $was_array || $item = [$item];
483
484
        /** @var InputMedia|null $media_item */
485
        foreach ($item as $media_item) {
486
            if (!($media_item instanceof InputMedia)) {
487
                continue;
488
            }
489
490
            // Make a list of all possible media that can be handled by the helper.
491
            $possible_medias = array_filter([
492
                '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

492
                'media' => $media_item->/** @scrutinizer ignore-call */ getMedia(),
Loading history...
493
                '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

493
                'thumb' => $media_item->/** @scrutinizer ignore-call */ getThumb(),
Loading history...
494
            ]);
495
496
            foreach ($possible_medias as $type => $media) {
497
                // Allow absolute paths to local files.
498
                if (is_string($media) && strpos($media, 'attach://') !== 0 && file_exists($media)) {
499
                    $media = new Stream(self::encodeFile($media));
500
                }
501
502
                if (is_resource($media) || $media instanceof Stream) {
503
                    $has_resource = true;
504
                    $unique_key   = uniqid($type . '_', false);
505
                    $multipart[]  = ['name' => $unique_key, 'contents' => $media];
506
507
                    // We're literally overwriting the passed media type data!
508
                    $media_item->$type           = 'attach://' . $unique_key;
509
                    $media_item->raw_data[$type] = 'attach://' . $unique_key;
510
                }
511
            }
512
        }
513
514
        $was_array || $item = reset($item);
515
516
        return json_encode($item);
517
    }
518
519
    /**
520
     * Get the current action that's being executed
521
     *
522
     * @return string
523
     */
524 7
    public static function getCurrentAction(): string
525
    {
526 7
        return self::$current_action;
527
    }
528
529
    /**
530
     * Execute HTTP Request
531
     *
532
     * @param string $action Action to execute
533
     * @param array  $data   Data to attach to the execution
534
     *
535
     * @return string Result of the HTTP Request
536
     * @throws TelegramException
537
     */
538
    public static function execute(string $action, array $data = []): string
539
    {
540
        $request_params          = self::setUpRequestParams($data);
541
        $request_params['debug'] = TelegramLog::getDebugLogTempStream();
542
543
        try {
544
            $response = self::$client->post(
545
                '/bot' . self::$telegram->getApiKey() . '/' . $action,
546
                $request_params
547
            );
548
            $result   = (string) $response->getBody();
549
        } catch (RequestException $e) {
550
            $response = null;
551
            $result   = $e->getResponse() ? (string) $e->getResponse()->getBody() : '';
552
        }
553
554
        //Logging verbose debug output
555
        if (TelegramLog::$always_log_request_and_response || $response === null) {
556
            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

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

929
                    $requests = array_map('intval', /** @scrutinizer ignore-type */ $requests);
Loading history...
930
931
                    $chat_per_second   = ($requests['LIMIT_PER_SEC'] === 0);    // No more than one message per second inside a particular chat
932
                    $global_per_second = ($requests['LIMIT_PER_SEC_ALL'] < 30); // No more than 30 messages per second to different chats
933
                    $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
934
935
                    if ($chat_per_second && $global_per_second && $groups_per_minute) {
936
                        break;
937
                    }
938
939
                    $timeout--;
940
                    usleep((int) (self::$limiter_interval * 1000000));
941
                }
942
943
                DB::insertTelegramRequest($action, $data);
944
            }
945
        }
946
    }
947
948
    /**
949
     * 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.
950
     *
951
     * @deprecated
952
     * @see Request::banChatMember()
953
     *
954
     * @param array $data
955
     *
956
     * @return ServerResponse
957
     */
958
    public static function kickChatMember(array $data = []): ServerResponse
959
    {
960
        return static::banChatMember($data);
961
    }
962
}
963