Completed
Push — master ( 203d4a...ef9e39 )
by
unknown
04:46 queued 02:35
created

Request::assignEncodedFile()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 6
ccs 0
cts 4
cp 0
rs 9.4285
cc 3
eloc 3
nc 2
nop 3
crap 12
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
        'getMe',
58
        'sendMessage',
59
        'forwardMessage',
60
        'sendPhoto',
61
        'sendAudio',
62
        'sendDocument',
63
        'sendSticker',
64
        'sendVideo',
65
        'sendVoice',
66
        'sendLocation',
67
        'sendVenue',
68
        'sendContact',
69
        'sendChatAction',
70
        'getUserProfilePhotos',
71
        'getFile',
72
        'kickChatMember',
73
        'leaveChat',
74
        'unbanChatMember',
75
        'getChat',
76
        'getChatAdministrators',
77
        'getChatMember',
78
        'getChatMembersCount',
79
        'answerCallbackQuery',
80
        'answerInlineQuery',
81
        'editMessageText',
82
        'editMessageCaption',
83
        'editMessageReplyMarkup',
84
        'getWebhookInfo',
85
    ];
86
87
    /**
88
     * Initialize
89
     *
90
     * @param \Longman\TelegramBot\Telegram $telegram
91
     *
92
     * @throws \Longman\TelegramBot\Exception\TelegramException
93
     */
94 39
    public static function initialize(Telegram $telegram)
95
    {
96 39
        if (is_object($telegram)) {
97 39
            self::$telegram = $telegram;
98 39
            self::$client   = new Client(['base_uri' => self::$api_base_uri]);
99
        } else {
100
            throw new TelegramException('Telegram pointer is empty!');
101
        }
102 39
    }
103
104
    /**
105
     * Set input from custom input or stdin and return it
106
     *
107
     * @return string
108
     * @throws \Longman\TelegramBot\Exception\TelegramException
109
     */
110
    public static function getInput()
111
    {
112
        // First check if a custom input has been set, else get the PHP input.
113
        if (!($input = self::$telegram->getCustomInput())) {
114
            $input = file_get_contents('php://input');
115
        }
116
117
        // Make sure we have a string to work with.
118
        if (is_string($input)) {
119
            self::$input = $input;
120
        } else {
121
            throw new TelegramException('Input must be a string!');
122
        }
123
124
        TelegramLog::update(self::$input);
125
126
        return self::$input;
127
    }
128
129
    /**
130
     * Generate general fake server response
131
     *
132
     * @param array $data Data to add to fake response
133
     *
134
     * @return array Fake response data
135
     */
136 6
    public static function generateGeneralFakeServerResponse(array $data = [])
137
    {
138
        //PARAM BINDED IN PHPUNIT TEST FOR TestServerResponse.php
139
        //Maybe this is not the best possible implementation
140
141
        //No value set in $data ie testing setWebhook
142
        //Provided $data['chat_id'] ie testing sendMessage
143
144 6
        $fake_response = ['ok' => true]; // :)
145
146 6
        if ($data === []) {
147 1
            $fake_response['result'] = true;
148
        }
149
150
        //some data to let iniatilize the class method SendMessage
151 6
        if (isset($data['chat_id'])) {
152 6
            $data['message_id'] = '1234';
153 6
            $data['date']       = '1441378360';
154 6
            $data['from']       = [
155
                'id'         => 123456789,
156
                'first_name' => 'botname',
157
                'username'   => 'namebot',
158
            ];
159 6
            $data['chat']       = ['id' => $data['chat_id']];
160
161 6
            $fake_response['result'] = $data;
162
        }
163
164 6
        return $fake_response;
165
    }
166
167
    /**
168
     * Properly set up the request params
169
     *
170
     * If any item of the array is a resource, reformat it to a multipart request.
171
     * Else, just return the passed data as form params.
172
     *
173
     * @param array $data
174
     *
175
     * @return array
176
     */
177
    private static function setUpRequestParams(array $data)
178
    {
179
        $has_resource = false;
180
        $multipart    = [];
181
182
        //Reformat data array in multipart way if it contains a resource
183
        foreach ($data as $key => $item) {
184
            $has_resource |= is_resource($item);
185
            $multipart[] = ['name' => $key, 'contents' => $item];
186
        }
187
        if ($has_resource) {
188
            return ['multipart' => $multipart];
189
        }
190
191
        return ['form_params' => $data];
192
    }
