function redeemVoucher() { $voucher = post('voucher', '-'); try { get_lock("redeem_voucher", 2); list($currency, $amount) = redeem_voucher($voucher); release_lock("redeem_voucher"); } catch (Exception $e) { release_lock("redeem_voucher"); throw new Exception($e->getMessage()); } return array("status" => "OK", "currency" => $currency, "amount" => internal_to_numstr($amount)); }
function process_api_request($function_to_run, $permission_needed) { global $is_logged_in; $lock = false; try { verify_api_request($permission_needed); log_api($function_to_run); get_user_lock($lock = $is_logged_in); $ret = $function_to_run(); } catch (Exception $e) { $error = $e->getMessage(); addlog(LOG_API, sprintf("[%s] API error: \"%s\": %s: %s", getenv("REMOTE_ADDR"), $error, $function_to_run, file_get_contents("php://input"))); $ret = array("error" => $error); } if ($lock) { release_lock($lock); } echo json_encode($ret); }
<?php require_once '../util.php'; $is_logged_in = 'sync_to_bitcoin'; foreach (bitcoin_list_accounts(CONFIRMATIONS_FOR_DEPOSIT) as $account => $balance) { if ($balance) { try { get_openid_for_user($account); // check they have an account } catch (Exception $e) { continue; } get_user_lock($account); addlog(LOG_CRONJOB, sprintf("add %s BTC for user %s", internal_to_numstr($balance), $account)); sync_to_bitcoin((string) $account); release_lock($account); } }
function HandleEventQueue() { $lockname = "HandleEventQueue"; if (!get_lock($lockname)) { return; } $events = doquery("SELECT * FROM event_queue ORDER BY due_time LIMIT 5", 'NOTABLE'); while ($event = mysql_fetch_array($events)) { switch ($event['type']) { case "building": UpdatePlanetBatimentQueueList($event['id']); break; case "tech": break; default: assert(false); } } release_lock($lockname); }
case 'get_entry': $myReturn = get_entry($_POST); if (isset($myReturn['minutes_locked']) && $myReturn['minutes_locked'] > 31) { $data = array('user_id' => $myReturn['fields']['lock'], 'id' => $myReturn['fields']['id']); release_lock($data); $myReturn = get_entry($_POST); } break; case 'get_table_data': $myReturn = get_table_data($_POST['access_level'] * 1); break; case 'get_groups': $myReturn['groups'] = get_groups($_POST['nuid']); break; case 'release_lock': $myReturn = release_lock($_POST); break; case 'delete_revisions': $myReturn = delete_revisions($_POST); break; default: $myReturn['error'] = 'Not prepared to handle action "' . $_POST['action'] . '"'; break; } // end switch $myReturn['action'] = $_POST['action']; $myReturn['last_accessed'] = log_user_access($_POST); } else { $myReturn['error'] = 'No action requested.'; } // end if get toolbar
echo "<div class='content_box'>\n"; echo "<h3>" . _("Deposit Voucher") . "</h3>\n"; $code = post('code', '-'); try { get_lock("redeem_voucher", 2); list($curr_type, $amount) = redeem_voucher($code); echo "<p><strong>" . sprintf(_("%s has been credited to your account."), internal_to_numstr($amount) . " {$curr_type}") . "</strong></p>\n"; echo "<p>" . _("got any more?") . "</p>\n"; show_deposit_voucher_form($code); } catch (Exception $e) { $message = $e->getMessage(); echo "<p>" . _("error") . ": {$message}</p>\n"; echo "<p>" . _("try again?") . "</p>\n"; show_deposit_voucher_form($code); } release_lock("redeem_voucher"); echo "</div>\n"; } else { try { $addy = bitcoin_get_account_address((string) $is_logged_in); } catch (Exception $e) { if ($e->getMessage() != 'Unable to connect.') { throw $e; } $addy = ''; } $query = "\n SELECT deposref\n FROM users\n WHERE uid='{$is_logged_in}';\n "; $result = do_query($query); $row = get_row($result); $deposref = $row['deposref']; $formatted_deposref = format_deposref($deposref);
$account_id = $db->getField('account_id'); $to_email = $db->getField('email'); $to_name = $db->getField('first_name') . ' ' . $db->getField('last_name'); // debug output echo $account_id . '. Preparing mail for ' . $to_name . ' <' . $to_email . '>... '; // set a bounce address we can process later $mail->From = 'bounce_' . $account_id . '@smrealms.de'; $mail->AddAddress($to_email, $to_name); if (!$mail->Send()) { echo 'error.' . EOL . $mail->ErrorInfo; $mail->SmtpClose(); ob_flush(); exit; } else { echo 'sent.' . EOL; } $total++; // Clear all addresses for next loop $mail->ClearAddresses(); //sleep(1); } $mail->SmtpClose(); echo 'Total ' . $total . ' mails sent.' . EOL; release_lock(); exit; } else { $mail->AddAddress($_REQUEST['to_email'], $_REQUEST['to_email']); $mail->Send(); $mail->SmtpClose(); } forward(create_container('skeleton.php', 'newsletter_send.php'));
function process() { do_query("SET div_precision_increment = 8"); // find and cancel any active orders from users with negative BTC or FIAT balances // this should never happen unless someone is trying to double-spend their balance $query = "\n SELECT orderid, orderbook.amount as amount, orderbook.type, orderbook.uid as uid\n FROM orderbook\n JOIN purses\n ON orderbook.uid = purses.uid\n WHERE\n status != 'CLOSED' AND\n status != 'CANCEL' AND\n purses.amount < 0\n GROUP BY orderid\n "; $result = b_query($query); while ($row = mysql_fetch_array($result)) { $orderid = $row['orderid']; $amount = $row['amount']; $type = $row['type']; $uid = $row['uid']; try { echo "cancelling order {$orderid} (spend ", internal_to_numstr($amount), " {$type} for user {$uid}) due to negative balance\n"; wait_for_lock($uid); $query = "\n UPDATE orderbook\n SET status = 'CANCEL'\n WHERE orderid = '{$orderid}'\n "; b_query($query); add_funds($uid, $amount, $type); // these records indicate returned funds. create_record($orderid, $amount, 0, 0, -1, 0); release_lock($uid); } catch (Error $e) { if ($e->getTitle() == 'Lock Error') { echo "can't get lock for {$uid}\n"; } else { throw $e; } } } $query = "\n SELECT orderid\n FROM orderbook\n WHERE processed=FALSE\n ORDER BY timest ASC\n "; $result = b_query($query); while ($row = mysql_fetch_array($result)) { $orderid = $row['orderid']; echo "Processing {$orderid}...\n"; fulfill_order($orderid); echo "Completed.\n\n"; $query = "\n UPDATE orderbook\n SET processed=TRUE\n WHERE orderid='{$orderid}'\n "; b_query($query); } }
} $request_uid = get_request_uid($reqid); get_lock_without_waiting($request_uid); $result = do_query("SELECT reqid FROM requests WHERE reqid='{$reqid}' AND status='VERIFY'"); if (has_results($result)) { $query = "\n UPDATE\n requests\n SET\n requests.status='FINAL'\n WHERE\n reqid='{$reqid}'\n AND status='VERIFY'\n AND req_type='WITHDR'\n AND curr_type = '" . CURRENCY . "'\n "; do_query($query); echo " <div class='content_box'>\n"; echo " <h3>" . _("Finished!") . "</h3>\n"; echo " <p>" . sprintf(_("Request %s has been set to %s status."), $reqid, translate_request_code("FINAL")) . "</p>\n"; } else { echo " <div class='content_box'>\n"; echo " <h3>" . _("Warning!") . "</h3>\n"; echo " <p>" . sprintf(_("Request %s was cancelled before we could mark it as finished."), $reqid) . "</p>\n"; } release_lock($request_uid); } else { if ($is_admin) { $uid_check = ""; } else { $uid_check = "AND uid='{$uid}'"; } $query = "\n SELECT\n req_type,\n amount,\n curr_type,\n " . sql_format_date("timest") . " AS timest,\n status\n FROM requests\n WHERE reqid='{$reqid}' {$uid_check}\n "; $result = do_query($query); if (!has_results($result)) { throw new Problem('No request here', "Don't have viewing permissions."); } $row = get_row($result); $req_type = $row['req_type']; $amount = internal_to_numstr($row['amount']); $curr_type = $row['curr_type'];
function test_api() { global $is_logged_in; // the API tries to get a lock on our user. this will block if we're already locked if ($is_logged_in) { try { release_lock($is_logged_in); } catch (Exception $e) { echo $e->getMessage(); } } try { $wbx = new WBX_API(API_KEY, API_SECRET); // test_api_info($wbx); // test_api_vouchers($wbx); // test_api_orders($wbx); // test_get_deposit_address($wbx); // test_api_withdraw_fiat($wbx); test_api_withdraw_bitcoin($wbx); } catch (Exception $e) { echo "caught Exception: {$e->getMessage()}<br/>\n"; } // re-obtain the lock. switcher will later try to unlock it if ($is_logged_in) { get_user_lock($is_logged_in); } }
function switcher($page) { global $is_logged_in, $is_admin, $is_verified; try { $lock = false; if (!preg_match("/^[0-9_a-z]*\$/", $page)) { $page = 'junk'; } // delay showing the header when logging in until we know whether the login worked or not if ($page != 'download' && $page != 'login' && $page != 'graph') { show_header($page, $is_logged_in); } if ($is_logged_in) { get_user_lock($lock = $is_logged_in); } addlog(LOG_SWITCHER, sprintf("[%s] visit page '%s'", getenv("REMOTE_ADDR"), $page)); switch ($page) { //////////////////////////////////////////////////////////////////////// // for general consumption //////////////////////////////////////////////////////////////////////// case '404': case 'graph': case 'help': case 'news': case 'orderbook': case 'test': case 'trade': case 'view_trades': include "{$page}.php"; break; //////////////////////////////////////////////////////////////////////// // for logged in users only //////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////// // for logged in users only //////////////////////////////////////////////////////////////////////// case 'api': case 'deposit': case 'identity': case 'place_order': case 'profile': case 'statement': case 'turn_on_duo': case 'view_order': case 'view_request': case 'withdraw': if ($is_logged_in) { include "{$page}.php"; } else { log_badpage($page); } break; //////////////////////////////////////////////////////////////////////// // for admin only //////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////// // for admin only //////////////////////////////////////////////////////////////////////// case 'add_cash': case 'bank': case 'commission': case 'docs': case 'download': case 'freeze': case 'users': if ($is_admin) { include "{$page}.php"; } else { log_badpage($page); } break; case 'login': if (!$is_logged_in) { include "login.php"; // we just tried to log in, so check whether or not it worked before showing the footer get_login_status(); } else { addlog(LOG_LOGIN, " already logged in"); log_badpage($page); } break; case 'logout': setcookie('autologin', FALSE, time() - 60 * 60 * 24 * 365); logout(); default: sleep(3); log_badpage($page); break; } // debugging for session stuff if (0) { echo "<div class='content_box'>\n"; echo "<h3>Debug</h3>\n"; echo "<p>\n"; echo "session id: ", session_id(), "<br/>\n"; echo "session age: ", time() - $_SESSION['creation_time'], " seconds<br/>\n"; if (isset($inactivity)) { echo "you were inactive for {$inactivity} seconds<br/>\n"; } echo "MAX_IDLE_MINUTES_BEFORE_LOGOUT = ", MAX_IDLE_MINUTES_BEFORE_LOGOUT, " minutes = ", MAX_IDLE_MINUTES_BEFORE_LOGOUT * 60, " seconds<br/>\n"; echo "MAX_SESSION_ID_LIFETIME = ", MAX_SESSION_ID_LIFETIME, " minutes = ", MAX_SESSION_ID_LIFETIME * 60, " seconds<br/>\n"; echo "</p></div>\n"; } } catch (Error $e) { global $shown_header; report_exception($e, SEVERITY::ERROR); // Same as below, but flag + log this for review, if (!$shown_header) { show_header($page, $is_logged_in); } echo "<div class='content_box'><h3>{$e->getTitle()}</h3>"; echo "<p>{$e->getMessage()}</p></div>"; } catch (Problem $e) { global $shown_header; if (!$shown_header) { show_header($page, $is_logged_in); } echo "<div class='content_box'><h3>{$e->getTitle()}</h3>"; echo "<p>{$e->getMessage()}</p></div>"; } catch (Exception $e) { global $shown_header; if (!$shown_header) { show_header($page, $is_logged_in); } echo "<div class='content_box'><h3>Technical difficulties</h3>"; echo "<p>{$e->getMessage()}</p></div>"; } show_footer($is_logged_in, $is_admin, $is_verified); if ($lock) { release_lock($lock); } }
check_frozen(); // find and cancel any active requests from users with negative BTC or FIAT balances // this should never happen unless someone is trying to double-spend their balance $query = "\n SELECT\n reqid, requests.amount as amount, requests.uid as uid\n FROM requests\n JOIN purses\n ON requests.uid = purses.uid\n WHERE\n req_type = 'WITHDR'\n AND curr_type = 'BTC'\n AND (status = 'VERIFY' OR status = 'PROCES')\n AND purses.amount < 0\n GROUP BY reqid\n"; $result = do_query($query); while ($row = mysql_fetch_array($result)) { $reqid = $row['reqid']; $amount = $row['amount']; $uid = $row['uid']; try { echo "cancelling reqid {$reqid} (withdraw ", internal_to_numstr($amount), " BTC for user {$uid}) due to negative balance\n"; wait_for_lock($uid); $query = "\n UPDATE requests\n SET status = 'CANCEL'\n WHERE reqid = '{$reqid}'\n "; do_query($query); add_funds($uid, $amount, 'BTC'); release_lock($uid); } catch (Error $e) { if ($e->getTitle() == 'Lock Error') { echo "can't get lock for {$uid}\n"; } else { throw $e; } } } $query = "\n SELECT\n requests.reqid AS reqid,\n users.uid AS uid,\n amount,\n addy\n FROM requests\n JOIN bitcoin_requests\n ON requests.reqid=bitcoin_requests.reqid\n JOIN users\n ON users.uid=requests.uid\n WHERE\n req_type='WITHDR'\n AND amount > 1000000\n AND status='VERIFY'\n AND curr_type='BTC'\n AND (users.uid < " . LOWEST_UNTRUSTED_USERID . " OR verified)\n "; $result = do_query($query); while ($row = mysql_fetch_assoc($result)) { $reqid = $row['reqid']; $uid = $row['uid']; $amount = $row['amount']; $addy = $row['addy'];
function acquire_lock($sector) { global $db, $lock; if ($lock) { return true; } // Insert ourselves into the queue. $db->query('INSERT INTO locks_queue (game_id,account_id,sector_id,timestamp) VALUES(' . SmrSession::$game_id . ',' . SmrSession::$old_account_id . ',' . $sector . ',' . time() . ')'); $lock = $db->insert_id(); for ($i = 0; $i < 200; ++$i) { // If there is someone else before us in the queue we sleep for a while $db->query('SELECT COUNT(*) FROM locks_queue WHERE lock_id<' . $lock . ' AND sector_id=' . $sector . ' and game_id=' . SmrSession::$game_id . ' LIMIT 1'); $db->next_record(); if ($db->f('COUNT(*)')) { //usleep(100000 + mt_rand(0,50000)); // We can only have one lock in the queue, anything more means someone is screwing around $db->query('SELECT COUNT(*) FROM locks_queue WHERE account_id=' . SmrSession::$old_account_id . ' AND sector_id=' . $sector . ' LIMIT 1'); if ($db->next_record()) { if ($db->f('COUNT(*)') > 1) { create_error("Multiple actions cannot be performed at the same time!"); $db->query('DELETE FROM locks_queue WHERE lock_id=' . $lock); exit; } } usleep(25000 * $db->f('COUNT(*)')); continue; } else { return true; } } release_lock($lock); return false; }
function exitNPC() { global $NPC_LOGIN; debug('Exiting NPC script.'); if ($NPC_LOGIN !== null) { $db = new SmrMySqlDatabase(); $db->query('UPDATE npc_logins SET working=' . $db->escapeBoolean(false) . ' WHERE login='******'Login'])); if ($db->getChangedRows() > 0) { debug('Unlocked NPC: ' . $NPC_LOGIN['Login']); } else { debug('Failed to unlock NPC: ' . $NPC_LOGIN['Login']); } } else { debug('NPC_LOGIN is null.'); } release_lock(); exit; }