-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathnamesilo-price-sync.php
1354 lines (1066 loc) · 38.5 KB
/
namesilo-price-sync.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
/*
Script for synchronizing TLD prices with namesilo, adds information directly to the database, needs to be called using CLI/cron
php namesilo-price-sync.php [-margin=0.00[%/p]] [-update=none/already-added/namesilo-only/all] [-make-default-registrar=false/true] [-round-to-next=0.00] [-template=.tld] [-exclude=.tld,...] [-include=.tld,...]
Arguments:
-margin=0.0[%/p]
Profit margin to add on each price, it can be a fixed amount or a percentage (by using p or % at the end of the number)
Examples: 5.10, 3p, 22%
Default value is: 0.00
*Cron treats percent signs in a special way, if used escape the percent sign or use p instead
-update=[all/already-added/namesilo-only/none]
TLDs that will be updated or added by the script
all - Adds all the TLDs from namesilo's price list
already-added - Updates all TLDs already registered on WHMCS (excluding those not supported)
namesilo-only - Updates only the TLDs that use namesilo as their registrar
none - Doesn't add any TLD, TLDs in the inclusion or exclusion lists are still considered
Example: all
Default value: none
-make-default=registrar=[true/false]
Changes the registrar on all updated TLDs to namesilo
Example: true
Default: false
-round-to-next=0.00
Rounds each price to the next decimal specified
Example: 0.20
-template=.tld
The TLD to take as a base for newly added TLDs, prices are not copied
Example: .com
-exclude=.tld,...
TLDs to exclude during the update, accepts a comma separated list
Example: .com,.net,.org
-include=.tld,...
TLDs to include during the update, accepts a comma separated list
Example: .com,.net,.org
Sample call:
php namesilo-price-sync.php -margin=15% -update=namesilo-only -make-default-registrar=true -round-to-next=0.50 -template=.com -exclude=.xyz -include=.buzz,.top
*/
if (isset($_SERVER['REMOTE_ADDR'])) {
exit ('ERROR: Script called from web environment');
}
/*****************************************/
/* Grab Required Includes */
/*****************************************/
$module_dir = dirname(__FILE__);
chdir($module_dir);
require '../../../init.php';
require '../../../includes/functions.php';
require '../../../includes/registrarfunctions.php';
use WHMCS\Database\Capsule;
/*****************************************/
/* Process arguments */
/*****************************************/
foreach ($argv as $ar) {
if (preg_match('/^-{1,2}margin=/i', $ar)) {
$margin = explode('=', $ar);
(count($margin) > 1) ? $margin = $margin[1] : $margin = null;
if ($margin) {
$marginType = 'fixed';
if (preg_match('/(%|p)/i', $margin)) {
$marginType = 'percentage';
$margin = preg_replace('/(%|p)/i', '', $margin);
}
$margin = (float)$margin;
}
break;
}
}
if (!isset($margin) || is_null($margin)) {
$margin = 0.0;
$marginType = 'fixed';
}
foreach ($argv as $ar) {
if (preg_match('/^-{1,2}update=/i', $ar)) {
$updateTarget = explode('=', $ar);
(count($updateTarget) > 1) ? $updateTarget = $updateTarget[1] : $updateTarget = null;
if ($updateTarget) {
if (preg_match('/^all/i', $updateTarget)) {
$updateTarget = 'all';
} else if (preg_match('/^already-added/i', $updateTarget)) {
$updateTarget = 'alreadyAdded';
} else if (preg_match('/^namesilo-only/i', $updateTarget)) {
$updateTarget = 'namesiloOnly';
} else {
$updateTarget = 'none';
}
}
break;
}
}
if (!isset($updateTarget) || is_null($updateTarget)) {
$updateTarget = 'none';
}
foreach ($argv as $ar) {
if (preg_match('/^-{1,2}make-default-registrar=/i', $ar)) {
$makeDefaultRegistrar = explode('=', $ar);
(count($makeDefaultRegistrar) > 1) ? $makeDefaultRegistrar = $makeDefaultRegistrar[1] : $makeDefaultRegistrar = null;
if ($makeDefaultRegistrar) {
if (preg_match('/^true/i', $makeDefaultRegistrar)) {
$makeDefaultRegistrar = true;
} else {
$makeDefaultRegistrar = false;
}
}
break;
}
}
if (!isset($makeDefaultRegistrar) || is_null($makeDefaultRegistrar)) {
$makeDefaultRegistrar = false;
}
foreach ($argv as $ar) {
if (preg_match('/^-{1,2}round-to-next=/i', $ar)) {
$roundToNext = explode('=', $ar);
(count($roundToNext) > 1) ? $roundToNext = $roundToNext[1] : $roundToNext = null;
(is_numeric($roundToNext)) ? $roundToNext = (float)$roundToNext : $roundToNext = null;
if ($roundToNext !== null) {
$roundToNext = round($roundToNext , 2);
if ($roundToNext >= 1.00 || $roundToNext < 0.00) {
$roundToNext = null;
}
}
break;
}
}
if (!isset($roundToNext)) {
$roundToNext = null;
}
foreach ($argv as $ar) {
if (preg_match('/^-{1,2}template=/i', $ar)) {
$templateTld = explode('=', $ar);
(count($templateTld) > 1) ? $templateTld = $templateTld[1] : $templateTld = null;
if ($templateTld !== null) {
$templateTld = preg_replace('/(\'|"|\s)/', '', $templateTld);
$templateTld = preg_replace('/^\./', '', $templateTld);
$templateTld = strtolower($templateTld);
$templateTld = '.' . $templateTld;
}
break;
}
}
if (!isset($templateTld)) {
$templateTld = null;
}
foreach ($argv as $ar) {
if (preg_match('/^-{1,2}exclude=/i', $ar)) {
$excludedTld = explode('=', $ar);
(count($excludedTld) > 1) ? $excludedTld = $excludedTld[1] : $excludedTld = null;
if ($excludedTld !== null) {
$excludedTld = preg_replace('/(\'|"|\s)/', '', $excludedTld);
$excludedTld = strtolower($excludedTld);
$excludedTld = explode(',', $excludedTld);
$excludedTld = preg_replace('/^\./', '', $excludedTld);
$excludedTld = preg_replace('/^/', '.', $excludedTld);
}
break;
}
}
if (!isset($excludedTld) || is_null($excludedTld)) {
$excludedTld = [];
}
foreach ($argv as $ar) {
if (preg_match('/^-{1,2}include=/i', $ar)) {
$includedTld = explode('=', $ar);
(count($includedTld) > 1) ? $includedTld = $includedTld[1] : $includedTld = null;
if ($includedTld !== null) {
$includedTld = preg_replace('/(\'|"|\s)/', '', $includedTld);
$includedTld = strtolower($includedTld);
$includedTld = explode(',', $includedTld);
$includedTld = preg_replace('/^\./', '', $includedTld);
$includedTld = preg_replace('/^/', '.', $includedTld);
}
break;
}
}
if (!isset($includedTld) || is_null($includedTld)) {
$includedTld = [];
}
/*****************************************/
/* Define Clases */
/*****************************************/
Class NamesiloPrices {
public $priceList;
private $nsListCall;
function __construct($apiCall) {
$this->nsListCall = $apiCall;
$this->priceList = [];
//$this->updateList();
}
function getPrice($tld, $operation) {
$price = null;
foreach ($this->priceList as $entry) {
if ($tld == $entry['tld']) {
foreach ($entry['prices'] as $entryOperation => $entryPrice) {
if ($entryOperation == $operation) {
$price = $entryPrice;
break;
}
}
break;
}
}
return $price;
}
function updateList() {
$apiPrices = $this->_transactionProcessor();
if (!isset($apiPrices['prices'])) {
throw new Exception('API Error: ' . $apiPrices['error']);
}
foreach ($apiPrices['prices'] as $apiPrice) {
$listTld = $apiPrice['tld'];
unset($apiPrice['tld']);
$this->priceList[] = array('tld' => '.' . $listTld, 'prices' => $apiPrice);
}
}
function _transactionProcessor() {
$call = $this->nsListCall;
# Set CURL Options
$options = array(
CURLOPT_RETURNTRANSFER => true, // return web page
CURLOPT_HEADER => false, // don't return headers
CURLOPT_USERAGENT => "NameSilo Domain Sync 1.3", // For use with WHMCS 6x
);
# Initialize CURL
$ch = curl_init($call);
# Import CURL options array
curl_setopt_array($ch, $options);
# Execute and store response
$content = curl_exec( $ch );
# Process any CURL errors
$curl_err = false;
if (curl_error ( $ch )) {
$curl_err = 'CURL Error: ' . curl_errno ( $ch ) . ' - ' . curl_error ( $ch );
throw new Exception('CURL Error: ' . curl_errno ( $ch ) . ' - ' . curl_error ( $ch ));
//exit ( 'CURL Error: ' . curl_errno ( $ch ) . ' - ' . curl_error ( $ch ) );
}
# Log error(s)
if ($curl_err) { $cronreport .= "Error connecting to API: $curl_err"; }
curl_close( $ch );
# Process XML result
$xml = new SimpleXMLElement($content);
$code = (int) $xml->reply->code;
$detail = (string) $xml->reply->detail;
$result = [];
if ($code == "300") {
$result["prices"] = [];
foreach ($xml->reply->children() as $tld) {
if ($tld->count() === 3) {
$result["prices"][] = array(
"tld" => (string)$tld->getName(),
"registration" => number_format((float)str_replace(',', '', $tld->registration), 2, '.', ''),
"renew" => number_format((float)str_replace(',', '', $tld->renew), 2, '.', ''),
"transfer" => number_format((float)str_replace(',', '', $tld->transfer), 2, '.', ''),
);
}
}
}
$result['error'] = $detail;
# Return result
return $result;
}
}
Class WhmcsDbHandler {
//Handles connection betweed the database and local data
//Returns false on failed operations, exceptions are sent to log callback and hidden
public $entryList;
//Main entry list, contains local data from the database
private $dbTableName;
//Table name used
private $logFn;
//Callback used for loggin errors
//logFn($exception)
//$exception can be an Exception or just a string
public $primaryKey;
//Element/field to be used as primary identifier
//[element, dbBinding]
//Default: ['id', 'id']
public $requiredElements;
//Elements required to add an entry
//[element1, element2]
public $uniqueElements;
//Values that are verified to be unique in the list while adding a new entry, can be bundled using commas
//['element1', 'element2,element3']
public $databaseTemplate;
//Default database values to use while adding new elements
//[[dbColumn, defaultValue]]
public $elements;
//Values/fields to be used in entryList and their database column binding
//[[element, dbBinding]]
function __construct($tableName, $logFn=null, $elements=null, $dbTemplate=null, $primaryKey=null, $requiredElements=null, $uniqueElements=null) {
$this->entryList = [];
$this->dbTableName = $tableName;
$this->logFn = $logFn;
is_null($elements) ? $this->elements = [] : $this->elements = $elements;
is_null($dbTemplate) ? $this->dbTemplate = [] : $this->dbTemplate = $dbTemplate;
is_null($requiredElements) ? $this->requiredElements = [] : $this->requiredElements = $requiredElements;
is_null($uniqueElements) ? $this->uniqueElements = [] : $this->uniqueElements = $uniqueElements;
is_null($primaryKey) ? $this->primaryKey = ['id', 'id'] : $this->primaryKey = $primaryKey;
}
function updateList() {
//Updates the local list with database data
//Clear entry values
$this->entryList = [];
//Create selector for database data
$dbSelector = [];
$dbSelector[] = $this->primaryKey[1];
foreach ($this->elements as $element) {
$dbSelector[] = $element[1];
}
$dbData = $this->_getTable()->select($dbSelector)->get();
if(!is_array($dbData)){
$dbData->toArray();
}
//Convert and add each database row to entry list
foreach ($dbData as $dbEntry) {
$this->entryList[] = $this->_dbToEntry((array) $dbEntry);
}
}
function addEntry($entryData) {
//$entryData: assoc array using $elements and $items ['element' => 'value']
//Add an entry to the database and list
//Returns array with new entry data
//Required value handling
if (!$this->_hasRequiredFields($entryData)) {
$this->_log(json_encode($entryData) . ': Required values not found');
return false;
}
//Duplicate handling
if ($this->_isDuplicate($entryData)) {
$this->_log(json_encode($entryData) . ': Duplicate entry exists');
return false;
}
//Insert to database
try {
$dbData= $this->_pushToDatabase($entryData);
$dbData = $dbData['dbData'];
} catch (Exception $ex) {
$this->_log($ex);
return false;
}
//Load data from database result
$newEntry = $this->_dbToEntry($dbData);
//Add to list
$this->entryList[] = $newEntry;
return $newEntry;
}
function updateEntry($entryData, $selector) {
//$entryData: assoc array using $elements and $items ['element' => 'value'], data is inserted to database
//$selector: assoc array using elements and items ['element' => 'value'], used to locate an entry to be updated
// the selector must match only one entry, it can accept a non array value, this value will be converted to an array using the primary key as the key
//Updates an entry in the database and list
$updatedEntry = [];
//Find entry index using selector
try {
$entryIndex = $this->_find($selector);
} catch (Exception $ex) {
$this->_log($ex);
return false;
}
if (is_null($entryIndex)) {
$this->_log(json_encode($selector) . ': Entry not found');
return false;
}
$originalEntry = $this->entryList[$entryIndex];
//Add original data to new list entry
foreach ($originalEntry as $oKey => $oValue) {
$updatedEntry[$oKey] = $oValue;
}
//Update entry data with new data
foreach ($entryData as $dKey => $dValue) {
if (isset($updatedEntry[$dKey])) {
$updatedEntry[$dKey] = $dValue;
}
}
//Check duplicates
$this->entryList[$entryIndex] = [];
$duplicate = $this->_isDuplicate($updatedEntry);
$this->entryList[$entryIndex] = $originalEntry;
if ($duplicate) {
$this->_log(json_encode($selector) . ': Duplicate entry exists');
return false;
}
if ($originalEntry == $updatedEntry) {
$this->_log(json_encode($selector) . ': No data changes found');
return false;
}
//Send data to database
try {
if (!$this->_pushToDatabase($entryData, $selector)['result']) {
$this->_log(json_encode($selector) . ': Database update failed');
return false;
}
} catch (Exception $ex) {
$this->_log($ex);
return false;
}
//Insert into local list
$this->entryList[$entryIndex] = $updatedEntry;
}
function deleteEntry($selector) {
//$selector: assoc array using elements and items ['element' => 'value'], used to locate an entry to be updated
// the selector must match only one entry, it can accept a non array value, this value will be converted to an array using the primary key as the key
//Deletes an entry in the database and list
//Find entry
try {
$entryIndex = $this->_find($selector);
} catch (Exception $ex) {
$this->_log($ex);
return false;
}
if (is_null($entryIndex)) {
$this->_log(json_encode($selector) . ': Entry not found');
return false;
}
//Delete data on database
try {
if (!$this->_databaseDelete($selector)) {
$this->_log(json_encode($selector) . ': Database delete failed');
return false;
}
} catch (Exception $ex) {
$this->_log($ex);
return false;
}
//Remove data on local list
array_splice($this->entryList, $entryIndex, 1);
}
function getEntry($selector) {
//$selector: assoc array using elements and items ['element' => 'value'], used to locate an entry to be updated
// the selector for this method can match multiple items, it can accept a non array value, this value will be converted to an array using the primary key as the key
//This method returns an array with the entries found
$resultEntries = [];
//Find entries
$indexArr = $this->_findAll($selector);
//Copy entries to result
foreach ($indexArr as $idx) {
$newResult = [];
foreach ($this->entryList[$idx] as $element => $value) {
$newResult[$element] = $value;
}
$resultEntries[] = $newResult;
}
return $resultEntries;
}
function _isDuplicate($entryData) {
//$entryData: assoc array using elements and items ['element' => 'value']
//Checks if an entry already exists using the instance's unique fields
//Prepare unique element check array from unique elements declared and entry data
foreach ($this->uniqueElements as $uVal) {
$uValKeys = explode(',', $uVal);
$uValArr = [];
foreach ($uValKeys as $uKey) {
if (isset($entryData[$uKey])) {
$uValArr[$uKey] = $entryData[$uKey];
} else {
$uValArr[$uKey] = null;
}
}
//Check entry list using check array
$duplicate = false;
foreach ($this->entryList as $entry) {
if (count($entry) == 0) {
continue;
}
foreach ($uValArr as $uKey => $uVal) {
$duplicate = $entry[$uKey] == $uVal;
if (!$duplicate) {
break;
}
}
if ($duplicate) {
break;
}
}
if ($duplicate) {
return true;
}
}
return false;
}
function _hasRequiredFields($entryData) {
//$entryData: assoc array using elements and items ['element' => 'value']
//Checks if the data has the elements defined as required by the instance
//Check required elements in entry data
foreach ($this->requiredElements as $rVal) {
if (!isset($entryData[$rVal])) {
return false;
}
}
return true;
}
function _createDbSelector($selector) {
//$selector: assoc array using elements and items ['element' => 'value']
//Converts a selector to be used with the database
//Returns converted array
//Convert selector elements and items using their database bindings
$newDbSelector = $this->_entryToDb($selector, false);
//Replace primary key
if (isset($selector[$this->primaryKey[0]])) {
$newDbSelector[$this->primaryKey[1]] = $selector[$this->primaryKey[0]];
}
return $newDbSelector;
}
function _find($selector) {
//$selector: assoc array using elements and items ['element' => 'value'], used to locate an entry
// the selector must match only one entry, it can accept a non array value, this value will be converted to an array using the primary key as the key
//Finds an entry using the selector
//The method returns the index of the element found (int) or null
//Throws an exception if more than one item is found
//Find entries on list using selector
$indexArr = $this->_findAll($selector);
//If there are more than one results throw an exception
if (count($indexArr) > 1) {
throw new Exception('Non-unique selector');
}
//Return the index of the element found
if (isset($indexArr[0])) {
return $indexArr[0];
}
return null;
}
function _findAll($selector) {
//$selector: assoc array using elements and items ['element' => 'value'], used to locate an entry
// the selector for this method can match multiple items, it can accept a non array value, this value will be converted to an array using the primary key as the key
//Finds all entries matching the selector
//The method returns an array with the indexes of the items found
//Convert selector to array if required
if (!is_array($selector)) {
$selectorValue = $selector;
$selector = [];
$selector[$this->primaryKey] = $selectorValue;
}
$entryIndexes = [];
//Parse entry list and check each item using the selector
for ($i = 0; $i < count($this->entryList); $i++) {
$selected = true;
foreach ($selector as $sKey => $sValue) {
if (!(isset($this->entryList[$i][$sKey]) && $this->entryList[$i][$sKey] == $sValue)) {
$selected = false;
break;
}
}
if ($selected) {
$entryIndexes[] = $i;
}
}
return $entryIndexes;
}
function _pushToDatabase($data, $selector=null) {
//$entryData: assoc array using elements and items ['element' => 'value'], elements are converted to database bindings, this data is sent to the database
//$selector assoc array using elements and items ['element' => 'value'], elements are converted to database bindings, this data is used to select the row that will be updated
// if null, the data in entryData is added to a new row
//Adds data to database
//Returns the data sent to the database
//Check if data will be inserted or updated on database
is_null($selector) ? $pushType = 'insert' : $pushType = 'update';
//Replace entries with database bindings on selector and data
if ($pushType == 'insert') {
$dbEntry = $this->_entryToDb($data, true);
$querySelector = [];
} else {
$dbEntry = $this->_entryToDb($data, false);
$querySelector = $this->_createDbSelector($selector);
}
$queryResult = [];
//Send data to database
if ($pushType == 'insert') {
$id = $this->_getTable()->insertGetId($dbEntry, $this->primaryKey[1]);
//Add id to data set
$dbEntry[$this->primaryKey[1]] = $id;
$queryResult['result'] = true;
} else {
$queryResult['result'] = (bool) $this->_getTable()->where($querySelector, '=')->take(1)->update($dbEntry);
}
$queryResult['dbData'] = $dbEntry;
return $queryResult;
}
function _databaseDelete($selector) {
//$selector assoc array using elements and items ['element' => 'value'], elements are converted to database bindings, this data is used to select the row that will be deleted
//Deletes a database row using the selector
$selector = $this->_createDbSelector($selector);
return (bool) $this->_getTable()->where($selector, '=')->take(1)->delete();
}
function _getTable() {
//Returns a table instance
return Capsule::table($this->dbTableName);
}
function _entryToDb($entry, $useTemplate) {
//$entryData: assoc array using elements and items ['element' => 'value'], elements are converted to database bindings
//$useTemplate: use the data in the instance's template
//Replaces elements in entries with their database bindings
//Returns an array with database ready data
$newDbEntry = [];
//Load template data for db
if ($useTemplate) {
foreach ($this->databaseTemplate as $tField) {
$newDbEntry[$tField[0]] = $tField[1];
}
}
//Replace elements
foreach ($this->elements as $element) {
if (isset($entry[$element[0]])) {
$newDbEntry[$element[1]] = $entry[$element[0]];
}
}
return $newDbEntry;
}
function _dbToEntry($dbData) {
//$dbData: assoc array with database ready data ['dbBinding' => 'value']
//Replaces database bindings with elements and creates entries
//Returns an entry made from the database data, elements not found get a null value
$newEntry = [];
//Add primary key to new entry
if (isset($dbData[$this->primaryKey[1]])) {
$newEntry[$this->primaryKey[0]] = $dbData[$this->primaryKey[1]];
} else {
$newEntry[$this->primaryKey[0]] = null;
}
//Add database data to new entry
foreach ($this->elements as $element) {
if (isset($dbData[$element[1]])) {
$newEntry[$element[0]] = $dbData[$element[1]];
} else {
$newEntry[$element[0]] = null;
}
}
return $newEntry;
}
function _log($excp) {
//$excp: Exception or string
//Logs errors using callback function (if provided)
if (is_callable($this->logFn)) {
call_user_func($this->logFn, $excp);
}
}
}
Class WhmcsPriceDbHandler extends WhmcsDbHandler {
//Adds item support for handling row values in WHMCS database structure
public $items;
//Operations (eg: registrations or renewals), their database value and their element/binding (column)
//Uses an optional database template, added to new items, the template has database columns and database values, this item can be omited
//[[item, dbValue, dbBinding, [dbTemplateColumn => dbTemplateData]]]
function __construct($tableName, $logFn=null, $elements=null, $items=null, $dbTemplate=null, $primaryKey=null, $requiredElements=null, $uniqueElements=null) {
parent::__construct($tableName, $logFn, $elements, $dbTemplate, $primaryKey, $requiredElements, $uniqueElements);
is_null($items) ? $this->items = [] : $this->items = $items;
}
function updateList() {
//Updates entry lists, removes any entries not using the item list values, for items active in the element list
parent::updateList();
$activeItems = [];
//List of item values and their elements
//[[element, [value1, value2, ...]], ...]
//Get active items
foreach ($this->items as $item) {
foreach ($this->elements as $element) {
//If the item has an entry in element list
if ($item[2] == $element[1]) {
//Check activeItem list, if the element is already there, add the item to it, else create new element
$isNewActiveItem = true;
//'&' Allow $activeItems modifications
foreach ($activeItems as &$aItem) {
if ($element[0] == $aItem[0]) {
$aItem[1][] = $item[0];
$isNewActiveItem = false;
break;
}
}
if ($isNewActiveItem) {
$activeItems[] = [$element[0], [$item[0]]];
}
break;
}
}
}
//Check item values on entry list, if an entry doesn't have elements with the values defined for the items, remove it
//This removes unrelated entries from the list, which is used for other prices in WHMCS
for ($i = count($this->entryList) - 1; $i >= 0; $i--) {
foreach ($activeItems as $aItem) {
if (!(isset($this->entryList[$i][$aItem[0]]) && in_array($this->entryList[$i][$aItem[0]], $aItem[1]))) {
array_splice($this->entryList, $i, 1);
break;
}
}
}
}
function _entryToDb($entry, $useTemplate) {
//$entryData: assoc array using elements and items ['element' => 'value'], elements are converted to database bindings
//$useTemplate: use the data in the instance's template
//Replaces elements in entries with their database bindings
//Returns an array with database ready data
$newDbEntry = parent::_entryToDb($entry, $useTemplate);
//Replace item values
foreach ($this->items as $item) {
if (isset($newDbEntry[$item[2]])) {
if ($newDbEntry[$item[2]] == $item[0]) {
$newDbEntry[$item[2]] = $item[1];
//Add item database template
if ($useTemplate) {
if (isset($item[3])) {
foreach ($item[3] as $tKey => $tValue) {
if (!isset($newDbEntry[$tKey])) {
$newDbEntry[$tKey] = $tValue;
}
}
}
}
}
}
}
return $newDbEntry;
}
function _dbToEntry($dbData) {
//$dbData: assoc array with database ready data ['dbBinding' => 'value']
//Replaces database bindings with elements and creates entries
//Returns an entry made from the database data, elements not found get a null value
//Replace database bindings with items
foreach ($this->items as $item) {
if (isset($dbData[$item[2]])) {
if ($dbData[$item[2]] == $item[1]) {
$dbData[$item[2]] = $item[0];
}
}
}
$newEntry = parent::_dbToEntry($dbData);
return $newEntry;
}
}
Class ScriptLogger {
//Logger class, adds all data to $logStore, can be a tring or an array
//$msgAppend gets appended to all log entries
public $logStore;
public $msgAppend;
function __construct($logStore=null) {
is_null($logStore) ? $this->logStore = [] : $this->logStore = $logStore;
$this->msgAppend = '';
}
function log($msg) {
if ($msg instanceof Exception) {
$this->_append($msg->getMessage());
} else {
$this->_append($msg);
}
}
function _append($msg) {
if (is_array($this->logStore)) {
$this->logStore[] = $msg . $this->msgAppend;
} else {
$this->logStore .= $msg . $this->msgAppend;
}
}
}
/*****************************************/
/* Helper functions */
/*****************************************/
function roundToNextDecimal($number, $decimal) {
//Round number to next decimal provided ($decimal must be a value between 0 and 1)
//$number - The number being rounded, $decimal - round target
$next = floor($number) + $decimal;
if ($next >= $number) {
return $next;
} else {
return $next + 1;
}
}
/*****************************************/
/* Script data */
/*****************************************/
$apiCall = "/api/getPrices?version=1&type=xml&key=#apiKey#";
//WHMCS table names
$currencyTable = 'tblcurrencies';
$tldTable = 'tbldomainpricing';
$priceTable = 'tblpricing';
//Tld fields not considered for template
$tldTemplateExclusions = ['id', 'extension', 'autoreg', 'order', 'created_at', 'updated_at'];
//Operations/prices to synchronize
$priceOperationList = ['register', 'renew', 'transfer'];
/*****************************************/
/* Get Registrar Config Options */
/*****************************************/
$params = getregistrarconfigoptions('namesilo');
/*****************************************/
/* Define Test Mode */
/*****************************************/
$ns_test_mode = @$params['Test_Mode'];
/*****************************************/
/* Define Sync Due Date */