-
Notifications
You must be signed in to change notification settings - Fork 166
/
util.php
1482 lines (1277 loc) · 42.6 KB
/
util.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
require_once 'db.php';
require_once 'jsonRPCClient.php';
date_default_timezone_set(TIMEZONE);
class BASE_CURRENCY
{
const A = 0;
const B = 1;
}
function fiat_to_numstr($num)
{
return sprintf("%." . FIAT_PRECISION . "f %s", $num, CURRENCY);
}
function btc_to_numstr($num)
{
return sprintf("%." . BTC_PRECISION . "f %s", $num, "BTC");
}
function fiat_and_btc_to_price($fiat, $btc, $round = 'round')
{
$fiat = gmp_strval($fiat);
$btc = gmp_strval($btc);
if (gmp_cmp($btc, "0") == 0)
return "";
else if ($round == 'round') {
$price = bcdiv($fiat, $btc, PRICE_PRECISION+1);
return sprintf("%." . PRICE_PRECISION . "f", $price);
} else if ($round == 'down') {
$price = bcdiv($fiat, $btc, PRICE_PRECISION);
// echo "rounding $fiat / $btc = " . bcdiv($fiat, $btc, 8) . " down to $price<br/>\n";
return $price;
} else if ($round == 'up') {
$raw = bcdiv($fiat, $btc, 8);
$adjust = bcsub(bcdiv(1, pow(10, PRICE_PRECISION), 8),
'0.00000001', 8);
$price = bcadd($raw, $adjust, PRICE_PRECISION);
// echo "rounding $fiat / $btc = $raw up to $price<br/>\n";
return $price;
} else
throw new Error("Bad Argument", "fiat_and_btc_to_price() has round = '$round'");
}
function show_contact_info()
{
echo "<h3>" . _("Contact info") . "</h3>\n";
printf("<p>%s: <a href=\"mailto:%s\">%s</a></p>\n",
_("Email"),
CONTACT_EMAIL_ADDRESS, CONTACT_EMAIL_ADDRESS);
printf("<p>%s: <a href=\"skype:%s?call\">%s</a></p>\n",
_("Skype"),
CONTACT_SKYPE_ADDRESS, CONTACT_SKYPE_ADDRESS);
printf("<p>%s: <a target=\"_blank\" href=\"%s\">%s</a></p>\n",
_("Facebook"),
CONTACT_FACEBOOK_URL, CONTACT_FACEBOOK_NAME);
printf("<p>%s: <a target=\"_blank\" href=\"http://twitter.com/%s\">@%s</a></p>\n",
_("Twitter"),
CONTACT_TWITTER_NAME, CONTACT_TWITTER_NAME);
printf("<p>%s: %s</p>\n",
_("Call"),
CONTACT_PHONE_NUMBER);
printf("<p>%s: %s</p> \n",
_("Office Hours"),
CONTACT_OFFICE_HOURS);
printf("<p>(%s: %s - %s %s)</p>\n",
_("Standard time zone"),
CONTACT_TIME_ZONE,
_("it is currently"), get_time_text());
printf("<p>%s</p>\n",
CONTACT_ADDRESS_ETC);
}
function send_email($to, $subject, $body)
{
$headers = "From: " . EMAIL_FROM_ADDRESS;
addlog(LOG_EMAIL, sprintf("mail('%s', '%s', '%s', '%s')", $to, $subject, $body, $headers));
mail($to, $subject, $body, $headers);
}
function email_tech($subject, $body)
{
send_email(TECH_EMAIL_ADDRESS, $subject, $body);
}
function freeze_file()
{
return LOCK_DIR . "/FREEZE";
}
function set_frozen($freeze = true)
{
if ($freeze) {
$umask = umask(0);
umask(0);
if (!($fp = fopen(freeze_file(), "w")))
throw new Error('Freeze Error', "Can't create freeze file " . freeze_file());
} else {
unlink(freeze_file());
if (file_exists(freeze_file()))
throw new Error('Unfreeze Error', "Can't unlink freeze file " . freeze_file());
}
}
function is_frozen()
{
return file_exists(freeze_file());
}
function check_frozen()
{
if (is_frozen())
throw new Error(_("Frozen"), _("Trading on the exchange is temporarily frozen"));
}
function sql_format_date($date)
{
return "CONCAT(DATE_FORMAT($date, '%h:%i'), " .
"LOWER(DATE_FORMAT($date, '%p')), " .
"DATE_FORMAT($date, ' %d-%b-%y'))";
}
function create_record($our_orderid, $our_amount, $our_commission,
$them_orderid, $them_amount, $them_commission)
{
// record keeping
$query = "
INSERT INTO transactions (
a_orderid,
a_amount,
a_commission,
b_orderid,
b_amount,
b_commission
) VALUES (
'$our_orderid',
'$our_amount',
'$our_commission',
'$them_orderid',
'$them_amount',
'$them_commission'
);
";
do_query($query);
}
function add_funds($uid, $amount, $type)
{
// eventually plan to move these to prepared mysql statements once the queries become more mature.
$query = "
UPDATE purses
SET
amount = amount + '$amount'
WHERE
uid='$uid'
AND type='$type';
";
do_query($query);
}
function find_total_trades_available_at_rate($rate, $have_curr)
{
// find the total 'amount' and 'want_amount' in the book from people having $have_curr offering a rate of $rate or better (for us)
do_query("SET div_precision_increment = 8");
if ($have_curr == 'BTC')
$query = "
SELECT
SUM(amount) AS amount,
SUM(want_amount) as want_amount,
MAX(initial_want_amount/initial_amount) as worst_price
FROM
orderbook
WHERE
type='BTC'
AND status='OPEN'
AND initial_want_amount/initial_amount <= $rate
";
else
$query = "
SELECT
SUM(amount) AS amount,
SUM(want_amount) as want_amount,
MIN(initial_amount/initial_want_amount) as worst_price
FROM
orderbook
WHERE
type='" . CURRENCY . "'
AND status='OPEN'
AND initial_amount/initial_want_amount >= $rate
";
return mysql_fetch_array(do_query($query));
}
function calc_exchange_rate($curr_a, $curr_b, $base_curr=BASE_CURRENCY::A)
{
// how is the rate calculated? is it a/b or b/a?
if ($base_curr == BASE_CURRENCY::A)
$invertor = 'TRUE';
else
$invertor = 'FALSE';
$query = "
SELECT
SUM(amount) AS total_amount,
SUM(want_amount) as total_wanted,
ROUND(
IF(
$invertor,
MIN(initial_want_amount/initial_amount),
MAX(initial_amount/initial_want_amount)
), " . PRICE_PRECISION . ") AS rate
FROM
orderbook
WHERE
type='$curr_a'
AND want_type='$curr_b'
AND status='OPEN'
";
$total_result = do_query($query);
list($total_amount, $total_want_amount, $rate) = mysql_fetch_array($total_result);
if (!isset($total_amount) || !isset($total_want_amount) || !isset($rate))
return NULL;
$total_amount = internal_to_numstr($total_amount);
$total_want_amount = internal_to_numstr($total_want_amount);
return array($total_amount, $total_want_amount, $rate);
}
function logout()
{
session_destroy();
// expire the session cookie
if (ini_get("session.use_cookies")) {
$params = session_get_cookie_params();
setcookie(session_name(), '', time() - 36*60*60, $params["path"], $params["domain"], $params["secure"], $params["httponly"]);
}
header('Location: .');
exit();
}
$is_logged_in = 0;
$is_admin = false;
$oidlogin = '';
function get_login_status()
{
global $is_logged_in, $is_admin, $is_verified, $oidlogin;
if (!isset($_SESSION['uid']) || !isset($_SESSION['oidlogin'])) {
list ($is_logged_in, $is_admin, $oidlogin) = array(0, false, '');
return;
}
// just having a 'uid' in the session isn't enough to be logged in
// check that the oidlogin matches the uid in case database has been reset
$uid = $_SESSION['uid'];
$oid = $_SESSION['oidlogin'];
$result = do_query("
SELECT is_admin, verified
FROM users
WHERE oidlogin = '$oid'
AND uid = '$uid'
");
if (has_results($result)) {
$row = mysql_fetch_array($result);
list ($is_logged_in, $is_admin, $is_verified, $oidlogin) = array($uid, $row['is_admin'] == '1', $row['verified'] == '1', $oid);
if (!REQUIRE_IDENTIFICATION)
$is_verified = true;
return;
}
if (isset($_GET['fancy'])) {
list ($is_logged_in, $is_admin, $is_verified, $oidlogin) = array(0, false, false, '');
return;
}
logout();
}
function get_openid_for_user($uid)
{
$result = do_query("
SELECT oidlogin
FROM users
WHERE uid = '$uid'
");
if (!has_results($result))
throw new Error("Unknown User", "User ID $uid isn't known");
$row = mysql_fetch_array($result);
return $row['oidlogin'];
}
function get_uid_for_openid($openid)
{
$result = do_query("
SELECT uid
FROM users
WHERE oidlogin = '$openid'
");
if (!has_results($result))
throw new Error("Unknown User", "OpenID $openid isn't known");
$row = mysql_fetch_array($result);
return $row['uid'];
}
function get_account_creation_timest_for_user($uid)
{
$result = do_query("
SELECT " . sql_format_date("timest") . " AS timest
FROM users
WHERE uid = '$uid'
");
if (!has_results($result))
throw new Error("Unknown User", "User ID $uid isn't known");
$row = mysql_fetch_array($result);
return $row['timest'];
}
function check_verified()
{
global $is_verified;
if (!$is_verified)
throw new Exception("Your account is not verified. Please identify yourself at " . SITE_URL . "?page=identity");
}
function verify_user($uid)
{
addlog(LOG_RESULT, " verified user $uid");
do_query("UPDATE users SET verified = 1 WHERE uid = '$uid'");
return mysql_affected_rows();
}
function unverify_user($uid)
{
addlog(LOG_RESULT, " unverified user $uid");
do_query("UPDATE users SET verified = 0 WHERE uid = '$uid'");
return mysql_affected_rows();
}
function get_verified_for_user($uid)
{
$result = do_query("
SELECT verified
FROM users
WHERE uid = '$uid'
");
if (!has_results($result))
throw new Error("Unknown User", "User ID $uid isn't known");
$row = mysql_fetch_array($result);
return $row['verified'];
}
function user_id()
{
global $is_logged_in;
if (!$is_logged_in)
// grave error. This should never happen and should be reported as an urgent breach.
throw new Error('Login 404', "You're not logged in. Proceed to the <a href='?login.php'>login</a> form.");
return $is_logged_in;
}
function get_wait_lock($uid)
{
$lock = LOCK_DIR . "/" . $uid . ".wait";
$umask = umask(0);
if (!($fp = fopen($lock, "w"))) {
umask($umask);
throw new Error(_('Lock Error'), "Can't create wait lockfile for $uid");
}
if (!flock($fp, LOCK_EX|LOCK_NB)) {
umask($umask);
return false;
}
umask($umask);
return $fp;
}
function release_wait_lock($fp)
{
flock($fp, LOCK_UN);
fclose($fp);
}
$lock_count = array();
$lock_fp = array();
// $block = 0: fail instantly if already locked
// $block = 1: wait for lock if nobody else is already waiting, else fail instantly
// $block = 2: wait for lock, even if someone else is already waiting
function get_lock($uid, $block)
{
global $lock_count, $lock_fp;
$log = $uid != 'log';
if ($log) addlog(LOG_LOCK, "get_lock('$uid', $block);");
if (array_key_exists($uid, $lock_count)) {
$lock_count[$uid]++;
if ($log) addlog(LOG_LOCK, " lock already held - now count is " . $lock_count[$uid]);
return;
}
$lock = LOCK_DIR . "/" . $uid;
$umask = umask(0);
if (!($fp = fopen($lock, "w"))) {
umask($umask);
if ($log) addlog(LOG_LOCK, " can't create lockfile");
throw new Error(_('Lock Error'), "Can't create lockfile for $uid");
}
$block_flags = LOCK_EX;
$no_block_flags = LOCK_EX|LOCK_NB;
if ($block == 0) {
if (!flock($fp, $no_block_flags)) {
umask($umask);
if ($log) addlog(LOG_LOCK, " locked and not waiting");
throw new Error(_('Lock Error'), sprintf(_("User %s is already doing stuff."), $uid) . "<br/>");
}
} else if ($block == 2) {
// try to get wait_lock. don't care whether we get it or not, only doing it to tell others who care that we're waiting
$wait_lock = get_wait_lock($uid);
if (!flock($fp, $block_flags)) {
if ($wait_lock)
release_wait_lock($wait_lock);
umask($umask);
if ($log) addlog(LOG_LOCK, " waited but still didn't get lock");
throw new Error(_('Lock Error'), sprintf(_("Can't get lock for user %s, even after waiting."), $uid) . "<br/>");
}
if ($wait_lock)
release_wait_lock($wait_lock);
} else if ($block == 1) {
// try getting the lock without blocking first
if (!flock($fp, $no_block_flags)) {
// if we can't, then check whether anyone else is already waiting
$wait_lock = get_wait_lock($uid);
if ($wait_lock) {
// if not, then wait
if (!flock($fp, $block_flags)) {
release_wait_lock($wait_lock);
umask($umask);
if ($log) addlog(LOG_LOCK, " waited but still didn't get lock");
throw new Error(_('Lock Error'), sprintf(_("Can't get lock for user %s, even after waiting."), $uid) . "<br/>");
}
release_wait_lock($wait_lock);
} else {
umask($umask);
if ($log) addlog(LOG_LOCK, " this lock is already being waited for");
throw new Error(_('Lock Error'), sprintf(_("User %s is already doing stuff, and also already waiting for lock."), $uid) . "<br/>");
}
}
}
umask($umask);
$lock_count[$uid] = 1;
$lock_fp[$uid] = $fp;
if ($log) addlog(LOG_LOCK, " got lock '$uid'");
return;
}
function get_lock_without_waiting($uid)
{
get_lock($uid, 0);
}
function wait_for_lock_if_no_others_are_waiting($uid)
{
get_lock($uid, 1);
}
function wait_for_lock($uid)
{
get_lock($uid, 2);
}
function release_lock($uid)
{
global $lock_count, $lock_fp;
$log = $uid != 'log';
if ($log) addlog(LOG_LOCK, "release_lock('$uid');");
if (array_key_exists($uid, $lock_count)) {
$lock_count[$uid]--;
if ($lock_count[$uid] == 0) {
$fp = $lock_fp[$uid];
flock($fp, LOCK_UN);
fclose($fp);
unset($lock_count[$uid]);
unset($lock_fp[$uid]);
if ($log) addlog(LOG_LOCK, " released lock");
}
else
if ($log) addlog(LOG_LOCK, " lock held multiple times - now count is " . $lock_count[$uid]);
return;
}
throw new Error('Unlock error', "lock for user $uid isn't held - can't release it");
}
function get_user_lock($uid)
{
if (BLOCKING_LOCKS)
wait_for_lock_if_no_others_are_waiting($uid);
else
get_lock_without_waiting($uid);
}
function cleanup_string($val, $extra='')
{
$extra = str_replace('/', '\/', $extra);
$val = preg_replace("/[^A-Za-z0-9 .$extra]/", '', $val);
return mysql_real_escape_string($val);
}
function post($key, $extra='')
{
if (!isset($_POST[$key]))
throw new Error('Ooops!', "Missing posted value $key!");
$value = cleanup_string($_POST[$key], $extra);
addlog(LOG_PARAMS, " post '$key' = '$value'");
return $value;
}
function get($key, $extra='')
{
if (!isset($_GET[$key]))
throw new Error('Ooops!', "Missing get value $key!");
$value = cleanup_string($_GET[$key], $extra);
addlog(LOG_PARAMS, " get '$key' = '$value'");
return $value;
}
$bitcoin = false;
function maybe_connect_bitcoin()
{
global $bitcoin;
if (!$bitcoin)
$bitcoin = connect_bitcoin();
return $bitcoin;
}
function bitcoin_get_account_address($account)
{
$bitcoin = maybe_connect_bitcoin();
return $bitcoin->getaccountaddress((string)$account);
}
function bitcoin_get_balance($account, $confirmations)
{
$bitcoin = maybe_connect_bitcoin();
return $bitcoin->getbalance($account, $confirmations);
}
function bitcoin_list_accounts($minconf = 1)
{
$bitcoin = maybe_connect_bitcoin();
$accounts = $bitcoin->listaccounts($minconf);
if (!INTEGER_BITCOIND)
foreach ($accounts as $name => $value)
$accounts[$name] = bitcoin_to_internal($value);
return $accounts;
}
function bitcoin_move($from_account, $to_account, $amount)
{
if (!INTEGER_BITCOIND)
$amount = internal_to_numstr($amount, 8);
$bitcoin = maybe_connect_bitcoin();
return $bitcoin->move($from_account, $to_account, $amount);
}
function bitcoin_send_to_address($address, $amount)
{
if (!INTEGER_BITCOIND)
$amount = internal_to_numstr($amount, 8);
$bitcoin = maybe_connect_bitcoin();
return $bitcoin->sendtoaddress($address, $amount);
}
function bitcoin_validate_address($address)
{
$bitcoin = maybe_connect_bitcoin();
return $bitcoin->validateaddress($address);
}
function bitcoin_to_internal($str)
{
// remove the decimal point from strings representing numbers with 8 decimal places
if (is_string($str)) {
$new_str = preg_replace('/^(-?\d+)[.](\d{8})$/', '$1$2', $str);
if ($new_str !== $str)
$str = preg_replace('/^(-?)0+(.)/', '$1$2', $new_str); /* remove leading zeros, or it gets read as octal */
}
return $str;
}
function sync_to_bitcoin($uid)
{
if (!is_string($uid))
throw new Error('Coding error!', "sync_to_bitcoin() expects a string, not type '" . gettype($uid) . "'");
try {
$balance = bitcoin_get_balance($uid, CONFIRMATIONS_FOR_DEPOSIT);
if (is_float($balance))
throw new Error(_("bitcoind version error"), _("bitcoind getbalance should return an integer not a float"));
if (gmp_cmp($balance, '0') > 0) {
bitcoin_move($uid, '', $balance);
$query = "
INSERT INTO requests (req_type, uid, amount, curr_type)
VALUES ('DEPOS', '$uid', '$balance', 'BTC');
";
do_query($query);
$we_have = bitcoin_get_balance('*', 1);
if (gmp_cmp($we_have, numstr_to_internal(WARN_HIGH_WALLET_THRESHOLD)) > 0)
email_tech(_("Exchange Wallet Balance is High"),
sprintf(_("The exchange wallet has %s BTC available."),
internal_to_numstr($we_have, BTC_PRECISION)));
}
} catch (Exception $e) {
if ($e->getMessage() != 'Unable to connect.')
throw $e;
}
}
function fetch_committed_balances($uid)
{
// returns an array of amounts of balances currently committed in unfilled orders
$balances = array(CURRENCY=>'0','BTC'=>'0');
sync_to_bitcoin($uid);
$query = "
SELECT sum(amount) as amount, type
FROM orderbook
WHERE uid = '$uid'
AND status = 'OPEN'
GROUP BY type;
";
$result = do_query($query);
while ($row = mysql_fetch_array($result)) {
$amount = $row['amount'];
$type = $row['type'];
$balances[$type] = $amount;
}
return $balances;
}
function fetch_balances($uid)
{
$balances = array();
sync_to_bitcoin($uid);
$query = "
SELECT amount, type
FROM purses
WHERE uid='$uid';
";
$result = do_query($query);
while ($row = mysql_fetch_array($result)) {
$amount = $row['amount'];
$type = $row['type'];
$balances[$type] = $amount;
}
return $balances;
}
function show_committed_balances($uid, $indent=false)
{
$balances = fetch_committed_balances($uid);
if ($indent)
echo "<p class='indent'>";
else
echo "<p>";
echo "You have ", internal_to_numstr($balances[CURRENCY]), " " . CURRENCY . " and ",
internal_to_numstr($balances['BTC']), " BTC ",
"tied up in the orderbook.</p>\n";
}
function balances_text($uid)
{
$balances = fetch_balances($uid);
return sprintf("%s %s and %s %s",
internal_to_numstr($balances[CURRENCY], FIAT_PRECISION, false), CURRENCY,
internal_to_numstr($balances['BTC'], BTC_PRECISION, false), 'BTC' );
}
function show_balances($uid, $indent=false)
{
$balances = fetch_balances($uid);
foreach($balances as $type => $amount) {
$amount = internal_to_numstr($amount);
if ($indent)
echo "<p class='indent'>";
else
echo "<p>";
echo "You have $amount $type.</p>\n";
}
}
function get_last_price()
{
$query = "
SELECT
a_amount,
b_amount
FROM
transactions
WHERE
b_amount > 0
ORDER BY
txid DESC
LIMIT 1
";
$result = do_query($query);
if (has_results($result)) {
$row = get_row($result);
$last = fiat_and_btc_to_price($row['a_amount'], $row['b_amount']);
}
else
$last = 0;
return $last;
}
// {"ticker":
// {"high":11.89, highest traded price in last 24h
// "low":9.903, lowest traded price in last 24h
// "avg":10.743607598, mean traded price in last 24h (sum of price / number of prices)
// "vwap":10.844024918, volume weighted average price (sum of price*amount / sum of amount)
// "vol":49103, volume (in BTC)
// "last":11.35, last traded price
// "buy":11.35, highest buy offer
// "sell":11.38967 lowest sell offer
// }
// }
//
// I'm doing the divisions using bcdiv() in PHP rather than in the SQL
// query because even with SET div_precision_increment = 4; it was
// giving 8 digits of precision:
//
// mysql> SELECT a_amount, b_amount, a_amount/b_amount, sum(a_amount/b_amount) as sum,
// sum(a_amount/b_amount)/1 as sumover1
// FROM transactions WHERE b_amount > 0 AND timest > NOW() - INTERVAL 1 DAY;
//
// +-----------+----------+-------------------+---------+-------------+
// | a_amount | b_amount | a_amount/b_amount | sum | sumover1 |
// +-----------+----------+-------------------+---------+-------------+
// | 500000000 | 22727272 | 22.000000704 | 22.0000 | 22.00000070 |
// +-----------+----------+-------------------+---------+-------------+
function get_ticker_data()
{
$query = "
SELECT
ROUND(MAX(a_amount/b_amount), " . PRICE_PRECISION . ") AS high,
ROUND(MIN(a_amount/b_amount), " . PRICE_PRECISION . ") AS low,
SUM(a_amount/b_amount) AS sum_of_prices,
COUNT(*) AS number_of_prices,
SUM(a_amount) AS sum_of_a_amounts,
SUM(b_amount) AS sum_of_b_amounts,
SUM(b_amount) AS vol
FROM
transactions
WHERE
b_amount > 0
AND timest > NOW() - INTERVAL 1 DAY;
";
$result = do_query($query);
$row = get_row($result);
if (isset($row['vol'])) {
$sum_of_prices = $row['sum_of_prices'];
$number_of_prices = $row['number_of_prices'];
$sum_of_a_amounts = $row['sum_of_a_amounts'];
$sum_of_b_amounts = $row['sum_of_b_amounts'];
$high = $row['high'];
$low = $row['low'];
$avg = fiat_and_btc_to_price($sum_of_prices, $number_of_prices);
$vwap = fiat_and_btc_to_price($sum_of_a_amounts, $sum_of_b_amounts);
$vol = internal_to_numstr($row['vol'], BTC_PRECISION);
} else
$high = $low = $avg = $vwap = $vol = 0;
$exchange_fields = calc_exchange_rate(CURRENCY, 'BTC', BASE_CURRENCY::B);
if (!$exchange_fields)
$buy = 0;
else
list($total_amount, $total_want_amount, $buy) = $exchange_fields;
$exchange_fields = calc_exchange_rate('BTC', CURRENCY, BASE_CURRENCY::A);
if (!$exchange_fields)
$sell = 0;
else
list($total_amount, $total_want_amount, $sell) = $exchange_fields;
$last = get_last_price();
// for testing layout when all stats have 4 decimal places
// return array('21.1234', '20.1234', '21.6789', '21.4567', '1234567.3456', '21.5543', '21.2345', '22.1257');
return array($high, $low, $avg, $vwap, $vol, $last, $buy, $sell);
}
function has_enough($amount, $curr_type)
{
$uid = user_id();
sync_to_bitcoin($uid);
$query = "
SELECT 1
FROM purses
WHERE uid='$uid' AND type='$curr_type' AND amount >= '$amount'
LIMIT 1;
";
$result = do_query($query);
return has_results($result);
}
function active_table_row($class, $url)
{
printf ("<tr %s %s %s %s>",
"class=\"$class\"",
'onmouseover="style.backgroundColor=\'#8ae3bf\';"',
'onmouseout="style.backgroundColor=\'#7ad3af\';"',
"onclick=\"document.location='$url';\"");
}
function active_table_cell($content, $url, $right=false)
{
printf ("<td class='active%s' %s %s %s>%s</td>",
$right ? " right" : "",
'onmouseover="style.backgroundColor=\'#8ae3bf\';"',
'onmouseout="style.backgroundColor=\'#7ad3af\';"',
"onclick=\"document.location='$url';\"",
$content);
}
function active_table_cell_for_order($content, $orderid)
{
active_table_cell($content, "?page=view_order&orderid=$orderid");
}
function active_table_cell_for_request($content, $reqid)
{
active_table_cell($content, "?page=view_request&reqid=$reqid");
}
function active_table_cell_link_to_user_statement($user, $interval = '')
{
if ($interval)
$url = "?page=statement&user=$user&interval=$interval";
else
$url = "?page=statement&user=$user";
printf("<td class='active' %s %s %s>$user</td>",
"onmouseover=\"style.backgroundColor='#8ae3bf';\"",
"onmouseout=\"style.backgroundColor='#7ad3af';\"",
"onclick=\"document.location='$url'\"");
}
class OrderInfo
{
public $orderid, $uid, $initial_amount, $amount, $type, $initial_want_amount, $want_amount, $want_type, $commission, $status, $timest, $processed;
public function __construct($row)
{
$this->orderid = $row['orderid'];
$this->uid = $row['uid'];
$this->initial_amount = $row['initial_amount'];
$this->amount = $row['amount'];
$this->type = $row['type'];
$this->initial_want_amount = $row['initial_want_amount'];
$this->want_amount = $row['want_amount'];
$this->want_type = $row['want_type'];
$this->commission = $row['commission'];
$this->status = $row['status'];
$this->timest = $row['timest_format'];
$this->processed = (bool)$row['processed'];
}
}
function fetch_order_info($orderid)
{
$query = "
SELECT
*,
" . sql_format_date("timest") . " AS timest_format
FROM orderbook
WHERE orderid='$orderid';
";
$result = do_query($query);
$row = get_row($result);
$info = new OrderInfo($row);
return $info;
}
function deduct_funds($amount, $curr_type)
{
add_funds(user_id(), -$amount, $curr_type);
}
function curr_supported_check($curr_type)
{
$supported_currencies = array(CURRENCY, 'BTC');
if (!in_array($curr_type, $supported_currencies))
throw new Error(_('Ooops!'),
_('Bad currency supplied. Do you have Javascript disabled in your web browser? This site needs Javascript enabled.'));
}
function order_worthwhile_check($amount, $amount_disp, $currency, $min_str='0.5')
{
if (!is_numeric($amount_disp))
throw new Problem(_('Numbers. Numbers.'), _('The value you entered was not a number.'));
$min = numstr_to_internal($min_str);
if ($amount < $min)
throw new Problem(_("Try again..."), sprintf(_("Your order size is too small. The minimum is %s %s."), $min_str, $currency));
}
function enough_money_check($amount, $curr_type)
{
if (!has_enough($amount, $curr_type))
throw new Problem(_("Where's the gold?"), sprintf(_("You don't have enough %s."), $curr_type));
}
function translate_order_code($code)
{
// OPEN CANCEL CLOSED
switch ($code)
{
case 'OPEN':
return _('Open');
case 'CANCEL':
return _('Cancelled');
case 'CLOSED':
return _('Completed');
default:
throw new Error(_('No such order'), _('This order is wrong...'));
}
}
function translate_request_type($type)
{
switch ($type)
{
case 'WITHDR':
return _('Withdraw');
case 'DEPOS':
return _('Deposit');
default:
throw new Error(_('No such request type'), _('This request is wrong...'));
}
}
function translate_request_code($code)
{
// VAL VERIF PRO OK FIN NO RET
// jei verifies payments
// I verify (process) payments
// we both confirm (OK) them
// they either complete (SENT, FIN) or deny (NO, RET)
switch ($code)
{
case 'VERIFY':
return _('Verifying');
case 'PROCES':
return _('Processing');
case 'FINAL':
return _('Finished');
case 'IGNORE':
return _('Ignored');
case 'REJECT':
return _('Rejected');
case 'CANCEL':
return _('Cancelled');