193
194
    /**
195
     * Execute HTTP Request
196
     *
197
     * @param string $action Action to execute
198
     * @param array  $data   Data to attach to the execution
199
     *
200
     * @return string Result of the HTTP Request
201
     * @throws \Longman\TelegramBot\Exception\TelegramException
202
     */
203
    public static function execute($action, array $data = [])
204
    {
205
        //Fix so that the keyboard markup is a string, not an object
206
        if (isset($data['reply_markup'])) {
207
            $data['reply_markup'] = (string)$data['reply_markup'];
208
        }
209
210
        $request_params = self::setUpRequestParams($data);
211
212
        $debug_handle            = TelegramLog::getDebugLogTempStream();
213
        $request_params['debug'] = $debug_handle;
214
215
        try {
216
            $response = self::$client->post(
217
                '/bot' . self::$telegram->getApiKey() . '/' . $action,
218
                $request_params
219
            );
220
            $result   = (string)$response->getBody();
221
222
            //Logging getUpdates Update
223
            if ($action === 'getUpdates') {
224
                TelegramLog::update($result);
225
            }
226
        } catch (RequestException $e) {
227
            $result = (string)$e->getResponse()->getBody();
228
        } finally {
229
            //Logging verbose debug output
230
            TelegramLog::endDebugLogTempStream("Verbose HTTP Request output:\n%s\n");
231
        }
232
233
        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...
234
    }
235
236
    /**
237
     * Download file
238
     *
239
     * @param \Longman\TelegramBot\Entities\File $file
240
     *
241
     * @return boolean
242
     * @throws \Longman\TelegramBot\Exception\TelegramException
243
     */
244
    public static function downloadFile(File $file)
245
    {
246
        $tg_file_path = $file->getFilePath();
247
        $file_path    = self::$telegram->getDownloadPath() . '/' . $tg_file_path;
248
249
        $file_dir = dirname($file_path);
250
        //For safety reasons, first try to create the directory, then check that it exists.
251
        //This is in case some other process has created the folder in the meantime.
252
        if (!@mkdir($file_dir, 0755, true) && !is_dir($file_dir)) {
253
            throw new TelegramException('Directory ' . $file_dir . ' can\'t be created');
254
        }
255
256
        $debug_handle = TelegramLog::getDebugLogTempStream();
257
258
        try {
259
            self::$client->get(
260
                '/file/bot' . self::$telegram->getApiKey() . '/' . $tg_file_path,
261
                ['debug' => $debug_handle, 'sink' => $file_path]
262
            );
263
264
            return filesize($file_path) > 0;
265
        } catch (RequestException $e) {
266
            return (string)$e->getResponse()->getBody();
267
        } finally {
268
            //Logging verbose debug output
269
            TelegramLog::endDebugLogTempStream("Verbose HTTP File Download Request output:\n%s\n");
270
        }
271
    }
272
273
    /**
274
     * Encode file
275
     *
276
     * @param string $file
277
     *
278
     * @return resource
279
     * @throws \Longman\TelegramBot\Exception\TelegramException
280
     */
281
    protected static function encodeFile($file)
282
    {
283
        $fp = fopen($file, 'r');
284
        if ($fp === false) {
285
            throw new TelegramException('Cannot open ' . $file . ' for reading');
286
        }
287
288
        return $fp;
289
    }
290
291
    /**
292
     * Send command
293
     *
294
     * @todo Fake response doesn't need json encoding?
295
     *
296
     * @param string $action
297
     * @param array  $data
298
     *
299
     * @return \Longman\TelegramBot\Entities\ServerResponse
300
     * @throws \Longman\TelegramBot\Exception\TelegramException
301
     */
302 5
    public static function send($action, array $data = [])
303
    {
304 5
        self::ensureValidAction($action);
305
306 5
        $bot_name = self::$telegram->getBotName();
307
308 5
        if (defined('PHPUNIT_TESTSUITE')) {
309 5
            $fake_response = self::generateGeneralFakeServerResponse($data);
310
311 5
            return new ServerResponse($fake_response, $bot_name);
312
        }
313
314
        self::ensureNonEmptyData($data);
315
316
        $response = json_decode(self::execute($action, $data), true);
317
318
        if (null === $response) {
319
            throw new TelegramException('Telegram returned an invalid response! Please review your bot name and API key.');
320
        }
321
322
        return new ServerResponse($response, $bot_name);
323
    }
