Passed
Push — master ( 78024d...fb0f34 )
by Armando
02:41
created

Request   F

Complexity

Total Complexity 90

Size/Duplication

Total Lines 775
Duplicated Lines 0 %

Test Coverage

Coverage 10.53%

Importance

Changes 37
Bugs 3 Features 1
Metric Value
eloc 303
c 37
b 3
f 1
dl 0
loc 775
ccs 20
cts 190
cp 0.1053
rs 2
wmc 90

20 Methods

Rating   Name   Duplication   Size   Complexity  
A getCurrentAction() 0 3 1
A getInput() 0 16 3
A setClient() 0 3 1
A initialize() 0 4 2
C setUpRequestParams() 0 30 12
A generateGeneralFakeServerResponse() 0 29 3
B mediaInputHelper() 0 37 10
A setLimiter() 0 15 4
A sendToActiveChats() 0 18 3
A downloadFile() 0 30 5
A ensureNonEmptyData() 0 4 2
B execute() 0 31 6
A ensureValidAction() 0 4 2
A __callStatic() 0 7 1
A sendMessage() 0 14 2
B send() 0 44 10
A encodeFile() 0 8 2
A emptyResponse() 0 3 1
A addDummyParamIfNecessary() 0 5 2
D limitTelegramRequests() 0 69 18

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
25
/**
26
 * Class Request
27
 *
28
 * @method static ServerResponse getUpdates(array $data)                      Use this method to receive incoming updates using long polling (wiki). An Array of Update objects is returned.
29
 * @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.
30
 * @method static ServerResponse deleteWebhook()                              Use this method to remove webhook integration if you decide to switch back to getUpdates. Returns True on success. Requires no parameters.
31
 * @method static ServerResponse getWebhookInfo()                             Use this method to get current webhook status. Requires no parameters. On success, returns a WebhookInfo object. If the bot is using getUpdates, will return an object with the url field empty.
32
 * @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.
33
 * @method static ServerResponse forwardMessage(array $data)                  Use this method to forward messages of any kind. On success, the sent Message is returned.
34
 * @method static ServerResponse sendPhoto(array $data)                       Use this method to send photos. On success, the sent Message is returned.
35
 * @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.
36
 * @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.
37
 * @method static ServerResponse sendSticker(array $data)                     Use this method to send .webp stickers. On success, the sent Message is returned.
38
 * @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.
39
 * @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.
40
 * @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.
41
 * @method static ServerResponse sendVideoNote(array $data)                   Use this method to send video messages. On success, the sent Message is returned.
42
 * @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.
43
 * @method static ServerResponse sendLocation(array $data)                    Use this method to send point on the map. On success, the sent Message is returned.
44
 * @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.
45
 * @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.
46
 * @method static ServerResponse sendVenue(array $data)                       Use this method to send information about a venue. On success, the sent Message is returned.
47
 * @method static ServerResponse sendContact(array $data)                     Use this method to send phone contacts. On success, the sent Message is returned.
48
 * @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.
49
 * @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.
50
 * @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.
51
 * @method static ServerResponse getUserProfilePhotos(array $data)            Use this method to get a list of profile pictures for a user. Returns a UserProfilePhotos object.
52
 * @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.
53
 * @method static ServerResponse kickChatMember(array $data)                  Use this method to kick a user from a group, a supergroup or a channel. In the case of 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.
54
 * @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.
55
 * @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.
56
 * @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.
57
 * @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.
58
 * @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.
59
 * @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.
60
 * @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.
61
 * @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.
62
 * @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.
63
 * @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.
64
 * @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.
65
 * @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.
66
 * @method static ServerResponse leaveChat(array $data)                       Use this method for your bot to leave a group, supergroup or channel. Returns True on success.
67
 * @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.
68
 * @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.
69
 * @method static ServerResponse getChatMembersCount(array $data)             Use this method to get the number of members in a chat. Returns Int on success.
70
 * @method static ServerResponse getChatMember(array $data)                   Use this method to get information about a member of a chat. Returns a ChatMember object on success.
71
 * @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.
72
 * @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.
73
 * @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.
74
 * @method static ServerResponse answerInlineQuery(array $data)               Use this method to send answers to an inline query. On success, True is returned.
75
 * @method static ServerResponse setMyCommands(array $data)                   Use this method to change the list of the bot's commands. Returns True on success.
76
 * @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.
77
 * @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.
78
 * @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.
79
 * @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.
80
 * @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.
81
 * @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.
82
 * @method static ServerResponse deleteMessage(array $data)                   Use this method to delete a message, including service messages, with certain limitations. Returns True on success.
83
 * @method static ServerResponse getStickerSet(array $data)                   Use this method to get a sticker set. On success, a StickerSet object is returned.
84
 * @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.
85
 * @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.
86
 * @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.
87
 * @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.
88
 * @method static ServerResponse deleteStickerFromSet(array $data)            Use this method to delete a sticker from a set created by the bot. Returns True on success.
89
 * @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.
90
 * @method static ServerResponse sendInvoice(array $data)                     Use this method to send invoices. On success, the sent Message is returned.
91
 * @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.
92
 * @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.
93
 * @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.
94
 * @method static ServerResponse sendGame(array $data)                        Use this method to send a game. On success, the sent Message is returned.
95
 * @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.
96
 * @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.
97
 */
