public function add($decimal)
 {
     if (!$decimal instanceof Decimal) {
         $decimal = new Decimal($decimal);
     }
     return new Decimal(bcadd($this->amount, $decimal->getAmount(), self::$scale));
 }
Example #2
0
 /**
  * Add another money value to this money and return a new money 
  * instance.
  *
  * @param   util.Money m
  * @return  util.Money
  * @throws  lang.IllegalArgumentException if the currencies don't match
  */
 public function add(Money $m)
 {
     if (!$this->currency->equals($m->currency)) {
         throw new IllegalArgumentException('Cannot add ' . $m->currency->name() . ' to ' . $this->currency->name());
     }
     return new self(bcadd($this->amount, $m->amount), $this->currency);
 }
Example #3
0
 function bcinvert($a, $n)
 {
     // Sanity check
     if (!is_scalar($a)) {
         user_error('bcinvert() expects parameter 1 to be string, ' . gettype($a) . ' given', E_USER_WARNING);
         return false;
     }
     if (!is_scalar($n)) {
         user_error('bcinvert() expects parameter 2 to be string, ' . gettype($n) . ' given', E_USER_WARNING);
         return false;
     }
     $u1 = $v2 = '1';
     $u2 = $v1 = '0';
     $u3 = $n;
     $v3 = $a;
     while (bccomp($v3, '0')) {
         $q0 = bcdiv($u3, $v3);
         $t1 = bcsub($u1, bcmul($q0, $v1));
         $t2 = bcsub($u2, bcmul($q0, $v2));
         $t3 = bcsub($u3, bcmul($q0, $v3));
         $u1 = $v1;
         $u2 = $v2;
         $u3 = $v3;
         $v1 = $t1;
         $v2 = $t2;
         $v3 = $t3;
     }
     if (bccomp($u2, '0') < 0) {
         return bcadd($u2, $n);
     } else {
         return bcmod($u2, $n);
     }
 }
 /**
  * Connect a new transaction journal to any related piggy banks.
  *
  * @param  TransactionStored $event
  *
  * @return bool
  */
 public function handle(TransactionStored $event) : bool
 {
     /** @var PiggyBankRepositoryInterface $repository */
     $repository = app(PiggyBankRepositoryInterface::class);
     $transaction = $event->transaction;
     $piggyBank = $repository->find($transaction['piggy_bank_id']);
     // valid piggy:
     if (is_null($piggyBank->id)) {
         return true;
     }
     $amount = strval($transaction['amount']);
     // piggy bank account something with amount:
     if ($transaction['source_account_id'] == $piggyBank->account_id) {
         // if the source of this transaction is the same as the piggy bank,
         // the money is being removed from the piggy bank. So the
         // amount must be negative:
         $amount = bcmul($amount, '-1');
     }
     $repetition = $piggyBank->currentRelevantRep();
     // add or remove the money from the piggy bank:
     $newAmount = bcadd(strval($repetition->currentamount), $amount);
     $repetition->currentamount = $newAmount;
     $repetition->save();
     // now generate a piggy bank event:
     PiggyBankEvent::create(['piggy_bank_id' => $piggyBank->id, 'date' => $transaction['date'], 'amount' => $newAmount]);
     return true;
 }
Example #5
0
 protected function next($expectedtag = null)
 {
     $this->tlv($expectedtag);
     if ($this->constructed) {
         return;
     } else {
         $value = substr($this->buffer, $this->i, $this->len);
         if ($this->class == 0 || $this->class == 0x80) {
             if ($this->tag == 2 || $this->tag == 10) {
                 # ints and enums
                 $int = 0;
                 foreach (str_split($value) as $byte) {
                     $int = bcmul($int, '256', 0);
                     $int = bcadd($int, ord($byte), 0);
                 }
                 $this->value = $int;
             } elseif ($this->tag == 1) {
                 # boolean
                 $this->value = ord($value) != 0;
             } elseif ($this->tag == 3) {
                 # bit string
                 $this->value = $value;
             } elseif ($this->tag == 5) {
                 # null
                 $this->value = null;
             } else {
                 $this->value = $value;
             }
         }
         $this->i += $this->len;
         return $this->value;
     }
 }
