-
Notifications
You must be signed in to change notification settings - Fork 5
/
BinaryBeast.php
1452 lines (1344 loc) · 45.6 KB
/
BinaryBeast.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
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* The main library class, used to communicate with the API and as a factory to generate model objects
*
* ## Before you do ANYTHING else - setup the configuration values
*
* You must setup the configuration values in {@link BBConfiguration}
*
*
*
*
* ### Getting started ###
*
* This class is your starting point for everything - and there are a few ways to instantiate it
* Here are a few examples of how to instantiate this class
*
* ********
* <b>Example: Minimal setup, use settings from {@link lib/BBConfiguration.php}</b>
* <code>
* $bb = new BinaryBeast();
* </code>
*
* ********
* <b>Example: Manually define your api_key</b>
* <code>
* $bb = new BinaryBeast('e17d31bfcbedd1c39bcb018c5f0d0fbf.4dcb36f5cc0d74.24632846');
* </code>
*
* ********
* <b>Example: Use a custom BBConfiguration object</b><br />
* Pass in a custom {@link BBConfiguration} instance, and define classes for we would like to use for extending {@link BBTournament} and {@link BBTeam}<br /><br />
* <code>
* $config = new BBConfiguration;
* $config->models_extensions['BBTournament'] = 'LocalTournament';
* $config->models_extensions['BBTeam'] = 'LocalTeam';
*
* $bb = new BinaryBeast($config);
* </code>
*
*
*
*
* ### Debugging ###
* We recommend {@link enable_dev_mode()} when developing, as it will
* automatically display errors for you
*
* <br /><br />
* You may refer to {@link $last_error} and {@link $error_history} at any time to try to view recent errors
*
*
*
* ### Models ### .[#models]
*
* Model objects are the heart and soul of this library, ***most of your work will be with model objects***
*
* <br /><br />
* There are two types of model objects:
* - Full ({@link http://en.wikipedia.org/wiki/Crud CRUD})<br />
* (Ability to view and fully manipulate any object
* - Simple <br />
* Used only for loading lists and fetching data, like a list of games, or maps within a game etc
*
*
* ### Full Models ###
*
* Full models are objects that can be <b>loaded</b>, <b>changed</b>, and <b>deleted</b>, and represent data hosted by<br />
* BinaryBeast.com, like a tournament or a match result
*
* <br />
* Models are designed so that the object's data is loaded only on-demand when you try to access or change something,<br />
* which is particularly nice when you have a complicated tournament model with hundreds of match results
*
*
* <b>Available models: </b>
* - {@link BBTournament}: A full tournament object
* - {@link BBTeam}: Teams / Players within a tournamnet
* - {@link BBRound}: Round Format / Configuration within a tournament
* - {@link BBMatch}: Used for reporting and viewing match results within a tournament
* - {@link BBMatchGame}: Single detailed game results within a match
*
* ### Simple models
*
* Simple models are used for <b>searching / listing only</b>
*
* {@link BinaryBeast} offers some "magic" properties for conveniently and quickly accessing these models
*
* <b>Example - Load a list of popular games: </b>
* <b>Note:</b> We're using the magic <var>$game</var> property to access {@link BBGame}
* <code>
* $games = $bb->game->list_popular();
* foreach($games as $game) {
* echo '<div class="game">' .
* $game->game . '(' . $game->game_code . ')' .
* '<img src="' . $game->game_icon . '" /></div>';
* }
* </code>
*
* Each simple model has documentation with examples...<br />
* <b>Available simple models:</b>
* - {@link BBCountry}
* - {@link BBGame}
* - {@link BBMap}
* - {@link BBRace}
* - {@link BBCache}
* - {@link BBCallback}
*
*
* ### Error Handling
*
* Any time an error is encountered, false or null is returned when you expected an object..
* check {@link BinaryBeast::last_error} and {@link BinaryBeast::error_history}, there is likely
* an explanation in there
*
* You can use this page to view a full log your recent API requests, and the response you were given: {@link http://binarybeast.com/user/settings/api_history}
*
*
* ### Backwards Compatibility
*
* If your application is currently using an older version of this library, it will still work with this one
*
* To make that possible, we've included {@link lib/BBLegacy.php}, which hosts all of the old
* legacy api service wrappers from the previous version of this library
*
*
* ### Quick Tutorials and Examples ###
*
* Each example assumes the following has already been executed,
* and that <b>you've set the values in {@link BBConfiguration}</b>
*
* <code>
* require('BinaryBeast.php');
* $bb = new BinaryBeast();
* </code>
*
*
* ### More Tutorials
*
* <b>Next step:</b> Begin by skimming through the documentation for {@link BBTournament}
*
*
* ### Extending the Model Classes
*
* Coming soon...
*
*
* @property BBTournament $tournament
* <b>Alias for {@link BinaryBeast::tournament()}</b><br />
* A new {@link BBTournamament} object<br />
*
* @property BBTeam $team
* <b>Alias for {@link BinaryBeast::team()}</b><br />
* A new {@link BBTeam} object
*
* @property BBRound $round
* <b>Alias for {@link BinaryBeast::round()}</b><br />
* A new {@link BBRound} object
*
* @property BBMatch $match
* <b>Alias for {@link BinaryBeast::match()}</b><br />
* A new {@link BBMatch} object
*
* @property BBMatchGame $match_game
* <b>Alias for {@link BinaryBeast::match_game()}</b><br />
* A new {@link BBMatchGame} instance, used by {@link BBMatch} to define play-by-play details within the match
*
* @property BBMap $map
* <b>Alias for {@link BinaryBeast::map()}</b><br />
* A {@link BBMap} object, that you can use to search for maps and map_ids<br />
*
* @property BBCountry $country
* <b>Alias for {@link BinaryBeast::country()}</b><br />
* A {@link BBCountry} object, that you can use to search for countries and country codes<br />
*
* @property BBGame $game
* <b>Alias for {@link BinaryBeast::game()}</b><br />
* Returns a {@link BBGame} object, that you can use to search for games and game_codes<br />
*
* @property BBRace $race
* <b>Alias for {@link BinaryBeast::race()}</b><br />
* Returns a {@link BBRace} object, that you can use to search for races and race_ids
*
* @property BBLegacy $legacy
* <b>Alias for {@link BinaryBeast::legacy()}</b><br />
* Returns the BBLegacy class, that is used to execute the old wrapper methods that were provided in earlier versions of this library
*
* @property BBCallback $callback
* <b>Alias for {@link BinaryBeast::callback()}</b><br />
* Returns the BBCallback class, used for managing event-triggered callbacks (also known as hooks)
*
* @property BBCache $cache
* <b>Alias for {@link BinaryBeast::cache()}</b><br />
* The {@link BBCache} class, which is used to save and retrieve API responses from a local database, to cut down on API calls<br />
* <b>NULL</b> if your settings in {@link BBConfiguration} are invalid / not set
*
* @property BBConfiguration $config
* <b>Alias for {@link config()}</b><br />
* The current configuration object
*
*
* @package BinaryBeast
*
* @version 3.2.1
* @date 2016-02-17
* @since 2013-02-10
* @author Brandon Simmons <[email protected]>
* @license http://www.opensource.org/licenses/mit-license.php
* @license http://www.gnu.org/licenses/gpl.html
*/
class BinaryBeast {
/**
* URL to which to send API requests
* @var string
*/
private static $url = 'https://api.binarybeast.com/';
/**
* Store the result codes / values for the previous
* API Request response
* @var object
*/
public $last_error;
/**
* A summary of the last API call made
* @var object
*/
public $last_result;
/**
* A friendly translation of the last result code sent back from the API
* @var string
*/
public $last_friendly_result;
/**
* A history of error messages
* @var object[]
*/
public $error_history = array();
/**
* A history of API call results
* @var object[]
*/
public $result_history = array();
/**
* Simple constant that contains the library version
* @var string
*/
const API_VERSION = '3.2.1';
//<editor-fold defaultstate="collapsed" desc="Private Properties">
/**
* Base path to the BinaryBeast library folder
* @var string
*/
private $lib_path;
/**
* BinaryBeast API Key
* @access private
* @var string
*/
private $api_key = null;
/**
* Login email cache
* @var string
*/
private $email = null;
/**
* Login password - goes along with {@link $email}
* @var string
*/
private $password = null;
/**
* If the ssl verification causes issues, developers can disable it
* @var boolean
*/
private $verify_ssl = true;
/**
* Constructor flags whether or not server is capable of requesting and processing the API requests
* Static so that we don't have to check it more than once if instantiated again
* @var boolean
*/
private static $server_ready = null;
/**
* Cached instance of BBLegacy
* @var BBLegacy
*/
private $legacy = null;
/**
* Cached instance of BBCallback
* @var BBCallback
*/
private $callback = null;
/**
* Store an instance of BBCache
* @var BBCache;
*/
private $cache;
/**
* Cache of simple models
*/
private $models_cache = array();
/**
* List of dependent models to auto-load when we load
* a library that needs them
* @var array[]
*/
private static $auto_load_libraries = array(
'BBTournament' => array('BBTeam', 'BBRound', 'BBMatch'),
'BBMatch' => array('BBMatchGame')
);
/**
* The first time this class is instantiated, we'll auto-load
* some libraries, but skip that step if another instance is created
* @var boolean
*/
private static $first = true;
/**
* Object that stores our application-specific configuration values
* @var BBConfiguration
*/
private $config;
/**
* Flag development: enabled / disabled
* @var bool
*/
private $dev_mode = false;
//</editor-fold>
//<editor-fold desc="Service constants">
/**
* Service name used to log in using an API key,
* which will return account information
* @var string
*/
const SERVICE_API_KEY_LOGIN = 'User.UserLogin.APIKey';
/**
* Service name used to simply ping the API,
* used to test communication and configuration,
* as it would fail if called anonymously (aka your api_key must be valid)
* @var string
*/
const SERVICE_PING = 'Ping.Ping.Ping';
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="Tournament constants">
/**
* Each bracket is identified by a number,
* 0 indicates group rounds
* @var int
*/
const BRACKET_GROUPS = 0;
/**
* Each bracket is identified by a number,
* 1 indicates winners' bracket
* @var int
*/
const BRACKET_WINNERS = 1;
/**
* Each bracket is identified by a number,
* 2 indicates loser' bracket
* @var int
*/
const BRACKET_LOSERS = 2;
/**
* Each bracket is identified by a number,
* 3 indicates grand finals
* @var int
*/
const BRACKET_FINALS = 3;
/**
* Each bracket is identified by a number,
* 4 indicates bronze / 3rd place decider
* @var int
*/
const BRACKET_BRONZE = 4;
/**
* Single elimination mode
* @var int
*/
const ELIMINATION_SINGLE = 1;
/**
* Double elimination mode
* @var int
*/
const ELIMINATION_DOUBLE = 2;
/**
* <b>Tournament type</b><br />
* Elimination brackets only
* @var int
*/
const TOURNEY_TYPE_BRACKETS = 0;
/**
* <b>Tournament type</b><br />
* group rounds following by elimination brackets
* @var int
*/
const TOURNEY_TYPE_CUP = 1;
/**
* <b>Seeding type</b><br />
* Randomized seeds / ranks / groups
* Affects both group rounds and brackets
* @var string
*/
const SEEDING_RANDOM = 'random';
/**
* <b>Seeding type</b><br />
* Positions are determined by rank
* Affects elimination brackets only
* @var string
*/
const SEEDING_SPORTS = 'sports';
/**
* <b>Seeding type</b><br />
* Positions are determined by rank, but matchups are more
* fair than traditional / sports seeding type
* Affects elimination brackets only
* @var string
*/
const SEEDING_BALANCED = 'balanced';
/**
* <b>Seeding type</b><br />
* Positions are manually defined
* Affects both group rounds and brackets
* @var string
*/
const SEEDING_MANUAL = 'manual';
/**
* <b>Replay download mode</b><br />
* Replays can never be downloaded
* @var int
*/
const REPLAY_DOWNLOADS_DISABLED = 0;
/**
* <b>Replay download mode</b><br />
* Replays can be downloaded at any time
* @var int
*/
const REPLAY_DOWNLOADS_ENABLED = 1;
/**
* <b>Replay download mode</b><br />
* Replays can only be downloaded once the tournament is complete
* @var int
*/
const REPLAY_DOWNLOADS_POST_COMPLETE = 2;
/**
* <b>Replay upload mode</b><br />
* Replays cannot be uploaded
* @var int
*/
const REPLAY_UPLOADS_DISABLED = 0;
/**
* <b>Replay upload mode</b><br />
* Replays can be uploaded
* @var int
*/
const REPLAY_UPLOADS_OPTIONAL = 1;
/**
* <b>Replay upload mode</b><br />
* Replays <b>MUST</b> be uploaded
* @var int
*/
const REPLAY_UPLOADS_MANDATORY = 2;
/**
* <b>Team status</b><br />
* Unconfirmed - the team will NOT be included in the tournament
* @var int
*/
const TEAM_STATUS_UNCONFIRMED = 0;
/**
* <b>Team status</b><br />
* Confirmed - the team will be included in the tournament
* @var int
*/
const TEAM_STATUS_CONFIRMED = 1;
/**
* <b>Team status</b><br />
* Banned - the team will NOT be included in the tournament, and has no permission to take any action<br />
* This means if a user had permisssion to this team, he would not be able to report wins, confirm, leave the tournament, etc
* @var int
*/
const TEAM_STATUS_BANNED = -1;
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="Result code constants">
/**
* <b>API Result Code</b><br />
* The API call was successful
* @var int
*/
const RESULT_SUCCESS = 200;
/**
* <b>API Result Code</b><br />
* Your api_key or email/password is invalid - you were not logged in
* @var int
*/
const RESULT_NOT_LOGGED_IN = 401;
/**
* <b>API Result Code</b><br />
* Your account does not have the authority to perform that action
* @var int
*/
const RESULT_AUTH = 403;
/**
* <b>API Result Code</b><br />
* Invalid service name, or ID
* @var int
*/
const RESULT_NOT_FOUND = 404;
/**
* <b>API Result Code</b><br />
* That service is not enabled for public API use
* @var int
*/
const RESULT_API_NOT_ALLOWED = 405;
/**
* <b>API Result Code</b><br />
* The email you tried to log in with is invalid
* @var int
*/
const RESULT_LOGIN_EMAIL_INVALID = 406;
/**
* <b>API Result Code</b><br />
* The email provied is already being used
* @var int
*/
const RESULT_EMAIL_UNAVAILABLE = 415;
/**
* <b>API Result Code</b><br />
* The email provided is not a valid email address
* @var int
*/
const RESULT_INVALID_EMAIL_FORMAT = 416;
/**
* <b>API Result Code</b><br />
* Your account is currently pending activation
* @var int
*/
const RESULT_PENDING_ACTIVIATION = 418;
/**
* <b>API Result Code</b><br />
* Your account has been banned
* @var int
*/
const RESULT_LOGIN_USER_BANNED = 425;
/**
* <b>API Result Code</b><br />
* Incorrect login password
* @var int
*/
const RESULT_PASSWORD_INVALID = 450;
/**
* <b>API Result Code</b><br />
* The game_code value you provided does not exist
* @var int
*/
const RESULT_GAME_CODE_INVALID = 461;
/**
* <b>API Result Code</b><br />
* Invalid bracket integer
* @var int
*/
const RESULT_INVALID_BRACKET_NUMBER = 465;
/**
* <b>API Result Code</b><br />
* Duplicate entry - must be unique
* @var int
*/
const RESULT_DUPLICATE_ENTRY = 470;
/**
* <b>API Result Code</b><br />
* General processing error<br />
* <b>Please report these to BinaryBeast <[email protected]>
* @var int
*/
const RESULT_ERROR = 500;
/**
* <b>API Result Code</b><br />
* The search filter value is too short, please include at least 2 characters
* @var int
*/
const RESULT_SEARCH_FILTER_TOO_SHORT = 601;
/**
* <b>API Result Code</b><br />
* Provided user_id does not exist
* @var int
*/
const RESULT_INVALID_USER_ID = 604;
/**
* <b>API Result Code</b><br />
* Invalid tournament id
* @var int
*/
const RESULT_TOURNAMENT_NOT_FOUND = 704;
/**
* <b>API Result Code</b><br />
* The given team and tournament do not belong to eachother
* @var int
*/
const TEAM_NOT_IN_TOURNEY_ID = 705;
/**
* <b>API Result Code</b><br />
* Invalid team id
* @var int
*/
const TOURNEY_TEAM_ID_INVALID = 706;
/**
* <b>API Result Code</b><br />
* Invalid match id
* @var int
*/
const RESULT_MATCH_ID_INVALID = 708;
/**
* <b>API Result Code</b><br />
* Invalid match_game id
* @var int
*/
const RESULT_MATCH_GAME_ID_INVALID = 709;
/**
* <b>API Result Code</b><br />
* Your tournament does not have enough confirmed teams to fill enough groups to match $group_count<br />
* You need at least 2 teams per {@link BBTournament::$group_count}
* @var int
*/
const RESULT_NOT_ENOUGH_TEAMS_FOR_GROUPS = 711;
/**
* <b>API Result Code</b><br />
* The current tournament status does not allow that action<br />
* Could be anything from trying to add / remove teams in an active tournament, or trying to start
* a tournament that has already finished
* @var int
*/
const RESULT_TOURNAMENT_STATUS = 715;
//</editor-fold>
/**
* Library constructor
*
* You can either provide a BBConfiguration instance, or an api_key as the argument
*
* @param string|BBConfiguration
* You can pass in either the api_key, or a customized BBConfiguration object
*/
function __construct($api_key = null) {
//Determine the path to the library directory
$this->lib_path = str_replace('\\', '/', dirname(__FILE__ )) . '/lib/';
/**
* Make sure this server supports json and cURL
* Static because there's no point in checking for each instantiation
*/
self::$server_ready = self::check_server();
//Execute the static "constructor", but only for the first instantiation
if(self::$first) self::init($this);
//Use a custom BBConfiguration object
if($api_key instanceof BBConfiguration) $this->config = $api_key;
//Store default configuration
else {
$this->config = new BBConfiguration();
//Use a custom api_key
if(!is_null($api_key)) $this->config->api_key = $api_key;
}
}
/**
* Pseudo-static constructor, this method only once,
* only the first time this class is instantiated
*
* It's used to pre-load some of the core library classes that
* we are most likely to use - most other libraries (for example BBLegacy, BBTournament),
* are only loaded as they are used
*
* @param BinaryBeast $bb Since it's a static method, we need a reference to the instance
*
* @return void
*/
private static function init(&$bb) {
$bb->load_library('BBConfiguration');
$bb->load_library('BBHelper');
$bb->load_library('BBSimpleModel');
$bb->load_library('BBModel');
$bb->load_library('BBCache');
$bb->load_library('BBCallback');
$bb->load_library('BBDev');
//Next instantiation will know not to call this method
self::$first = false;
}
/**
* Checks to make sure this server supports json and cURL
*
* @return boolean
*/
private static function check_server() {
return function_exists('json_decode') && function_exists('curl_version');
}
/**
* Alternative Email/Password authentication
*
* This library defaults to using an api_key, but you can
* alternatively use this method to log in using
* a more traditional email and password
*
* @param string $email
* @param string $password
* @param bool $test
*
* @return boolean
*/
public function login($email, $password, $test = false) {
$this->email = $email;
$this->password = $password;
if($test) return $this->test_login();
return true;
}
/**
* Determines whether or not the provided api_key or email/password
* are valid
*
* It calls the Ping.Ping.Ping service, which is NOT
* an anonymously accessible service, therefore if authentication
* fails, we will easily be able to determine that, as the
* result code would be reflect it
*
* If you want the result code directly instead of a boolean,
* pass in true for the argument
*
* @param bool $get_code Defaults to false, return the result code instead of a boolean
*
* @return boolean
*/
public function test_login($get_code = false) {
$result = $this->call(self::SERVICE_PING);
return $get_code ? $result->result : $result->result == 200;
}
/**
* If SSL Host verification causes any issues, call this method to disable it
* @return void
*/
public function disable_ssl_verification() {
$this->verify_ssl = false;
}
/**
* Re-enable ssl verification
* @return void
*/
public function enable_ssl_verification() {
$this->verify_ssl = true;
}
/**
* Returns the current ssl-verification mode, true = enabled, false = disabled
* @return boolean
*/
public function ssl_verification() {
return $this->verify_ssl;
}
/**
* Executes an API service, and returns the raw unprocessed value
*
* It can be useful if your PHP can't handle JSON, but you want to use it
* to feed json results to a local ajax request or something similiar
*
* Otherwise, it's just used internally so ignore it lol
*
* <br /><br />
* The arguments are indentical to those in {@link call()}
*
* @param string $svc
* @param array $args
* @param string $return_type
* <b>Possible Values:</b>
* - json
* - jsonp
* - xml
*
* @return string
*/
public function call_raw($svc, $args = null, $return_type = null) {
//This server isn't ready for processing API requests
if (!self::$server_ready) {
return $this->get_server_ready_error();
}
//Add the service to the arguments, and the return type
if(is_null($args)) $args = array();
$args['api_return'] = is_null($return_type) ? 'json' : $return_type;
$args['api_service'] = $svc;
//This will soon become the default, but for now we have to specify that we want to use lowercase_under format for variables
$args['api_use_underscores'] = true;
//Specify the library language / version for logging / statistics
$args['api_agent'] = 'BinaryBeast API PHP: Version ' . self::API_VERSION;
//If caching is configured, indicate that in the api_agent value
if($this->cache() != false) $args['api_agent'] .= ' (local caching)';
//API Key authentication
if (!is_null($this->config->api_key)) {
$args['api_key'] = $this->config->api_key;
}
//Alternative email + password authentication
else if (!is_null($this->email)) {
$args['api_email'] = $this->email;
$args['api_password'] = $this->password;
}
//Who you gonna call?
return $this->call_curl(http_build_query($args));
}
/**
* Make a service call to the remote BinaryBeast API
*
* @param string $svc Service to call (ie Tourney.TourneyCreate.Create)
* @param array $args Arguments to send
* @param int $ttl If you configured the BBCache class, use this to define how many minutes this result should be cached
* @param int $object_type For caching objects: see BBCache::type_ constants
* @param mixed $object_id For caching objects: The id of this the object, like tourney_id or tourney_team_id
* @return object
*/
public function call($svc, $args = null, $ttl = null, $object_type = null, $object_id = null) {
//This server does not support curl or fopen
if (!self::$server_ready) {
return $this->get_server_ready_error();
}
//Cache?
if(!is_null($ttl)) {
if($this->cache() !== false) {
return $this->cache->call($svc, $args, $ttl, $object_type, $object_id);
}
}
//GOGOGO! grab the raw result (call_raw), and parse it through decode for json decoding + (object) casting
$response = $this->decode($this->call_raw($svc, $args));
//Store the latest result code, so developers can have easy access to it in $bb->result[_friendly]
$this->set_result($response, $svc, $args);
//Success!
return $response;
}
/**
* Store an error into $this->error, developers can refer to it
* as $tournament|$match|etc->error()
*
* In order to standardize error values, it accepts arrays, or strings
* but if you provide a string, it is converted into array('error_message'=>$in)
*
* This method will return the new error value, in case we
* decided to reformat it / add to it, so that model classes
* can be sure to stash the same error set here
*
* @param mixed $error Error value to save
* @param string $class Name of the class setting this error
* @param string $error_title
* @param boolean $warning
* @param boolean $fatal
* @return object
*/
public function set_error($error = null, $class = null, $error_title = null, $warning = false, $fatal = false) {
//Convert arrays into objects
if(is_array($error)) $error = (object)$error;
//Either store it into a new array, or add some values to the input
if(!is_null($error)) {
//Default to BinaryBeast.php if class name not provided
if(is_null($class)) {
$class = 'BinaryBeast.php';
}
//Compile an array using the input
$details = (object)array('class' => $class);
//For existing objects, simply add our details
if(is_object($error)) $error = (object)array_merge((array)$details, (array)$error);
//For everything else, add the input into a new object
else $error = (object)array_merge((array)$details, array('error_message' => $error));
}
//Stash it!
$this->last_error = $error;
//Add it to our error history log
if(!is_null($error)) $this->error_history[] = $this->last_error;
//Print it
BBDev::print_error($this, $this->last_error, $error_title, debug_backtrace(), $warning, $fatal);
//Return the new value we came up with so that models store it the same way we did here
return $this->last_error;
}
/**
* Modal classes call this to clear out any prior error results
* @return void
*/
public function clear_error() {
$this->set_error(null);
}
/**
* Stores the result code from the latest API Request, so developers can
* always access the latest result in $bb->result, or $bb->result(), or $bb->result_friendly etc
*
* @param object $result A reference to the API's response
* @param string $svc Service name called
* @param array $args Arguments used
* @return void
*/
private function set_result(&$result, $svc, $args) {
//Stash the new values, and try to translate the result code to be more readable
$this->last_result = isset($result->result) ? $result->result : false;
$this->last_friendly_result = BBHelper::translate_result($this->last_result);
//Parse into an object for storage / dumping
$result_history = (object)array('result' => $this->last_result, 'friendly' => $this->last_friendly_result, 'svc' => $svc, 'args' => $args);
//Store it in the result history array too
$this->result_history[] = $result_history;
//Dump failed calls
if($this->last_result != 200) {
$title = 'API Failure (' . $this->last_friendly_result . ')';
BBDev::print_error($this, $this->last_result, $title, debug_backtrace());
}
}
/**
* Simply returns an array with a Result to return in case no method could be determined
*
* @return object {int result, string Message}
*/
private function get_server_ready_error() {
$data = (object)array(
'message' => 'Your server must support both json_decode, and curl!',
'function_exists: json_decode' => function_exists('json_decode'),
'function_exists: curl' => function_exists('curl_version')
);
BBDev::print_error($this, $data, 'Server Configuration Error', false, false, true);
return (object)array('result' => false,
'message' => 'Please verify that both cURL and json are enabled your server!'
);
}
/**
* Make a service call to the BinaryBeast API via the cURL library
*
* @ignore
*
* @param string $args
* URL encoded arguments
*
* @return string
*/
private function call_curl($args) {
//Get a curl instance
$curl = curl_init();
$curl_config = [
CURLOPT_URL => self::$url,
CURLOPT_SSL_VERIFYHOST => $this->verify_ssl ? 2 : 0,
CURLOPT_SSL_VERIFYPEER => $this->verify_ssl,
CURLOPT_SSLVERSION => CURL_SSLVERSION_TLSv1_2,
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POSTFIELDS => $args,
];
//Enable for debugging
if($this->dev_mode) {