Completed
Push — 811-helper_for_media_groups ( d77b66 )
by Armando
02:52
created

Request::setLimiter()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 17

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

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

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
395
                $media_item->raw_data['media'] = 'attach://' . $rnd_key;
0 ignored issues
show
Bug introduced by
Accessing raw_data on the interface Longman\TelegramBot\Entities\InputMedia\InputMedia suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
396
            }
397
        }
398
399
        $was_array || $item = reset($item);
400
401
        return json_encode($item);
402
    }
403
404
    /**
405
     * Execute HTTP Request
406
     *
407
     * @param string $action Action to execute
408
     * @param array  $data   Data to attach to the execution
409
     *
410
     * @return string Result of the HTTP Request
411
     * @throws \Longman\TelegramBot\Exception\TelegramException
412
     */
413
    public static function execute($action, array $data = [])
414
    {
415
        //Fix so that the keyboard markup is a string, not an object
416
        if (isset($data['reply_markup'])) {
417
            $data['reply_markup'] = json_encode($data['reply_markup']);
418
        }
419
420
        $result                  = null;
421
        $request_params          = self::setUpRequestParams($data);
422
        $request_params['debug'] = TelegramLog::getDebugLogTempStream();
423
424
        try {
425
            $response = self::$client->post(
426
                '/bot' . self::$telegram->getApiKey() . '/' . $action,
427
                $request_params
428
            );
429
            $result   = (string) $response->getBody();
430
431
            //Logging getUpdates Update
432
            if ($action === 'getUpdates') {
433
                TelegramLog::update($result);
434
            }
435
        } catch (RequestException $e) {
436
            $result = ($e->getResponse()) ? (string) $e->getResponse()->getBody() : '';
437
        } finally {
438
            //Logging verbose debug output
439
            TelegramLog::endDebugLogTempStream('Verbose HTTP Request output:' . PHP_EOL . '%s' . PHP_EOL);
440
        }
441
442
        return $result;
443
    }
444
445
    /**
446
     * Download file
447
     *
448
     * @param \Longman\TelegramBot\Entities\File $file
449
     *
450
     * @return boolean
451
     * @throws \Longman\TelegramBot\Exception\TelegramException
452
     */
453
    public static function downloadFile(File $file)
454
    {
455
        if (empty($download_path = self::$telegram->getDownloadPath())) {
456
            throw new TelegramException('Download path not set!');
457
        }
458
459
        $tg_file_path = $file->getFilePath();
460
        $file_path    = $download_path . '/' . $tg_file_path;
461
462
        $file_dir = dirname($file_path);
463
        //For safety reasons, first try to create the directory, then check that it exists.
464
        //This is in case some other process has created the folder in the meantime.
465
        if (!@mkdir($file_dir, 0755, true) && !is_dir($file_dir)) {
466
            throw new TelegramException('Directory ' . $file_dir . ' can\'t be created');
467
        }
468
469
        $debug_handle = TelegramLog::getDebugLogTempStream();
470
471
        try {
472
            self::$client->get(
473
                '/file/bot' . self::$telegram->getApiKey() . '/' . $tg_file_path,
474
                ['debug' => $debug_handle, 'sink' => $file_path]
475
            );
476
477
            return filesize($file_path) > 0;
478
        } catch (RequestException $e) {
479
            return ($e->getResponse()) ? (string) $e->getResponse()->getBody() : '';
480
        } finally {
481
            //Logging verbose debug output
482
            TelegramLog::endDebugLogTempStream('Verbose HTTP File Download Request output:' . PHP_EOL . '%s' . PHP_EOL);
483
        }
484
    }
485
486
    /**
487
     * Encode file
488
     *
489
     * @param string $file
490
     *
491
     * @return resource
492
     * @throws \Longman\TelegramBot\Exception\TelegramException
493
     */
494
    public static function encodeFile($file)
495
    {
496
        $fp = fopen($file, 'rb');
497
        if ($fp === false) {
498
            throw new TelegramException('Cannot open "' . $file . '" for reading');
499
        }
500
501
        return $fp;
502
    }
503
504
    /**
505
     * Send command
506
     *
507
     * @todo Fake response doesn't need json encoding?
508
     * @todo Write debug entry on failure
509
     *
510
     * @param string $action
511
     * @param array  $data
512
     *
513
     * @return \Longman\TelegramBot\Entities\ServerResponse
514
     * @throws \Longman\TelegramBot\Exception\TelegramException
515
     */
516
    public static function send($action, array $data = [])