98
class Request
99
{
100
    /**
101
     * Telegram object
102
     *
103
     * @var Telegram
104
     */
105
    private static $telegram;
106
107
    /**
108
     * URI of the Telegram API
109
     *
110
     * @var string
111
     */
112
    private static $api_base_uri = 'https://api.telegram.org';
113
114
    /**
115
     * Guzzle Client object
116
     *
117
     * @var ClientInterface
118
     */
119
    private static $client;
120
121
    /**
122
     * Request limiter
123
     *
124
     * @var boolean
125
     */
126
    private static $limiter_enabled;
127
128
    /**
129
     * Request limiter's interval between checks
130
     *
131
     * @var float
132
     */
133
    private static $limiter_interval;
134
135
    /**
136
     * Get the current action that is being executed
137
     *
138
     * @var string
139
     */
140
    private static $current_action;
141
142
    /**
143
     * Available actions to send
144
     *
145
     * This is basically the list of all methods listed on the official API documentation.
146
     *
147
     * @link https://core.telegram.org/bots/api
148
     *
149
     * @var array
150
     */
151
    private static $actions = [
152
        'getUpdates',
153
        'setWebhook',
154
        'deleteWebhook',
155
        'getWebhookInfo',
156
        'getMe',
157
        'sendMessage',
158
        'forwardMessage',
159
        'sendPhoto',
160
        'sendAudio',
161
        'sendDocument',
162
        'sendSticker',
163
        'sendVideo',
164
        'sendAnimation',
165
        'sendVoice',
166
        'sendVideoNote',
167
        'sendMediaGroup',
168
        'sendLocation',
169
        'editMessageLiveLocation',
170
        'stopMessageLiveLocation',
171
        'sendVenue',
172
        'sendContact',
173
        'sendPoll',
174
        'sendDice',
175
        'sendChatAction',
176
        'getUserProfilePhotos',
177
        'getFile',
178
        'kickChatMember',
179
        'unbanChatMember',
180
        'restrictChatMember',
181
        'promoteChatMember',
182
        'setChatAdministratorCustomTitle',
183
        'setChatPermissions',
184
        'exportChatInviteLink',
185
        'setChatPhoto',
186
        'deleteChatPhoto',
187
        'setChatTitle',
188
        'setChatDescription',
189
        'pinChatMessage',
190
        'unpinChatMessage',
191
        'leaveChat',
192
        'getChat',
193
        'getChatAdministrators',
194
        'getChatMembersCount',
195
        'getChatMember',
196
        'setChatStickerSet',
197
        'deleteChatStickerSet',
198
        'answerCallbackQuery',
199
        'answerInlineQuery',
200
        'setMyCommands',
201
        'getMyCommands',
202
        'editMessageText',
203
        'editMessageCaption',
204
        'editMessageMedia',
205
        'editMessageReplyMarkup',
206
        'stopPoll',
207
        'deleteMessage',
208
        'getStickerSet',
209
        'uploadStickerFile',
210
        'createNewStickerSet',
211
        'addStickerToSet',
212
        'setStickerPositionInSet',
213
        'deleteStickerFromSet',
214
        'setStickerSetThumb',
215
        'sendInvoice',
216
        'answerShippingQuery',
217
        'answerPreCheckoutQuery',
218
        'setPassportDataErrors',
219
        'sendGame',
220
        'setGameScore',
221
        'getGameHighScores',
222
    ];
223
224
    /**
225
     * Some methods need a dummy param due to certain cURL issues.
226
     *
227
     * @see Request::addDummyParamIfNecessary()
228
     *
229
     * @var array
230
     */
231
    private static $actions_need_dummy_param = [
232
        'deleteWebhook',
233
        'getWebhookInfo',
234
        'getMe',
235
        'getMyCommands',
236
    ];
237
238
    /**
239
     * Available fields for InputFile helper
240
     *
241
     * This is basically the list of all fields that allow InputFile objects
242
     * for which input can be simplified by providing local path directly  as string.
243
     *
244
     * @var array
245
     */
246
    private static $input_file_fields = [
247
        'setWebhook'          => ['certificate'],
248
        'sendPhoto'           => ['photo'],
249
        'sendAudio'           => ['audio', 'thumb'],
250
        'sendDocument'        => ['document', 'thumb'],
251
        'sendVideo'           => ['video', 'thumb'],
252
        'sendAnimation'       => ['animation', 'thumb'],
253
        'sendVoice'           => ['voice', 'thumb'],
254
        'sendVideoNote'       => ['video_note', 'thumb'],
255
        'setChatPhoto'        => ['photo'],
256
        'sendSticker'         => ['sticker'],
257
        'uploadStickerFile'   => ['png_sticker'],
258
        'createNewStickerSet' => ['png_sticker', 'tgs_sticker'],
259
        'addStickerToSet'     => ['png_sticker', 'tgs_sticker'],
260
        'setStickerSetThumb'  => ['thumb'],
261
    ];
262
263
    /**
264
     * Initialize
265
     *
266
     * @param Telegram $telegram
267
     */
268 30
    public static function initialize(Telegram $telegram)
269
    {
270 30
        self::$telegram = $telegram;
271 30
        self::setClient(self::$client ?: new Client(['base_uri' => self::$api_base_uri]));
272 30
    }
273
274
    /**
275
     * Set a custom Guzzle HTTP Client object
276
     *
277
     * @param ClientInterface $client
278
     */
279 30
    public static function setClient(ClientInterface $client)
280
    {
281 30
        self::$client = $client;
282 30
    }
283
284
    /**
285
     * Set input from custom input or stdin and return it
286
     *
287
     * @return string
288
     * @throws TelegramException
289
     */
290
    public static function getInput()
291
    {
292
        // First check if a custom input has been set, else get the PHP input.
293
        $input = self::$telegram->getCustomInput();
294
        if (empty($input)) {
295
            $input = file_get_contents('php://input');
296
        }
297
298
        // Make sure we have a string to work with.
299
        if (!is_string($input)) {
0 ignored issues
show
introduced by
The condition is_string($input) is always true.
Loading history...
300
            throw new TelegramException('Input must be a string!');
301
        }
302
303
        TelegramLog::update($input);
304
305
        return $input;
306
    }
307
308
    /**
309
     * Generate general fake server response
310
     *
311
     * @param array $data Data to add to fake response
312
     *
313
     * @return array Fake response data
314
     */
315 1
    public static function generateGeneralFakeServerResponse(array $data = [])
316
    {
317
        //PARAM BINDED IN PHPUNIT TEST FOR TestServerResponse.php
318
        //Maybe this is not the best possible implementation
319
320
        //No value set in $data ie testing setWebhook
321
        //Provided $data['chat_id'] ie testing sendMessage
322
323 1
        $fake_response = ['ok' => true]; // :)
324
325 1
        if ($data === []) {
326 1
            $fake_response['result'] = true;
327
        }
328
329
        //some data to let iniatilize the class method SendMessage
330 1
        if (isset($data['chat_id'])) {
331 1
            $data['message_id'] = '1234';
332 1
            $data['date']       = '1441378360';
333 1
            $data['from']       = [
334
                'id'         => 123456789,
335
                'first_name' => 'botname',
336
                'username'   => 'namebot',
337
            ];
338 1
            $data['chat']       = ['id' => $data['chat_id']];
339
340 1
            $fake_response['result'] = $data;
341
        }
342
343 1
        return $fake_response;
344
    }
345
346
    /**
347
     * Properly set up the request params
348
     *
349
     * If any item of the array is a resource, reformat it to a multipart request.
350
     * Else, just return the passed data as form params.
351
     *
352
     * @param array $data
353
     *
354
     * @return array
355
     * @throws TelegramException
356
     */
357
    private static function setUpRequestParams(array $data)
358
    {
359
        $has_resource = false;
360
        $multipart    = [];
361
362
        foreach ($data as $key => &$item) {
363
            if ($key === 'media') {
364
                // Magical media input helper.
365
                $item = self::mediaInputHelper($item, $has_resource, $multipart);
366
            } elseif (array_key_exists(self::$current_action, self::$input_file_fields) && in_array($key, self::$input_file_fields[self::$current_action], true)) {
367
                // Allow absolute paths to local files.
368
                if (is_string($item) && file_exists($item)) {
369
                    $item = new Stream(self::encodeFile($item));
370
                }
371
            } elseif (is_array($item) || is_object($item)) {
372
                // Convert any nested arrays or objects into JSON strings.
373
                $item = json_encode($item);
374
            }
375
376
            // Reformat data array in multipart way if it contains a resource
377
            $has_resource = $has_resource || is_resource($item) || $item instanceof Stream;
378
            $multipart[]  = ['name' => $key, 'contents' => $item];
379
        }
380
        unset($item);
381
382
        if ($has_resource) {
383
            return ['multipart' => $multipart];
384
        }
385
386
        return ['form_params' => $data];
387
    }
388
389
    /**
390
     * Magical input media helper to simplify passing media.
391
     *
392
     * This allows the following:
393
     * Request::editMessageMedia([
394
     *     ...
395
     *     'media' => new InputMediaPhoto([
396
     *         'caption' => 'Caption!',
397
     *         'media'   => Request::encodeFile($local_photo),
398
     *     ]),
399
     * ]);
400
     * and
401
     * Request::sendMediaGroup([
402
     *     'media'   => [
403
     *         new InputMediaPhoto(['media' => Request::encodeFile($local_photo_1)]),
404
     *         new InputMediaPhoto(['media' => Request::encodeFile($local_photo_2)]),
405
     *         new InputMediaVideo(['media' => Request::encodeFile($local_video_1)]),
406
     *     ],
407
     * ]);
408
     * and even
409
     * Request::sendMediaGroup([
410
     *     'media'   => [
411
     *         new InputMediaPhoto(['media' => $local_photo_1]),
412
     *         new InputMediaPhoto(['media' => $local_photo_2]),
413
     *         new InputMediaVideo(['media' => $local_video_1]),
414
     *     ],
415
     * ]);
416
     *
417
     * @param mixed $item
418
     * @param bool  $has_resource
419
     * @param array $multipart
420
     *
421
     * @return mixed
422
     * @throws TelegramException
423
     */
424
    private static function mediaInputHelper($item, &$has_resource, array &$multipart)
425
    {
426
        $was_array = is_array($item);
427
        $was_array || $item = [$item];
428
429
        foreach ($item as $media_item) {
430
            if (!($media_item instanceof InputMedia)) {
431
                continue;
432
            }
433
434
            // Make a list of all possible media that can be handled by the helper.
435
            $possible_medias = array_filter([
436
                '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

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

437
                'thumb' => $media_item->/** @scrutinizer ignore-call */ getThumb(),
Loading history...
438
            ]);
439
440
            foreach ($possible_medias as $type => $media) {
441
                // Allow absolute paths to local files.
442
                if (is_string($media) && file_exists($media)) {
443
                    $media = new Stream(self::encodeFile($media));
444
                }
445
446
                if (is_resource($media) || $media instanceof Stream) {
447
                    $has_resource = true;
448
                    $unique_key   = uniqid($type . '_', false);
449
                    $multipart[]  = ['name' => $unique_key, 'contents' => $media];
450
451
                    // We're literally overwriting the passed media type data!
452
                    $media_item->$type           = 'attach://' . $unique_key;
453
                    $media_item->raw_data[$type] = 'attach://' . $unique_key;
454
                }
455
            }
456
        }
457
458
        $was_array || $item = reset($item);
459
460
        return json_encode($item);
461
    }
462
463
    /**
464
     * Get the current action that's being executed
465
     *
466
     * @return string
467
     */
468 7
    public static function getCurrentAction()
469
    {
470 7
        return self::$current_action;
471
    }
472
473
    /**
474
     * Execute HTTP Request
475
     *
476
     * @param string $action Action to execute
477
     * @param array  $data   Data to attach to the execution
478
     *
479
     * @return string Result of the HTTP Request
480
     * @throws TelegramException
481
     */
482
    public static function execute($action, array $data = [])
483
    {
484
        $result                  = null;
485
        $response                = null;
0 ignored issues
show
Unused Code introduced by
The assignment to $response is dead and can be removed.
Loading history...
486
        $request_params          = self::setUpRequestParams($data);
487
        $request_params['debug'] = TelegramLog::getDebugLogTempStream();
488
489
        try {
490
            $response = self::$client->post(
491
                '/bot' . self::$telegram->getApiKey() . '/' . $action,
492
                $request_params
493
            );
494
            $result   = (string) $response->getBody();
495
496
            //Logging getUpdates Update
497
            if ($action === 'getUpdates') {
498
                TelegramLog::update($result);
499
            }
500
        } catch (RequestException $e) {
501
            $response = null;
502
            $result   = $e->getResponse() ? (string) $e->getResponse()->getBody() : '';
503
        } finally {
504
            //Logging verbose debug output
505
            if (TelegramLog::$always_log_request_and_response || $response === null) {
506
                TelegramLog::debug('Request data:' . PHP_EOL . print_r($data, true));
507
                TelegramLog::debug('Response data:' . PHP_EOL . $result);
508
                TelegramLog::endDebugLogTempStream('Verbose HTTP Request output:' . PHP_EOL . '%s' . PHP_EOL);
509
            }
510
        }
511
512
        return $result;
513
    }
514
515
    /**
516
     * Download file
517
     *
518
     * @param File $file
519
     *
520
     * @return boolean
521
     * @throws TelegramException
522
     */
523
    public static function downloadFile(File $file)
524
    {
525
        if (empty($download_path = self::$telegram->getDownloadPath())) {
526
            throw new TelegramException('Download path not set!');
527
        }
528
529
        $tg_file_path = $file->getFilePath();
530
        $file_path    = $download_path . '/' . $tg_file_path;
531
532
        $file_dir = dirname($file_path);
533
        //For safety reasons, first try to create the directory, then check that it exists.
534
        //This is in case some other process has created the folder in the meantime.
535
        if (!@mkdir($file_dir, 0755, true) && !is_dir($file_dir)) {
536
            throw new TelegramException('Directory ' . $file_dir . ' can\'t be created');
537
        }
538
539
        $debug_handle = TelegramLog::getDebugLogTempStream();
540
541
        try {
542
            self::$client->get(
543
                '/file/bot' . self::$telegram->getApiKey() . '/' . $tg_file_path,
544
                ['debug' => $debug_handle, 'sink' => $file_path]
545
            );
546
547
            return filesize($file_path) > 0;
548
        } catch (RequestException $e) {
549
            return false;
550
        } finally {
551
            //Logging verbose debug output
552
            TelegramLog::endDebugLogTempStream('Verbose HTTP File Download Request output:' . PHP_EOL . '%s' . PHP_EOL);
553
        }
554
    }
555
556
    /**
557
     * Encode file
558
     *
559
     * @param string $file
560
     *
561
     * @return resource
562
     * @throws TelegramException
563
     */
564
    public static function encodeFile($file)
565
    {
566
        $fp = fopen($file, 'rb');
567
        if ($fp === false) {
568
            throw new TelegramException('Cannot open "' . $file . '" for reading');
569
        }
570
571
        return $fp;
572
    }
573
574
    /**
575
     * Send command
576
     *
577
     * @todo Fake response doesn't need json encoding?
578
     * @todo Write debug entry on failure
579
     *
580
     * @param string $action
581
     * @param array  $data
582
     *
583
     * @return ServerResponse
584
     * @throws TelegramException
585
     */
586
    public static function send($action, array $data = [])
587
    {
588
        self::ensureValidAction($action);
589
        self::addDummyParamIfNecessary($action, $data);
590
591
        $bot_username = self::$telegram->getBotUsername();
592
593
        if (defined('PHPUNIT_TESTSUITE')) {
594
            $fake_response = self::generateGeneralFakeServerResponse($data);
595
596
            return new ServerResponse($fake_response, $bot_username);
597
        }
598
599
        self::ensureNonEmptyData($data);
600
601
        self::limitTelegramRequests($action, $data);
602
603
        // Remember which action is currently being executed.
604
        self::$current_action = $action;
605
606
        $raw_response = self::execute($action, $data);
607
        $response     = json_decode($raw_response, true);
608
609
        if (null === $response) {
610
            TelegramLog::debug($raw_response);
611
            throw new TelegramException('Telegram returned an invalid response!');
612
        }
613
614
        $response = new ServerResponse($response, $bot_username);
615
616
        if (!$response->isOk() && $response->getErrorCode() === 401 && $response->getDescription() === 'Unauthorized') {
617
            throw new InvalidBotTokenException();
618
        }
619
620
        // Special case for sent polls, which need to be saved specially.
621
        // @todo Take into account if DB gets extracted into separate module.
622
        if ($response->isOk() && ($message = $response->getResult()) && ($message instanceof Message) && $poll = $message->getPoll()) {
623
            DB::insertPollRequest($poll);
624
        }
625
626
        // Reset current action after completion.
627
        self::$current_action = null;
628
629
        return $response;
630
    }
631
632
    /**
633
     * Add a dummy parameter if the passed action requires it.
634
     *
635
     * If a method doesn't require parameters, we need to add a dummy one anyway,
636
     * because of some cURL version failed POST request without parameters.
637
     *
638
     * @link https://github.com/php-telegram-bot/core/pull/228
639
     *
640
     * @todo Would be nice to find a better solution for this!
641
     *
642
     * @param string $action
643
     * @param array  $data
644
     */
645
    protected static function addDummyParamIfNecessary($action, array &$data)
646
    {
647
        if (in_array($action, self::$actions_need_dummy_param, true)) {
648
            // Can be anything, using a single letter to minimise request size.
649
            $data = ['d'];
650
        }
651
    }
652
653
    /**
654
     * Make sure the data isn't empty, else throw an exception
655
     *
656
     * @param array $data
657
     *
658
     * @throws TelegramException
659
     */
660
    private static function ensureNonEmptyData(array $data)
661
    {
662
        if (count($data) === 0) {
663
            throw new TelegramException('Data is empty!');
664
        }
665
    }
666
667
    /**
668
     * Make sure the action is valid, else throw an exception
669
     *
670
     * @param string $action
671
     *
672
     * @throws TelegramException
673
     */
674
    private static function ensureValidAction($action)
675
    {
676
        if (!in_array($action, self::$actions, true)) {
677
            throw new TelegramException('The action "' . $action . '" doesn\'t exist!');
678
        }
679
    }
680
681
    /**
682
     * Use this method to send text messages. On success, the sent Message is returned
683
     *
684
     * @link https://core.telegram.org/bots/api#sendmessage
685
     *
686
     * @param array $data
687
     *
688
     * @return ServerResponse
689
     * @throws TelegramException
690
     */
691
    public static function sendMessage(array $data)
692
    {
693
        $text = $data['text'];
694
695
        do {
696
            //Chop off and send the first message
697
            $data['text'] = mb_substr($text, 0, 4096);
698
            $response     = self::send('sendMessage', $data);
699
700
            //Prepare the next message
701
            $text = mb_substr($text, 4096);
702
        } while (mb_strlen($text, 'UTF-8') > 0);
703
704
        return $response;
705
    }
706
707
    /**
708
     * Any statically called method should be relayed to the `send` method.
709
     *
710
     * @param string $action
711
     * @param array  $data
712
     *
713
     * @return ServerResponse
714
     */
715
    public static function __callStatic($action, array $data)
716
    {
717
        // Make sure to add the action being called as the first parameter to be passed.
718
        array_unshift($data, $action);
719
720
        // @todo Use splat operator for unpacking when we move to PHP 5.6+
721
        return call_user_func_array('static::send', $data);
722
    }
723
724
    /**
725
     * Return an empty Server Response
726
     *
727
     * No request to telegram are sent, this function is used in commands that
728
     * don't need to fire a message after execution
729
     *
730
     * @return ServerResponse
731
     */
732
    public static function emptyResponse()
733
    {
734
        return new ServerResponse(['ok' => true, 'result' => true], null);
735
    }
736
737
    /**
738
     * Send message to all active chats
739
     *
740
     * @param string $callback_function
741
     * @param array  $data
742
     * @param array  $select_chats_params
743
     *
744
     * @return array
745
     * @throws TelegramException
746
     */
747
    public static function sendToActiveChats(
748
        $callback_function,
749
        array $data,
750
        array $select_chats_params
751
    ) {
752
        self::ensureValidAction($callback_function);
753
754
        $chats = DB::selectChats($select_chats_params);
755
756
        $results = [];
757
        if (is_array($chats)) {
758
            foreach ($chats as $row) {
759
                $data['chat_id'] = $row['chat_id'];
760
                $results[]       = self::send($callback_function, $data);
761
            }
762
        }
763
764
        return $results;
765
    }
766
767
    /**
768
     * Enable request limiter
769
     *
770
     * @param boolean $enable
771
     * @param array   $options
772
     *
773
     * @throws TelegramException
774
     */
775
    public static function setLimiter($enable = true, array $options = [])
776
    {
777
        if (DB::isDbConnected()) {
778
            $options_default = [
779
                'interval' => 1,
780
            ];
781
782
            $options = array_merge($options_default, $options);
783
784
            if (!is_numeric($options['interval']) || $options['interval'] <= 0) {
785
                throw new TelegramException('Interval must be a number and must be greater than zero!');
786
            }
787
788
            self::$limiter_interval = $options['interval'];
789
            self::$limiter_enabled  = $enable;
790
        }
791
    }
792
793
    /**
794
     * This functions delays API requests to prevent reaching Telegram API limits
795
     *  Can be disabled while in execution by 'Request::setLimiter(false)'
796
     *
797
     * @link https://core.telegram.org/bots/faq#my-bot-is-hitting-limits-how-do-i-avoid-this
798
     *
799
     * @param string $action
800
     * @param array  $data
801
     *
802
     * @throws TelegramException
803
     */
804
    private static function limitTelegramRequests($action, array $data = [])
805
    {
806
        if (self::$limiter_enabled) {
807
            $limited_methods = [
808
                'sendMessage',
809
                'forwardMessage',
810
                'sendPhoto',
811
                'sendAudio',
812
                'sendDocument',
813
                'sendSticker',
814
                'sendVideo',
815
                'sendAnimation',
816
                'sendVoice',
817
                'sendVideoNote',
818
                'sendMediaGroup',
819
                'sendLocation',
820
                'editMessageLiveLocation',
821
                'stopMessageLiveLocation',
822
                'sendVenue',
823
                'sendContact',
824
                'sendPoll',
825
                'sendDice',
826
                'sendInvoice',
827
                'sendGame',
828
                'setGameScore',
829
                'setMyCommands',
830
                'editMessageText',
831
                'editMessageCaption',
832
                'editMessageMedia',
833
                'editMessageReplyMarkup',
834
                'stopPoll',
835
                'setChatTitle',
836
                'setChatDescription',
837
                'setChatStickerSet',
838
                'deleteChatStickerSet',
839
                'setPassportDataErrors',
840
            ];
841
842
            $chat_id           = isset($data['chat_id']) ? $data['chat_id'] : null;
843
            $inline_message_id = isset($data['inline_message_id']) ? $data['inline_message_id'] : null;
844
845
            if (($chat_id || $inline_message_id) && in_array($action, $limited_methods, true)) {
846
                $timeout = 60;
847
848
                while (true) {
849
                    if ($timeout <= 0) {
850
                        throw new TelegramException('Timed out while waiting for a request spot!');
851
                    }
852
853
                    if (!($requests = DB::getTelegramRequestCount($chat_id, $inline_message_id))) {
854
                        break;
855
                    }
856
857
                    // Make sure we're handling integers here.
858
                    $requests = array_map('intval', $requests);
859
860
                    $chat_per_second   = ($requests['LIMIT_PER_SEC'] === 0);    // No more than one message per second inside a particular chat
861
                    $global_per_second = ($requests['LIMIT_PER_SEC_ALL'] < 30); // No more than 30 messages per second to different chats
862
                    $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
863
864
                    if ($chat_per_second && $global_per_second && $groups_per_minute) {
865
                        break;
866
                    }
867
868
                    $timeout--;
869
                    usleep((int) (self::$limiter_interval * 1000000));
870
                }
871
872
                DB::insertTelegramRequest($action, $data);
873
            }
874
        }
875
    }
876
}
877