324
325
    /**
326
     * Make sure the data isn't empty, else throw an exception
327
     *
328
     * @param array $data
329
     *
330
     * @throws \Longman\TelegramBot\Exception\TelegramException
331
     */
332
    private static function ensureNonEmptyData(array $data)
333
    {
334
        if (count($data) === 0) {
335
            throw new TelegramException('Data is empty!');
336
        }
337
    }
338
339
    /**
340
     * Make sure the action is valid, else throw an exception
341
     *
342
     * @param string $action
343
     *
344
     * @throws \Longman\TelegramBot\Exception\TelegramException
345
     */
346 5
    private static function ensureValidAction($action)
347
    {
348 5
        if (!in_array($action, self::$actions, true)) {
349
            throw new TelegramException('The action " . $action . " doesn\'t exist!');
350
        }
351 5
    }
352
353
    /**
354
     * Assign an encoded file to a data array
355
     *
356
     * @param array  $data
357
     * @param string $field
358
     * @param string $file
359
     *
360
     * @throws \Longman\TelegramBot\Exception\TelegramException
361
     */
362
    private static function assignEncodedFile(&$data, $field, $file)
363
    {
364
        if ($file !== null && $file !== '') {
365
            $data[$field] = self::encodeFile($file);
366
        }
367
    }
368
369
    /**
370
     * Returns basic information about the bot in form of a User object
371
     *
372
     * @link https://core.telegram.org/bots/api#getme
373
     *
374
     * @return \Longman\TelegramBot\Entities\ServerResponse
375
     * @throws \Longman\TelegramBot\Exception\TelegramException
376
     */
377
    public static function getMe()
378
    {
379
        // Added fake parameter, because of some cURL version failed POST request without parameters
380
        // see https://github.com/akalongman/php-telegram-bot/pull/228
381
        return self::send('getMe', ['whoami']);
382
    }
383
384
    /**
385
     * Use this method to send text messages. On success, the sent Message is returned
386
     *
387
     * @link https://core.telegram.org/bots/api#sendmessage
388
     *
389
     * @param array $data
390
     *
391
     * @return \Longman\TelegramBot\Entities\ServerResponse
392
     * @throws \Longman\TelegramBot\Exception\TelegramException
393
     */
394 5
    public static function sendMessage(array $data)
395
    {
396 5
        $text = $data['text'];
397
398
        do {
399
            //Chop off and send the first message
400 5
            $data['text'] = mb_substr($text, 0, 4096);
401 5
            $response = self::send('sendMessage', $data);
402
403
            //Prepare the next message
404 5
            $text = mb_substr($text, 4096);
405 5
        } while (mb_strlen($text, 'UTF-8') > 0);
406
407 5
        return $response;
408
    }
409
410
    /**
411
     * Use this method to forward messages of any kind. On success, the sent Message is returned
412
     *
413
     * @link https://core.telegram.org/bots/api#forwardmessage
414
     *
415
     * @param array $data
416
     *
417
     * @return \Longman\TelegramBot\Entities\ServerResponse
418
     * @throws \Longman\TelegramBot\Exception\TelegramException
419
     */
420
    public static function forwardMessage(array $data)
421
    {
422
        return self::send('forwardMessage', $data);
423
    }
424
425
    /**
426
     * Use this method to send photos. On success, the sent Message is returned
427
     *
428
     * @link https://core.telegram.org/bots/api#sendphoto
429
     *
430
     * @param array  $data
431
     * @param string $file
432
     *
433
     * @return \Longman\TelegramBot\Entities\ServerResponse
434
     * @throws \Longman\TelegramBot\Exception\TelegramException
435
     */
436
    public static function sendPhoto(array $data, $file = null)
437
    {
438
        self::assignEncodedFile($data, 'photo', $file);
439
440
        return self::send('sendPhoto', $data);
441
    }
442
443
    /**
444
     * Use this method to send audio files
445
     *
446
     * Your audio must be in the .mp3 format. On success, the sent Message is returned.
447
     * Bots can currently send audio files of up to 50 MB in size, this limit may be changed in the future.
448
     * For sending voice messages, use the sendVoice method instead.
449
     *
450
     * @link https://core.telegram.org/bots/api#sendaudio
451
     *
452
     * @param array  $data
453
     * @param string $file
454
     *
455
     * @return \Longman\TelegramBot\Entities\ServerResponse
456
     * @throws \Longman\TelegramBot\Exception\TelegramException
457
     */