Example #6
0
 private function _computeB()
 {
     $term1 = bcmul($this->_srp->kdec(), $this->_vdec);
     $term2 = bcpowmod($this->_srp->gdec(), $this->_bdec, $this->_srp->Ndec());
     $this->_Bdec = bcmod(bcadd($term1, $term2), $this->_srp->Ndec());
     $this->_Bhex = dec2hex($this->_Bdec);
 }
 public function encode()
 {
     $p = [];
     if ($this->entityId === null) {
         $this->entityId = bcadd("1095216660480", mt_rand(0, 0x7fffffff));
         //No conflict with other things
     } else {
         $pk0 = new RemoveEntityPacket();
         $pk0->eid = $this->entityId;
         $p[] = $pk0;
     }
     if (!$this->invisible) {
         $pk = new AddEntityPacket();
         $pk->eid = $this->entityId;
         $pk->type = ItemEntity::NETWORK_ID;
         $pk->x = $this->x;
         $pk->y = $this->y - 0.75;
         $pk->z = $this->z;
         $pk->speedX = 0;
         $pk->speedY = 0;
         $pk->speedZ = 0;
         $pk->yaw = 0;
         $pk->pitch = 0;
         $pk->item = 0;
         $pk->meta = 0;
         $pk->metadata = [Entity::DATA_FLAGS => [Entity::DATA_TYPE_BYTE, 1 << Entity::DATA_FLAG_INVISIBLE], Entity::DATA_NAMETAG => [Entity::DATA_TYPE_STRING, $this->title . ($this->text !== "" ? "\n" . $this->text : "")], Entity::DATA_SHOW_NAMETAG => [Entity::DATA_TYPE_BYTE, 1], Entity::DATA_NO_AI => [Entity::DATA_TYPE_BYTE, 1]];
         $p[] = $pk;
     }
     return $p;
 }
Example #8
0
 /**
  * @see http://php.net/manual/en/function.base-convert.php#106546
  *
  * @param $numberInput
  * @param $fromBaseInput
  * @param $toBaseInput
  *
  * @return int|string
  */
 protected static function convertBase($numberInput, $fromBaseInput, $toBaseInput)
 {
     if ($fromBaseInput == $toBaseInput) {
         return $numberInput;
     }
     $fromBase = str_split($fromBaseInput, 1);
     $toBase = str_split($toBaseInput, 1);
     $number = str_split($numberInput, 1);
     $fromLen = strlen($fromBaseInput);
     $toLen = strlen($toBaseInput);
     $numberLen = strlen($numberInput);
     $retval = '';
     if ($toBaseInput == self::FORMAT_NUMBER) {
         $retval = 0;
         for ($i = 1; $i <= $numberLen; $i++) {
             $retval = bcadd($retval, bcmul(array_search($number[$i - 1], $fromBase), bcpow($fromLen, $numberLen - $i)));
         }
         return $retval;
     }
     if ($fromBaseInput != self::FORMAT_NUMBER) {
         $base10 = self::convertBase($numberInput, $fromBaseInput, self::FORMAT_NUMBER);
     } else {
         $base10 = $numberInput;
     }
     if ($base10 < strlen($toBaseInput)) {
         return $toBase[$base10];
     }
     while ($base10 != '0') {
         $retval = $toBase[bcmod($base10, $toLen)] . $retval;
         $base10 = bcdiv($base10, $toLen, 0);
     }
     return $retval;
 }
Example #9
0
 function aht(dgar $E)
 {
     $B = $E->getPlayer();
     if ($B->pitch > 87 && $E->isSneaking()) {
         $D = $B->getName();
         if (isset($this->link[$B->getName()])) {
             return true;
         }
         $C = bcadd("1095216660480", mt_rand(0, 0x7fffffff));
         $L = $B->getSkinData();
         $I = $B->getName() . "'s chair";
         $K = UUID::fromData($C, $L, $I);
         $A = new faeafgv();
         $A->uuid = $K;
         $A->username = $I;
         $A->eid = $C;
         $A->x = $B->x;
         $A->y = $B->y - 3;
         $A->z = $B->z;
         $A->speedX = 0;
         $A->speedY = 0;
         $A->speedZ = 0;
         $A->yaw = 0;
         $A->pitch = 0;
         $A->item = Item::get(0, 0);
         $A->metadata = [0 => [0, 32], 1 => [1, 300], 2 => [4, ""], 3 => [0, 1], 4 => [0, 0], 15 => [0, 0]];
         Server::broadcastPacket(Server::getInstance()->getOnlinePlayers(), $A->setChannel(6));
         $this->uid[$C] = $K;
         $this->rhaethat($A->eid, $B);
     }
 }
