Completed
Push — develop ( 417d28...e71538 )
by Armando
23:49 queued 21:40
created

Request::editMessageReplyMarkup()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 4
ccs 0
cts 2
cp 0
rs 10
cc 1
eloc 2
nc 1
nop 1
crap 2
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\TelegramException;
18
19
class Request
20
{
21
    /**
22
     * Telegram object
23
     *
24
     * @var \Longman\TelegramBot\Telegram
25
     */
26
    private static $telegram;
27
28
    /**
29
     * URI of the Telegram API
30
     *
31
     * @var string
32
     */
33
    private static $api_base_uri = 'https://api.telegram.org';
34
35
    /**
36
     * Guzzle Client object
37
     *
38
     * @var \GuzzleHttp\Client
39
     */
40
    private static $client;
41
42
    /**
43
     * Input value of the request
44
     *
45
     * @var string
46
     */
47
    private static $input;
48
49
    /**
50
     * Available actions to send
51
     *
52
     * @var array
53
     */
54
    private static $actions = [
55
        'getUpdates',
56
        'setWebhook',
57
        'deleteWebhook',
58
        'getMe',
59
        'sendMessage',
60
        'forwardMessage',
61
        'sendPhoto',
62
        'sendAudio',
63
        'sendDocument',
64
        'sendSticker',
65
        'sendVideo',
66
        'sendVoice',
67
        'sendLocation',
68
        'sendVenue',
69
        'sendContact',
70
        'sendChatAction',
71
        'getUserProfilePhotos',
72
        'getFile',
73
        'kickChatMember',
74
        'leaveChat',
75
        'unbanChatMember',
76
        'getChat',
77
        'getChatAdministrators',
78
        'getChatMember',
79
        'getChatMembersCount',
80
        'answerCallbackQuery',
81
        'answerInlineQuery',
82
        'editMessageText',
83
        'editMessageCaption',
84
        'editMessageReplyMarkup',
85
        'getWebhookInfo',
86
    ];
87
88
    /**
89
     * Initialize
90
     *
91
     * @param \Longman\TelegramBot\Telegram $telegram
92
     *
93
     * @throws \Longman\TelegramBot\Exception\TelegramException
94
     */
95 39
    public static function initialize(Telegram $telegram)
96
    {
97 39
        if (is_object($telegram)) {
98 39
            self::$telegram = $telegram;
99 39
            self::$client   = new Client(['base_uri' => self::$api_base_uri]);
100
        } else {
101
            throw new TelegramException('Telegram pointer is empty!');
102
        }
103 39
    }
104
105
    /**
106
     * Set input from custom input or stdin and return it
107
     *
108
     * @return string
109
     * @throws \Longman\TelegramBot\Exception\TelegramException
110
     */
111
    public static function getInput()
112
    {
113
        // First check if a custom input has been set, else get the PHP input.
114
        if (!($input = self::$telegram->getCustomInput())) {
115
            $input = file_get_contents('php://input');
116
        }
117
118
        // Make sure we have a string to work with.
119
        if (is_string($input)) {
120
            self::$input = $input;
121
        } else {
122
            throw new TelegramException('Input must be a string!');
123
        }
124
125
        TelegramLog::update(self::$input);
126
127
        return self::$input;
128
    }
129
130
    /**
131
     * Generate general fake server response
132
     *
133
     * @param array $data Data to add to fake response
134
     *
135
     * @return array Fake response data
136
     */
137 6
    public static function generateGeneralFakeServerResponse(array $data = [])
138
    {
139
        //PARAM BINDED IN PHPUNIT TEST FOR TestServerResponse.php
140
        //Maybe this is not the best possible implementation
141
142
        //No value set in $data ie testing setWebhook
143
        //Provided $data['chat_id'] ie testing sendMessage
144
145 6
        $fake_response = ['ok' => true]; // :)
146
147 6
        if ($data === []) {
148 1
            $fake_response['result'] = true;
149
        }
150
151
        //some data to let iniatilize the class method SendMessage
152 6
        if (isset($data['chat_id'])) {
153 6
            $data['message_id'] = '1234';
154 6
            $data['date']       = '1441378360';
155 6
            $data['from']       = [
156
                'id'         => 123456789,
157
                'first_name' => 'botname',
158
                'username'   => 'namebot',
159
            ];
160 6
            $data['chat']       = ['id' => $data['chat_id']];
161
162 6
            $fake_response['result'] = $data;
163
        }
164
165 6
        return $fake_response;
166
    }
167
168
    /**
169
     * Properly set up the request params
170
     *
171
     * If any item of the array is a resource, reformat it to a multipart request.
172
     * Else, just return the passed data as form params.
173
     *
174
     * @param array $data
175
     *
176
     * @return array
177
     */
178
    private static function setUpRequestParams(array $data)
179
    {
180
        $has_resource = false;
181
        $multipart    = [];
182
183
        //Reformat data array in multipart way if it contains a resource
184
        foreach ($data as $key => $item) {
185
            $has_resource |= is_resource($item);
186
            is_array($item) && $item = json_encode($item);
187
            $multipart[] = ['name' => $key, 'contents' => $item];
188
        }
189
        if ($has_resource) {
190
            return ['multipart' => $multipart];
191
        }
192
193
        return ['form_params' => $data];
194
    }
195
196
    /**
197
     * Execute HTTP Request
198
     *
199
     * @param string $action Action to execute
200
     * @param array  $data   Data to attach to the execution
201
     *
202
     * @return string Result of the HTTP Request
203
     * @throws \Longman\TelegramBot\Exception\TelegramException
204
     */
205
    public static function execute($action, array $data = [])
206
    {
207
        //Fix so that the keyboard markup is a string, not an object
208
        if (isset($data['reply_markup'])) {
209
            $data['reply_markup'] = json_encode($data['reply_markup']);
210
        }
211
212
        $request_params = self::setUpRequestParams($data);
213
214
        $debug_handle            = TelegramLog::getDebugLogTempStream();
215
        $request_params['debug'] = $debug_handle;
216
217
        try {
218
            $response = self::$client->post(
219
                '/bot' . self::$telegram->getApiKey() . '/' . $action,
220
                $request_params
221
            );
222
            $result   = (string)$response->getBody();
223
224
            //Logging getUpdates Update
225
            if ($action === 'getUpdates') {
226
                TelegramLog::update($result);
227
            }
228
        } catch (RequestException $e) {
229
            $result = (string)$e->getResponse()->getBody();
230
        } finally {
231
            //Logging verbose debug output
232
            TelegramLog::endDebugLogTempStream("Verbose HTTP Request output:\n%s\n");
233
        }
234
235
        return $result;
0 ignored issues
show
Bug introduced by
The variable $result does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
236
    }
237
238
    /**
239
     * Download file
240
     *
241
     * @param \Longman\TelegramBot\Entities\File $file
242
     *
243
     * @return boolean
244
     * @throws \Longman\TelegramBot\Exception\TelegramException
245
     */
246
    public static function downloadFile(File $file)
247
    {
248
        $tg_file_path = $file->getFilePath();
249
        $file_path    = self::$telegram->getDownloadPath() . '/' . $tg_file_path;
250
251
        $file_dir = dirname($file_path);
252
        //For safety reasons, first try to create the directory, then check that it exists.
253
        //This is in case some other process has created the folder in the meantime.
254
        if (!@mkdir($file_dir, 0755, true) && !is_dir($file_dir)) {
255
            throw new TelegramException('Directory ' . $file_dir . ' can\'t be created');
256
        }
257
258
        $debug_handle = TelegramLog::getDebugLogTempStream();
259
260
        try {
261
            self::$client->get(
262
                '/file/bot' . self::$telegram->getApiKey() . '/' . $tg_file_path,
263
                ['debug' => $debug_handle, 'sink' => $file_path]
264
            );
265
266
            return filesize($file_path) > 0;
267
        } catch (RequestException $e) {
268
            return (string)$e->getResponse()->getBody();
269
        } finally {
270
            //Logging verbose debug output
271
            TelegramLog::endDebugLogTempStream("Verbose HTTP File Download Request output:\n%s\n");
272
        }
273
    }
274
275
    /**
276
     * Encode file
277
     *
278
     * @param string $file
279
     *
280
     * @return resource
281
     * @throws \Longman\TelegramBot\Exception\TelegramException
282
     */
283
    protected static function encodeFile($file)
284
    {
285
        $fp = fopen($file, 'r');
286
        if ($fp === false) {
287
            throw new TelegramException('Cannot open "' . $file . '" for reading');
288
        }
289
290
        return $fp;
291
    }
292
293
    /**
294
     * Send command
295
     *
296
     * @todo Fake response doesn't need json encoding?
297
     *
298
     * @param string $action
299
     * @param array  $data
300
     *
301
     * @return \Longman\TelegramBot\Entities\ServerResponse
302
     * @throws \Longman\TelegramBot\Exception\TelegramException
303
     */
304 5
    public static function send($action, array $data = [])
305
    {
306 5
        self::ensureValidAction($action);
307
308 5
        $bot_name = self::$telegram->getBotName();
309
310 5
        if (defined('PHPUNIT_TESTSUITE')) {
311 5
            $fake_response = self::generateGeneralFakeServerResponse($data);
312
313 5
            return new ServerResponse($fake_response, $bot_name);
314
        }
315
316
        self::ensureNonEmptyData($data);
317
318
        $response = json_decode(self::execute($action, $data), true);
319
320
        if (null === $response) {
321
            throw new TelegramException('Telegram returned an invalid response! Please review your bot name and API key.');
322
        }
323
324
        return new ServerResponse($response, $bot_name);
325
    }
326
327
    /**
328
     * Make sure the data isn't empty, else throw an exception
329
     *
330
     * @param array $data
331
     *
332
     * @throws \Longman\TelegramBot\Exception\TelegramException
333
     */
334
    private static function ensureNonEmptyData(array $data)
335
    {
336
        if (count($data) === 0) {
337
            throw new TelegramException('Data is empty!');
338
        }
339
    }
340
341
    /**
342
     * Make sure the action is valid, else throw an exception
343
     *
344
     * @param string $action
345
     *
346
     * @throws \Longman\TelegramBot\Exception\TelegramException
347
     */
348 5
    private static function ensureValidAction($action)
349
    {
350 5
        if (!in_array($action, self::$actions, true)) {
351
            throw new TelegramException('The action "' . $action . '" doesn\'t exist!');
352
        }
353 5
    }
354
355
    /**
356
     * Assign an encoded file to a data array
357
     *
358
     * @param array  $data
359
     * @param string $field
360
     * @param string $file
361
     *
362
     * @throws \Longman\TelegramBot\Exception\TelegramException
363
     */
364
    private static function assignEncodedFile(&$data, $field, $file)
365
    {
366
        if ($file !== null && $file !== '') {
367
            $data[$field] = self::encodeFile($file);
368
        }
369
    }
370
371
    /**
372
     * Returns basic information about the bot in form of a User object
373
     *
374
     * @link https://core.telegram.org/bots/api#getme
375
     *
376
     * @return \Longman\TelegramBot\Entities\ServerResponse
377
     * @throws \Longman\TelegramBot\Exception\TelegramException
378
     */
379
    public static function getMe()
380
    {
381
        // Added fake parameter, because of some cURL version failed POST request without parameters
382
        // see https://github.com/akalongman/php-telegram-bot/pull/228
383
        return self::send('getMe', ['whoami']);
384
    }
385
386
    /**
387
     * Use this method to send text messages. On success, the sent Message is returned
388
     *
389
     * @link https://core.telegram.org/bots/api#sendmessage
390
     *
391
     * @param array $data
392
     *
393
     * @return \Longman\TelegramBot\Entities\ServerResponse
394
     * @throws \Longman\TelegramBot\Exception\TelegramException
395
     */
396 5
    public static function sendMessage(array $data)
397
    {
398 5
        $text = $data['text'];
399
400
        do {
401
            //Chop off and send the first message
402 5
            $data['text'] = mb_substr($text, 0, 4096);
403 5
            $response     = self::send('sendMessage', $data);
404
405
            //Prepare the next message
406 5
            $text = mb_substr($text, 4096);
407 5
        } while (mb_strlen($text, 'UTF-8') > 0);
408
409 5
        return $response;
410
    }
411
412
    /**
413
     * Use this method to forward messages of any kind. On success, the sent Message is returned
414
     *
415
     * @link https://core.telegram.org/bots/api#forwardmessage
416
     *
417
     * @param array $data
418
     *
419
     * @return \Longman\TelegramBot\Entities\ServerResponse
420
     * @throws \Longman\TelegramBot\Exception\TelegramException
421
     */
422
    public static function forwardMessage(array $data)
423
    {
424
        return self::send('forwardMessage', $data);
425
    }
426
427
    /**
428
     * Use this method to send photos. On success, the sent Message is returned
429
     *
430
     * @link https://core.telegram.org/bots/api#sendphoto
431
     *
432
     * @param array  $data
433
     * @param string $file
434
     *
435
     * @return \Longman\TelegramBot\Entities\ServerResponse
436
     * @throws \Longman\TelegramBot\Exception\TelegramException
437
     */
438
    public static function sendPhoto(array $data, $file = null)
439
    {
440
        self::assignEncodedFile($data, 'photo', $file);
441
442
        return self::send('sendPhoto', $data);
443
    }
444
445
    /**
446
     * Use this method to send audio files
447
     *
448
     * Your audio must be in the .mp3 format. On success, the sent Message is returned.
449
     * Bots can currently send audio files of up to 50 MB in size, this limit may be changed in the future.
450
     * For sending voice messages, use the sendVoice method instead.
451
     *
452
     * @link https://core.telegram.org/bots/api#sendaudio
453
     *
454
     * @param array  $data
455
     * @param string $file
456
     *
457
     * @return \Longman\TelegramBot\Entities\ServerResponse
458
     * @throws \Longman\TelegramBot\Exception\TelegramException
459
     */
460
    public static function sendAudio(array $data, $file = null)
461
    {
462
        self::assignEncodedFile($data, 'audio', $file);
463
464
        return self::send('sendAudio', $data);
465
    }
466
467
    /**
468
     * Use this method to send general files. On success, the sent Message is returned.
469
     *
470
     * Bots can currently send files of any type of up to 50 MB in size, this limit may be changed in the future.
471
     *
472
     * @link https://core.telegram.org/bots/api#senddocument
473
     *
474
     * @param array  $data
475
     * @param string $file
476
     *
477
     * @return \Longman\TelegramBot\Entities\ServerResponse
478
     * @throws \Longman\TelegramBot\Exception\TelegramException
479
     */
480
    public static function sendDocument(array $data, $file = null)
481
    {
482
        self::assignEncodedFile($data, 'document', $file);
483
484
        return self::send('sendDocument', $data);
485
    }
486
487
    /**
488
     * Use this method to send .webp stickers. On success, the sent Message is returned.
489
     *
490
     * @link https://core.telegram.org/bots/api#sendsticker
491
     *
492
     * @param array  $data
493
     * @param string $file
494
     *
495
     * @return \Longman\TelegramBot\Entities\ServerResponse
496
     * @throws \Longman\TelegramBot\Exception\TelegramException
497
     */
498
    public static function sendSticker(array $data, $file = null)
499
    {
500
        self::assignEncodedFile($data, 'sticker', $file);
501
502
        return self::send('sendSticker', $data);
503
    }
504
505
    /**
506
     * Use this method to send video files. On success, the sent Message is returned.
507
     *
508
     * Telegram clients support mp4 videos (other formats may be sent as Document).
509
     * Bots can currently send video files of up to 50 MB in size, this limit may be changed in the future.
510
     *
511
     * @link https://core.telegram.org/bots/api#sendvideo
512
     *
513
     * @param array  $data
514
     * @param string $file
515
     *
516
     * @return \Longman\TelegramBot\Entities\ServerResponse
517
     * @throws \Longman\TelegramBot\Exception\TelegramException
518
     */
519
    public static function sendVideo(array $data, $file = null)
520
    {
521
        self::assignEncodedFile($data, 'video', $file);
522
523
        return self::send('sendVideo', $data);
524
    }
525
526
    /**
527
     * Use this method to send audio files. On success, the sent Message is returned.
528
     *
529
     * Telegram clients will display the file as a playable voice message.
530
     * For this to work, your audio must be in an .ogg file encoded with OPUS (other formats may be sent as Audio or Document).
531
     * Bots can currently send voice messages of up to 50 MB in size, this limit may be changed in the future.
532
     *
533
     * @link https://core.telegram.org/bots/api#sendvoice
534
     *
535
     * @param array  $data
536
     * @param string $file
537
     *
538
     * @return \Longman\TelegramBot\Entities\ServerResponse
539
     * @throws \Longman\TelegramBot\Exception\TelegramException
540
     */
541
    public static function sendVoice(array $data, $file = null)
542
    {
543
        self::assignEncodedFile($data, 'voice', $file);
544
545
        return self::send('sendVoice', $data);
546
    }
547
548
    /**
549
     * Use this method to send point on the map. On success, the sent Message is returned.
550
     *
551
     * @link https://core.telegram.org/bots/api#sendlocation
552
     *
553
     * @param array $data
554
     *
555
     * @return \Longman\TelegramBot\Entities\ServerResponse
556
     * @throws \Longman\TelegramBot\Exception\TelegramException
557
     */
558
    public static function sendLocation(array $data)
559
    {
560
        return self::send('sendLocation', $data);
561
    }
562
563
    /**
564
     * Use this method to send information about a venue. On success, the sent Message is returned.
565
     *
566
     * @link https://core.telegram.org/bots/api#sendvenue
567
     *
568
     * @param array $data
569
     *
570
     * @return \Longman\TelegramBot\Entities\ServerResponse
571
     * @throws \Longman\TelegramBot\Exception\TelegramException
572
     */
573
    public static function sendVenue(array $data)
574
    {
575
        return self::send('sendVenue', $data);
576
    }
577
578
    /**
579
     * Use this method to send phone contacts. On success, the sent Message is returned.
580
     *
581
     * @link https://core.telegram.org/bots/api#sendcontact
582
     *
583
     * @param array $data
584
     *
585
     * @return \Longman\TelegramBot\Entities\ServerResponse
586
     * @throws \Longman\TelegramBot\Exception\TelegramException
587
     */
588
    public static function sendContact(array $data)
589
    {
590
        return self::send('sendContact', $data);
591
    }
592
593
    /**
594
     * Use this method when you need to tell the user that something is happening on the bot's side.
595
     *
596
     * The status is set for 5 seconds or less.
597
     * (when a message arrives from your bot, Telegram clients clear its typing status)
598
     *
599
     * @link https://core.telegram.org/bots/api#sendchataction
600
     *
601
     * @param array $data
602
     *
603
     * @return \Longman\TelegramBot\Entities\ServerResponse
604
     * @throws \Longman\TelegramBot\Exception\TelegramException
605
     */
606
    public static function sendChatAction(array $data)
607
    {
608
        return self::send('sendChatAction', $data);
609
    }
610
611
    /**
612
     * Use this method to get a list of profile pictures for a user. Returns a UserProfilePhotos object.
613
     *
614
     * @param array $data
615
     *
616
     * @return \Longman\TelegramBot\Entities\ServerResponse
617
     * @throws \Longman\TelegramBot\Exception\TelegramException
618
     */
619
    public static function getUserProfilePhotos(array $data)
620
    {
621
        return self::send('getUserProfilePhotos', $data);
622
    }
623
624
    /**
625
     * Use this method to get basic info about a file and prepare it for downloading. On success, a File object is returned.
626
     *
627
     * For the moment, bots can download files of up to 20MB in size.
628
     * The file can then be downloaded via the link https://api.telegram.org/file/bot<token>/<file_path>,
629
     * where <file_path> is taken from the response.
630
     * It is guaranteed that the link will be valid for at least 1 hour.
631
     * When the link expires, a new one can be requested by calling getFile again.
632
     *
633
     * @link https://core.telegram.org/bots/api#getfile
634
     *
635
     * @param array $data
636
     *
637
     * @return \Longman\TelegramBot\Entities\ServerResponse
638
     * @throws \Longman\TelegramBot\Exception\TelegramException
639
     */
640
    public static function getFile(array $data)
641
    {
642
        return self::send('getFile', $data);
643
    }
644
645
    /**
646
     * Use this method to kick a user from a group or a supergroup. Returns True on success.
647
     *
648
     * In the case of supergroups, the user will not be able to return to the group on their own using invite links, etc., unless unbanned first.
649
     * The bot must be an administrator in the group for this to work.
650
     *
651
     * @link https://core.telegram.org/bots/api#kickchatmember
652
     *
653
     * @param array $data
654
     *
655
     * @return \Longman\TelegramBot\Entities\ServerResponse
656
     * @throws \Longman\TelegramBot\Exception\TelegramException
657
     */
658
    public static function kickChatMember(array $data)
659
    {
660
        return self::send('kickChatMember', $data);
661
    }
662
663
    /**
664
     * Use this method for your bot to leave a group, supergroup or channel. Returns True on success.
665
     *
666
     * @link https://core.telegram.org/bots/api#leavechat
667
     *
668
     * @param array $data
669
     *
670
     * @return \Longman\TelegramBot\Entities\ServerResponse
671
     * @throws \Longman\TelegramBot\Exception\TelegramException
672
     */
673
    public static function leaveChat(array $data)
674
    {
675
        return self::send('leaveChat', $data);
676
    }
677
678
    /**
679
     * Use this method to unban a previously kicked user in a supergroup. Returns True on success.
680
     *
681
     * The user will not return to the group automatically, but will be able to join via link, etc.
682
     * The bot must be an administrator in the group for this to work.
683
     *
684
     * @link https://core.telegram.org/bots/api#unbanchatmember
685
     *
686
     * @param array $data
687
     *
688
     * @return \Longman\TelegramBot\Entities\ServerResponse
689
     * @throws \Longman\TelegramBot\Exception\TelegramException
690
     */
691
    public static function unbanChatMember(array $data)
692
    {
693
        return self::send('unbanChatMember', $data);
694
    }
695
696
    /**
697
     * 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.
698
     *
699
     * @todo add get response in ServerResponse.php?
700
     *
701
     * @link https://core.telegram.org/bots/api#getchat
702
     *
703
     * @param array $data
704
     *
705
     * @return \Longman\TelegramBot\Entities\ServerResponse
706
     * @throws \Longman\TelegramBot\Exception\TelegramException
707
     */
708
    public static function getChat(array $data)
709
    {
710
        return self::send('getChat', $data);
711
    }
712
713
    /**
714
     * Use this method to get a list of administrators in a chat.
715
     *
716
     * On success, returns an Array of ChatMember objects that contains information about all chat administrators except other bots.
717
     * If the chat is a group or a supergroup and no administrators were appointed, only the creator will be returned.
718
     *
719
     * @todo add get response in ServerResponse.php?
720
     *
721
     * @link https://core.telegram.org/bots/api#getchatadministrators
722
     *
723
     * @param array $data
724
     *
725
     * @return \Longman\TelegramBot\Entities\ServerResponse
726
     * @throws \Longman\TelegramBot\Exception\TelegramException
727
     */
728
    public static function getChatAdministrators(array $data)
729
    {
730
        return self::send('getChatAdministrators', $data);
731
    }
732
733
    /**
734
     * Use this method to get the number of members in a chat. Returns Int on success.
735
     *
736
     * @todo add get response in ServerResponse.php?
737
     *
738
     * @link https://core.telegram.org/bots/api#getchatmemberscount
739
     *
740
     * @param array $data
741
     *
742
     * @return \Longman\TelegramBot\Entities\ServerResponse
743
     * @throws \Longman\TelegramBot\Exception\TelegramException
744
     */
745
    public static function getChatMembersCount(array $data)
746
    {
747
        return self::send('getChatMembersCount', $data);
748
    }
749
750
    /**
751
     * Use this method to get information about a member of a chat. Returns a ChatMember object on success.
752
     *
753
     * @todo add get response in ServerResponse.php?
754
     *
755
     * @link https://core.telegram.org/bots/api#getchatmember
756
     *
757
     * @param array $data
758
     *
759
     * @return \Longman\TelegramBot\Entities\ServerResponse
760
     * @throws \Longman\TelegramBot\Exception\TelegramException
761
     */
762
    public static function getChatMember(array $data)
763
    {
764
        return self::send('getChatMember', $data);
765
    }
766
767
    /**
768
     * Use this method to send answers to callback queries sent from inline keyboards. On success, True is returned.
769
     *
770
     * The answer will be displayed to the user as a notification at the top of the chat screen or as an alert.
771
     *
772
     * @link https://core.telegram.org/bots/api#answercallbackquery
773
     *
774
     * @param array $data
775
     *
776
     * @return \Longman\TelegramBot\Entities\ServerResponse
777
     * @throws \Longman\TelegramBot\Exception\TelegramException
778
     */
779
    public static function answerCallbackQuery(array $data)
780
    {
781
        return self::send('answerCallbackQuery', $data);
782
    }
783
784
    /**
785
     * Get updates
786
     *
787
     * @link https://core.telegram.org/bots/api#getupdates
788
     *
789
     * @param array $data
790
     *
791
     * @return \Longman\TelegramBot\Entities\ServerResponse
792
     * @throws \Longman\TelegramBot\Exception\TelegramException
793
     */
794
    public static function getUpdates(array $data)
795
    {
796
        return self::send('getUpdates', $data);
797
    }
798
799
    /**
800
     * Set webhook
801
     *
802
     * @link https://core.telegram.org/bots/api#setwebhook
803
     *
804
     * @param string $url
805
     * @param array  $data Optional parameters.
806
     *
807
     * @return \Longman\TelegramBot\Entities\ServerResponse
808
     * @throws \Longman\TelegramBot\Exception\TelegramException
809
     */
810
    public static function setWebhook($url = '', array $data = [])
811
    {
812
        $data        = array_intersect_key($data, array_flip([
813
            'certificate',
814
            'max_connections',
815
            'allowed_updates',
816
        ]));
817
        $data['url'] = $url;
818
819
        if (isset($data['certificate'])) {
820
            self::assignEncodedFile($data, 'certificate', $data['certificate']);
821
        }
822
823
        return self::send('setWebhook', $data);
824
    }
825
826
    /**
827
     * Delete webhook
828
     *
829
     * @link https://core.telegram.org/bots/api#deletewebhook
830
     *
831
     * @return \Longman\TelegramBot\Entities\ServerResponse
832
     * @throws \Longman\TelegramBot\Exception\TelegramException
833
     */
834
    public static function deleteWebhook()
835
    {
836
        // Must send some arbitrary data for this to work for now...
837
        return self::send('deleteWebhook', ['delete']);
838
    }
839
840
    /**
841
     * Use this method to edit text and game messages sent by the bot or via the bot (for inline bots).
842
     *
843
     * On success, if edited message is sent by the bot, the edited Message is returned, otherwise True is returned.
844
     *
845
     * @link https://core.telegram.org/bots/api#editmessagetext
846
     *
847
     * @param array $data
848
     *
849
     * @return \Longman\TelegramBot\Entities\ServerResponse
850
     * @throws \Longman\TelegramBot\Exception\TelegramException
851
     */
852
    public static function editMessageText(array $data)
853
    {
854
        return self::send('editMessageText', $data);
855
    }
856
857
    /**
858
     * Use this method to edit captions of messages sent by the bot or via the bot (for inline bots).
859
     *
860
     * On success, if edited message is sent by the bot, the edited Message is returned, otherwise True is returned.
861
     *
862
     * @link https://core.telegram.org/bots/api#editmessagecaption
863
     *
864
     * @param array $data
865
     *
866
     * @return \Longman\TelegramBot\Entities\ServerResponse
867
     * @throws \Longman\TelegramBot\Exception\TelegramException
868
     */
869
    public static function editMessageCaption(array $data)
870
    {
871
        return self::send('editMessageCaption', $data);
872
    }
873
874
    /**
875
     * Use this method to edit only the reply markup of messages sent by the bot or via the bot (for inline bots).
876
     *
877
     * On success, if edited message is sent by the bot, the edited Message is returned, otherwise True is returned.
878
     *
879
     * @link https://core.telegram.org/bots/api#editmessagereplymarkup
880
     *
881
     * @param array $data
882
     *
883
     * @return \Longman\TelegramBot\Entities\ServerResponse
884
     * @throws \Longman\TelegramBot\Exception\TelegramException
885
     */
886
    public static function editMessageReplyMarkup(array $data)
887
    {
888
        return self::send('editMessageReplyMarkup', $data);
889
    }
890
891
    /**
892
     * Use this method to send answers to an inline query. On success, True is returned.
893
     *
894
     * No more than 50 results per query are allowed.
895
     *
896
     * @link https://core.telegram.org/bots/api#answerinlinequery
897
     *
898
     * @param array $data
899
     *
900
     * @return \Longman\TelegramBot\Entities\ServerResponse
901
     * @throws \Longman\TelegramBot\Exception\TelegramException
902
     */
903
    public static function answerInlineQuery(array $data)
904
    {
905
        return self::send('answerInlineQuery', $data);
906
    }
907
908
    /**
909
     * Return an empty Server Response
910
     *
911
     * No request to telegram are sent, this function is used in commands that
912
     * don't need to fire a message after execution
913
     *
914
     * @return \Longman\TelegramBot\Entities\ServerResponse
915
     * @throws \Longman\TelegramBot\Exception\TelegramException
916
     */
917
    public static function emptyResponse()
918
    {
919
        return new ServerResponse(['ok' => true, 'result' => true], null);
920
    }
921
922
    /**
923
     * Send message to all active chats
924
     *
925
     * @param string  $callback_function
926
     * @param array   $data
927
     * @param boolean $send_groups
928
     * @param boolean $send_super_groups
929
     * @param boolean $send_users
930
     * @param string  $date_from
931
     * @param string  $date_to
932
     *
933
     * @return array
934
     * @throws \Longman\TelegramBot\Exception\TelegramException
935
     */
936
    public static function sendToActiveChats(
937
        $callback_function,
938
        array $data,
939
        $send_groups = true,
940
        $send_super_groups = true,
941
        $send_users = true,
942
        $date_from = null,
943
        $date_to = null
944
    ) {
945
        $callback_path = __NAMESPACE__ . '\Request';
946
        if (!method_exists($callback_path, $callback_function)) {
947
            throw new TelegramException('Method "' . $callback_function . '" not found in class Request.');
948
        }
949
950
        $chats = DB::selectChats($send_groups, $send_super_groups, $send_users, $date_from, $date_to);
951
952
        $results = [];
953
        if (is_array($chats)) {
954
            foreach ($chats as $row) {
955
                $data['chat_id'] = $row['chat_id'];
956
                $results[]       = call_user_func_array($callback_path . '::' . $callback_function, [$data]);
957
            }
958
        }
959
960
        return $results;
961
    }
962
963
    /**
964
     * Use this method to get current webhook status.
965
     *
966
     * @link https://core.telegram.org/bots/api#getwebhookinfo
967
     *
968
     * @return Entities\ServerResponse
969
     * @throws \Longman\TelegramBot\Exception\TelegramException
970
     */
971
    public static function getWebhookInfo()
972
    {
973
        // Must send some arbitrary data for this to work for now...
974
        return self::send('getWebhookInfo', ['info']);
975
    }
976
}
977