<?php

require_once './lib/bitcoin.php';
$scheme = 'http';
$username = '******';
$password = '******';
$address = "localhost";
// Local
$port = 18332;
// Testnet
$bitcoin_client = new BitcoinClient($scheme, $username, $password, $address, $port);
if ($bitcoin_client->can_connect() !== TRUE) {
    echo 'The Bitcoin server is presently unavailable. Please contact the site administrator.';
    exit;
}
 /**
  * Process the payment
  * @param string $order_number
  * @param float $order_total
  * @param array $d
  * @return boolean true if bitcoin
  */
 function process_payment($order_number, $order_total, &$d)
 {
     include_once CLASSPATH . "payment/ps_bitcoin.cfg.php";
     // TODO: handle conversions via to-be-written converter script
     // it's also available as global $vendor_currency
     //"currency_code" => $_SESSION['vendor_currency'],
     global $vmLogger;
     $bitcoin_client = new BitcoinClient(BITCOIN_SCHEME, BITCOIN_USERNAME, BITCOIN_PASSWORD, BITCOIN_HOST, BITCOIN_PORT, BITCOIN_CERTIFICATE);
     if (TRUE !== ($fault = $bitcoin_client->can_connect())) {
         $vmLogger->err("The Bitcoin server is presently unavailable. Please contact the site administrator.");
         return false;
     }
     // stuff the (long) order number, the total order price and a timestamp into the bitcoin address's label
     $label = $order_number . " " . number_format($order_total, 2, ".", "") . " " . time();
     try {
         $address = $bitcoin_client->query("getnewaddress", $label);
     } catch (BitcoinClientException $e) {
         $vmLogger->err("The Bitcoin server was unable to generate an address for your payment. Please contact the site administrator.");
         return false;
     }
     if (!Bitcoin::checkAddress($address)) {
         $vmLogger->err("The Bitcoin server returned an invalid address. Please contact the site administrator.");
         return false;
     }
     // stuff the payment address into the session so the "extra info" code can access it
     // TODO: There's gotta be a better way...
     $_SESSION["bitcoin_address"] = $address;
     $d['include_comment'] = "Y";
     $d['order_comment'] = "Please send your payment to Bitcoin address " . $address;
     return true;
 }
/**
 * Process Bitcoin checkout.
 *
 * @param string $separator
 * @param integer $sessionid
 * @todo Document better
 */
function gateway_bitcoin($separator, $sessionid)
{
    global $wpdb, $wpsc_cart;
    include_once "library/bitcoin.inc";
    $bitcoin_client = new BitcoinClient(get_option("bitcoin_scheme"), get_option("bitcoin_username"), get_option("bitcoin_password"), get_option("bitcoin_address"), get_option("bitcoin_port"), get_option("bitcoin_certificate_path"));
    if (TRUE !== ($fault = $bitcoin_client->can_connect())) {
        bitcoin_checkout_fail($session, 'The Bitcoin server is presently unavailable. Please contact the site administrator.', $fault);
        return;
    }
    $row = $wpdb->get_row("SELECT id,totalprice FROM " . WPSC_TABLE_PURCHASE_LOGS . " WHERE sessionid=" . $sessionid);
    $label = $row->id . " " . $row->totalprice;
    try {
        $address = $bitcoin_client->query("getnewaddress", $label);
    } catch (BitcoinClientException $e) {
        bitcoin_checkout_fail($session, 'The Bitcoin server is presently unavailable. Please contact the site administrator.', $e->getMessage());
        return;
    }
    if (!Bitcoin::checkAddress($address)) {
        bitcoin_checkout_fail($session, 'The Bitcoin server returned an invalid address. Please contact the site administrator.', $e->getMessage());
        return;
    }
    //var_dump($_SESSION);
    unset($_SESSION['WpscGatewayErrorMessage']);
    // Set the transaction to pending payment and log the Bitcoin address as its transaction ID
    $wpdb->query("UPDATE " . WPSC_TABLE_PURCHASE_LOGS . " SET processed='1', transactid='" . $address . "' WHERE sessionid=" . $sessionid);
    $_SESSION['bitcoin'] = 'success';
    $_SESSION['bitcoin_address_display'] = $address;
    $_SESSION['bitcoin_address_mail'] = $address;
    header("Location: " . get_option('transact_url') . $separator . "sessionid=" . $sessionid);
    exit;
}
global $vmLogger;
// slurp in all the open Bitcoin transactions
$sql = "select #__{vm}_orders.order_id,order_payment_name,order_number,order_total ";
$sql .= "from #__{vm}_order_payment left join #__{vm}_orders on #__{vm}_orders.order_id = #__{vm}_order_payment.order_id ";
// TODO: Extract "BC" in some intelligent, safe manner
$sql .= "where payment_method_id=(select payment_method_id from #__{vm}_payment_method where payment_method_code='BC') and order_status='" . BITCOIN_PENDING_STATUS . "'";
$db = new ps_DB();
$db->query($sql);
if (!$db->next_record()) {
    die("No open Bitcoin transactions");
}
require_once CLASSPATH . 'ps_order.php';
require_once CLASSPATH . "payment/ps_bitcoin.php";
// prepare the JSON-RPC client
$bitcoin_client = new BitcoinClient(BITCOIN_SCHEME, BITCOIN_USERNAME, BITCOIN_PASSWORD, BITCOIN_HOST, BITCOIN_PORT, BITCOIN_CERTIFICATE);
if (TRUE !== ($fault = $bitcoin_client->can_connect())) {
    $vmLogger->err("Bitcoin cronjob: Unable to connect to Bitcoin server, fault: " . $fault);
    die("Bitcoin cronjob: Unable to connect to Bitcoin server, fault: " . $fault);
}
//$bitcoin_client->setDebug(2);
// loop through the open transactions
do {
    // check for transaction completion
    $address = $db->f("order_payment_name");
    try {
        $paid = $bitcoin_client->query("getreceivedbyaddress", $address, intval(BITCOIN_CONFIRMS));
    } catch (BitcoinClientException $e) {
        $vmLogger->err("Bitcoin server communication failed on getreceivedbyaddress " . $address . " with fault string " . $e->getMessage());
        continue;
    }
    $ps_order = new ps_order();