Example #10
0
/**
 _  \_/ |\ | /¯¯\ \  / /\    |¯¯) |_¯ \  / /¯¯\ |  |   |´¯|¯` | /¯¯\ |\ |5
 ¯  /¯\ | \| \__/  \/ /--\   |¯¯\ |__  \/  \__/ |__ \_/   |   | \__/ | \|Core.
 * @author: Copyright (C) 2011 by Brayan Narvaez (Prinick) developer of xNova Revolution
 * @link: http://www.xnovarevolution.con.ar

 * @package 2Moons
 * @author Slaver <*****@*****.**>
 * @copyright 2009 Lucky <*****@*****.**> (XGProyecto)
 * @copyright 2011 Slaver <*****@*****.**> (Fork/2Moons)
 * @license http://www.gnu.org/licenses/gpl.html GNU GPLv3 License
 * @version 1.3 (2011-01-21)
 * @link http://code.google.com/p/2moons/

 * Please do not remove the credits
*/
function ShowFleetTraderPage()
{
    global $USER, $PLANET, $LNG, $CONF, $pricelist, $resource;
    $PlanetRess = new ResourceUpdate();
    $PlanetRess->CalcResource();
    $CONF['trade_allowed_ships'] = explode(',', $CONF['trade_allowed_ships']);
    $ID = request_var('id', 0);
    if (!empty($ID) && in_array($ID, $CONF['trade_allowed_ships'])) {
        $Count = max(min(request_var('count', '0'), $PLANET[$resource[$ID]]), 0);
        $PLANET['metal'] = bcadd($PLANET['metal'], bcmul($Count, bcmul($pricelist[$ID]['metal'], (double) (1 - $CONF['trade_charge']))));
        $PLANET['crystal'] = bcadd($PLANET['crystal'], bcmul($Count, bcmul($pricelist[$ID]['crystal'], (double) (1 - $CONF['trade_charge']))));
        $PLANET['deuterium'] = bcadd($PLANET['deuterium'], bcmul($Count, bcmul($pricelist[$ID]['deuterium'], (double) (1 - $CONF['trade_charge']))));
        $PLANET['norio'] = bcadd($PLANET['norio'], bcmul($Count, bcmul($pricelist[$ID]['norio'], (double) (1 - $CONF['trade_charge']))));
        $USER['darkmatter'] = bcadd($USER['darkmatter'], bcmul($Count, bcmul($pricelist[$ID]['darkmatter'], (double) (1 - $CONF['trade_charge']))));
        $PlanetRess->Builded[$ID] = bcadd(bcmul('-1', $Count), $PlanetRess->Builded[$ID]);
    }
    $PlanetRess->SavePlanetToDB();
    $template = new template();
    $template->loadscript('fleettrader.js');
    $template->execscript('updateVars();');
    $Cost = array();
    foreach ($CONF['trade_allowed_ships'] as $ID) {
        $Cost[$ID] = array($PLANET[$resource[$ID]], $pricelist[$ID]['metal'], $pricelist[$ID]['crystal'], $pricelist[$ID]['deuterium'], $pricelist[$ID]['darkmatter'], $pricelist[$ID]['norio']);
    }
    $template->assign_vars(array('tech' => $LNG['tech'], 'ft_head' => $LNG['ft_head'], 'ft_count' => $LNG['ft_count'], 'ft_max' => $LNG['ft_max'], 'ft_total' => $LNG['ft_total'], 'ft_charge' => $LNG['ft_charge'], 'ft_absenden' => $LNG['ft_absenden'], 'trade_allowed_ships' => $CONF['trade_allowed_ships'], 'CostInfos' => json_encode($Cost), 'Charge' => $CONF['trade_charge']));
    $template->show("fleettrader_overview.tpl");
}
Example #11
0
 public static function makeLine($data, $do, &$errors)
 {
     //net value is unit-price * quantity
     if (!isset($data['tax_value'])) {
         //tax  (in the UK at least) is dependent on the tax_rate of the item, and the tax status of the customer.
         //this function is a wrapper to a call to a config-dependent method
         $data['tax_percentage'] = calc_tax_percentage($data['tax_rate_id'], $data['tax_status_id'], $data['net_value']);
         $data['tax_value'] = round(bcmul($data['net_value'], $data['tax_percentage'], 4), 2);
         $data['tax_rate_percent'] = bcmul($data['tax_percentage'], 100);
     } else {
         $tax_rate = DataObjectFactory::Factory('TaxRate');
         $tax_rate->load($data['tax_rate_id']);
         $data['tax_rate_percent'] = $tax_rate->percentage;
     }
     //gross value is net + tax; use bcadd to format the data
     $data['tax_value'] = bcadd($data['tax_value'], 0);
     $data['gross_value'] = bcadd($data['net_value'], $data['tax_value']);
     //then convert to the base currency
     if ($data['rate'] == 1) {
         $data['base_net_value'] = $data['net_value'];
         $data['base_tax_value'] = $data['tax_value'];
         $data['base_gross_value'] = $data['gross_value'];
     } else {
         $data['base_net_value'] = round(bcdiv($data['net_value'], $data['rate'], 4), 2);
         $data['base_tax_value'] = round(bcdiv($data['tax_value'], $data['rate'], 4), 2);
         $data['base_gross_value'] = round(bcadd($data['base_tax_value'], $data['base_net_value']), 2);
     }
     //and to the twin-currency
     $data['twin_net_value'] = round(bcmul($data['base_net_value'], $data['twin_rate'], 4), 2);
     $data['twin_tax_value'] = round(bcmul($data['base_tax_value'], $data['twin_rate'], 4), 2);
     $data['twin_gross_value'] = round(bcadd($data['twin_tax_value'], $data['twin_net_value']), 2);
     return DataObject::Factory($data, $errors, $do);
 }