458
    public static function sendAudio(array $data, $file = null)
459
    {
460
        self::assignEncodedFile($data, 'audio', $file);
461
462
        return self::send('sendAudio', $data);
463
    }
464
465
    /**
466
     * Use this method to send general files. On success, the sent Message is returned.
467
     *
468
     * Bots can currently send files of any type of up to 50 MB in size, this limit may be changed in the future.
469
     *
470
     * @link https://core.telegram.org/bots/api#senddocument
471
     *
472
     * @param array  $data
473
     * @param string $file
474
     *
475
     * @return \Longman\TelegramBot\Entities\ServerResponse
476
     * @throws \Longman\TelegramBot\Exception\TelegramException
477
     */
478
    public static function sendDocument(array $data, $file = null)
479
    {
480
        self::assignEncodedFile($data, 'document', $file);
481
482
        return self::send('sendDocument', $data);
483
    }
484
485
    /**
486
     * Use this method to send .webp stickers. On success, the sent Message is returned.
487
     *
488
     * @link https://core.telegram.org/bots/api#sendsticker
489
     *
490
     * @param array  $data
491
     * @param string $file
492
     *
493
     * @return \Longman\TelegramBot\Entities\ServerResponse
494
     * @throws \Longman\TelegramBot\Exception\TelegramException
495
     */
496
    public static function sendSticker(array $data, $file = null)
497
    {
498
        self::assignEncodedFile($data, 'sticker', $file);
499
500
        return self::send('sendSticker', $data);
501
    }
502
503
    /**
504
     * Use this method to send video files. On success, the sent Message is returned.
505
     *
506
     * Telegram clients support mp4 videos (other formats may be sent as Document).
507
     * Bots can currently send video files of up to 50 MB in size, this limit may be changed in the future.
508
     *
509
     * @link https://core.telegram.org/bots/api#sendvideo
510
     *
511
     * @param array  $data
512
     * @param string $file
513
     *
514
     * @return \Longman\TelegramBot\Entities\ServerResponse
515
     * @throws \Longman\TelegramBot\Exception\TelegramException
516
     */
517
    public static function sendVideo(array $data, $file = null)
518
    {
519
        self::assignEncodedFile($data, 'video', $file);
520
521
        return self::send('sendVideo', $data);
522
    }
523
524
    /**
525
     * Use this method to send audio files. On success, the sent Message is returned.
526
     *
527
     * Telegram clients will display the file as a playable voice message.
528
     * For this to work, your audio must be in an .ogg file encoded with OPUS (other formats may be sent as Audio or Document).
529
     * Bots can currently send voice messages of up to 50 MB in size, this limit may be changed in the future.
530
     *
531
     * @link https://core.telegram.org/bots/api#sendvoice
532
     *
533
     * @param array  $data
534
     * @param string $file
535
     *
536
     * @return \Longman\TelegramBot\Entities\ServerResponse
537
     * @throws \Longman\TelegramBot\Exception\TelegramException
538
     */
539
    public static function sendVoice(array $data, $file = null)
540
    {
541
        self::assignEncodedFile($data, 'voice', $file);
542
543
        return self::send('sendVoice', $data);
544
    }
545
546
    /**
547
     * Use this method to send point on the map. On success, the sent Message is returned.
548
     *
549
     * @link https://core.telegram.org/bots/api#sendlocation
550
     *
551
     * @param array $data
552
     *
553
     * @return \Longman\TelegramBot\Entities\ServerResponse
554
     * @throws \Longman\TelegramBot\Exception\TelegramException
555
     */
556
    public static function sendLocation(array $data)
557
    {
558
        return self::send('sendLocation', $data);
559
    }
560
561
    /**
562
     * Use this method to send information about a venue. On success, the sent Message is returned.
563
     *
564
     * @link https://core.telegram.org/bots/api#sendvenue
565
     *
566
     * @param array $data
567
     *
568
     * @return \Longman\TelegramBot\Entities\ServerResponse
569
     * @throws \Longman\TelegramBot\Exception\TelegramException
570
     */
571
    public static function sendVenue(array $data)
572
    {
573
        return self::send('sendVenue', $data);
574
    }
