Completed
Push — develop ( f09bf5...728003 )
by Armando
24s queued 13s
created

Request::setClient()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

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

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

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