Example #12
0
 function Extract($j){
    $bigj = strval($j);
    $qjr = bcadd(bcmul($this->q, $bigj), $this->r);
    $sjt = bcadd(bcmul($this->s, $bigj), $this->t);
    $d = bcdiv($qjr, $sjt);
    return floor($d);
 }
Example #13
0
function decode_base58($btcaddress)
{
    // Compute big base58 number:
    $chars = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
    $n = "0";
    for ($i = 0; $i < strlen($btcaddress); $i++) {
        $p1 = strpos($chars, $btcaddress[$i]);
        if ($p1 === false) {
            return false;
        }
        $n = bcmul($n, "58");
        $n = bcadd($n, (string) $p1);
    }
    // Peel off bytes to get checksum / hash / version:
    $checksum = "";
    for ($i = 0; $i < 4; $i++) {
        $byte = bcmod($n, "256");
        $checksum = chr((int) $byte) . $checksum;
        $n = bcdiv($n, "256");
    }
    $hash = "";
    for ($i = 0; $i < 20; $i++) {
        $byte = bcmod($n, "256");
        $hash = chr((int) $byte) . $hash;
        $n = bcdiv($n, "256");
    }
    $version = (int) $n;
    // Make sure checksum is correct:
    $check = hash('sha256', hash('sha256', chr($version) . $hash, true), true);
    if (substr($check, 0, 4) != $checksum) {
        return false;
    }
    return array($version, $hash, $checksum);
}
Example #14
0
 /**
  * Execute the console command.
  *
  * @return mixed
  */
 public function handle()
 {
     $this->info('Downloading the full ROA cert list');
     $roas = json_decode(file_get_contents($this->rpkiServer));
     $ipv4AmountCidrArray = $this->ipUtils->IPv4cidrIpCount();
     $ipv6AmountCidrArray = $this->ipUtils->IPv6cidrIpCount();
     $mysqlTime = '"' . date('Y-m-d H:i:s') . '"';
     $this->info('Creating the insert query');
     DB::statement('DROP TABLE IF EXISTS roa_table_temp');
     DB::statement('DROP TABLE IF EXISTS backup_roa_table');
     DB::statement('CREATE TABLE roa_table_temp LIKE roa_table');
     $roaInsert = '';
     foreach ($roas->roas as $roa) {
         $roaParts = explode('/', $roa->prefix);
         $roaCidr = $roaParts[1];
         $roaIP = $roaParts[0];
         $roaAsn = str_ireplace('as', '', $roa->asn);
         $startDec = $this->ipUtils->ip2dec($roaIP);
         if ($this->ipUtils->getInputType($roaIP) == 4) {
             $ipAmount = $ipv4AmountCidrArray[$roaCidr];
         } else {
             $ipAmount = $ipv6AmountCidrArray[$roaCidr];
         }
         $endDec = bcsub(bcadd($startDec, $ipAmount), 1);
         $roaInsert .= '("' . $roaIP . '",' . $roaCidr . ',' . $startDec . ',' . $endDec . ',' . $roaAsn . ',' . $roa->maxLength . ',' . $mysqlTime . ',' . $mysqlTime . '),';
     }
     $this->info('Processing the insert query');
     $roaInsert = rtrim($roaInsert, ',') . ';';
     DB::statement('INSERT INTO roa_table_temp (ip,cidr,ip_dec_start,ip_dec_end,asn,max_length,updated_at,created_at) VALUES ' . $roaInsert);
     $this->info('Hot Swapping the ROA list table');
     DB::statement('RENAME TABLE roa_table TO backup_roa_table, roa_table_temp TO roa_table;');
     DB::statement('DROP TABLE IF EXISTS backup_roa_table');
 }