575
576
    /**
577
     * Use this method to send phone contacts. On success, the sent Message is returned.
578
     *
579
     * @link https://core.telegram.org/bots/api#sendcontact
580
     *
581
     * @param array $data
582
     *
583
     * @return \Longman\TelegramBot\Entities\ServerResponse
584
     * @throws \Longman\TelegramBot\Exception\TelegramException
585
     */
586
    public static function sendContact(array $data)
587
    {
588
        return self::send('sendContact', $data);
589
    }
590
591
    /**
592
     * Use this method when you need to tell the user that something is happening on the bot's side.
593
     *
594
     * The status is set for 5 seconds or less.
595
     * (when a message arrives from your bot, Telegram clients clear its typing status)
596
     *
597
     * @link https://core.telegram.org/bots/api#sendchataction
598
     *
599
     * @param array $data
600
     *
601
     * @return \Longman\TelegramBot\Entities\ServerResponse
602
     * @throws \Longman\TelegramBot\Exception\TelegramException
603
     */
604
    public static function sendChatAction(array $data)
605
    {
606
        return self::send('sendChatAction', $data);
607
    }
608
609
    /**
610
     * Use this method to get a list of profile pictures for a user. Returns a UserProfilePhotos object.
611
     *
612
     * @param array $data
613
     *
614
     * @return \Longman\TelegramBot\Entities\ServerResponse
615
     * @throws \Longman\TelegramBot\Exception\TelegramException
616
     */
617
    public static function getUserProfilePhotos(array $data)
618
    {
619
        return self::send('getUserProfilePhotos', $data);
620
    }
621
622
    /**
623
     * Use this method to get basic info about a file and prepare it for downloading. On success, a File object is returned.
624
     *
625
     * For the moment, bots can download files of up to 20MB in size.
626
     * The file can then be downloaded via the link https://api.telegram.org/file/bot<token>/<file_path>,
627
     * where <file_path> is taken from the response.
628
     * It is guaranteed that the link will be valid for at least 1 hour.
629
     * When the link expires, a new one can be requested by calling getFile again.
630
     *
631
     * @link https://core.telegram.org/bots/api#getfile
632
     *
633
     * @param array $data
634
     *
635
     * @return \Longman\TelegramBot\Entities\ServerResponse
636
     * @throws \Longman\TelegramBot\Exception\TelegramException
637
     */
638
    public static function getFile(array $data)
639
    {
640
        return self::send('getFile', $data);
641
    }
642
643
    /**
644
     * Use this method to kick a user from a group or a supergroup. Returns True on success.
645
     *
646
     * 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.
647
     * The bot must be an administrator in the group for this to work.
648
     *
649
     * @link https://core.telegram.org/bots/api#kickchatmember
650
     *
651
     * @param array $data
652
     *
653
     * @return \Longman\TelegramBot\Entities\ServerResponse
654
     * @throws \Longman\TelegramBot\Exception\TelegramException
655
     */
656
    public static function kickChatMember(array $data)
657
    {
658
        return self::send('kickChatMember', $data);
659
    }
660
661
    /**
662
     * Use this method for your bot to leave a group, supergroup or channel. Returns True on success.
663
     *
664
     * @link https://core.telegram.org/bots/api#leavechat
665
     *
666
     * @param array $data
667
     *
668
     * @return \Longman\TelegramBot\Entities\ServerResponse
669
     * @throws \Longman\TelegramBot\Exception\TelegramException
670
     */
671
    public static function leaveChat(array $data)
672
    {
673
        return self::send('leaveChat', $data);
674
    }
675
676
    /**
677
     * Use this method to unban a previously kicked user in a supergroup. Returns True on success.
678
     *
679
     * The user will not return to the group automatically, but will be able to join via link, etc.
680
     * The bot must be an administrator in the group for this to work.
681
     *
682
     * @link https://core.telegram.org/bots/api#unbanchatmember
683
     *
684
     * @param array $data
685
     *
686
     * @return \Longman\TelegramBot\Entities\ServerResponse
687
     * @throws \Longman\TelegramBot\Exception\TelegramException
688
     */
689
    public static function unbanChatMember(array $data)
690
    {
691
        return self::send('unbanChatMember', $data);
692
    }