517
    {
518
        self::ensureValidAction($action);
519
        self::addDummyParamIfNecessary($action, $data);
520
521
        $bot_username = self::$telegram->getBotUsername();
522
523
        if (defined('PHPUNIT_TESTSUITE')) {
524
            $fake_response = self::generateGeneralFakeServerResponse($data);
525
526
            return new ServerResponse($fake_response, $bot_username);
527
        }
528
529
        self::ensureNonEmptyData($data);
530
531
        self::limitTelegramRequests($action, $data);
532
533
        $raw_response = self::execute($action, $data);
534
        $response = json_decode($raw_response, true);
535
536
        if (null === $response) {
537
            TelegramLog::debug($raw_response);
538
            throw new TelegramException('Telegram returned an invalid response!');
539
        }
540
541
        $response = new ServerResponse($response, $bot_username);
542
543
        if (!$response->isOk() && $response->getErrorCode() === 401 && $response->getDescription() === 'Unauthorized') {
544
            throw new InvalidBotTokenException();
545
        }
546
547
        return $response;
548
    }
549
550
    /**
551
     * Add a dummy parameter if the passed action requires it.
552
     *
553
     * If a method doesn't require parameters, we need to add a dummy one anyway,
554
     * because of some cURL version failed POST request without parameters.
555
     *
556
     * @link https://github.com/php-telegram-bot/core/pull/228
557
     *
558
     * @todo Would be nice to find a better solution for this!
559
     *
560
     * @param string $action
561
     * @param array  $data
562
     */
563
    protected static function addDummyParamIfNecessary($action, array &$data)
564
    {
565
        if (in_array($action, self::$actions_need_dummy_param, true)) {
566
            // Can be anything, using a single letter to minimise request size.
567
            $data = ['d'];
568
        }
569
    }
570
571
    /**
572
     * Make sure the data isn't empty, else throw an exception
573
     *
574
     * @param array $data
575
     *
576
     * @throws \Longman\TelegramBot\Exception\TelegramException
577
     */
578
    private static function ensureNonEmptyData(array $data)
579
    {
580
        if (count($data) === 0) {
581
            throw new TelegramException('Data is empty!');
582
        }
583
    }
584
585
    /**
586
     * Make sure the action is valid, else throw an exception
587
     *
588
     * @param string $action
589
     *
590
     * @throws \Longman\TelegramBot\Exception\TelegramException
591
     */
592
    private static function ensureValidAction($action)
593
    {
594
        if (!in_array($action, self::$actions, true)) {
595
            throw new TelegramException('The action "' . $action . '" doesn\'t exist!');
596
        }
597
    }
598
599
    /**
600
     * Use this method to send text messages. On success, the sent Message is returned
601
     *
602
     * @link https://core.telegram.org/bots/api#sendmessage
603
     *
604
     * @param array $data
605
     *
606
     * @return \Longman\TelegramBot\Entities\ServerResponse
607
     * @throws \Longman\TelegramBot\Exception\TelegramException
608
     */
609
    public static function sendMessage(array $data)
610
    {
611
        $text = $data['text'];
612
613
        do {
614
            //Chop off and send the first message
615
            $data['text'] = mb_substr($text, 0, 4096);
616
            $response     = self::send('sendMessage', $data);
617
618
            //Prepare the next message
619
            $text = mb_substr($text, 4096);
620
        } while (mb_strlen($text, 'UTF-8') > 0);
621
622
        return $response;
623
    }
624
625
    /**
626
     * Any statically called method should be relayed to the `send` method.
627
     *
628
     * @param string $action
629
     * @param array  $data
630
     *
631
     * @return \Longman\TelegramBot\Entities\ServerResponse
632
     * @throws \Longman\TelegramBot\Exception\TelegramException
633
     */
634
    public static function __callStatic($action, array $data)
635
    {
636
        // Make sure to add the action being called as the first parameter to be passed.
637
        array_unshift($data, $action);
638
639
        // @todo Use splat operator for unpacking when we move to PHP 5.6+
640
        return call_user_func_array('static::send', $data);
641
    }
642
643
    /**
644
     * Return an empty Server Response
645
     *
646
     * No request to telegram are sent, this function is used in commands that
647
     * don't need to fire a message after execution
648
     *
649
     * @return \Longman\TelegramBot\Entities\ServerResponse
650
     * @throws \Longman\TelegramBot\Exception\TelegramException
651
     */
652
    public static function emptyResponse()
653
    {
654
        return new ServerResponse(['ok' => true, 'result' => true], null);
655
    }
656
657
    /**
658
     * Send message to all active chats
659
     *
660
     * @param string $callback_function
661
     * @param array  $data
662
     * @param array  $select_chats_params
663
     *
664
     * @return array
665
     * @throws TelegramException
666
     */