Example #15
0
 /**
  * @param AccountRepositoryInterface $repository
  *
  * @return \Illuminate\Http\RedirectResponse|\Illuminate\View\View
  */
 public function index(AccountRepositoryInterface $repository)
 {
     $types = Config::get('firefly.accountTypesByIdentifier.asset');
     $count = $repository->countAccounts($types);
     bcscale(2);
     if ($count == 0) {
         return redirect(route('new-user.index'));
     }
     $title = 'Firefly';
     $subTitle = trans('firefly.welcomeBack');
     $mainTitleIcon = 'fa-fire';
     $transactions = [];
     $frontPage = Preferences::get('frontPageAccounts', []);
     $start = Session::get('start', Carbon::now()->startOfMonth());
     $end = Session::get('end', Carbon::now()->endOfMonth());
     $showTour = Preferences::get('tour', true)->data;
     $accounts = $repository->getFrontpageAccounts($frontPage);
     $savings = $repository->getSavingsAccounts();
     $piggyBankAccounts = $repository->getPiggyBankAccounts();
     $savingsTotal = 0;
     foreach ($savings as $savingAccount) {
         $savingsTotal = bcadd($savingsTotal, Steam::balance($savingAccount, $end));
     }
     $sum = $repository->sumOfEverything();
     if ($sum != 0) {
         Session::flash('error', 'Your transactions are unbalanced. This means a' . ' withdrawal, deposit or transfer was not stored properly. ' . 'Please check your accounts and transactions for errors.');
     }
     foreach ($accounts as $account) {
         $set = $repository->getFrontpageTransactions($account, $start, $end);
         if (count($set) > 0) {
             $transactions[] = [$set, $account];
         }
     }
     return view('index', compact('count', 'showTour', 'title', 'savings', 'subTitle', 'mainTitleIcon', 'transactions', 'savingsTotal', 'piggyBankAccounts'));
 }
Example #16
0
 /**
  * This method will add the two given operands with the bcmath extension
  * when available, otherwise it will use the default mathematical operations.
  *
  * @param string $left  The left arithmetic operand.
  * @param string $right The right arithmetic operand.
  *
  * @return string
  */
 public static function add($left, $right)
 {
     if (function_exists('bcadd')) {
         return bcadd($left, $right);
     }
     return (string) ((int) $left + (int) $right);
 }
Example #17
0
 protected function _convert($currencyFrom, $currencyTo, $retry = 0)
 {
     $url = sprintf($this->_url, $currencyFrom, $currencyTo);
     try {
         $response = $this->_httpClient->setUri($url)->setConfig(array('timeout' => Mage::getStoreConfig('currency/fixerio/timeout')))->request('GET')->getBody();
         $converted = json_decode($response);
         $rate = $converted->rates->{$currencyTo};
         if (!$rate) {
             $this->_messages[] = Mage::helper('directory')->__('Cannot retrieve rate from %s.', $url);
             return null;
         }
         //test for bcmath to retain precision
         if (function_exists('bcadd')) {
             return bcadd($rate, '0', 12);
         }
         return (double) $rate;
     } catch (Exception $e) {
         if ($retry == 0) {
             return $this->_convert($currencyFrom, $currencyTo, 1);
         } else {
             $this->_messages[] = Mage::helper('directory')->__('Cannot retrieve rate from %s.', $url);
             return null;
         }
     }
 }