693
694
    /**
695
     * 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.
696
     *
697
     * @todo add get response in ServerResponse.php?
698
     *
699
     * @link https://core.telegram.org/bots/api#getchat
700
     *
701
     * @param array $data
702
     *
703
     * @return \Longman\TelegramBot\Entities\ServerResponse
704
     * @throws \Longman\TelegramBot\Exception\TelegramException
705
     */
706
    public static function getChat(array $data)
707
    {
708
        return self::send('getChat', $data);
709
    }
710
711
    /**
712
     * Use this method to get a list of administrators in a chat.
713
     *
714
     * On success, returns an Array of ChatMember objects that contains information about all chat administrators except other bots.
715
     * If the chat is a group or a supergroup and no administrators were appointed, only the creator will be returned.
716
     *
717
     * @todo add get response in ServerResponse.php?
718
     *
719
     * @link https://core.telegram.org/bots/api#getchatadministrators
720
     *
721
     * @param array $data
722
     *
723
     * @return \Longman\TelegramBot\Entities\ServerResponse
724
     * @throws \Longman\TelegramBot\Exception\TelegramException
725
     */
726
    public static function getChatAdministrators(array $data)
727
    {
728
        return self::send('getChatAdministrators', $data);
729
    }
730
731
    /**
732
     * Use this method to get the number of members in a chat. Returns Int on success.
733
     *
734
     * @todo add get response in ServerResponse.php?
735
     *
736
     * @link https://core.telegram.org/bots/api#getchatmemberscount
737
     *
738
     * @param array $data
739
     *
740
     * @return \Longman\TelegramBot\Entities\ServerResponse
741
     * @throws \Longman\TelegramBot\Exception\TelegramException
742
     */
743
    public static function getChatMembersCount(array $data)
744
    {
745
        return self::send('getChatMembersCount', $data);
746
    }
747
748
    /**
749
     * Use this method to get information about a member of a chat. Returns a ChatMember object on success.
750
     *
751
     * @todo add get response in ServerResponse.php?
752
     *
753
     * @link https://core.telegram.org/bots/api#getchatmember
754
     *
755
     * @param array $data
756
     *
757
     * @return \Longman\TelegramBot\Entities\ServerResponse
758
     * @throws \Longman\TelegramBot\Exception\TelegramException
759
     */
760
    public static function getChatMember(array $data)
761
    {
762
        return self::send('getChatMember', $data);
763
    }
764
765
    /**
766
     * Use this method to send answers to callback queries sent from inline keyboards. On success, True is returned.
767
     *
768
     * The answer will be displayed to the user as a notification at the top of the chat screen or as an alert.
769
     *
770
     * @link https://core.telegram.org/bots/api#answercallbackquery
771
     *
772
     * @param array $data
773
     *
774
     * @return \Longman\TelegramBot\Entities\ServerResponse
775
     * @throws \Longman\TelegramBot\Exception\TelegramException
776
     */
777
    public static function answerCallbackQuery(array $data)
778
    {
779
        return self::send('answerCallbackQuery', $data);
780
    }
781
782
    /**
783
     * Get updates
784
     *
785
     * @link https://core.telegram.org/bots/api#getupdates
786
     *
787
     * @param array $data
788
     *
789
     * @return \Longman\TelegramBot\Entities\ServerResponse
790
     * @throws \Longman\TelegramBot\Exception\TelegramException
791
     */
792
    public static function getUpdates(array $data)
793
    {
794
        return self::send('getUpdates', $data);
795
    }
796
797
    /**
798
     * Set webhook
799
     *
800
     * @link https://core.telegram.org/bots/api#setwebhook
801
     *
802
     * @param string $url
803
     * @param string $file
804
     *
805
     * @return \Longman\TelegramBot\Entities\ServerResponse
806
     * @throws \Longman\TelegramBot\Exception\TelegramException
807
     */
808
    public static function setWebhook($url = '', $file = null)
809
    {
810
        $data = ['url' => $url];
811
812
        self::assignEncodedFile($data, 'certificate', $file);
813
814
        return self::send('setWebhook', $data);
815
    }
816
817
    /**
818
     * Use this method to edit text and game messages sent by the bot or via the bot (for inline bots).
819
     *
820
     * On success, if edited message is sent by the bot, the edited Message is returned, otherwise True is returned.
821
     *
822
     * @link https://core.telegram.org/bots/api#editmessagetext
823
     *
824
     * @param array $data
825
     *
826
     * @return \Longman\TelegramBot\Entities\ServerResponse
827
     * @throws \Longman\TelegramBot\Exception\TelegramException
828
     */
