Passed
Push — 1049_bot_api_4.6 ( 239a99 )
by Armando
02:50
created

Request::send()   B

Complexity

Conditions 10
Paths 5

Size

Total Lines 44
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 110

Importance

Changes 4
Bugs 0 Features 0
Metric Value
cc 10
eloc 21
c 4
b 0
f 0
nc 5
nop 2
dl 0
loc 44
ccs 0
cts 22
cp 0
crap 110
rs 7.6666

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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

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

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