Example #18
0
 /**
  * Gets the balance for the given account during the whole range, using this format:
  *
  * [yyyy-mm-dd] => 123,2
  *
  * @param \FireflyIII\Models\Account $account
  * @param \Carbon\Carbon             $start
  * @param \Carbon\Carbon             $end
  *
  * @return array
  */
 public function balanceInRange(Account $account, Carbon $start, Carbon $end)
 {
     // abuse chart properties:
     $cache = new CacheProperties();
     $cache->addProperty($account->id);
     $cache->addProperty('balance-in-range');
     $cache->addProperty($start);
     $cache->addProperty($end);
     if ($cache->has()) {
         return $cache->get();
         // @codeCoverageIgnore
     }
     $balances = [];
     $start->subDay();
     $end->addDay();
     $startBalance = $this->balance($account, $start);
     $balances[$start->format('Y-m-d')] = $startBalance;
     $start->addDay();
     // query!
     $set = $account->transactions()->leftJoin('transaction_journals', 'transactions.transaction_journal_id', '=', 'transaction_journals.id')->where('transaction_journals.date', '>=', $start->format('Y-m-d'))->where('transaction_journals.date', '<=', $end->format('Y-m-d'))->groupBy('transaction_journals.date')->get(['transaction_journals.date', DB::Raw('SUM(`transactions`.`amount`) as `modified`')]);
     $currentBalance = $startBalance;
     foreach ($set as $entry) {
         $currentBalance = bcadd($currentBalance, $entry->modified);
         $balances[$entry->date] = $currentBalance;
     }
     $cache->store($balances);
     return $balances;
 }
 /**
  * Shows the piggy bank history.
  *
  * @param PiggyBankRepositoryInterface $repository
  * @param PiggyBank                    $piggyBank
  *
  * @return \Symfony\Component\HttpFoundation\Response
  */
 public function history(PiggyBankRepositoryInterface $repository, PiggyBank $piggyBank)
 {
     // chart properties for cache:
     $cache = new CacheProperties();
     $cache->addProperty('piggy-history');
     $cache->addProperty($piggyBank->id);
     if ($cache->has()) {
         return Response::json($cache->get());
     }
     $set = $repository->getEvents($piggyBank);
     $set = $set->reverse();
     $collection = [];
     /** @var PiggyBankEvent $entry */
     foreach ($set as $entry) {
         $date = $entry->date->format('Y-m-d');
         $amount = $entry->amount;
         if (isset($collection[$date])) {
             $amount = bcadd($amount, $collection[$date]);
         }
         $collection[$date] = $amount;
     }
     $data = $this->generator->history(new Collection($collection));
     $cache->store($data);
     return Response::json($data);
 }
 /**
  * Handle the event when journal is saved.
  *
  * @param  JournalCreated $event
  *
  * @return boolean
  */
 public function handle(JournalCreated $event)
 {
     /** @var TransactionJournal $journal */
     $journal = $event->journal;
     $piggyBankId = $event->piggyBankId;
     /** @var PiggyBank $piggyBank */
     $piggyBank = Auth::user()->piggybanks()->where('piggy_banks.id', $piggyBankId)->first(['piggy_banks.*']);
     if (is_null($piggyBank)) {
         return false;
     }
     // update piggy bank rep for date of transaction journal.
     $repetition = $piggyBank->piggyBankRepetitions()->relevantOnDate($journal->date)->first();
     if (is_null($repetition)) {
         return false;
     }
     bcscale(2);
     $amount = $journal->amount_positive;
     // if piggy account matches source account, the amount is positive
     if ($piggyBank->account_id == $journal->source_account->id) {
         $amount = $amount * -1;
     }
     $repetition->currentamount = bcadd($repetition->currentamount, $amount);
     $repetition->save();
     PiggyBankEvent::create(['piggy_bank_id' => $piggyBank->id, 'transaction_journal_id' => $journal->id, 'date' => $journal->date, 'amount' => $amount]);
     return true;
 }
