This repository has been archived by the owner on Jul 26, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmojang-api.class.php
816 lines (731 loc) · 27.4 KB
/
mojang-api.class.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
<?php
/**
* Fast and easy way to access Mojang API
*
* Can be used to get Mojang status, UUID and username conversions, names history, and fetch skin.
* Usually, if NULL is returned, it means empty, and FALSE means failure
* Also, UUIDs returned are minified (without dashes)
*
* @author MineTheCube
* @link https://github.com/MineTheCube/MojangAPI
* @see http://wiki.vg/Mojang_API
*/
class MojangAPI
{
/**
* Get Mojang status
*
* @return array|bool Array with status, FALSE on failure
*/
public static function getStatus()
{
$json = static::fetchJson('https://status.mojang.com/check');
if (is_array($json)) {
$status = array();
foreach ($json as $array) {
if (!empty($array)) {
list($key, $value) = each($array);
$status[$key] = $value;
}
}
return $status;
}
return false;
}
/**
* Get UUID from username, an optional time can be provided
*
* @param string $username
* @param int $time optional
* @return string|bool UUID (without dashes) on success, FALSE on failure
*/
public static function getUuid($username, $time = 0)
{
$profile = static::getProfile($username, $time);
if (is_array($profile) and isset($profile['id'])) {
return $profile['id'];
}
return false;
}
/**
* Get username from UUID
*
* @param string $uuid
* @return string|bool Username on success, FALSE on failure
*/
public static function getUsername($uuid)
{
$history = static::getNameHistory($uuid);
if (is_array($history)) {
$last = array_pop($history);
if (is_array($last) and array_key_exists('name', $last)) {
return $last['name'];
}
}
return false;
}
/**
* Get profile (username and UUID) from username, an optional time can be provided
*
* @param string $username
* @param int $time optional
* @return array|bool Array with id and name, FALSE on failure
*/
public static function getProfile($username, $time = 0)
{
if (static::isValidUsername($username) and is_numeric($time)) {
return static::fetchJson(
'https://api.mojang.com/users/profiles/minecraft/'
. $username
. ($time > 0 ? '?at=' . $time : '')
);
}
return false;
}
/**
* Get name history from UUID
*
* @param string $uuid
* @return array|bool Array with his username's history, FALSE on failure
*/
public static function getNameHistory($uuid)
{
if (static::isValidUuid($uuid)) {
return static::fetchJson('https://api.mojang.com/user/profiles/' . static::minifyUuid($uuid) . '/names');
}
return false;
}
/**
* Check if string is a valid Minecraft username
*
* @param string $string to check
* @return bool Whether username is valid or not
*/
public static function isValidUsername($string)
{
return is_string($string)
and strlen($string) >= 2
and strlen($string) <= 16
and ctype_alnum(str_replace('_', '', $string));
}
/**
* Check if string is a valid UUID, with or without dashes
*
* @param string $string to check
* @return bool Whether UUID is valid or not
*/
public static function isValidUuid($string)
{
return is_string(static::minifyUuid($string));
}
/**
* Remove dashes from UUID
*
* @param string $uuid
* @return string|bool UUID without dashes (32 chars), FALSE on failure
*/
public static function minifyUuid($uuid)
{
if (is_string($uuid)) {
$minified = str_replace('-', '', $uuid);
if (strlen($minified) === 32) {
return $minified;
}
}
return false;
}
/**
* Add dashes to an UUID
*
* @param string $uuid
* @return string|bool UUID with dashes (36 chars), FALSE on failure
*/
public static function formatUuid($uuid)
{
$uuid = static::minifyUuid($uuid);
if (is_string($uuid)) {
return substr($uuid, 0, 8)
. '-' . substr($uuid, 8, 4)
. '-' . substr($uuid, 12, 4)
. '-' . substr($uuid, 16, 4)
. '-' . substr($uuid, 20, 12);
}
return false;
}
/**
* Check if username is Alex or Steve is a valid UUID, with or without dashes
*
* @param string $uuid
* @return bool|null TRUE if Alex, FALSE if Steve, NULL on error
*/
public static function isAlex($uuid)
{
$uuid = static::minifyUuid($uuid);
if (is_string($uuid)) {
$sub = array();
for ($i = 0; $i < 4; $i++) {
$sub[$i] = intval('0x' . substr($uuid, $i * 8, 8) + 0, 16);
}
return (bool) ((($sub[0] ^ $sub[1]) ^ ($sub[2] ^ $sub[3])) % 2);
}
return null;
}
/**
* Get profile (username and UUID) from UUID
*
* This has a rate limit to 1 per minute per profile
*
* @param string $uuid
* @return array|bool Array with profile and properties, FALSE on failure
*/
public static function getSessionProfile($uuid)
{
if (static::isValidUuid($uuid)) {
return static::fetchJson('https://sessionserver.mojang.com/session/minecraft/profile/'
. static::minifyUuid($uuid));
}
return false;
}
/**
* Get textures (usually skin and cape, or empty array) from UUID
*
* This has a rate limit to 1 per minute per profile
* @see getSessionProfile($uuid)
*
* @param string $uuid
* @return array|bool Array with profile and properties, FALSE on failure
*/
public static function getTextures($uuid)
{
$profile = static::getSessionProfile($uuid);
if (is_array($profile)
and array_key_exists('properties', $profile)
and is_array($profile['properties'])
and !empty($profile['properties'])
and array_key_exists('value', $profile['properties'][0])
) {
$json = base64_decode($profile['properties'][0]['value']);
if (!empty($json)) {
$textures = static::parseJson($json);
if (array_key_exists('textures', $textures) and is_array($textures['textures'])) {
return $textures['textures'];
}
}
}
return false;
}
/**
* Get skin url of player
*
* This has a rate limit to 1 per minute per profile
* @see getSessionProfile($uuid)
*
* @param string $uuid
* @return string|null|bool Skin url, NULL if he hasn't a skin, FALSE on failure
*/
public static function getSkinUrl($uuid)
{
$textures = static::getTextures($uuid);
if (is_array($textures)) {
if (array_key_exists('SKIN', $textures)
and array_key_exists('url', $textures['SKIN'])
and !empty($textures['SKIN']['url'])
and is_string($textures['SKIN']['url'])
) {
return $textures['SKIN']['url'];
}
return null;
}
return false;
}
/**
* Get skin (in raw png) of player
*
* This has a rate limit to 1 per minute per profile
* @see getSessionProfile($uuid)
*
* @param string $uuid
* @return string|null|bool Skin picture, NULL if he hasn't a skin, FALSE on failure
*/
public static function getSkin($uuid)
{
$skinUrl = static::getSkinUrl($uuid);
if (is_string($skinUrl)) {
return static::fetch($skinUrl);
}
return $skinUrl;
}
/**
* Get player head (in raw png) of player
*
* This has a rate limit to 1 per minute per profile
* @see getSessionProfile($uuid)
*
* @param string $uuid
* @param int $size in pixels
* @return string|null|bool Player head, NULL if he hasn't a skin, FALSE on failure
*/
public static function getPlayerHead($uuid, $size = 100)
{
$skin = static::getSkin($uuid);
if (is_string($skin)) {
return static::getPlayerHeadFromSkin($skin, $size);
}
return $skin;
}
/**
* Get Steve skin (in raw png)
*
* @return string Steve skin
*/
public static function getSteveSkin()
{
return base64_decode(
'iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAAFDUlEQVR42u2a20sUURzH97G0LKMotPuWbVpslj1olJXdjCgyisow'
.'sSjzgrB0gSKyC5UF1ZNQWEEQSBQ9dHsIe+zJ/+nXfM/sb/rN4ZwZ96LOrnPgyxzP/M7Z+X7OZc96JpEISfWrFhK0YcU8knlozeJK'
.'unE4HahEqSc2nF6zSEkCgGCyb+82enyqybtCZQWAzdfVVFgBJJNJn1BWFgC49/VpwGVlD0CaxQiA5HSYEwBM5sMAdKTqygcAG9+8'
.'coHKY/XXAZhUNgDYuBSPjJL/GkzVVhAEU5tqK5XZ7cnFtHWtq/TahdSw2l0HUisr1UKIWJQBAMehDuqiDdzndsP2EZECAG1ZXaWM'
.'wOCODdXqysLf++uXUGv9MhUHIByDOijjdiSAoH3ErANQD73C7TXXuGOsFj1d4YH4OTJAEy8y9Hd0mCaeZ5z8dfp88zw1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DO/+ceADkCpuMFiFKbApEHkOv7BfzfXt+5gpT8V7rpfYJcDz+jAsB233r6'
.'yyBsJ0mlBCDofuBJkel4vOwBFPv8fyYAFPJ+wbSf/88UANNRVy4Awo6+Ig2gkCmgA5DHWjoA+X7AlM//owLANkX0w0359od++pvX'
.'8fdMAcj3/QJ9iJsAFPQCxHSnQt8vMJ3v2wCYpkhkAOR7vG7q4aCXoMoSgG8hFAuc/grMdAD4B/kHl9da7Ne9AAAAAElFTkSuQmCC'
);
}
/**
* Get Alex skin (in raw png)
*
* @return string Alex skin
*/
public static function getAlexSkin()
{
return base64_decode(
'iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAAAAXNSR0IArs4c6QAAAAZiS0dEAIwAuACKS3UjegAAAAlwSFlzAAAL'
.'EwAACxMBAJqcGAAAAAd0SU1FB94IFA0kCPwApjEAAAAWaVRYdENvbW1lbnQAAAAAAG1vZGVsPXNsaW1TpLy5AAAIAElEQVR42uWa'
.'728URRjH968wanznj5DoC9BASIopJFKgHFIbCUmlNQVLGhoDoqRa0rQaAgJFDRoSEuGNJmITrVrPKIgmGo0EXlg1/CYkBIwoUOUt'
.'L9b7Pt3v9NnnZq/X2722XDf5ZmZndu/2+5lnZnd2Nggm2K4dXBaK9tWHRflCerb/8ZIKUm6XD+bGNLC0OF9IR/oWllTqTZslgIvv'
.'LpL0r0M5Z3Rwd1tMmQFQZgng9P4lkl451OyMfrS7PabsAESGYZYgBEAEhObf394UEyFkEQEwDLMEIQAiIDR/sKc5JkLIJAJiAFQ3'
.'QHnVAUSGHQDVDVA+JQAgAaC6A/YB4PLPH1QdACQAVHfAPgBc+unDKgMwg57u/1DVAZhBT/d/qOoAXH/XdwEVBQTgUxYAXH/XdwEV'
.'BQTgUyYA9ODHVrddoJTS/r8e/NjqtguUUtkhTqM0afu8Sz23Rd9xGpwv5e9rczq0bZ93qee26DtOg/Ol/P0g0UjChXMMsGaSoLly'
.'TxShLNFIwoVzDLBmkqC5ck8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/88IUL+6oXh4L8bI5JyX+dZlzmASr8vmGj9'
.'P6nOFwFsZcmr9wU6OjKPgLTfFxSt8EYGYTapzkZAUiuXqststpj2+wK99u9MqvV/DcHVFeQbBHUE6PcFdgzIdLqc9vsCGGNft2v8'
.'3k9gPAB87wtQV877gv8BjY2wPg7jcKEAAAAASUVORK5CYII='
);
}
/**
* Get Steve head (in raw png)
*
* @return string Steve head
*/
public static function getSteveHead($size = 100)
{
return static::getPlayerHeadFromSkin(static::getSteveSkin(), $size);
}
/**
* Get Alex head (in raw png)
*
* @return string Alex head
*/
public static function getAlexHead($size = 100)
{
return static::getPlayerHeadFromSkin(static::getAlexSkin(), $size);
}
/**
* Get player head (in raw png) from skin
*
* @param string $skin returned by getSkin($uuid)
* @param int $size in pixels
* @return string|bool Player head, FALSE on failure
*/
public static function getPlayerHeadFromSkin($skin, $size = 100)
{
if (is_string($skin)) {
$im = @imagecreatefromstring($skin);
if (is_resource($im)) {
$av = imagecreatetruecolor($size, $size);
imagecopyresized($av, $im, 0, 0, 8, 8, $size, $size, 8, 8); // Face
imagecolortransparent($im, imagecolorat($im, 63, 0)); // Black Hat Issue
imagecopyresized($av, $im, 0, 0, 8 + 32, 8, $size, $size, 8, 8); // Accessories
ob_start();
imagepng($av);
$img = ob_get_clean();
imagedestroy($im);
imagedestroy($av);
return $img;
}
}
return false;
}
/**
* Print image from raw png
*
* Nothing should be displayed on the page other than this image
*
* @param string $img
* @param int $cache in seconds, 0 to disable
*/
public static function printImage($img, $cache = 86400)
{
header('Content-type: image/png');
header('Pragma: public');
header('Cache-Control: max-age=' . $cache);
header('Expires: '. gmdate('D, d M Y H:i:s \G\M\T', time() + $cache));
echo $img;
}
/**
* Embed image for <img> tag
*
* @param string $img
* @return string embed image
*/
public static function embedImage($img)
{
return substr($img, 0, strlen('data:image')) === 'data:image'
? $img
: 'data:image/png;base64,' . base64_encode($img);
}
/**
* Authenticate with a Minecraft account
*
* After a few fails, Mojang server will deny all requests !
*
* @param string $id Minecraft username or Mojang email
* @param string $password Account's password
* @return array|bool Array with id and name, FALSE if authentication failed
*/
public static function authenticate($id, $password)
{
if (!function_exists('curl_init') or !extension_loaded('curl')) {
return false;
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://authserver.mojang.com/authenticate');
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode(array(
'agent' => array(
'name' => 'Minecraft',
'version' => 1,
),
'username' => $id,
'password' => $password
)));
$output = curl_exec($ch);
curl_close($ch);
$json = static::parseJson($output);
if (is_array($json)
and array_key_exists('selectedProfile', $json)
and is_array($json['selectedProfile'])
and array_key_exists('id', $json['selectedProfile'])
and array_key_exists('name', $json['selectedProfile'])
) {
return array(
'id' => $json['selectedProfile']['id'],
'name' => $json['selectedProfile']['name']
);
}
return false;
}
/**
* Query a Minecraft server
*
* @see https://github.com/xPaw/PHP-Minecraft-Query/
*
* @param string $address Server's address
* @param int $port Server's port, default is 25565
* @param int $timeout Timeout (in seconds), default is 2
* @return array|bool Array with query result, FALSE if query failed
*/
public static function query($address, $port = 25565, $timeout = 2)
{
// Check arguments and if functions exists
if (!is_numeric($timeout) or $timeout < 0 or !function_exists('fsockopen')) {
return false;
}
// Try to connect
$start = microtime(true);
$socket = @fsockopen('udp://' . $address, (int) $port, $errNo, $errStr, $timeout);
if ($errNo or $socket === false) {
return false;
}
// Set read/write timeout
stream_set_timeout($socket, $timeout);
stream_set_blocking($socket, true);
// Send handshake
$data = static::queryWriteData($socket, 0x09);
if ($data === false) {
return false;
}
// And query
$challenge = pack('N', $data);
$data = static::queryWriteData($socket, 0x00, $challenge . pack('c*', 0x00, 0x00, 0x00, 0x00));
if (!$data) {
return false;
}
$last = '';
$info = array();
// Extract data
$data = substr($data, 11);
$data = explode("\x00\x00\x01player_\x00\x00", $data);
if (count($data) !== 2) {
return false;
}
$players = substr($data[1], 0, -2);
$data = explode("\x00", $data[0]);
// Array with known keys in order to validate the result
$keys = array(
'hostname' => 'motd',
'gametype' => 'gametype',
'version' => 'version',
'plugins' => 'plugins',
'map' => 'map',
'numplayers' => 'players',
'maxplayers' => 'maxplayers',
'hostport' => 'hostport',
'hostip' => 'hostip',
'game_id' => 'gamename'
);
$mb_convert_encoding = function_exists('mb_convert_encoding');
foreach ($data as $key => $value) {
if (~$key & 1) {
if (!array_key_exists($value, $keys)) {
$last = false;
continue;
}
$last = $keys[$value];
$info[$last] = '';
} elseif ($last !== false) {
if (strlen($value)) {
$info[$last] = $mb_convert_encoding ? mb_convert_encoding($value, 'UTF-8') : $value;
} else {
$info[$last] = null;
}
}
}
// Ints
$info['players'] = intval($info['players']);
$info['maxplayers'] = intval($info['maxplayers']);
$info['hostport'] = intval($info['hostport']);
// Parse "plugins" if any
if ($info['plugins']) {
$data = explode(": ", $info['plugins'], 2);
$info['rawplugins'] = $info['plugins'];
$info['software'] = $data[0];
if (count($data) == 2) {
$info['plugins'] = explode("; ", $data[1]);
}
}
if (empty($players)) {
$info['playerlist'] = null;
} else {
$info['playerlist'] = explode("\x00", $players);
}
$info['timeout'] = microtime(true) - $start;
fclose($socket);
return $info;
}
/**
* Ping a Minecraft server
*
* @see https://github.com/xPaw/PHP-Minecraft-Query/
*
* @param string $address Server's address
* @param int $port Server's port, default is 25565
* @param int $timeout Timeout (in seconds), default is 2
* @return array|bool Array with query result, FALSE if query failed
*/
public static function ping($address, $port = 25565, $timeout = 2)
{
// Check arguments and if functions exists
if (!is_numeric($timeout) or $timeout < 0 or !function_exists('fsockopen')) {
return false;
}
// Try to connect
$start = microtime(true);
$socket = @fsockopen($address, (int) $port, $errNo, $errStr, $timeout);
if ($errNo or $socket === false) {
return false;
}
// Set read/write timeout
stream_set_timeout($socket, $timeout);
// See http://wiki.vg/Protocol (Status Ping)
$packet = "\x00\x04" . pack('c', strlen($address)) . $address . pack('n', $port) . "\x01";
$data = pack('c', strlen($packet)) . $packet;
// Send handshake and ping
fwrite($socket, $data);
fwrite($socket, "\x01\x00");
// Read response
$packetLength = static::pingReadVarInt($socket);
if ($packetLength === false or $packetLength < 10) {
return false;
}
fgetc($socket);
$length = static::pingReadVarInt($socket);
if ($length === false) {
return false;
}
$data = '';
do {
if (microtime(true) - $start > $timeout) {
return false;
}
$remainder = $length - strlen($data);
$block = fread($socket, $remainder);
if (!$block) {
return false;
}
$data .= $block;
} while (strlen($data) < $length);
$data = static::parseJson($data);
if (empty($data)
or json_last_error() !== JSON_ERROR_NONE
or !array_key_exists('players', $data)
or !is_array($data['players'])
or !array_key_exists('online', $data['players'])
) {
return false;
}
if (array_key_exists('description', $data)
and is_array($data['description'])
and array_key_exists('extra', $data['description'])
and empty($data['description']['text'])
) {
$motd = '';
foreach ($data['description']['extra'] as $key => $value) {
$motd .= $value['text'];
}
$data['description']['text'] = $motd;
}
$data['timeout'] = microtime(true) - $start;
return $data;
}
/**
* Parse JSON
*
* @param string $json
* @return string|bool json data, FALSE on failure
*/
private static function parseJson($json)
{
$data = json_decode($json, true);
return empty($data) ? false : $data;
}
/**
* Fetch url content
*
* @param string $url
* @return string|false content, FALSE on failure
*/
private static function fetch($url)
{
if (function_exists('curl_init') and extension_loaded('curl')) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
$output = curl_exec($ch);
curl_close($ch);
return $output;
} else {
return @file_get_contents($url);
}
}
/**
* Fetch url content as JSON
*
* @param string $url
* @return array|false json data, FALSE on failure
*/
private static function fetchJson($url)
{
$output = static::fetch($url);
if (!empty($output)) {
$json = static::parseJson($output);
if (is_array($json) and !array_key_exists('error', $json)) {
return $json;
}
}
return false;
}
/**
* Write data in a socket for query
*
* @param socket $socket
* @param string $command
* @param string $append, default is ''
* @return string|false data, FALSE on failure
*/
private static function queryWriteData($socket, $command, $append = '')
{
$command = pack('c*', 0xFE, 0xFD, $command, 0x01, 0x02, 0x03, 0x04) . $append;
$length = strlen($command);
if ($length !== fwrite($socket, $command, $length)) {
return false;
}
$data = fread($socket, 4096);
if ($data === false or strlen($data) < 5 or $data[0] != $command[2]) {
return false;
}
return substr($data, 5);
}
/**
* Read var int in a socket for ping
*
* @param socket $socket
* @return int|false var int, FALSE on failure
*/
private static function pingReadVarInt($socket)
{
$i = $j = 0;
while (true) {
$k = @fgetc($socket);
if ($k === false) {
return false;
}
$k = ord($k);
$i |= ($k & 0x7F) << $j++ * 7;
if ($j > 5) {
return false;
}
if (($k & 0x80) != 128) {
break;
}
}
return $i;
}
}