Completed
Pull Request — develop (#865)
by Saeed
02:47
created

Request::send()   B

Complexity

Conditions 6
Paths 4

Size

Total Lines 35

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 42

Importance

Changes 0
Metric Value
dl 0
loc 35
ccs 0
cts 19
cp 0
rs 8.7377
c 0
b 0
f 0
cc 6
nc 4
nop 2
crap 42
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 Longman\TelegramBot\Entities\File;
16
use Longman\TelegramBot\Entities\ServerResponse;
17
use Longman\TelegramBot\Exception\InvalidBotTokenException;
18
use Longman\TelegramBot\Exception\TelegramException;
19
20
/**
21
 * Class Request
22
 *
23
 * @method static ServerResponse getUpdates(array $data)              Use this method to receive incoming updates using long polling (wiki). An Array of Update objects is returned.
24
 * @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.
25
 * @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.
26
 * @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.
27
 * @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.
28
 * @method static ServerResponse forwardMessage(array $data)          Use this method to forward messages of any kind. On success, the sent Message is returned.
29
 * @method static ServerResponse sendPhoto(array $data)               Use this method to send photos. On success, the sent Message is returned.
30
 * @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.
31
 * @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.
32
 * @method static ServerResponse sendSticker(array $data)             Use this method to send .webp stickers. On success, the sent Message is returned.
33
 * @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.
34
 * @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.
35
 * @method static ServerResponse sendVideoNote(array $data)           Use this method to send video messages. On success, the sent Message is returned.
36
 * @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.
37
 * @method static ServerResponse sendLocation(array $data)            Use this method to send point on the map. On success, the sent Message is returned.
38
 * @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.
39
 * @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.
40
 * @method static ServerResponse sendVenue(array $data)               Use this method to send information about a venue. On success, the sent Message is returned.
41
 * @method static ServerResponse sendContact(array $data)             Use this method to send phone contacts. On success, the sent Message is returned.
42
 * @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.
43
 * @method static ServerResponse getUserProfilePhotos(array $data)    Use this method to get a list of profile pictures for a user. Returns a UserProfilePhotos object.
44
 * @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.
45
 * @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.
46
 * @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.
47
 * @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.
48
 * @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.
49
 * @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.
50
 * @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.
51
 * @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.
52
 * @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.
53
 * @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.
54
 * @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.
55
 * @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.
56
 * @method static ServerResponse leaveChat(array $data)               Use this method for your bot to leave a group, supergroup or channel. Returns True on success.
57
 * @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.
58
 * @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.
59
 * @method static ServerResponse getChatMembersCount(array $data)     Use this method to get the number of members in a chat. Returns Int on success.
60
 * @method static ServerResponse getChatMember(array $data)           Use this method to get information about a member of a chat. Returns a ChatMember object on success.
61
 * @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.
62
 * @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.
63
 * @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.
64
 * @method static ServerResponse answerInlineQuery(array $data)       Use this method to send answers to an inline query. On success, True is returned.
65
 * @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.
66
 * @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.
67
 * @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.
68
 * @method static ServerResponse deleteMessage(array $data)           Use this method to delete a message, including service messages, with certain limitations. Returns True on success.
69
 * @method static ServerResponse getStickerSet(array $data)           Use this method to get a sticker set. On success, a StickerSet object is returned.
70
 * @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.
71
 * @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.
72
 * @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.
73
 * @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.
74
 * @method static ServerResponse deleteStickerFromSet(array $data)    Use this method to delete a sticker from a set created by the bot. Returns True on success.
75
 * @method static ServerResponse sendInvoice(array $data)             Use this method to send invoices. On success, the sent Message is returned.
76
 * @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.
77
 * @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.
78
 * @method static ServerResponse sendGame(array $data)                Use this method to send a game. On success, the sent Message is returned.
79
 * @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.
80
 * @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.
81
 */
82
class Request
83
{
84
    /**
85
     * Telegram object
86
     *
87
     * @var \Longman\TelegramBot\Telegram
88
     */
89
    private static $telegram;
90
91
    /**
92
     * URI of the Telegram API
93
     *
94
     * @var string
95
     */
96
    private static $api_base_uri = 'https://api.telegram.org';
97
98
    /**
99
     * Guzzle Client object
100
     *
101
     * @var \GuzzleHttp\Client
102
     */
103
    private static $client;
104
105
    /**
106
     * Input value of the request
107
     *
108
     * @var string
109
     */
110
    private static $input;
111
112
    /**
113
     * Request limiter
114
     *
115
     * @var boolean
116
     */
117
    private static $limiter_enabled;
118
119
    /**
120
     * Request limiter's interval between checks
121
     *
122
     * @var float
123
     */
124
    private static $limiter_interval;
125
126
    /**
127
     * Available actions to send
128
     *
129
     * This is basically the list of all methods listed on the official API documentation.
130
     *
131
     * @link https://core.telegram.org/bots/api
132
     *
133
     * @var array
134
     */
135
    private static $actions = [
136
        'getUpdates',
137
        'setWebhook',
138
        'deleteWebhook',
139
        'getWebhookInfo',
140
        'getMe',
141
        'sendMessage',
142
        'forwardMessage',
143
        'sendPhoto',
144
        'sendAudio',
145
        'sendDocument',
146
        'sendSticker',
147
        'sendVideo',
148
        'sendVoice',
149
        'sendVideoNote',
150
        'sendMediaGroup',
151
        'sendLocation',
152
        'editMessageLiveLocation',
153
        'stopMessageLiveLocation',
154
        'sendVenue',
155
        'sendContact',
156
        'sendChatAction',
157
        'getUserProfilePhotos',
158
        'getFile',
159
        'kickChatMember',
160
        'unbanChatMember',
161
        'restrictChatMember',
162
        'promoteChatMember',
163
        'exportChatInviteLink',
164
        'setChatPhoto',
165
        'deleteChatPhoto',
166
        'setChatTitle',
167
        'setChatDescription',
168
        'pinChatMessage',
169
        'unpinChatMessage',
170
        'leaveChat',
171
        'getChat',
172
        'getChatAdministrators',
173
        'getChatMembersCount',
174
        'getChatMember',
175
        'setChatStickerSet',
176
        'deleteChatStickerSet',
177
        'answerCallbackQuery',
178
        'answerInlineQuery',
179
        'editMessageText',
180
        'editMessageCaption',
181
        'editMessageReplyMarkup',
182
        'deleteMessage',
183
        'getStickerSet',
184
        'uploadStickerFile',
185
        'createNewStickerSet',
186
        'addStickerToSet',
187
        'setStickerPositionInSet',
188
        'deleteStickerFromSet',
189
        'sendInvoice',
190
        'answerShippingQuery',
191
        'answerPreCheckoutQuery',
192
        'sendGame',
193
        'setGameScore',
194
        'getGameHighScores',
195
    ];
196
197
    /**
198
     * Some methods need a dummy param due to certain cURL issues.
199
     *
200
     * @see Request::addDummyParamIfNecessary()
201
     *
202
     * @var array
203
     */
204
    private static $actions_need_dummy_param = [
205
        'deleteWebhook',
206
        'getWebhookInfo',
207
        'getMe',
208
    ];
209
210
    /**
211
     * Initialize
212
     *
213
     * @param \Longman\TelegramBot\Telegram $telegram
214
     *
215
     * @throws TelegramException
216
     */
217 30
    public static function initialize(Telegram $telegram)
218
    {
219 30
        if (!($telegram instanceof Telegram)) {
220
            throw new TelegramException('Invalid Telegram pointer!');
221
        }
222
223 30
        self::$telegram = $telegram;
224 30
        self::setClient(new Client(['base_uri' => self::$api_base_uri]));
225 30
    }
226
227
    /**
228
     * Set a custom Guzzle HTTP Client object
229
     *
230
     * @param Client $client
231
     *
232
     * @throws TelegramException
233
     */
234 30
    public static function setClient(Client $client)
235
    {
236 30
        if (!($client instanceof Client)) {
237
            throw new TelegramException('Invalid GuzzleHttp\Client pointer!');
238
        }
239
240 30
        self::$client = $client;
241 30
    }
242
243
    /**
244
     * Set input from custom input or stdin and return it
245
     *
246
     * @return string
247
     * @throws \Longman\TelegramBot\Exception\TelegramException
248
     */
249
    public static function getInput()
250
    {
251
        // First check if a custom input has been set, else get the PHP input.
252
        if (!($input = self::$telegram->getCustomInput())) {
253
            $input = file_get_contents('php://input');
254
        }
255
256
        // Make sure we have a string to work with.
257
        if (!is_string($input)) {
258
            throw new TelegramException('Input must be a string!');
259
        }
260
261
        self::$input = $input;
262
263
        TelegramLog::update(self::$input);
264
265
        return self::$input;
266
    }
267
268
    /**
269
     * Generate general fake server response
270
     *
271
     * @param array $data Data to add to fake response
272
     *
273
     * @return array Fake response data
274
     */
275 1
    public static function generateGeneralFakeServerResponse(array $data = [])
276
    {
277
        //PARAM BINDED IN PHPUNIT TEST FOR TestServerResponse.php
278
        //Maybe this is not the best possible implementation
279
280
        //No value set in $data ie testing setWebhook
281
        //Provided $data['chat_id'] ie testing sendMessage
282
283 1
        $fake_response = ['ok' => true]; // :)
284
285 1
        if ($data === []) {
286 1
            $fake_response['result'] = true;
287
        }
288
289
        //some data to let iniatilize the class method SendMessage
290 1
        if (isset($data['chat_id'])) {
291 1
            $data['message_id'] = '1234';
292 1
            $data['date']       = '1441378360';
293 1
            $data['from']       = [
294
                'id'         => 123456789,
295
                'first_name' => 'botname',
296
                'username'   => 'namebot',
297
            ];
298 1
            $data['chat']       = ['id' => $data['chat_id']];
299
300 1
            $fake_response['result'] = $data;
301
        }
302
303 1
        return $fake_response;
304
    }
305
306
    /**
307
     * Properly set up the request params
308
     *
309
     * If any item of the array is a resource, reformat it to a multipart request.
310
     * Else, just return the passed data as form params.
311
     *
312
     * @param array $data
313
     *
314
     * @return array
315
     */
316
    private static function setUpRequestParams(array $data)
317
    {
318
        $has_resource = false;
319
        $multipart    = [];
320
321
        // Convert any nested arrays into JSON strings.
322
        array_walk($data, function (&$item) {
323
            is_array($item) && $item = json_encode($item);
324
        });
325
326
        //Reformat data array in multipart way if it contains a resource
327
        foreach ($data as $key => $item) {
328
            $has_resource |= (is_resource($item) || $item instanceof \GuzzleHttp\Psr7\Stream);
329
            $multipart[]  = ['name' => $key, 'contents' => $item];
330
        }
331
        if ($has_resource) {
332
            return ['multipart' => $multipart];
333
        }
334
335
        return ['form_params' => $data];
336
    }
337
338
    /**
339
     * Execute HTTP Request
340
     *
341
     * @param string $action Action to execute
342
     * @param array  $data   Data to attach to the execution
343
     *
344
     * @return string Result of the HTTP Request
345
     * @throws \Longman\TelegramBot\Exception\TelegramException
346
     */
347
    public static function execute($action, array $data = [])
348
    {
349
        //Fix so that the keyboard markup is a string, not an object
350
        if (isset($data['reply_markup'])) {
351
            $data['reply_markup'] = json_encode($data['reply_markup']);
352
        }
353
354
        $result                  = null;
355
        $request_params          = self::setUpRequestParams($data);
356
        $request_params['debug'] = TelegramLog::getDebugLogTempStream();
357
358
        try {
359
            $response = self::$client->post(
360
                '/bot' . self::$telegram->getApiKey() . '/' . $action,
361
                $request_params
362
            );
363
            $result   = (string) $response->getBody();
364
365
            //Logging getUpdates Update
366
            if ($action === 'getUpdates') {
367
                TelegramLog::update($result);
368
            }
369
        } catch (RequestException $e) {
370
            $result = ($e->getResponse()) ? (string) $e->getResponse()->getBody() : '';
371
        } finally {
372
            //Logging verbose debug output
373
            TelegramLog::endDebugLogTempStream('Verbose HTTP Request output:' . PHP_EOL . '%s' . PHP_EOL);
374
        }
375
376
        return $result;
377
    }
378
379
    /**
380
     * Download file
381
     *
382
     * @param \Longman\TelegramBot\Entities\File $file
383
     *
384
     * @return boolean
385
     * @throws \Longman\TelegramBot\Exception\TelegramException
386
     */
387
    public static function downloadFile(File $file)
388
    {
389
        if (empty($download_path = self::$telegram->getDownloadPath())) {
390
            throw new TelegramException('Download path not set!');
391
        }
392
393
        $tg_file_path = $file->getFilePath();
394
        $file_path    = $download_path . '/' . $tg_file_path;
395
396
        $file_dir = dirname($file_path);
397
        //For safety reasons, first try to create the directory, then check that it exists.
398
        //This is in case some other process has created the folder in the meantime.
399
        if (!@mkdir($file_dir, 0755, true) && !is_dir($file_dir)) {
400
            throw new TelegramException('Directory ' . $file_dir . ' can\'t be created');
401
        }
402
403
        $debug_handle = TelegramLog::getDebugLogTempStream();
404
405
        try {
406
            self::$client->get(
407
                '/file/bot' . self::$telegram->getApiKey() . '/' . $tg_file_path,
408
                ['debug' => $debug_handle, 'sink' => $file_path]
409
            );
410
411
            return filesize($file_path) > 0;
412
        } catch (RequestException $e) {
413
            return ($e->getResponse()) ? (string) $e->getResponse()->getBody() : '';
414
        } finally {
415
            //Logging verbose debug output
416
            TelegramLog::endDebugLogTempStream('Verbose HTTP File Download Request output:' . PHP_EOL . '%s' . PHP_EOL);
417
        }
418
    }
419
420
    /**
421
     * Encode file
422
     *
423
     * @param string $file
424
     *
425
     * @return resource
426
     * @throws \Longman\TelegramBot\Exception\TelegramException
427
     */
428
    public static function encodeFile($file)
429
    {
430
        $fp = fopen($file, 'rb');
431
        if ($fp === false) {
432
            throw new TelegramException('Cannot open "' . $file . '" for reading');
433
        }
434
435
        return $fp;
436
    }
437
438
    /**
439
     * Send command
440
     *
441
     * @todo Fake response doesn't need json encoding?
442
     * @todo Write debug entry on failure
443
     *
444
     * @param string $action
445
     * @param array  $data
446
     *
447
     * @return \Longman\TelegramBot\Entities\ServerResponse
448
     * @throws \Longman\TelegramBot\Exception\TelegramException
449
     */
450
    public static function send($action, array $data = [])
451
    {
452
        self::ensureValidAction($action);
453
        self::addDummyParamIfNecessary($action, $data);
454
455
        $bot_username = self::$telegram->getBotUsername();
456
457
        if (defined('PHPUNIT_TESTSUITE')) {
458
            $fake_response = self::generateGeneralFakeServerResponse($data);
459
460
            return new ServerResponse($fake_response, $bot_username);
461
        }
462
463
        self::ensureNonEmptyData($data);
464
465
        self::limitTelegramRequests($action, $data);
466
467
        self::sendChatActionIfNecessary($action, $data);
468
469
        $raw_response = self::execute($action, $data);
470
        $response = json_decode($raw_response, true);
471
472
        if (null === $response) {
473
            TelegramLog::debug($raw_response);
474
            throw new TelegramException('Telegram returned an invalid response!');
475
        }
476
477
        $response = new ServerResponse($response, $bot_username);
478
479
        if (!$response->isOk() && $response->getErrorCode() === 401 && $response->getDescription() === 'Unauthorized') {
480
            throw new InvalidBotTokenException();
481
        }
482
483
        return $response;
484
    }
485
486
    /**
487
     * Add a dummy parameter if the passed action requires it.
488
     *
489
     * If a method doesn't require parameters, we need to add a dummy one anyway,
490
     * because of some cURL version failed POST request without parameters.
491
     *
492
     * @link https://github.com/php-telegram-bot/core/pull/228
493
     *
494
     * @todo Would be nice to find a better solution for this!
495
     *
496
     * @param string $action
497
     * @param array  $data
498
     */
499
    protected static function addDummyParamIfNecessary($action, array &$data)
500
    {
501
        if (in_array($action, self::$actions_need_dummy_param, true)) {
502
            // Can be anything, using a single letter to minimise request size.
503
            $data = ['d'];
504
        }
505
    }
506
507
    /**
508
     * Make sure the data isn't empty, else throw an exception
509
     *
510
     * @param array $data
511
     *
512
     * @throws \Longman\TelegramBot\Exception\TelegramException
513
     */
514
    private static function ensureNonEmptyData(array $data)
515
    {
516
        if (count($data) === 0) {
517
            throw new TelegramException('Data is empty!');
518
        }
519
    }
520
521
    /**
522
     * Make sure the action is valid, else throw an exception
523
     *
524
     * @param string $action
525
     *
526
     * @throws \Longman\TelegramBot\Exception\TelegramException
527
     */
528
    private static function ensureValidAction($action)
529
    {
530
        if (!in_array($action, self::$actions, true)) {
531
            throw new TelegramException('The action "' . $action . '" doesn\'t exist!');
532
        }
533
    }
534
535
    /**
536
     * Use this method to send text messages. On success, the sent Message is returned
537
     *
538
     * @link https://core.telegram.org/bots/api#sendmessage
539
     *
540
     * @param array $data
541
     *
542
     * @return \Longman\TelegramBot\Entities\ServerResponse
543
     * @throws \Longman\TelegramBot\Exception\TelegramException
544
     */
545
    public static function sendMessage(array $data)
546
    {
547
        $text = $data['text'];
548
549
        do {
550
            //Chop off and send the first message
551
            $data['text'] = mb_substr($text, 0, 4096);
552
            $response     = self::send('sendMessage', $data);
553
554
            //Prepare the next message
555
            $text = mb_substr($text, 4096);
556
        } while (mb_strlen($text, 'UTF-8') > 0);
557
558
        return $response;
559
    }
560
561
    /**
562
     * Any statically called method should be relayed to the `send` method.
563
     *
564
     * @param string $action
565
     * @param array  $data
566
     *
567
     * @return \Longman\TelegramBot\Entities\ServerResponse
568
     * @throws \Longman\TelegramBot\Exception\TelegramException
569
     */
570
    public static function __callStatic($action, array $data)
571
    {
572
        // Make sure to add the action being called as the first parameter to be passed.
573
        array_unshift($data, $action);
574
575
        // @todo Use splat operator for unpacking when we move to PHP 5.6+
576
        return call_user_func_array('static::send', $data);
577
    }
578
579
    /**
580
     * Return an empty Server Response
581
     *
582
     * No request to telegram are sent, this function is used in commands that
583
     * don't need to fire a message after execution
584
     *
585
     * @return \Longman\TelegramBot\Entities\ServerResponse
586
     * @throws \Longman\TelegramBot\Exception\TelegramException
587
     */
588
    public static function emptyResponse()
589
    {
590
        return new ServerResponse(['ok' => true, 'result' => true], null);
591
    }
592
593
    /**
594
     * Send message to all active chats
595
     *
596
     * @param string $callback_function
597
     * @param array  $data
598
     * @param array  $select_chats_params
599
     *
600
     * @return array
601
     * @throws TelegramException
602
     */
603
    public static function sendToActiveChats(
604
        $callback_function,
605
        array $data,
606
        array $select_chats_params
607
    ) {
608
        if (!method_exists(Request::class, $callback_function)) {
609
            throw new TelegramException('Method "' . $callback_function . '" not found in class Request.');
610
        }
611
612
        $chats = DB::selectChats($select_chats_params);
613
614
        $results = [];
615
        if (is_array($chats)) {
616
            foreach ($chats as $row) {
617
                $data['chat_id'] = $row['chat_id'];
618
                $results[]       = call_user_func(Request::class . '::' . $callback_function, $data);
619
            }
620
        }
621
622
        return $results;
623
    }
624
625
    /**
626
     * Enable request limiter
627
     *
628
     * @param boolean $enable
629
     * @param array   $options
630
     *
631
     * @throws \Longman\TelegramBot\Exception\TelegramException
632
     */
633
    public static function setLimiter($enable = true, array $options = [])
634
    {
635
        if (DB::isDbConnected()) {
636
            $options_default = [
637
                'interval' => 1,
638
            ];
639
640
            $options = array_merge($options_default, $options);
641
642
            if (!is_numeric($options['interval']) || $options['interval'] <= 0) {
643
                throw new TelegramException('Interval must be a number and must be greater than zero!');
644
            }
645
646
            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...
647
            self::$limiter_enabled  = $enable;
648
        }
649
    }
650
651
    /**
652
     * This functions delays API requests to prevent reaching Telegram API limits
653
     *  Can be disabled while in execution by 'Request::setLimiter(false)'
654
     *
655
     * @link https://core.telegram.org/bots/faq#my-bot-is-hitting-limits-how-do-i-avoid-this
656
     *
657
     * @param string $action
658
     * @param array  $data
659
     *
660
     * @throws \Longman\TelegramBot\Exception\TelegramException
661
     */
662
    private static function limitTelegramRequests($action, array $data = [])
663
    {
664
        if (self::$limiter_enabled) {
665
            $limited_methods = [
666
                'sendMessage',
667
                'forwardMessage',
668
                'sendPhoto',
669
                'sendAudio',
670
                'sendDocument',
671
                'sendSticker',
672
                'sendVideo',
673
                'sendVoice',
674
                'sendVideoNote',
675
                'sendMediaGroup',
676
                'sendLocation',
677
                'editMessageLiveLocation',
678
                'stopMessageLiveLocation',
679
                'sendVenue',
680
                'sendContact',
681
                'sendInvoice',
682
                'sendGame',
683
                'setGameScore',
684
                'editMessageText',
685
                'editMessageCaption',
686
                'editMessageReplyMarkup',
687
                'setChatTitle',
688
                'setChatDescription',
689
                'setChatStickerSet',
690
                'deleteChatStickerSet',
691
            ];
692
693
            $chat_id           = isset($data['chat_id']) ? $data['chat_id'] : null;
694
            $inline_message_id = isset($data['inline_message_id']) ? $data['inline_message_id'] : null;
695
696
            if (($chat_id || $inline_message_id) && in_array($action, $limited_methods)) {
697
                $timeout = 60;
698
699
                while (true) {
700
                    if ($timeout <= 0) {
701
                        throw new TelegramException('Timed out while waiting for a request spot!');
702
                    }
703
704
                    $requests = DB::getTelegramRequestCount($chat_id, $inline_message_id);
705
706
                    $chat_per_second   = ($requests['LIMIT_PER_SEC'] == 0); // No more than one message per second inside a particular chat
707
                    $global_per_second = ($requests['LIMIT_PER_SEC_ALL'] < 30);    // No more than 30 messages per second to different chats
708
                    $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
709
710
                    if ($chat_per_second && $global_per_second && $groups_per_minute) {
711
                        break;
712
                    }
713
714
                    $timeout--;
715
                    usleep(self::$limiter_interval * 1000000);
716
                }
717
718
                DB::insertTelegramRequest($action, $data);
719
            }
720
        }
721
    }
722
723
724
725
    private static function sendChatActionIfNecessary($action, $data)
726
    {
727
728
        if (!isset($data['sendChatAction'])) {
729
            return false;
730
        }
731
732
        if ($data['sendChatAction'] === true) {
733
            return false;
734
        }
735
736
        $chatAction = null;
0 ignored issues
show
Unused Code introduced by
$chatAction is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
737
        switch ($action) {
738
            case 'sendMessage':
739
                $chatAction = ChatAction::TYPING;
740
                break;
741
            case 'sendPhoto':
742
                $chatAction = ChatAction::UPLOAD_PHOTO;
743
                break;
744
            case 'sendAudio':
745
                $chatAction = ChatAction::UPLOAD_AUDIO;
746
                break;
747
            case 'sendDocument':
748
                $chatAction = ChatAction::UPLOAD_DOCUMENT;
749
                break;
750
            case 'sendVideo':
751
                $chatAction = ChatAction::UPLOAD_VIDEO;
752
                break;
753
            case 'sendVoice':
754
                $chatAction = ChatAction::RECORD_AUDIO;
755
                break;
756
            case 'sendVideoNote':
757
                $chatAction = ChatAction::UPLOAD_VIDEO_NOTE;
758
                break;
759
            case 'sendLocation':
760
                $chatAction = ChatAction::FIND_LOCATION;
761
                break;
762
            default:
763
                $chatAction = ChatAction::TYPING;
764
                break;
765
        }
766
        $data['chatAction'] = $chatAction;
767
        self::sendChatAction($data);
768
    }
769
}
770