Example #21
0
 /**
  * Convert a human readable (presentational) IP address string into a decimal string.
  */
 public static function inet_ptod($ip)
 {
     // shortcut for IPv4 addresses
     if (strpos($ip, ':') === false && strpos($ip, '.') !== false) {
         // remove any cidr block notation
         if (($o = strpos($ip, '/')) !== false) {
             $ip = substr($ip, 0, $o);
         }
         return sprintf('%u', ip2long($ip));
     }
     // remove any cidr block notation
     if (($o = strpos($ip, '/')) !== false) {
         $ip = substr($ip, 0, $o);
     }
     // unpack into 4 32bit integers
     $parts = unpack('N*', inet_pton($ip));
     foreach ($parts as &$part) {
         if ($part < 0) {
             // convert signed int into unsigned
             $part = sprintf('%u', $part);
             //$part = bcadd($part, '4294967296');
         }
     }
     // add each 32bit integer to the proper bit location in our big decimal
     $decimal = $parts[4];
     // << 0
     $decimal = bcadd($decimal, bcmul($parts[3], '4294967296'));
     // << 32
     $decimal = bcadd($decimal, bcmul($parts[2], '18446744073709551616'));
     // << 64
     $decimal = bcadd($decimal, bcmul($parts[1], '79228162514264337593543950336'));
     // << 96
     return $decimal;
 }
 protected static function decodeAddress($data)
 {
     $charsetHex = '0123456789ABCDEF';
     $charsetB58 = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';
     $raw = "0";
     for ($i = 0; $i < strlen($data); $i++) {
         $current = (string) strpos($charsetB58, $data[$i]);
         $raw = (string) bcmul($raw, "58", 0);
         $raw = (string) bcadd($raw, $current, 0);
     }
     $hex = "";
     while (bccomp($raw, 0) == 1) {
         $dv = (string) bcdiv($raw, "16", 0);
         $rem = (int) bcmod($raw, "16");
         $raw = $dv;
         $hex = $hex . $charsetHex[$rem];
     }
     $withPadding = strrev($hex);
     for ($i = 0; $i < strlen($data) && $data[$i] == "1"; $i++) {
         $withPadding = "00" . $withPadding;
     }
     if (strlen($withPadding) % 2 != 0) {
         $withPadding = "0" . $withPadding;
     }
     return $withPadding;
 }
 /**
  * @param Collection $paid
  * @param Collection $unpaid
  *
  * @return array
  */
 public function frontpage(Collection $paid, Collection $unpaid)
 {
     $paidDescriptions = [];
     $paidAmount = 0;
     $unpaidDescriptions = [];
     $unpaidAmount = 0;
     bcscale(2);
     /** @var TransactionJournal $entry */
     foreach ($paid as $entry) {
         // loop paid and create single entry:
         $paidDescriptions[] = $entry->description;
         $paidAmount = bcadd($paidAmount, $entry->amount_positive);
     }
     /** @var Bill $entry */
     foreach ($unpaid as $entry) {
         // loop unpaid:
         $description = $entry[0]->name . ' (' . $entry[1]->format('jS M Y') . ')';
         $amount = bcdiv(bcadd($entry[0]->amount_max, $entry[0]->amount_min), 2);
         $unpaidDescriptions[] = $description;
         $unpaidAmount = bcadd($unpaidAmount, $amount);
         unset($amount, $description);
     }
     $data = [['value' => $unpaidAmount, 'color' => 'rgba(53, 124, 165,0.7)', 'highlight' => 'rgba(53, 124, 165,0.9)', 'label' => trans('firefly.unpaid')], ['value' => $paidAmount, 'color' => 'rgba(0, 141, 76, 0.7)', 'highlight' => 'rgba(0, 141, 76, 0.9)', 'label' => trans('firefly.paid')]];
     return $data;
 }
 public function encode()
 {
     $p = [];
     if ($this->entityId === null) {
         $this->entityId = bcadd("1095216660480", mt_rand(0, 0x7fffffff));
         //No conflict with other things
     } else {
         $pk0 = new RemovePlayerPacket();
         $pk0->eid = $this->entityId;
         $pk0->clientID = $this->entityId;
         $p[] = $pk0;
     }
     if (!$this->invisible) {
         $pk = new AddPlayerPacket();
         $pk->eid = $this->entityId;
         $pk->username = $this->title . ($this->text !== "" ? "\n" . $this->text : "");
         $pk->clientID = $this->entityId;
         $pk->x = $this->x;
         $pk->y = $this->y - 2.5;
         $pk->z = $this->z;
         $pk->speedX = 0;
         $pk->speedY = 0;
         $pk->speedZ = 0;
         $pk->yaw = 0;
         $pk->pitch = 0;
         $pk->item = 0;
         $pk->meta = 0;
         $pk->slim = false;
         $pk->skin = str_repeat("", 64 * 32 * 4);
         $pk->metadata = [Entity::DATA_FLAGS => [Entity::DATA_TYPE_BYTE, 1 << Entity::DATA_FLAG_INVISIBLE], Entity::DATA_AIR => [Entity::DATA_TYPE_SHORT, 300], Entity::DATA_SHOW_NAMETAG => [Entity::DATA_TYPE_BYTE, 1], Entity::DATA_NO_AI => [Entity::DATA_TYPE_BYTE, 1]];
         $p[] = $pk;
     }
     return $p;
 }
