Passed
Push — develop ( 728003...bee867 )
by Armando
19:43 queued 09:47
created

Request::encodeFile()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 2

Importance

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

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

433
                'thumb' => $media_item->/** @scrutinizer ignore-call */ getThumb(),
Loading history...
434
            ]);
435
436
            foreach ($possible_medias as $type => $media) {
437
                // Allow absolute paths to local files.
438
                if (is_string($media) && strpos($media, 'attach://') !== 0 && file_exists($media)) {
439
                    $media = new Stream(self::encodeFile($media));
440
                }
441
442
                if (is_resource($media) || $media instanceof Stream) {
443
                    $has_resource = true;
444
                    $unique_key   = uniqid($type . '_', false);
445
                    $multipart[]  = ['name' => $unique_key, 'contents' => $media];
446
447
                    // We're literally overwriting the passed media type data!
448
                    $media_item->$type           = 'attach://' . $unique_key;
449
                    $media_item->raw_data[$type] = 'attach://' . $unique_key;
450
                }
451
            }
452
        }
453
454
        $was_array || $item = reset($item);
455
456
        return json_encode($item);
457
    }
458
459
    /**
460
     * Get the current action that's being executed
461
     *
462
     * @return string
463
     */
464
    public static function getCurrentAction(): string
465
    {
466
        return self::$current_action;
467
    }
468
469
    /**
470
     * Execute HTTP Request
471
     *
472
     * @param string $action Action to execute
473
     * @param array  $data   Data to attach to the execution
474
     *
475
     * @return string Result of the HTTP Request
476
     * @throws TelegramException
477
     */
478
    public static function execute(string $action, array $data = []): string
479
    {
480
        $request_params          = self::setUpRequestParams($data);
481
        $request_params['debug'] = TelegramLog::getDebugLogTempStream();
482
483
        try {
484
            $response = self::$client->post(
485
                '/bot' . self::$telegram->getApiKey() . '/' . $action,
486
                $request_params
487
            );
488
            $result   = (string) $response->getBody();
489
490
            //Logging getUpdates Update
491
            if ($action === 'getUpdates') {
492
                TelegramLog::update($result);
493
            }
494
        } catch (RequestException $e) {
495
            $response = null;
496
            $result   = $e->getResponse() ? (string) $e->getResponse()->getBody() : '';
497
        }
498
499
        //Logging verbose debug output
500
        if (TelegramLog::$always_log_request_and_response || $response === null) {
501
            TelegramLog::debug('Request data:' . PHP_EOL . print_r($data, true));
502
            TelegramLog::debug('Response data:' . PHP_EOL . $result);
503
            TelegramLog::endDebugLogTempStream('Verbose HTTP Request output:' . PHP_EOL . '%s' . PHP_EOL);
504
        }
505
506
        return $result;
507
    }
508
509
    /**
510
     * Download file
511
     *
512
     * @param File $file
513
     *
514
     * @return bool
515
     * @throws TelegramException
516
     */
517
    public static function downloadFile(File $file): bool
518
    {
519
        if (empty($download_path = self::$telegram->getDownloadPath())) {
520
            throw new TelegramException('Download path not set!');
521
        }
522
523
        $tg_file_path = $file->getFilePath();
524
        $file_path    = $download_path . '/' . $tg_file_path;
525
526
        $file_dir = dirname($file_path);
527
        //For safety reasons, first try to create the directory, then check that it exists.
528
        //This is in case some other process has created the folder in the meantime.
529
        if (!@mkdir($file_dir, 0755, true) && !is_dir($file_dir)) {
530
            throw new TelegramException('Directory ' . $file_dir . ' can\'t be created');
531
        }
532
533
        $debug_handle = TelegramLog::getDebugLogTempStream();
534
535
        try {
536
            self::$client->get(
537
                '/file/bot' . self::$telegram->getApiKey() . '/' . $tg_file_path,
538
                ['debug' => $debug_handle, 'sink' => $file_path]
539
            );
540
541
            return filesize($file_path) > 0;
542
        } catch (Throwable $e) {
543
            return false;
544
        } finally {
545
            //Logging verbose debug output
546
            TelegramLog::endDebugLogTempStream('Verbose HTTP File Download Request output:' . PHP_EOL . '%s' . PHP_EOL);
0 ignored issues
show
Bug Best Practice introduced by
In this branch, the function will implicitly return null which is incompatible with the type-hinted return boolean. Consider adding a return statement or allowing null as return value.

For hinted functions/methods where all return statements with the correct type are only reachable via conditions, ?null? gets implicitly returned which may be incompatible with the hinted type. Let?s take a look at an example:

interface ReturnsInt {
    public function returnsIntHinted(): int;
}

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

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

850
                    $requests = array_map('intval', /** @scrutinizer ignore-type */ $requests);
Loading history...
851
852
                    $chat_per_second   = ($requests['LIMIT_PER_SEC'] === 0);    // No more than one message per second inside a particular chat
853
                    $global_per_second = ($requests['LIMIT_PER_SEC_ALL'] < 30); // No more than 30 messages per second to different chats
854
                    $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
855
856
                    if ($chat_per_second && $global_per_second && $groups_per_minute) {
857
                        break;
858
                    }
859
860
                    $timeout--;
861
                    usleep((int) (self::$limiter_interval * 1000000));
862
                }
863
864
                DB::insertTelegramRequest($action, $data);
865
            }
866
        }
867
    }
868
}
869