829
    public static function editMessageText(array $data)
830
    {
831
        return self::send('editMessageText', $data);
832
    }
833
834
    /**
835
     * Use this method to edit captions of messages sent by the bot or via the bot (for inline bots).
836
     *
837
     * On success, if edited message is sent by the bot, the edited Message is returned, otherwise True is returned.
838
     *
839
     * @link https://core.telegram.org/bots/api#editmessagecaption
840
     *
841
     * @param array $data
842
     *
843
     * @return \Longman\TelegramBot\Entities\ServerResponse
844
     * @throws \Longman\TelegramBot\Exception\TelegramException
845
     */
846
    public static function editMessageCaption(array $data)
847
    {
848
        return self::send('editMessageCaption', $data);
849
    }
850
851
    /**
852
     * Use this method to edit only the reply markup of messages sent by the bot or via the bot (for inline bots).
853
     *
854
     * On success, if edited message is sent by the bot, the edited Message is returned, otherwise True is returned.
855
     *
856
     * @link https://core.telegram.org/bots/api#editmessagereplymarkup
857
     *
858
     * @param array $data
859
     *
860
     * @return \Longman\TelegramBot\Entities\ServerResponse
861
     * @throws \Longman\TelegramBot\Exception\TelegramException
862
     */
863
    public static function editMessageReplyMarkup(array $data)
864
    {
865
        return self::send('editMessageReplyMarkup', $data);
866
    }
867
868
    /**
869
     * Use this method to send answers to an inline query. On success, True is returned.
870
     *
871
     * No more than 50 results per query are allowed.
872
     *
873
     * @link https://core.telegram.org/bots/api#answerinlinequery
874
     *
875
     * @param array $data
876
     *
877
     * @return \Longman\TelegramBot\Entities\ServerResponse
878
     * @throws \Longman\TelegramBot\Exception\TelegramException
879
     */
880
    public static function answerInlineQuery(array $data)
881
    {
882
        return self::send('answerInlineQuery', $data);
883
    }
884
885
    /**
886
     * Return an empty Server Response
887
     *
888
     * No request to telegram are sent, this function is used in commands that
889
     * don't need to fire a message after execution
890
     *
891
     * @return \Longman\TelegramBot\Entities\ServerResponse
892
     * @throws \Longman\TelegramBot\Exception\TelegramException
893
     */
894
    public static function emptyResponse()
895
    {
896
        return new ServerResponse(['ok' => true, 'result' => true], null);
897
    }
898
899
    /**
900
     * Send message to all active chats
901
     *
902
     * @param string  $callback_function
903
     * @param array   $data
904
     * @param boolean $send_groups
905
     * @param boolean $send_super_groups
906
     * @param boolean $send_users
907
     * @param string  $date_from
908
     * @param string  $date_to
909
     *
910
     * @return array
911
     * @throws \Longman\TelegramBot\Exception\TelegramException
912
     */
913
    public static function sendToActiveChats(
914
        $callback_function,
915
        array $data,
916
        $send_groups = true,
917
        $send_super_groups = true,
918
        $send_users = true,
919
        $date_from = null,
920
        $date_to = null
921
    ) {
922
        $callback_path = __NAMESPACE__ . '\Request';
923
        if (!method_exists($callback_path, $callback_function)) {
924
            throw new TelegramException('Method "' . $callback_function . '" not found in class Request.');
925
        }
926
927
        $chats = DB::selectChats($send_groups, $send_super_groups, $send_users, $date_from, $date_to);
928
929
        $results = [];
930
        if (is_array($chats)) {
931
            foreach ($chats as $row) {
932
                $data['chat_id'] = $row['chat_id'];
933
                $results[]       = call_user_func_array($callback_path . '::' . $callback_function, [$data]);
934
            }
935
        }
936
937
        return $results;
938
    }
939
940
    /**
941
     * Use this method to get current webhook status.
942
     *
943
     * @link https://core.telegram.org/bots/api#getwebhookinfo
944
     *
945
     * @return Entities\ServerResponse
946
     * @throws \Longman\TelegramBot\Exception\TelegramException
947
     */
948
    public static function getWebhookInfo()
949
    {
950
        // Must send some arbitrary data for this to work for now...
951
        return self::send('getWebhookInfo', ['info']);
952
    }
953
}
954