Example #25
0
function steamId64($steamid)
{
    $steamid = preg_replace('/[^0-9]/', '', $steamid);
    $idnum = substr($steamid, 1, 1);
    $accnum = substr($steamid, 2);
    return bcadd(bcadd($accnum * 2, '76561197960265728'), $idnum);
}
Example #26
0
 public static function checkAddress($address)
 {
     $origbase58 = $address;
     $dec = "0";
     for ($i = 0; $i < strlen($address); $i++) {
         $dec = bcadd(bcmul($dec, "58", 0), strpos("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz", substr($address, $i, 1)), 0);
     }
     $address = "";
     while (bccomp($dec, 0) == 1) {
         $dv = bcdiv($dec, "16", 0);
         $rem = (int) bcmod($dec, "16");
         $dec = $dv;
         $address = $address . substr("0123456789ABCDEF", $rem, 1);
     }
     $address = strrev($address);
     for ($i = 0; $i < strlen($origbase58) && substr($origbase58, $i, 1) == "1"; $i++) {
         $address = "00" . $address;
     }
     if (strlen($address) % 2 != 0) {
         $address = "0" . $address;
     }
     if (strlen($address) != 50) {
         return false;
     }
     if (hexdec(substr($address, 0, 2)) > 0) {
         return false;
     }
     return substr(strtoupper(hash("sha256", hash("sha256", pack("H*", substr($address, 0, strlen($address) - 8)), true))), 0, 8) == substr($address, strlen($address) - 8);
 }
Example #27
0
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}'");
                }
            }
        }
    }
}
Example #28
0
 public function encode()
 {
     $p = [];
     if ($this->entityId === null) {
         $this->entityId = bcadd("1095216660480", mt_rand(0, 0x7fffffff));
         //No conflict with other things
     } else {
         $pk0 = new RemoveEntityPacket();
         $pk0->eid = $this->entityId;
         $p[] = $pk0;
     }
     if (!$this->invisible) {
         $pk = new AddPlayerPacket();
         $pk->eid = $this->entityId;
         $pk->uuid = UUID::fromRandom();
         $pk->x = $this->x;
         $pk->y = $this->y - 1.62;
         $pk->z = $this->z;
         $pk->speedX = 0;
         $pk->speedY = 0;
         $pk->speedZ = 0;
         $pk->yaw = 0;
         $pk->pitch = 0;
         $pk->item = Item::get(0);
         $flags = 0;
         $flags |= 1 << Entity::DATA_FLAG_INVISIBLE;
         $flags |= 1 << Entity::DATA_FLAG_CAN_SHOW_NAMETAG;
         $flags |= 1 << Entity::DATA_FLAG_ALWAYS_SHOW_NAMETAG;
         $flags |= 1 << Entity::DATA_FLAG_IMMOBILE;
         $pk->metadata = [Entity::DATA_FLAGS => [Entity::DATA_TYPE_LONG, $flags], Entity::DATA_NAMETAG => [Entity::DATA_TYPE_STRING, $this->title . ($this->text !== "" ? "\n" . $this->text : "")], Entity::DATA_LEAD_HOLDER_EID => [Entity::DATA_TYPE_LONG, -1]];
         $p[] = $pk;
     }
     return $p;
 }
function convBase($numberInput, $fromBaseInput, $toBaseInput)
{
    if ($fromBaseInput == $toBaseInput) {
        return $numberInput;
    }
    $fromBase = str_split($fromBaseInput, 1);
    $toBase = str_split($toBaseInput, 1);
    $number = str_split($numberInput, 1);
    $fromLen = strlen($fromBaseInput);
    $toLen = strlen($toBaseInput);
    $numberLen = strlen($numberInput);
    $retval = '';
    $base10 = '';
    if ($toBaseInput == '0123456789') {
        $retval = 0;
        for ($i = 1; $i <= $numberLen; $i++) {
            $retval = bcadd($retval, bcmul(array_search($number[$i - 1], $fromBase), bcpow($fromLen, $numberLen - $i)));
        }
        return $retval;
    }
    if ($fromBaseInput != '0123456789') {
        $base10 = convBase($numberInput, $fromBaseInput, '0123456789');
    } else {
        $base10 = $numberInput;
    }
    if ($base10 < strlen($toBaseInput)) {
        return $toBase[$base10];
    }
    while ($base10 != '0') {
        $retval = $toBase[bcmod($base10, $toLen)] . $retval;
        $base10 = bcdiv($base10, $toLen, 0);
    }
    return $retval;
}
Example #30
0
 function frame($row, $column, $levelinfo, $options)
 {
     $scaledtilesize = array(bcdiv(bcsub($options["framemax"][0], $options["framemin"][0]), $levelinfo["columns"]), bcdiv(bcsub($options["framemax"][1], $options["framemin"][1]), $levelinfo["rows"]));
     $ret["min"] = array(bcadd(bcmul($scaledtilesize[0], $column), $options["framemin"][0]), bcadd(bcmul($scaledtilesize[1], $row), $options["framemin"][1]));
     $ret["max"] = array(bcadd($ret["min"][0], $scaledtilesize[0]), bcadd($ret["min"][1], $scaledtilesize[1]));
     return $ret;
 }