667
    public static function sendToActiveChats(
668
        $callback_function,
669
        array $data,
670
        array $select_chats_params
671
    ) {
672
        self::ensureValidAction($callback_function);
673
674
        $chats = DB::selectChats($select_chats_params);
675
676
        $results = [];
677
        if (is_array($chats)) {
678
            foreach ($chats as $row) {
679
                $data['chat_id'] = $row['chat_id'];
680
                $results[]       = self::send($callback_function, $data);
681
            }
682
        }
683
684
        return $results;
685
    }
686
687
    /**
688
     * Enable request limiter
689
     *
690
     * @param boolean $enable
691
     * @param array   $options
692
     *
693
     * @throws \Longman\TelegramBot\Exception\TelegramException
694
     */
695
    public static function setLimiter($enable = true, array $options = [])
696
    {
697
        if (DB::isDbConnected()) {
698
            $options_default = [
699
                'interval' => 1,
700
            ];
701
702
            $options = array_merge($options_default, $options);
703
704
            if (!is_numeric($options['interval']) || $options['interval'] <= 0) {
705
                throw new TelegramException('Interval must be a number and must be greater than zero!');
706
            }
707
708
            self::$limiter_interval = $options['interval'];
0 ignored issues
show
Documentation Bug introduced by
It seems like $options['interval'] can also be of type integer or string. However, the property $limiter_interval is declared as type double. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
709
            self::$limiter_enabled  = $enable;
710
        }
711
    }
712
713
    /**
714
     * This functions delays API requests to prevent reaching Telegram API limits
715
     *  Can be disabled while in execution by 'Request::setLimiter(false)'
716
     *
717
     * @link https://core.telegram.org/bots/faq#my-bot-is-hitting-limits-how-do-i-avoid-this
718
     *
719
     * @param string $action
720
     * @param array  $data
721
     *
722
     * @throws \Longman\TelegramBot\Exception\TelegramException
723
     */
724
    private static function limitTelegramRequests($action, array $data = [])
725
    {
726
        if (self::$limiter_enabled) {
727
            $limited_methods = [
728
                'sendMessage',
729
                'forwardMessage',
730
                'sendPhoto',
731
                'sendAudio',
732
                'sendDocument',
733
                'sendSticker',
734
                'sendVideo',
735
                'sendAnimation',
736
                'sendVoice',
737
                'sendVideoNote',
738
                'sendMediaGroup',
739
                'sendLocation',
740
                'editMessageLiveLocation',
741
                'stopMessageLiveLocation',
742
                'sendVenue',
743
                'sendContact',
744
                'sendInvoice',
745
                'sendGame',
746
                'setGameScore',
747
                'editMessageText',
748
                'editMessageCaption',
749
                'editMessageMedia',
750
                'editMessageReplyMarkup',
751
                'setChatTitle',
752
                'setChatDescription',
753
                'setChatStickerSet',
754
                'deleteChatStickerSet',
755
                'setPassportDataErrors',
756
            ];
757
758
            $chat_id           = isset($data['chat_id']) ? $data['chat_id'] : null;
759
            $inline_message_id = isset($data['inline_message_id']) ? $data['inline_message_id'] : null;
760
761
            if (($chat_id || $inline_message_id) && in_array($action, $limited_methods)) {
762
                $timeout = 60;
763
764
                while (true) {
765
                    if ($timeout <= 0) {
766
                        throw new TelegramException('Timed out while waiting for a request spot!');
767
                    }
768
769
                    $requests = DB::getTelegramRequestCount($chat_id, $inline_message_id);
770
771
                    $chat_per_second   = ($requests['LIMIT_PER_SEC'] == 0); // No more than one message per second inside a particular chat
772
                    $global_per_second = ($requests['LIMIT_PER_SEC_ALL'] < 30);    // No more than 30 messages per second to different chats
773
                    $groups_per_minute = (((is_numeric($chat_id) && $chat_id > 0) || !is_null($inline_message_id)) || ((!is_numeric($chat_id) || $chat_id < 0) && $requests['LIMIT_PER_MINUTE'] < 20));    // No more than 20 messages per minute in groups and channels
774
775
                    if ($chat_per_second && $global_per_second && $groups_per_minute) {
776
                        break;
777
                    }
778
779
                    $timeout--;
780
                    usleep(self::$limiter_interval * 1000000);
781
                }
782
783
                DB::insertTelegramRequest($action, $data);
784
            }
785
        }
786
    }
787
}
788