Repository navigation
Expand file tree
/
Copy pathHackapi.php
More file actions
executable file
·1903 lines (1746 loc) · 59 KB
/
Copy pathHackapi.php
File metadata and controls
executable file
·1903 lines (1746 loc) · 59 KB
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
/*
--------------------------------------------------------------------------------------------------------------------------------------
HackApi main Class
--------------------------------------------------------------------------------------------------------------------------------------
Copyright (C) 2023 by François Déchery - https://github.com/soif/
HackApi is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
HackApi is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
--------------------------------------------------------------------------------------------------------------------------------------
*/
class Hackapi{
private $version ='1.33'; // HackApi Version
// host and credentials -----------
protected $host =""; // (default) ip address or hostname
protected $use_ssl =false; // (default) use httpS ?
protected $user ="admin"; // (default) user name
protected $password =""; // (default) user password
private $preferences =false; // an array holding the above or FALSE when not set
protected $client_version ='0.00'; // API client Version, formatted as M.mm
protected $use_cookies =true; // do we automatically handles cookies?
protected $def_referer =''; // when set, default referer URL to add in the default headers. Starts with "/";
protected $def_endpoint =''; // default enpoint to use when not set in the CallEndpoint method
protected $def_headers =array(); // default headers to send with each call
protected $def_params =array(); // default parameters to always add in the CallEndpoint method
protected $is_logged =false; // Are we logged in ?
protected $last_call =array(); // contains all the Last Call parameters.
protected $last_error =array(); // contains the latest errors
// Durable auth cache (optional) — SetAuthCachePath enables JSON (+ cookie jar when use_cookies)
protected $auth_cache_ttl =1800; // default TTL seconds (drivers may override)
private $auth_cache_dir =null; // null = off (no durable JSON); ephemeral cookie jar still used when use_cookies
private $auth_cache_file =''; // full path to auth_*.json when dir set
private $_auth_from_cache =false; // session restored from file (for one-shot stale recovery)
private $_auth_recover_done =false; // at most one Clear+re-login per instance after Import
protected $api_error_codes =array(); // Populated with Api specific error api_code=>['DESCPRITION',error_code]
private $error_codes =array( // error codes meaning
0 =>'Returned False (No Error)',
1 =>'Malformed Request',
2 =>'Malformed Answer',
3 =>'Permission Issue',
4 =>'Exception thrown',
5 =>'Unexpected Error',
6 =>'Unimplemented Method/Endpoint',
7 =>'API Error',
8 =>'API Error (not mapped)',
);
private $min_apimethod_state=5; // Minimum allowed method dev state. Method with a lower state will throw an Exception
private $debug_level =0; // Debug Level: 0= no debug, 1=Error, 2 =+Info, 3=+Debug 4=+verbose
private $debug_output =0; // Debug Output: 0=None, 1=print
// PHP warnings / notices / deprecations from this tree. Separate from SetDebug.
// define('HACKAPI_SHOW_PHP_ERRORS', true) before require to let PHP print them.
private static $php_notice_depth =0;
private static $php_notice_prev =null;
private static $php_notice_phase ='load'; // load | call
private static $php_load_notices =array();
private static $php_call_notices =array();
private static $endpoint_depth =0;
private $cookies_file =""; // curl cookie jar path (ephemeral or under auth cache dir)
private $base_url =""; // the base url made of http(s)://host
protected $timeout_connect =2; // CURL's Connection Timeout (sec)
protected $timeout_request =5; // CURL's Request Timeout (sec)
// CSV parse defaults (device subclasses override dialect; no auto-detect) ---
protected $csv_delimiter =','; // field separator for ParseCsvBody
protected $csv_eol ="\n"; // preferred line ending (ParseCsvBody also tolerates \r\n/\r)
protected $csv_enclosure ='"'; // field enclosure for ParseCsvBody
private $_relogin_count =0; // used to prevent infinite Loop when using CallEndpointWhenLogged in the ApiLogin method
private $_relogin_max =3; // max count to try to relogin (when in an infinite loop condition)
/**
* an array (indexed by the standard method name) of fields mapping between the Standard expected fields and the API returnted fields.
* 'to_field' => 'from_field' .Both to/from fields may be hierarchized by '/. ie: 'lan/ip' means $arr['lan']['ip'] )
*
* @var array
*/
protected $std_fields_map=array(
'ApiCellStatus'=>array(
'prov_name' => 'api_field_path', // Provider Name
'prov_fullname' => 'api_field_path', // Provider Full Name
'mcc' => 'api_field_path', // MCC
'mnc' => 'api_field_path', // MNC
'rnc' => 'api_field_path', // RNC
'enbid' => 'api_field_path', // eNB ID
'lac' => 'api_field_path', // LAC
'rat' => 'api_field_path', // RAT
'tac' => 'api_field_path', // TAC
'channel' => 'api_field_path', // Channel (EARFCN)
'bands' => 'api_field_path', // Bands
'pci' => 'api_field_path', // PCI
'mode' => 'api_field_path', // Cellular network type: LTE,CMDA,...
'protocol' => 'api_field_path', // Protocol
'imei' => 'api_field_path', // IMEI
'imci' => 'api_field_path', // IMCI
'iccid' => 'api_field_path', // Sim ICCI
'imsi' => 'api_field_path', // Sim IMSI
'msisdn' => 'Msisdn', // Sim Phone Number
'strength' => 'api_field_path', // (%) Strength
'csq' => 'api_field_path', // CSQ
'rssi' => 'api_field_path', // (dBm) RSSI
'rscp' => 'api_field_path', // (dBm) RSCP
'rsrp' => 'api_field_path', // (dBm) RSRP
'ecio' => 'api_field_path', // (dB) ECIO
'rsrq' => 'api_field_path', // (dB) RSRQ
'sinr' => 'api_field_path', // (dB) SINR
'cell_id' => 'api_field_path', // Cell ID
'rx_speed' => 'api_field_path', // (Kbytes/sec) Download Speed
'tx_speed' => 'api_field_path', // (Kbytes/sec) Upload Speed
),
'ApiSmsList'=>array(
'id' => 'api_field_path', // SMS's ID (the one used to delete the SMS)
'date' => 'api_field_path', // SMS's Date, formatted as a SQL datetime (YYYY-MM-DD HH:MM:SS)
'phone' => 'api_field_path', // SMS's Phone Number
'text' => 'api_field_path', // SMS's Text Content
),
'ApiWanStatus'=>array(
'mac' => 'api_field_path', // MAC address
'up' => 'api_field_path', // (boolean) Are we connected ?
'since' => 'api_field_path', // Seconds since we are connected
'ipv4' => 'api_field_path', // IP address (v4)
'ipv6' => 'api_field_path', // IP address (v6)
'dns1v4' => 'api_field_path', // DNS Server 1 IP address (v4)
'dns2v4' => 'api_field_path', // DNS Server 2 IP address (v4)
'dns1v6' => 'api_field_path', // DNS Server 1 IP address (v6)
'dns2v6' => 'api_field_path', // DNS Server 2 IP address (v6)
'gatewayv4' => 'api_field_path', // Gateway IP address (v4)
'gatewayv6' => 'api_field_path', // Gateway IP address (v6)
'rx_realtime' => 'api_field_path', // (bytes) Realtime RX
'rx_peak' => 'api_field_path', // (bytes) Peak RX
'rx_day' => 'api_field_path', // (bytes) Daily RX
'rx_month' => 'api_field_path', // (bytes) Monthly RX
'rx_total' => 'api_field_path', // (bytes) Total RX
'tx_realtime' => 'api_field_path', // (bytes) Realtime TX
'tx_peak' => 'api_field_path', // (bytes) Peak TX
'tx_day' => 'api_field_path', // (bytes) Daily TX
'tx_month' => 'api_field_path', // (bytes) Monthly TX
'tx_total' => 'api_field_path', // (bytes) Total TX
),
'ApiWifiListClients'=>array(
'id' => 'api_field_path', // the internal ID assigned by the device (else set it to the MAC address)
'mac' => 'api_field_path', // MAC address
'ipv4' => 'api_field_path', // IP address (v4)
'ipv6' => 'api_field_path', // IP address (v6)
'dns_name' => 'api_field_path', // DNS host name
'name' => 'api_field_path', // host name (usually sent by client)
'alias' => 'api_field_path', // friendly host name (user-defined in the device)
'time' => 'api_field_path', // (unix time) Date when the client has been connected
'duration' => 'api_field_path', // (sec) How long the client has been connected
'level_send' => 'api_field_path', // (db) Send Level
'level_receive' => 'api_field_path', // (db) Receive Level
),
'ApiWifiListSsids'=>array(
'id' => 'api_field_path', // the internal Station ID/name assigned by the device (used to filter the ApiWifiListClients)
'bssid' => 'api_field_path', // BSSID MAC Address
'ssid' => 'api_field_path', // SSID MAC Address
'password' => 'api_field_path', // Password
'enabled' => 'api_field_path', // Is enabled ? (true|false)
'channel' => 'api_field_path', // Frequency Channel
'mode' => 'api_field_path', // Wifi Mode (11xxx)
),
);
// ############################################################################################
// -------------------------------------------------------------------------
/**
* Load defaults, build base URL, and initialize cookie jar paths.
*
* @return void
*/
public function __construct(){
$this->LoadDefaults();
$this->SetHost($this->host,$this->use_ssl);
$this->TakePhpNotices();
}
// ############################################################################################
// ## METHODS TO OVERRIDE (REQUIRED) ##########################################################
// ############################################################################################
// -------------------------------------------------------------------------
/**
* Log-in into the API. It must set $this->is_logged to TRUE, when succeeded
*
* @param string $user (optional) Forces User name (else $this->user is used)
* @param string $password (optional) Forces User password (else $this->password is used)
* @return bool Is Logged-in or not?
*/
public function ApiLogin($user='',$password=''){
$this->DebugLogError("Please override the ".__METHOD__." method. It should set the '\$this->is_logged' property to TRUE!");
$this->is_logged=true;
}
// ############################################################################################
// ## STANDARDISED METHODS TO OVERRIDE (Optional) ############################################
// ############################################################################################
// -------------------------------------------------------------------------
/**
* Log-out of the API. It must set $this->is_logged to FALSE, when succeeded
*
* @return bool Is Logged-out or not?
*/
public function ApiLogout(){
$this->DebugLogError("Please override the ".__METHOD__." method. It should set the '\$this->is_logged' property to FALSE!");
$this->is_logged=false;
$this->_auth_from_cache=false;
$this->AuthCacheClear();
}
// -------------------------------------------------------------------------
/**
* Asks API if we are logged-in or Not
*
* @return bool Are we logged-in of not?
*/
public function ApiIsLoggedIn(){
$this->DebugLogInfo("No Api call performed, this only from the class property 'is_logged'. You'd better have to Call the API if you can grab this state");
return $this->is_logged;
}
// -------------------------------------------------------------------------
/**
* Reboot the device
*
* @return bool Succeeded ?
*/
public function ApiReboot(){
$this->DebugLogError("Please override the ".__METHOD__." method.");
return true;
}
// for Cellular Modems #############################################################
// -------------------------------------------------------------------------
/**
* Cellular modems Status & Information
*
* @param boolean $fast_mode Require only minimum info needed to quickly point an Antenna, whenever the API requires multiple (slow) calls to get the full information
* @return array Basic Cell & signal information
*/
public function ApiCellStatus($fast_mode=false){
$this->DebugLogError("Please override the ".__METHOD__." method.");
}
// -------------------------------------------------------------------------
/**
* Returns a standardised array of Received SMS
*
* @param integer $read_type 0=all, 1=read, 2=unread
* @param integer $page Page to start at (1 to n)
* @param integer $limit Max messages per page
* @return array Array of sms, sorted by date DESC
*/
public function ApiSmsListReceived($read_type=0, $page=1, $limit=20){
$this->DebugLogError("Please override the ".__METHOD__." method. It should return an array of messages (or false), date DESC sorted");
}
// -------------------------------------------------------------------------
/**
* Returns a standardised array of Sent SMS
*
* @param integer $page Page to start at (1 to n)
* @param integer $max Max messages per page
* @return array Array of sms, sorted by date DESC
*/
public function ApiSmsListSent($page=1,$max=20){
$this->DebugLogError("Please override the ".__METHOD__." method. It should return an array of messages (or false), date DESC sorted");
}
// -------------------------------------------------------------------------
/**
* Send an SMS
*
* @param string $phone Recipient Number formatted as local or international phone number
* @param string $message Message to send
* @param string $priority (Not Implemented)
* @return bool
*/
public function ApiSmsSend($phone, $message, $priority=''){
$this->DebugLogError("Please override the ".__METHOD__." method. ");
}
// for Routers & Modems #############################################################
// -------------------------------------------------------------------------
/**
* Disconnect the WAN interface
*
* @return bool Succeeded ?
*/
public function ApiWanConnect(){
$this->DebugLogError("Please override the ".__METHOD__." method.");
}
// -------------------------------------------------------------------------
/**
* Connect the WAN interface
*
* @return bool Succeeded ?
*/
public function ApiWanDisconnect(){
$this->DebugLogError("Please override the ".__METHOD__." method.");
}
// -------------------------------------------------------------------------
/**
* WAN interface Status & Information
*
* @return array Basic WAN information & Stats
*/
public function ApiWanStatus(){
$this->DebugLogError("Please override the ".__METHOD__." method.");
}
// -------------------------------------------------------------------------
/**
* Reload the WAN interface. (ie refresh the WAN IP address)
*
* @return bool Succeeded ?
*/
public function ApiWanReload(){
$this->ApiWanDisconnect();
sleep(1);
return $this->ApiWanConnect();
}
// for Wifi capable Routers #########################################################
// -------------------------------------------------------------------------
/**
* List Wifi Clients
*
* @param string $id The Station ID to filter by
* @return array An array indexed by Station (ssid) id of client arrays, or an array of client arrays (if $id is set)
*/
public function ApiWifiListClients($id=''){
$this->DebugLogError("Please override the ".__METHOD__." method. It should returns an array ( indexed by id) of arrays of connected wifi stations,");
}
// -------------------------------------------------------------------------
/**
* List Wifi Station
*
* @param string $id Station Id
* @return void An array of Stations, or one Station (when $id is set)
*/
public function ApiWifiListSsids($id=''){
$this->DebugLogError("Please override the ".__METHOD__." method. It should returns an array ( indexed by id) of arrays of SSIDs available,");
}
// -------------------------------------------------------------------------
/**
* Turn Wifi ON
*
* @return bool Succeeded ?
*/
public function ApiWifiStart(){
$this->DebugLogError("Please override the ".__METHOD__." method. ");
}
// -------------------------------------------------------------------------
/**
* Turn Wifi OFF
*
* @return bool Succeeded ?
*/
public function ApiWifiStop(){
$this->DebugLogError("Please override the ".__METHOD__." method. ");
}
// ############################################################################################
// ## OUR METHODS ############################################################################
// ############################################################################################
// -------------------------------------------------------------------------
/**
* Set device host (IP or hostname) and HTTP/HTTPS base URL.
*
* @param string $ip_or_hostname Device address
* @param bool $use_ssl Use HTTPS when true
* @return void
*/
public function SetHost($ip_or_hostname, $use_ssl=false){
$ip_or_hostname and $this->host=$ip_or_hostname;
$use_ssl ? $scheme="https://" : $scheme="http://";
$this->use_ssl=$use_ssl;
$this->base_url=$scheme.$ip_or_hostname;
$this->def_referer and $this->def_headers[]="Referer: {$this->base_url}{$this->def_referer}";
$this->RefreshAuthPaths();
}
// -------------------------------------------------------------------------
/**
* Store API username and password for later login.
*
* @param string $user Username
* @param string $password Password
* @return void
*/
public function SetLogin($user, $password=''){
$this->user =$user;
$this->password =$password;
$this->RefreshAuthPaths();
}
// -------------------------------------------------------------------------
/**
* Enable durable auth cache under a directory (JSON session + cookie jar when use_cookies).
* Path is required. Optional TTL overrides driver/master default (1800s).
*
* @param string $path Directory (created if missing, mode 0750)
* @param int|null $ttl Seconds; null keeps driver/master $auth_cache_ttl
* @return bool
*/
public function SetAuthCachePath($path, $ttl=null){
$path=is_string($path) ? rtrim($path, "/\\") : '';
if($path===''){
$this->DebugLogError('SetAuthCachePath requires a non-empty directory path');
return false;
}
if(!is_dir($path)){
if(!@mkdir($path, 0750, true) and !is_dir($path)){
$this->DebugLogError("SetAuthCachePath cannot create directory: $path");
return false;
}
}
$this->auth_cache_dir=$path;
if($ttl!==null and $ttl!==''){
$this->auth_cache_ttl=(int)$ttl;
}
$this->RefreshAuthPaths();
return true;
}
// -------------------------------------------------------------------------
/**
* @deprecated Compat only — use SetAuthCachePath(). Forwards to SetAuthCachePath($path).
* Do not use in new code. Cookie vs token is an internal driver detail.
*
* @param string $path Directory for auth cache files (same as SetAuthCachePath)
* @return bool
*/
public function SetCookiePath($path='/tmp/'){
$path or $path=sys_get_temp_dir();
return $this->SetAuthCachePath($path, null);
}
// -------------------------------------------------------------------------
/**
* Set debug verbosity level and output mode.
*
* @param int $level Debug level
* @param int $output_mode 0=off/return path, else print-style modes used by DebugLine
* @return void
*/
public function SetDebug($level, $output_mode=0){
$this->debug_level =$level;
$this->debug_output =$output_mode;
}
// -------------------------------------------------------------------------
/**
* Return the last HTTP call metadata (url, headers, result, errors).
*
* @return array
*/
public function GetLastCall(){
return $this->last_call;
}
// -------------------------------------------------------------------------
/**
* Return loaded preference snapshot (host, ssl, user, …).
*
* @return array
*/
public function GetPreferences(){
return $this->preferences;
}
// -------------------------------------------------------------------------
/**
* Return this client library version string.
*
* @return string
*/
public function GetClientVersion(){
return $this->client_version;
}
// -------------------------------------------------------------------------
/**
* Clear the last error structure.
*
* @return void
*/
public function ResetLastError(){
$this->last_error='';
}
// -------------------------------------------------------------------------
/**
* Return the last error structure (or empty).
*
* @return array|string
*/
public function GetLastError(){
return $this->last_error;
}
// -------------------------------------------------------------------------
/**
* Set Error Code
*
* @param integer $code Code Number:
* 0 =>'Returned False (No Error)',
* 1 =>'Malformed Request',
* 2 =>'Malformed Answer',
* 3 =>'Permission Issue',
* 4 =>'Exception thrown',
* 5 =>'Unexpected Error',
* 6 =>'Unimplemented method/endpoint',
* 7 =>'API (known) Error',
* @param string $message Optional message
* @return void
*/
protected function SetError($code, $message=''){
if(isset($this->error_codes[$code])){
$this->_SetCategError('main','code', $code);
$this->_SetCategError('main','code_txt', $this->error_codes[$code]);
$message and $this->_SetCategError('main','mess', $message);
//$this->last_error['code'] =$code;
//$this->last_error['code_txt'] =$this->error_codes[$code];
//$message and $this->last_error['mess']=$message;
return true;
}
$this->DebugLogError("$code is not a valid error code");
}
// -------------------------------------------------------------------------
/**
* Map a main error code to its human description.
*
* @param int $err_code Main error code
* @return string|null
*/
public function GetErrorDesc($err_code){
return $this->error_codes[$err_code];
}
// -------------------------------------------------------------------------
/**
* Copy HTTP/curl failure details from the last call into last_error[call].
*
* @param string $key Optional extra key
* @param string $txt Optional extra text
* @return void
*/
protected function SetCallError($key='',$txt=''){
$cu=$this->GetLastCall();
$this->_SetCategError('call','http_code', $cu['http_code']);
$this->_SetCategError('call','err_code', $cu['err_code']);
$this->_SetCategError('call','err_txt', $cu['err_txt']);
if($txt){
$this->_SetCategError('call', $key, $txt);
}
}
// -------------------------------------------------------------------------
/**
* Store an XML parse/structure error under last_error[xml].
*
* @param string $key Error key
* @param string $txt Error text
* @return void
*/
protected function SetXmlError($key='',$txt=''){
$this->_SetCategError('xml',$key,$txt);
}
// -------------------------------------------------------------------------
/**
* Store a device API error code/message under last_error[api], mapping to a main error when known.
*
* @param mixed $code API error code
* @param string $message Optional message
* @param mixed $result Optional raw result for logging
* @return bool|null
*/
protected function SetApiErrorCode($code,$message='',$result=''){
if(isset($this->api_error_codes[$code])){
$code_txt=$this->api_error_codes[$code][0];
if(!isset($this->last_error['main']['code']) and isset($this->api_error_codes[$code][1])){
$this->SetError($this->api_error_codes[$code][1]);
}
}
else{
if(!isset($this->last_error['main']['code'])){
$this->SetError(5);
if($result){
$this->SetCallError('result',$result);
}
}
$code_txt="Undocumented API code '$code'";
$this->DebugLogError("$code_txt - $message",$result);
}
$this->_SetCategError('api','code', $code);
$this->_SetCategError('api','code_txt', $code_txt );
$message and $this->_SetCategError('api','mess', $message);
if(isset($this->api_error_codes[$code])){
return true;
}
}
// // -------------------------------------------------------------------------
// protected function SetApiError($key='',$txt){
// $this->_SetCategError('api',$key,$txt);
// }
// -------------------------------------------------------------------------
/**
* Write one key/value into last_error under a category bucket.
*
* @param string $category Error category (main|call|api|xml|…)
* @param string $key Key inside the category
* @param string $txt Value
* @return bool
*/
private function _SetCategError($category,$key='',$txt=''){
if(!$txt and !$key){
$this->DebugLogError("Empty error message");
return false;
}
/*
if(!isset($this->last_error['main']['code'])){
$this->SetError(5);
}
*/
if(!isset($this->last_error[$category])){
if(!is_array($this->last_error)){
$this->last_error=array();
}
$this->last_error[$category]=array();
}
if($key){
$this->last_error[$category][$key]=$txt;
}
else{
$this->last_error[$category][]=$txt;
}
//$this->DebugLogVerbose("$category error set to: $key -> ",$txt);
return true;
}
// -------------------------------------------------------------------------
/**
* Current time in milliseconds (for duration measurements).
*
* @return int
*/
protected function GetTimeMs(){
return round(microtime(true)*1000,0);
}
// -------------------------------------------------------------------------
/**
* Set the minimum template method state that may run without throwing.
*
* @param int $state Minimum allowed state (default 5)
* @return void
*/
public function SetApiMethodMinStateAllowed($state=5){
$this->min_apimethod_state=$state;
}
// -------------------------------------------------------------------------
/**
* Throw if the method state is below the configured minimum.
*
* @param int $state Method state from the template
* @throws \Exception When state is below the configured minimum
*/
protected function HandleApiMethodStateAllowed($state=5){
if($state < $this->min_apimethod_state){
$err=500+$state;
throw new Exception("This method with a state of $state is considered UNSTABLE. You can use it at you own risk by setting the 'SetApiMethodMinStateAllowed' to a lower value (currently {$this->min_apimethod_state} ) ",$err);
}
}
// -------------------------------------------------------------------------
/**
* Rebuild auth JSON + cookie jar paths from auth_cache_dir / host / user.
* When cache dir is off and use_cookies: ephemeral per-host jar under sys_get_temp_dir().
*
* @return void
*/
protected function RefreshAuthPaths(){
$class=$this->_AuthPathSafe(get_class($this));
$host=$this->_AuthPathSafe($this->host !== '' ? $this->host : 'nohost');
$user=$this->_AuthPathSafe($this->user !== '' ? $this->user : 'nouser');
if($this->auth_cache_dir){
$base=rtrim($this->auth_cache_dir, "/\\").DIRECTORY_SEPARATOR;
$key=$class.'_to-'.$host.'_user-'.$user;
$this->auth_cache_file=$base.'auth_'.$key.'.json';
if($this->use_cookies){
$this->cookies_file=$base.'cookies_'.$key;
$this->_TouchCookieFile();
}
return;
}
$this->auth_cache_file='';
if($this->use_cookies){
$tmp=rtrim(sys_get_temp_dir(), "/\\").DIRECTORY_SEPARATOR;
$this->cookies_file=$tmp.'hackapi_cookies_'.$class.'_to-'.$host;
$this->_TouchCookieFile();
}
}
// -------------------------------------------------------------------------
/**
* Sanitize a path key fragment.
*
* @param string $s Raw fragment
* @return string
*/
private function _AuthPathSafe($s){
$s=preg_replace('/[^a-zA-Z0-9._-]+/', '_', (string)$s);
return $s !== '' ? $s : 'x';
}
// -------------------------------------------------------------------------
/**
* Touch cookie jar with mode 0600.
*
* @return void
*/
private function _TouchCookieFile(){
if($this->cookies_file===''){
return;
}
if(!file_exists($this->cookies_file)){
@touch($this->cookies_file);
}
@chmod($this->cookies_file, 0600);
}
// -------------------------------------------------------------------------
/**
* Export session fields for durable cache. Override in drivers (token, sid, …).
* Default: cookie-only marker when use_cookies and jar has content.
*
* @return array|false Payload for JSON data, or false to skip JSON save
*/
protected function AuthSessionExport(){
if($this->use_cookies and $this->cookies_file!=='' and is_file($this->cookies_file) and filesize($this->cookies_file)>0){
return array('_cookies'=>1);
}
return false;
}
// -------------------------------------------------------------------------
/**
* Restore session from AuthCacheLoad data. Override in drivers.
* Default: cookie-only — set is_logged when jar exists.
*
* @param array $data Payload from JSON data
* @return bool
*/
protected function AuthSessionImport($data){
if(!is_array($data)){
return false;
}
if($this->use_cookies and $this->cookies_file!=='' and is_file($this->cookies_file) and filesize($this->cookies_file)>0){
$this->is_logged=true;
return true;
}
return false;
}
// -------------------------------------------------------------------------
/**
* Whether last_error indicates an auth failure that should clear cache + re-login.
* Drivers override (e.g. SFR code 115 / 116).
*
* @param mixed $code API error code from last_error[api][code]
* @return bool
*/
protected function IsAuthFailureApiCode($code){
return false;
}
// -------------------------------------------------------------------------
/**
* True when durable auth cache directory is set.
*
* @return bool
*/
/**
* True when durable auth cache directory is set.
*
* @return bool
*/
private function AuthCacheEnabled(){
return ($this->auth_cache_dir !== null and $this->auth_cache_dir !== '');
}
// -------------------------------------------------------------------------
/**
* Load auth JSON with flock. Returns assoc or false.
*
* @return array|false
*/
private function AuthCacheLoad(){
if(!$this->AuthCacheEnabled() or $this->auth_cache_file===''){
return false;
}
if(!is_file($this->auth_cache_file)){
return false;
}
$fp=@fopen($this->auth_cache_file, 'rb');
if(!$fp){
return false;
}
$raw='';
if(@flock($fp, LOCK_SH)){
$raw=stream_get_contents($fp);
@flock($fp, LOCK_UN);
}
fclose($fp);
if($raw==='' or $raw===false){
return false;
}
$row=json_decode($raw, true);
return is_array($row) ? $row : false;
}
// -------------------------------------------------------------------------
/**
* Whether a loaded auth cache row is still within TTL.
*
* @param array $row Loaded JSON
* @return bool
*/
private function AuthCacheIsFresh($row){
if(!is_array($row) or !isset($row['saved_at'])){
return false;
}
$ttl=isset($row['ttl']) ? (int)$row['ttl'] : (int)$this->auth_cache_ttl;
if($ttl<=0){
return false;
}
return ((int)$row['saved_at'] + $ttl) >= time();
}
// -------------------------------------------------------------------------
/**
* Persist session payload to auth JSON (flock, 0600). No-op if cache off.
*
* @param array $data Driver session data (no password)
* @return bool
*/
private function AuthCacheSave($data){
if(!$this->AuthCacheEnabled() or $this->auth_cache_file===''){
return false;
}
if(!is_array($data)){
$data=array();
}
$row=array(
'v'=>1,
'saved_at'=>time(),
'ttl'=>(int)$this->auth_cache_ttl,
'host'=>(string)$this->host,
'user'=>(string)$this->user,
'data'=>$data,
);
$json=json_encode($row);
if($json===false){
return false;
}
$fp=@fopen($this->auth_cache_file, 'c+b');
if(!$fp){
$this->DebugLogError('AuthCacheSave cannot open '.$this->auth_cache_file);
return false;
}
$ok=false;
if(@flock($fp, LOCK_EX)){
ftruncate($fp, 0);
rewind($fp);
$ok=(fwrite($fp, $json)!==false);
fflush($fp);
@flock($fp, LOCK_UN);
}
fclose($fp);
if($ok){
@chmod($this->auth_cache_file, 0600);
}
return $ok;
}
// -------------------------------------------------------------------------
/**
* Save AuthSessionExport() when it returns an array (or empty cookie marker).
*
* @return bool
*/
private function AuthCacheSaveFromSession(){
if(!$this->AuthCacheEnabled()){
return false;
}
$exp=$this->AuthSessionExport();
if($exp===false){
return false;
}
return $this->AuthCacheSave($exp);
}
// -------------------------------------------------------------------------
/**
* Delete auth JSON and cookie jar for the current class/host/user key.
*
* @return void
*/
private function AuthCacheClear(){
if($this->auth_cache_file!=='' and is_file($this->auth_cache_file)){
@unlink($this->auth_cache_file);
}
if($this->AuthCacheEnabled() and $this->use_cookies and $this->cookies_file!=='' and is_file($this->cookies_file)){
@unlink($this->cookies_file);
}
}
// -------------------------------------------------------------------------
/**
* After Import, if API reports auth failure: clear cache, re-login once, save.
* Call from drivers when a call fails with an auth error.
*
* @return bool True when a new login succeeded (caller should retry the request)
*/
protected function RecoverAuthSessionOnce(){
if(!$this->_auth_from_cache or $this->_auth_recover_done){
return false;
}
$code=isset($this->last_error['api']['code']) ? $this->last_error['api']['code'] : null;
if(!$this->IsAuthFailureApiCode($code)){
return false;
}
$this->_auth_recover_done=true;
$this->DebugLogDebug('Auth cache stale — clearing and re-login once');
$this->is_logged=false;
$this->_auth_from_cache=false;
$this->AuthCacheClear();
$this->ResetLastError();
if(!$this->ApiLogin()){
$this->AuthCacheClear();
return false;
}
$this->AuthCacheSaveFromSession();
return true;
}
// -------------------------------------------------------------------------
/**