public function addPointsTrade($user_id, $amount_fee, $trade_id, $wallet_init)
 {
     $logFile = 'points.log';
     Log::useDailyFiles(storage_path() . '/logs/points/' . $logFile);
     $setting = new Setting();
     $balance = new Balance();
     $wallet = wallet::where('type', 'POINTS')->first();
     $user = User::find($user_id);
     Log::info("\n" . '------------------------- Add Point Trade -----------------------------');
     Log::info("\n" . 'amount_fee ' . $amount_fee . ' . trade_id: ' . $trade_id . " -- wallet_init: " . $wallet_init);
     if (isset($wallet->id)) {
         $point_per_btc = $setting->getSetting('point_per_btc', 1);
         $percent_point_reward_trade = $setting->getSetting('percent_point_reward_trade', 0);
         $percent_point_reward_referred_trade = $setting->getSetting('percent_point_reward_referred_trade', 0);
         Log::info("\n" . 'Setting -- point_per_btc: ' . $point_per_btc . ' . percent_point_reward_trade: ' . $percent_point_reward_trade . " % -- percent_point_reward_referred_trade: " . $percent_point_reward_referred_trade . " %");
         //cong point cho $user_id
         if ($percent_point_reward_trade > 0) {
             $amount_reward = $amount_fee * $percent_point_reward_trade / 100;
             $point_reward = $amount_reward / $point_per_btc;
             Log::info("\n" . 'Add point for ' . $user->username . ' . amount_reward: ' . $amount_reward . " BTC -- point_reward: " . $point_reward . " POINTS");
             if ($point_reward > 0) {
                 $balance->addMoney($point_reward, $wallet->id, $user->id);
                 $deposit = new Deposit();
                 $deposit->user_id = $user->id;
                 $deposit->wallet_id = $wallet->id;
                 $deposit->amount = $point_reward;
                 $deposit->paid = 1;
                 $deposit->transaction_id = "Points earned from trade " . $trade_id;
                 $deposit->save();
             }
         }
         //cong point cho nguoi da gioi thieu $user_id nay neu co
         if (!empty($user->referral) && $percent_point_reward_referred_trade > 0) {
             $user_referred = User::where('username', $user->referral)->first();
             if (!empty($user_referred)) {
                 $amount_reward = $amount_fee * $percent_point_reward_referred_trade / 100;
                 $point_reward = $amount_reward / $point_per_btc;
                 Log::info("user_referred AAAAAAAAA: ", $user_referred);
                 Log::info("\n" . 'Add point for user referred: ' . $user_referred->username . ' . amount_reward: ' . $amount_reward . " BTC -- point_reward: " . $point_reward . " POINTS");
                 if ($point_reward > 0) {
                     $balance->addMoney($point_reward, $wallet->id, $user_referred->id);
                     $deposit = new Deposit();
                     $deposit->user_id = $user_referred->id;
                     $deposit->wallet_id = $wallet->id;
                     $deposit->amount = $point_reward;
                     $deposit->paid = 1;
                     $deposit->transaction_id = "Points earned from User " . $user->username . "( Trade: " . $trade_id . ")";
                     $deposit->save();
                 }
             }
         }
     } else {
         Log::info("\n" . 'No wallet POINTS');
     }
 }
Exemple #2
0
 public function compare()
 {
     // get a list of all months:
     $months = array();
     $first = BaseController::getFirst();
     $first->modify('first day of this month midnight');
     $today = new Carbon('now');
     $today->modify('first day of this month midnight');
     $prev = clone $today;
     $prev->sub(new DateInterval('P2D'));
     $prev->modify('first day of this month midnight');
     while ($first <= $today) {
         $index = $first->format('Y-m-d');
         $months[$index] = $first->format('F Y');
         $first->add(new DateInterval('P1M'));
     }
     // account list:
     $accs = Auth::user()->accounts()->get();
     $accounts = array(0 => '(all accounts)');
     foreach ($accs as $acc) {
         $accounts[intval($acc->id)] = Crypt::decrypt($acc->name);
     }
     $account = Setting::getSetting('defaultCheckingAccount');
     return View::make('pages.compare')->with('months', $months)->with('thisMonth', $today)->with('prevMonth', $prev)->with('account', $account)->with('accounts', $accounts);
 }
Exemple #3
0
 public function getHome()
 {
     $key = cacheKey('home', Session::get('period'));
     if (Cache::has($key)) {
         $data = Cache::get($key);
     } else {
         $max = 0;
         $min = 1000000;
         $data = array('accounts' => array(), 'budgets' => array(), 'targets' => array());
         // we need this list:
         $accounts = Auth::user()->accounts()->get();
         foreach ($accounts as $a) {
             $account = array('id' => intval($a->id), 'name' => Crypt::decrypt($a->name), 'currentbalance' => $a->balance());
             $account['header'] = $account['currentbalance'] < 0 ? array('style' => 'color:red;', 'class' => 'tt', 'title' => $account['name'] . ' has a balance below zero. Try to fix this.') : array();
             $min = $account['currentbalance'] < $min ? $account['currentbalance'] : $min;
             $max = $account['currentbalance'] > $max ? $account['currentbalance'] : $max;
             $data['accounts'][] = $account;
         }
         $min = $min > 0 ? 0 : $min;
         $max = $max < 0 ? 0 : $max;
         $min = floor($min / 1000) * 1000;
         $max = ceil($max / 1000) * 1000;
         $sum = 0;
         foreach ($data['accounts'] as $index => $account) {
             $sum += $account['currentbalance'];
         }
         $data['acc_data']['sum'] = $sum;
         // now everything for budgets:
         $data['budgets'] = Budget::getHomeOverview();
         // some extra budget data:
         $monthlyAmount = Setting::getSetting('monthlyAmount', Session::get('period')->format('Y-m-') . '01');
         if (is_null($monthlyAmount)) {
             $monthlyAmount = intval(Setting::getSetting('defaultAmount'));
         }
         $data['budget_data']['amount'] = $monthlyAmount;
         $data['budget_data']['spent_outside'] = floatval(Auth::user()->transactions()->where('amount', '<', 0)->whereNull('budget_id')->where(DB::Raw('DATE_FORMAT(`date`,"%m-%Y")'), '=', Session::get('period')->format('m-Y'))->sum('amount')) * -1;
         // targets, cant make it better im afraid.
         $data['targets'] = Target::getHomeOverview();
         Cache::put($key, $data, 2440);
     }
     // flash some warnings:
     if (Auth::user()->transactions()->count() == 0) {
         Session::flash('warning', 'There are no transactions saved yet. Create some to make this overview less boring (Create &rarr; New transaction).');
     }
     if (count($data['budgets']) == 0) {
         Session::flash('warning', 'You don\'t have any budgets defined.');
     }
     if (count($data['accounts']) == 0) {
         Session::flash('warning', 'You do not have any accounts added. You should do this first (Create &rarr; New account)');
     }
     if (Holmes::isMobile()) {
         return View::make('mobile.home.home')->with('data', $data);
     } else {
         return View::make('home.home')->with('data', $data);
     }
 }
Exemple #4
0
 /**
  * connect to the remote server
  * @return bool|\Net_SSH2
  */
 private function connect()
 {
     $ssh = new \Net_SSH2(Setting::getSetting('remote:host'));
     $key = new Crypt_RSA();
     $key->loadKey(file_get_contents(Setting::getSetting('ssh:priv_key')));
     if (!$ssh->login(Setting::getSetting('remote:user'), $key)) {
         $cli = new CLImate();
         $cli->error("Could not connect to server");
         return false;
     }
     return $ssh;
 }
Exemple #5
0
 /**
  * dumps the contents of the local database out to a file
  *
  * @param string $file_name the name of the file to save the data to. This should be the full path name
  *
  * @return the result of the shell_exec command
  */
 public function exportDB($file_name)
 {
     $host = Setting::getSetting('local-mysql:host');
     $user = Setting::getSetting('local-mysql:user');
     $pass = Setting::getSetting('local-mysql:pass');
     $db = Setting::getSetting('local-mysql:db');
     if (!empty($pass)) {
         $pass = "******" . $pass;
     }
     $command = 'mysqldump -h ' . $host . ' -u ' . $user . $pass . ' ' . $db . " > " . $file_name;
     return shell_exec($command);
 }
Exemple #6
0
 /**
  * Handles adding a new target to an existing rule.
  * @param int $id The ID of the rule of which to add the new target too.
  */
 public function postAddTarget($id)
 {
     // we'll first validate the data before continueing...
     $validator = Validator::make(array('target address' => Input::get('target'), 'max fails' => Input::get('maxfails'), 'fail timeout' => Input::get('failtimeout'), 'weight' => Input::get('weight')), array('target address' => array('required'), 'max fails' => array('integer', 'required'), 'fail timeout' => array('alpha_num', 'required'), 'weight' => array('numeric', 'between:1, 100')));
     if ($validator->passes()) {
         $rule = Rule::find($id);
         if ($rule) {
             $config = new NginxConfig();
             $config->setHostheaders($rule->hostheader);
             $config->readConfig(Setting::getSetting('nginxconfpath') . '/' . $config->serverNameToFileName() . '.enabled.conf');
             $config->addServerToNLB(array(strtolower(Input::get('target')), array('max_fails' => Input::get('maxfails'), 'fail_timeout' => Input::get('failtimeout'), 'weight' => Input::get('weight'))));
             $config->writeConfig()->toFile(Setting::getSetting('nginxconfpath') . '/' . $config->serverNameToFileName() . '.enabled.conf');
             $config->reloadConfig();
         }
         return Redirect::back()->with('flash_success', 'New target ' . strtolower(Input::get('target')) . ' has been added!');
     } else {
         $errors = $validator->messages();
         return Redirect::back()->withInput()->with('flash_error', 'The following validation errors occured, please correct them and try again:<br /><br /> * ' . implode('<br /> * ', $errors->all()));
     }
 }
Exemple #7
0
function listSetting()
{
    global $lang;
    $page_lang = scandir('inc/lang/' . $_SESSION['language']);
    foreach ($page_lang as $file) {
        if ($file != '.' && $file != '..') {
            $parts = explode(".", $file);
            $page = $parts[0];
            if ($page == 'setting') {
                $page_file = $file;
            }
        }
    }
    include_once 'inc/lang/' . $_SESSION['language'] . '/' . $page_file;
    if ($_SESSION['access']->settings > 0) {
        $results = array();
        $data = Setting::getSetting();
        $results['settings'] = $data['results'];
        $results['totalRows'] = $data['totalRows'];
        $results['pageTitle'] = "Site Settings";
        if (isset($_GET['success'])) {
            if ($_GET['success'] == "settingCreated") {
                $results['successMessage'] = "Your new setting has been created successully.";
            }
            if ($_GET['success'] == "changesSaved") {
                $results['successMessage'] = "Your setting changes have been saved.";
            }
            if ($_GET['attention'] == "locked") {
                $results['attentionMessage'] = "The previously created setting has been set as <strong>Locked!</strong> It will only be partialy editable to preserve system functionality.";
            }
        }
        require "inc/layout/listSettings.php";
    } else {
        require "inc/layout/noAccess.php";
    }
}
// admin header
session_start();
require_once 'lib/php/DOLib.php';
if (!swValidate('s_username')) {
    header("location: index.php");
}
connect();
// save new value and redirect to the page to view the change
$save = $_POST['save'];
if ($save) {
    Setting::setSetting($save, $_POST['value']);
}
//get default value for the textarea (either from selecting an item in the history, or from the current active record)
$id = $_GET['id'];
$row = Setting::getSetting($id);
if ($row) {
    $initValue = restoreValue($row[2]);
    $initName = restoreValue($row[1]);
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>standupweb CMS - Edit settings mode</title>
<link rel="stylesheet" href="css/style.css" type="text/css" media="all" />
<link rel="shortcut icon" href="images/favicon.ico" />

</head>
<body>
Exemple #9
0
 public static function getIntSetting($id)
 {
     $row = Setting::getSetting($id);
     return intval($row[2]);
 }
Exemple #10
0
| which may be used to do any work before or after a request into your
| application. Here you may also register your custom route filters.
|
*/
App::before(function ($request) {
    //echo "<pre>user: "******"</pre>";
    if (!Request::is('maintenance') && !Request::is('login') && !Request::is('first_auth') && !Request::is('user/login') && !Request::is('user/logout')) {
        $maintenance_check = true;
        if (!Auth::guest()) {
            $user = Confide::user();
            if (User::find($user->id)->hasRole('Admin')) {
                $maintenance_check = false;
            }
        }
        $setting = new Setting();
        $site_mode = $setting->getSetting('site_mode', 0);
        if ($site_mode == 1 && $maintenance_check) {
            return Redirect::to('/maintenance');
        }
    }
    if (!Auth::guest()) {
        $user = Confide::user();
        $timeout = trim($user->timeout);
        if (empty($timeout)) {
            $timeout = "45 minutes";
        }
        $lastest_login = $user->lastest_login;
        $new_date = date("Y-m-d H:i:s", strtotime($lastest_login . " +" . $timeout));
        $cur_date = date("Y-m-d H:i:s");
        if (strtotime($cur_date) >= strtotime($new_date)) {
            Confide::logout();
Exemple #11
0
<?php

View::composer('*', function ($view) {
    if (Auth::user()) {
        $view->with('useraccount', $useraccount = \User::find(\Auth::user()));
    }
    // Make the current system version avaliable to all pages.
    $view->with('turbineversion', Setting::getSetting('version'));
});
Exemple #12
0
 /**
  * @codeCoverageIgnore
  */
 public static function getFromFile($setting = null)
 {
     $output = array();
     $filename = "settings.ini";
     if (isset($GLOBALS['depth']) && !empty($GLOBALS['depth']) && is_numeric($GLOBALS['depth'])) {
         for ($i = 0; $i < $GLOBALS['depth']; $i++) {
             $filename = '../' . $filename;
         }
     }
     $handle = @fopen($filename, "r");
     if ($handle) {
         while (($line = fgets($handle, 4096)) !== false) {
             $arr = Setting::getSetting($line);
             foreach ($arr as $key => $value) {
                 if (empty($key)) {
                     continue;
                 }
                 $output[trim($key)] = $value;
                 if ($setting != null && strToLower(trim($key)) == strToLower(trim($setting))) {
                     return $value;
                 }
             }
         }
         if (!feof($handle)) {
             echo "Error: unexpected fgets() fail\n";
         }
         fclose($handle);
     }
     if ($setting != null) {
         return null;
     }
     return $output;
 }
Exemple #13
0
        $defaultSavings = intval(Crypt::decrypt($setting->value));
    }
    echo Form::select('defaultSavingsAccount', $acc, $defaultSavings);
    ?>
    <?php 
}
?>
    <h4>Correct the prediction chart</h4>
    <p>
      Since average amounts just don't cut it (they tend to "flat out") the prediction chart
      is usually predicting a way higher balance than it should. By checking this checkbox,
      it will always correct itself to your current balance instead of sticking to the current
      month's start amount.
    </p>
    <?php 
$setting = Setting::getSetting('correctPredictionChart');
$checked = $setting == 'true' ? true : false;
echo Form::checkbox('correctPredictionChart', 'true', $checked);
?>

    <p>
      &nbsp;
    </p>
    <p>
      <input type="submit" class="btn btn-primary" value="Save settings" />
    </p>
    <?php 
echo Form::close();
?>

Exemple #14
0
 public function getDatasChart($market_id, $timeSpan = '1 day')
 {
     //use google Candlesticks chart
     //$timeSpan='7 day';
     $setting = new Setting();
     $time_frame = $setting->getSetting('time_frame_chart', 30);
     $time_step_frame = '30 minutes';
     //1 cay nen trong chart lay trong khoang thoi gian la $time_step_frame (30 phut, 4 gio,...)
     if ($timeSpan == "7 day") {
         $time_step_frame = "4 hours";
     }
     if ($timeSpan == "1 month") {
         $time_step_frame = "6 hours";
     }
     if ($timeSpan == "3 month") {
         $time_step_frame = "8 hours";
     }
     if ($timeSpan == "6 month") {
         $time_step_frame = "10 hours";
     }
     if ($timeSpan == "12 month") {
         $time_step_frame = "12 hours";
     }
     //else get new data for chart
     $get_date = $this->getStartTimeChart($time_frame, $timeSpan);
     $start_time = $get_date['start_time'];
     $start_date = $get_date['start_date'];
     $closeprice = $this->getPreviousDataChart($market_id, $start_date);
     //$open_previous = $prior_perior['open_price'];
     $close_previous = $closeprice;
     //echo "date: ".date("Y-m-d H:i:s")."<br>";
     //echo "<pre>get_date: "; print_r($get_date); echo "</pre>";
     //echo "<pre>start_date: "; print_r($start_date); echo "</pre>";
     $trade_history = Trade::where('market_id', '=', $market_id)->where('created_at', '>=', $start_date)->orderBy('price', 'desc')->get();
     $data = $trade_history->toArray();
     //echo "<pre>trade_history: "; print_r($data); echo "</pre>";
     $temp_time = 0;
     $temp = 0;
     $datas_chart = array();
     $new_date = $start_date;
     //$date_ = strtotime(date("Y-m-d")." ".date('H',strtotime($start_date)).":".date('i',strtotime($start_date)));
     $date_ = strtotime(date("Y-m-d H:i:s"));
     $end_date = date("Y-m-d H:i", $date_);
     $str = "\n" . "new_date: " . $new_date . "\n" . "end_date: " . $end_date;
     //echo "new_date: ".$new_date."<br>";
     //echo "end_date: ".$end_date."<br>";
     //echo "str: ".$str;
     //echo "<pre>data 1: "; print_r($data); echo "</pre>";
     while (strtotime($new_date) <= strtotime($end_date)) {
         if ($temp == 0) {
             $temp_time = $start_time;
         }
         //$add_minute = strtotime($temp_time . " +30 minute");
         //echo "<br>temp_time: ".$temp_time;
         $add_minute = strtotime($temp_time . " +" . $time_step_frame);
         $temp_time_new = strftime("%H:%M", $add_minute);
         $old_date = $new_date;
         $date_temp_time = date("Y/m/d H:i", strtotime($old_date));
         $str .= "\n" . $date_temp_time;
         //$new_date = date("Y-m-d H:i", strtotime($new_date." +30 minutes"));// condition for while
         $new_date = date("Y-m-d H:i", strtotime($new_date . " +" . $time_step_frame));
         //echo "<br>------------------------------------------";
         //echo "<br>temp_time: ".$temp_time;
         //echo "<br>Old date: ".$old_date;
         //echo "<br>new_date : ".$new_date;
         //lay du lieu chart trong khung gio hien tai, du lieu nay dc sap xep theo gia tu cao den thap
         $data_chart_this_time = array_filter($data, function ($el) use($old_date, $new_date) {
             $created_at_time = strtotime($el['created_at']);
             return $created_at_time >= strtotime($old_date) && $created_at_time <= strtotime($new_date);
         });
         //echo "<pre>filtered 1: "; print_r($data_chart_this_time); echo "</pre>";
         if (count($data_chart_this_time > 0)) {
             $data_chart_this_time = array_values($data_chart_this_time);
             //get high & low ($data_chart_this_time is sort with price desc)
             $high = isset($data_chart_this_time[0]['price']) ? $data_chart_this_time[0]['price'] : 0;
             $low = isset($data_chart_this_time[count($data_chart_this_time) - 1]['price']) ? $data_chart_this_time[count($data_chart_this_time) - 1]['price'] : 0;
             $volumn = array_sum(array_fetch($data_chart_this_time, 'amount'));
             //get close_price, open_price (sort array with created desc)
             $cmp = function ($a, $b) {
                 return $b['created_at'] > $a['created_at'];
             };
             usort($data_chart_this_time, $cmp);
             //echo "<pre>filtered eee: "; print_r($data_chart_this_time); echo "</pre>";
             $open_price = isset($data_chart_this_time[count($data_chart_this_time) - 1]['price']) ? $data_chart_this_time[count($data_chart_this_time) - 1]['price'] : 0;
             $close_price = isset($data_chart_this_time[0]['price']) ? $data_chart_this_time[0]['price'] : 0;
             if ($close_previous == 0) {
                 $close_previous = $close_price;
             }
             $ha_data = $this->getDataHACandlesticks(array('high' => $high, 'low' => $low, 'open' => $open_price, 'close' => $close_price), $close_previous);
             //add data to chart
             $datas_chart[] = array($date_temp_time, (double) $ha_data['ha_low'], (double) $ha_data['ha_open'], (double) $ha_data['ha_close'], (double) $ha_data['ha_high'], $volumn);
         } else {
             $datas_chart[] = array($date_temp_time, 0, 0, 0, 0, 0);
         }
         $temp_time = $temp_time_new;
         $close_previous = $ha_data['ha_close'];
         $temp++;
     }
     //echo $str;
     //$datas_chart[] = array('date'=>date("Y-m-d H:i"),'low'=>$close_previous,'open'=>$close_previous,'close'=>$close_previous,'high'=>$close_previous, 'exchange_volume'=>0,'temp'=>$str);
     $result_data = json_encode($datas_chart);
     //$setting->putSetting('datachart_market_'.$market_id,serialize($datas_chart));
     return $result_data;
 }
 public function formTransfer($wallet_id = '')
 {
     $user = Confide::user();
     $user_id = $user->id;
     $data = array();
     if ($wallet_id == '') {
         $wallet = Wallet::first();
     } else {
         $wallet = Wallet::find($wallet_id);
     }
     $balance = new Balance();
     $data['page'] = 'transfercoin';
     $data['current_coin'] = $wallet->getType($wallet->id);
     $balance_amount = $balance->getBalance($wallet->id);
     $data['balance'] = sprintf('%.8f', $balance_amount);
     $data['wallet_id'] = $wallet->id;
     $setting = new Setting();
     $data['recaptcha_publickey'] = $setting->getSetting('recaptcha_publickey', '');
     return View::make('user.profile', $data);
 }
 public function triggerPusherTicket($market_id)
 {
     require_once app_path() . '/libraries/Pusher.php';
     $setting = new Setting();
     $pusher_app_id = $setting->getSetting('pusher_app_id', '');
     $pusher_app_key = $setting->getSetting('pusher_app_key', '');
     $pusher_app_secret = $setting->getSetting('pusher_app_secret', '');
     if ($pusher_app_id != '' && $pusher_app_key != '' && $pusher_app_secret != '') {
         $pusher = new Pusher($pusher_app_key, $pusher_app_secret, $pusher_app_id);
         $wallet = new Wallet();
         $market = Market::where('id', $market_id)->first();
         $from = strtoupper($wallet->getType($market->wallet_from));
         $to = strtoupper($wallet->getType($market->wallet_to));
         $order = new Order();
         $buyHighest = $order->getBuyHighest($market_id);
         $sellLowest = $order->getSellLowest($market_id);
         $topsell = array('price' => 0, 'amount' => 0);
         $topbuy = array('price' => 0, 'amount' => 0);
         if (count($sellLowest) > 0) {
             $topsell = array('amount' => sprintf("%.8f", $sellLowest->from_value), 'price' => sprintf("%.8f", $sellLowest->price));
         }
         if (count($buyHighest) > 0) {
             $topbuy = array('amount' => sprintf("%.8f", $buyHighest->from_value), 'price' => sprintf("%.8f", $buyHighest->price));
         }
         $message = array('channel' => 'ticker.' . $market_id, 'trade' => array('timestamp' => time(), 'datetime' => date("Y-m-d H:i:s T", time()), 'marketid' => $market_id, 'marketname' => $from . '/' . $to, 'topsell' => $topsell, 'topbuy' => $topbuy));
         $pusher->trigger('ticker.' . $market_id, 'message', $message);
     }
 }
 public function routePage($page = '')
 {
     //echo "<pre>user: "******"</pre>";
     switch ($page) {
         case "fees":
             $market = new Market();
             $wallet = new Wallet();
             $fees_trade = FeeTrade::get()->toArray();
             //echo "<pre>list_buy_orders: "; print_r($list_buy_orders); echo "</pre>";
             $fees_withdraw = FeeWithdraw::leftJoin('wallets', 'fee_withdraw.wallet_id', '=', 'wallets.id')->select('fee_withdraw.*', 'wallets.type', 'wallets.name')->get();
             foreach ($fees_trade as $key => $value) {
                 $wallet_type = $market->getWalletType($value['market_id']);
                 if (!empty($wallet_type)) {
                     $fees_trade[$key]['wallet_from'] = $wallet_type['wallet_from'];
                     $fees_trade[$key]['wallet_to'] = $wallet_type['wallet_to'];
                 }
             }
             $fee['fees_trade'] = $fees_trade;
             $fee['fees_withdraw'] = $fees_withdraw;
             return View::make('fees', $fee);
             break;
         case "voting":
             $setting = new Setting();
             $coinvotes = DB::table('coin_votes')->get();
             try {
                 $wallet = Wallet::where('type', 'BTC')->first();
                 $wallet->connectJsonRPCclient($wallet->wallet_username, $wallet->wallet_password, $wallet->wallet_ip, $wallet->port);
                 foreach ($coinvotes as $key => $value) {
                     $num_vote = Vote::where('coinvote_id', '=', $value->id)->count();
                     //echo "<pre>getreceivedbyaccount"; print_r($wallet->getReceivedByAddress($value->btc_address)); echo "</pre>";//$value->label_address
                     $btc_payment = $wallet->getReceivedByAddress($value->btc_address);
                     //'12X9jVe4S8pAqJ7EoKN7B4YwMQpzfgArtX'
                     $amount_btc_per_vote = $setting->getSetting('amount_btc_per_vote', 0.0001);
                     $num_payment = floor($btc_payment / $amount_btc_per_vote);
                     //echo "btc_payment: ".$btc_payment;
                     //echo "<br>num_payment: ".$num_payment;
                     $coinvotes[$key]->num_vote = $num_vote + $num_payment;
                 }
             } catch (Exception $e) {
                 $data['error_message'] = Lang::get('texts.not_connect_wallet');
                 //'Caught exception: '.$e->getMessage()."\n";  //"Not connect to this
             }
             //echo "<pre>coinvotes"; print_r($coinvotes); echo "</pre>";
             $data['coinvotes'] = $coinvotes;
             return View::make('voting', $data);
             break;
         case "security":
             return View::make('security');
             break;
         case "api":
             if (isset($_REQUEST['method'])) {
                 $method = $_REQUEST['method'];
                 $value = $this->api($method);
             } else {
                 $setting = new Setting();
                 $data['pusher_app_key'] = $setting->getSetting('pusher_app_key', '');
                 return View::make('api', $data);
             }
             print_r($value);
             break;
         case "apiprivate":
             $value = $this->apiprivate();
             break;
         case "all-trades":
             if (Auth::guest()) {
                 return Redirect::to('/login');
             }
             $record_per_page = 15;
             if (empty($_GET['pager_page'])) {
                 $pager_page = 1;
             } else {
                 $pager_page = $_GET['pager_page'];
             }
             $data['cur_page'] = $pager_page;
             $offset_start = ($pager_page - 1) * $record_per_page;
             $trade_history = Trade::leftjoin('market', 'market.id', '=', 'trade_history.market_id')->select('trade_history.*', 'market.wallet_from as from', 'market.wallet_to as to');
             $where = '';
             if (Input::has('market')) {
                 $fil_market = Input::get('market');
                 $trade_history->where("trade_history.market_id", "=", $fil_market);
             }
             if (Input::has('type')) {
                 $fil_type = Input::get('type');
                 $trade_history->where("trade_history.type", "=", $fil_type);
             }
             $total_records = $trade_history->get();
             $data['total_pages'] = ceil(count($total_records) / $record_per_page);
             $trades = $trade_history->skip($offset_start)->take($record_per_page)->orderby("created_at", "desc")->get();
             #echo "<pre>trade_history"; print_r($trades->toArray()); echo "</pre>";
             //echo "<pre>getQueryLog: ".dd(DB::getQueryLog())."</pre>";
             $data['tradehistories'] = $trades;
             $market = new Market();
             $markets = Market::get();
             $market_wallet = array();
             foreach ($markets as $value) {
                 $market_wallet[$value->id] = $market->getWalletType($value->id);
             }
             $data['markets'] = $market_wallet;
             return View::make('alltrades', $data);
             break;
         case "all-news":
             $news = Post::where('type', 'news')->orderby('created_at', 'desc')->get();
             $data['news'] = $news;
             return View::make('allnews', $data);
             break;
         default:
             return View::make('index');
             break;
     }
 }
Exemple #18
0
 /**
  * testClearCache
  *
  * jpn: 設定情報のキャッシュを削除する
  */
 public function testClearCache()
 {
     Configure::write('Setting.settings', array('tax_rate' => array('rule' => array('numeric')), 'tax_flg' => array('rule' => '/^[01]$/')));
     $result = Setting::setSetting(array('tax_rate' => 0.05, 'tax_flg' => true));
     $this->assertTrue($result);
     $this->assertTrue(file_exists(TMP . 'tests' . DS . 'cake_test_setting_cache'));
     // jpn: DB側の値を直接変更してしまう(本来はしない処理)
     $setting = $this->Setting->find('first', array('conditions' => array('Setting.key' => 'tax_rate')));
     $setting['Setting']['value'] = 0.1;
     $this->Setting->save($setting);
     $result = $this->Setting->find('first', array('conditions' => array('Setting.key' => 'tax_rate')));
     $this->assertIdentical((double) $result['Setting']['value'], 0.1);
     // jpn: キャッシュを見ているので元の値を出力する
     $result = Setting::getSetting('tax_rate');
     $this->assertIdentical($result, '0.05');
     // jpn: キャッシュをクリア
     $result = Setting::clearCache();
     // jpn: キャッシュがないのでDBを見に行く
     $result = Setting::getSetting('tax_rate');
     $this->assertIdentical((double) $result, 0.1);
 }
Exemple #19
0
 public function predictionChart()
 {
     // in order to predict the future, we look at the past.
     //$baseAccount = ?;
     //$startBalance = ?;
     $setting = Auth::user()->settings()->where('name', '=', 'defaultAmount')->first();
     $balance = intval(Crypt::decrypt($setting->value));
     $account = Auth::user()->accounts()->orderBy('id', 'ASC')->first();
     $debug = Input::get('debug') == 'true' ? true : false;
     $this->_debug = $debug;
     $key = $debug ? cacheKey('prediction', Session::get('period'), rand(1, 10000)) : cacheKey('prediction', Session::get('period'));
     // a setting related to corrections:
     $doCorrect = Setting::getSetting('correctPredictionChart') == 'true' ? true : false;
     if (Cache::has($key)) {
         $data = Cache::get($key);
     } else {
         $data = array('cols' => array(array('id' => 'day', 'label' => 'Day of the month', 'type' => 'string', 'p' => array('role' => 'domain')), array('id' => 'actualbalance', 'label' => 'Current balance', 'type' => 'number', 'p' => array('role' => 'data')), array('type' => 'boolean', 'p' => array('role' => 'certainty')), array('id' => 'predictedbalance', 'label' => 'Predicted balance', 'type' => 'number', 'p' => array('role' => 'data')), array('type' => 'number', 'p' => array('role' => 'interval')), array('type' => 'number', 'p' => array('role' => 'interval'))), 'rows' => array());
         // set the data array:
         // some working vars:
         $first = BaseController::getFirst();
         $this->_e('FIRST is ' . $first->format('d M Y'));
         $today = new Carbon('now');
         $this->_e('Today is ' . $today->format('d M Y'));
         $chartdate = new Carbon('now');
         $chartdate->modify('first day of this month');
         $index = 0;
         $this->_e('');
         $diff = $first->diff($today);
         $months = $diff->y * 12 + $diff->m;
         unset($diff);
         $specificAmount = Auth::user()->settings()->where('name', '=', 'monthlyAmount')->where('date', '=', $today->format('Y-m-d'))->first();
         if ($specificAmount) {
             $balance = floatval(Crypt::decrypt($specificAmount->value));
         }
         $this->_e('Opening balance: ' . $balance);
         // loop over each day of the month:
         $this->_e('start month loop');
         for ($i = 1; $i <= intval($today->format('t')); $i++) {
             $this->_e('Now at day #' . $i);
             // this array will be used to collect average amounts:
             $this->_e('Chartdate is: ' . $chartdate->format('Y-m-d'));
             $this->_e('Today is: ' . $today->format('Y-m-d'));
             if ($doCorrect && $chartdate > $today || !$doCorrect) {
                 $average = array();
                 // loop over each month:
                 // get all transaction results for this day of the month:
                 $transactions = Auth::user()->transactions()->where('amount', '<', 0)->where('onetime', '=', 0)->where(DB::Raw('DATE_FORMAT(`date`,"%e")'), '=', $i)->orderBy('amount', 'ASC')->get();
                 // lets see what we have
                 if (count($transactions) > 0) {
                     $min = floatval($transactions[count($transactions) - 1]->amount) * -1;
                     $max = floatval($transactions[0]->amount) * -1;
                     // fill the array for the averages later on:
                     foreach ($transactions as $t) {
                         //$this->_e('Add to avg['.count($average).'] for transactions: ' . (floatval($t->amount) * -1));
                         $average[] = floatval($t->amount) * -1;
                     }
                 } else {
                     $min = 0;
                     $max = 0;
                 }
                 // calc avg:
                 $avg = $months > 0 ? array_sum($average) / $months : array_sum($average);
                 //$this->_e('New avg: ' . $avg);
                 $this->_e('Max: ' . $max . ', min: ' . $min . ', avg: ' . $avg);
                 $data['rows'][$index]['c'][0]['v'] = $chartdate->format('j F');
                 $data['rows'][$index]['c'][1]['v'] = $account->balance($chartdate);
                 // actual balance
                 if ($chartdate > $today) {
                     $data['rows'][$index]['c'][2]['v'] = false;
                 } else {
                     $data['rows'][$index]['c'][2]['v'] = true;
                 }
                 $data['rows'][$index]['c'][3]['v'] = $balance - $avg;
                 // predicted balance
                 $data['rows'][$index]['c'][4]['v'] = $balance - $max;
                 // predicted max expenses.
                 $data['rows'][$index]['c'][5]['v'] = $balance - $min;
                 // predicted max expenses.
                 $balance = $balance - $avg;
             } else {
                 // don't predict.
                 //$balance = $account->balance($chartdate);
                 $this->_e('No prediction today!');
                 $balance = $account->balance($chartdate);
                 $data['rows'][$index]['c'][0]['v'] = $chartdate->format('j F');
                 $data['rows'][$index]['c'][1]['v'] = $balance;
                 // actual balance
                 $data['rows'][$index]['c'][2]['v'] = true;
                 $data['rows'][$index]['c'][3]['v'] = null;
                 $data['rows'][$index]['c'][4]['v'] = null;
                 $data['rows'][$index]['c'][5]['v'] = null;
             }
             $index++;
             $chartdate->addDay();
             $this->_e(' ');
         }
         Cache::put($key, $data, 1440);
     }
     if ($debug) {
         return '<pre>' . print_r($data, true) . '</pre>';
     }
     return Response::json($data);
 }
Exemple #20
0
 | The CSRF filter is responsible for protecting your application against
 | cross-site request forgery attacks. If this special token in a user
 | session does not match the one given in this request, we'll bail.
 |
*/
Route::filter('csrf', function () {
    if (Session::token() != Input::get('_token')) {
        throw new Illuminate\Session\TokenMismatchException();
    }
});
/**
 * Custom API auth filter for Turbine, requests that the username and the API key is honored by the
 * application and also that the API is in 'enabled' mode before actually responding to any API requests.
 */
Route::filter('auth.api', function () {
    if (Setting::getSetting('api_enabled') != 'true') {
        return Response::json(array('error' => true, 'message' => 'API is in disabled mode'), 401);
    }
    // Now we need to make an authentication request using the API key from the settings table.
    if (!Request::getUser() || !Request::getPassword()) {
        return Response::json(array('error' => true, 'message' => 'A valid API user and key is required'), 401);
    }
    $user = User::where('username', '=', Request::getUser())->first();
    // If NOT user and the API key doesn't match in the Settings table....
    // Can also use Request::getUser(); to get the HTTP Basic provided username too if required!
    if ($user && Setting::getSetting('api_key') == Request::getPassword()) {
        Auth::login($user);
    } else {
        return Response::json(array('error' => true, 'message' => 'Invalid credentials'), 401);
    }
});
Exemple #21
0
 /**
  * This handles the deletion of the deletion of the rule. (DELETE /rules/{id})
  * @param int $id The ID of the rule to delete.
  */
 public function destroy($id)
 {
     // Lets delete the record from the DB..
     $delete_rule = Rule::find($id);
     if ($delete_rule) {
         // Delete the config file.
         $config = new NginxConfig();
         $config->setHostheaders($delete_rule->hostheader);
         $config->readConfig(Setting::getSetting('nginxconfpath') . '/' . $config->serverNameToFileName() . '.enabled.conf');
         if ($config->deleteConfig(Setting::getSetting('nginxconfpath') . '/' . $config->serverNameToFileName() . '.enabled.conf')) {
             // We now delete the record from the DB...
             $delete_rule->delete();
         }
         $config->reloadConfig();
     }
     // As this method is called using both AJAX and the FORM on the Edit page, we only want to respond simply to the AJAX request otherwise we'll get Server 500 errors in our Javascript Console!
     if (Request::ajax()) {
         return Response::json(array('deleted' => true), 200);
     }
     // Request was ajax so we send a simple response instead!
     return Redirect::route('rules.index')->with('flash_success', 'The rule for ' . json_decode($config->toJSON())->server_name . ' has been deleted successfully!');
 }
Exemple #22
0
 public static function getUser($setting_name, $user_id = NULL)
 {
     return Setting::getSetting('user', $setting_name, $user_id);
 }
Exemple #23
0
 /**
  * @return string
  */
 public static function getHomePath()
 {
     return Setting::getSetting('remote:home');
 }
 public function routePage($page = '', $pager_page = '')
 {
     $markets = Market::where('active', 1)->get();
     $market_wallet = array();
     foreach ($markets as $market) {
         $market_wallet[$market->id] = $market->getWalletType($market->id);
     }
     $data['markets'] = $market_wallet;
     switch ($page) {
         case 'fee':
             $data['fee_trades'] = FeeTrade::leftJoin('market', 'fee_trade.market_id', '=', 'market.id')->leftJoin('wallets', 'market.wallet_from', '=', 'wallets.id')->select('fee_trade.*', 'market.wallet_from', 'wallets.name', 'wallets.type')->orderby('wallets.name', 'asc')->get();
             //echo "<pre>fee_trades: "; print_r($fee_trades); echo "</pre>";
             //echo "<pre>markets: "; print_r($markets); echo "</pre>";exit;
             return View::make('admin.setting_fee', $data);
             break;
         case 'fee-withdraw':
             $data['fee_withdraws'] = FeeWithdraw::leftjoin('wallets', 'fee_withdraw.wallet_id', '=', 'wallets.id')->select('fee_withdraw.*', 'wallets.type', 'wallets.name')->orderby('wallets.type')->get();
             return View::make('admin.setting_fee_withdraw', $data);
             break;
         case 'limit-trade':
             $record_per_page = 15;
             $total = WalletLimitTrade::count();
             if ($pager_page == '') {
                 $pager_page = 1;
             }
             $data['total_pages'] = ceil($total / $record_per_page);
             //15 user per page
             $data['cur_page'] = $pager_page;
             $offset_start = ($pager_page - 1) * $record_per_page;
             $data['wallets'] = Wallet::orderby('type')->get();
             $data['limit_trades'] = WalletLimitTrade::leftjoin('wallets', 'wallet_limittrade.wallet_id', '=', 'wallets.id')->select('wallet_limittrade.*', 'wallets.type as wallet_type', 'wallets.name as wallet_name')->skip($offset_start)->take($record_per_page)->orderby('wallet_type')->get();
             return View::make('admin.limittrade.setting_limittrade', $data);
             break;
             //add newbie
         //add newbie
         case 'time-limit-trade':
             $record_per_page = 15;
             $total = WalletTimeLimitTrade::count();
             if ($pager_page == '') {
                 $pager_page = 1;
             }
             $data['total_pages'] = ceil($total / $record_per_page);
             //15 user per page
             $data['cur_page'] = $pager_page;
             $offset_start = ($pager_page - 1) * $record_per_page;
             $data['wallets'] = Wallet::orderby('type')->get();
             $data['limit_trades'] = WalletTimeLimitTrade::leftjoin('wallets', 'wallet_timelimittrade.wallet_id', '=', 'wallets.id')->select('wallet_timelimittrade.*', 'wallets.type as wallet_type', 'wallets.name as wallet_name')->skip($offset_start)->take($record_per_page)->orderby('wallet_type')->get();
             return View::make('admin.limittrade.setting_timelimittrade', $data);
             break;
         case 'statistic-coin-exchanged':
             $select = "SELECT mk.wallet_from, mk.wallet_to, sum(amount) as total_amount from trade_history a left join market mk on a.market_id=mk.id";
             $select_maincoin = "SELECT mk.wallet_from, mk.wallet_to, sum(amount*price) as total_amount from trade_history a left join market mk on a.market_id=mk.id";
             $where = '';
             if (isset($_GET['filter_time']) && $_GET['filter_time'] != '') {
                 switch ($_GET['filter_time']) {
                     case 'hourly':
                         $hourly = date('Y-m-d H:i:s', strtotime('-1 hour'));
                         $where = $where == '' ? " Where a.created_at>='" . $hourly . "'" : $where . " Where a.created_at>='" . $hourly . "'";
                         break;
                     case 'daily':
                         $daily = date('Y-m-d H:i:s', strtotime('-24 hour'));
                         $where = $where == '' ? " Where a.created_at>='" . $daily . "'" : $where . " Where a.created_at>='" . $daily . "'";
                         break;
                     case 'weekly':
                         $thisweek = date('Y-m-d', strtotime('-7 day'));
                         $where = $where == '' ? " Where a.created_at>='" . $thisweek . "'" : $where . " Where a.created_at>='" . $thisweek . "'";
                         break;
                     case 'monthly':
                         $thismonth = date('Y-m-1', strtotime('-1 month'));
                         $where = $where == '' ? " Where a.created_at>='" . $thismonth . "'" : $where . " Where a.created_at>='" . $thismonth . "'";
                         break;
                 }
             }
             $select .= " " . $where . " group by mk.wallet_from";
             $coins_exchanged = DB::select($select);
             $data['coins_exchanged'] = $coins_exchanged;
             $select_maincoin .= " " . $where . " group by mk.wallet_to";
             $maincoins_exchanged = DB::select($select_maincoin);
             $data['maincoins_exchanged'] = $maincoins_exchanged;
             // echo "<pre>"; print_r($fees); echo "</pre>";
             $wallets_temp = Wallet::get();
             $wallets = array();
             foreach ($wallets_temp as $wallet) {
                 $wallets[$wallet->id] = $wallet;
             }
             $data['wallets'] = $wallets;
             return View::make('admin.statistics.statistic_coin_exchanged', $data);
             break;
         case 'statistic-fees':
             $select = "SELECT mk.wallet_from, mk.wallet_to, sum(fee_sell) as fee_sell, sum(fee_buy) as fee_buy from trade_history a left join market mk on a.market_id=mk.id";
             $where = '';
             if (isset($_GET['filter_time']) && $_GET['filter_time'] != '') {
                 switch ($_GET['filter_time']) {
                     case 'hourly':
                         $hourly = date('Y-m-d H:i:s', strtotime('-1 hour'));
                         $where = $where == '' ? " Where a.created_at>='" . $hourly . "'" : $where . " Where a.created_at>='" . $hourly . "'";
                         break;
                     case 'daily':
                         $daily = date('Y-m-d H:i:s', strtotime('-24 hour'));
                         $where = $where == '' ? " Where a.created_at>='" . $daily . "'" : $where . " Where a.created_at>='" . $daily . "'";
                         break;
                     case 'weekly':
                         $thisweek = date('Y-m-d', strtotime('-7 day'));
                         $where = $where == '' ? " Where a.created_at>='" . $thisweek . "'" : $where . " Where a.created_at>='" . $thisweek . "'";
                         break;
                     case 'monthly':
                         $thismonth = date('Y-m-1', strtotime('-1 month'));
                         $where = $where == '' ? " Where a.created_at>='" . $thismonth . "'" : $where . " Where a.created_at>='" . $thismonth . "'";
                         break;
                 }
             }
             $select .= " " . $where . " group by a.market_id order by `created_at` desc";
             $fees = DB::select($select);
             $data['fees'] = $fees;
             // echo "<pre>"; print_r($fees); echo "</pre>";
             $wallets_temp = Wallet::get();
             $wallets = array();
             foreach ($wallets_temp as $wallet) {
                 $wallets[$wallet->id] = $wallet;
             }
             $data['wallets'] = $wallets;
             return View::make('admin.statistics.statistic_fees', $data);
             break;
         case 'statistic-fee-withdraw':
             $select = "SELECT w.type, w.name, sum(fee_amount) as total_fee from withdraws a left join wallets w on a.wallet_id=w.id";
             $where = '';
             if (isset($_GET['filter_time']) && $_GET['filter_time'] != '') {
                 switch ($_GET['filter_time']) {
                     case 'hourly':
                         $hourly = date('Y-m-d H:i:s', strtotime('-1 hour'));
                         $where = $where == '' ? " Where a.created_at>='" . $hourly . "'" : $where . " Where a.created_at>='" . $hourly . "'";
                         break;
                     case 'daily':
                         $daily = date('Y-m-d H:i:s', strtotime('-24 hour'));
                         $where = $where == '' ? " Where a.created_at>='" . $daily . "'" : $where . " Where a.created_at>='" . $daily . "'";
                         break;
                     case 'weekly':
                         $thisweek = date('Y-m-d', strtotime('-7 day'));
                         $where = $where == '' ? " Where a.created_at>='" . $thisweek . "'" : $where . " Where a.created_at>='" . $thisweek . "'";
                         break;
                     case 'monthly':
                         $thismonth = date('Y-m-1', strtotime('-1 month'));
                         $where = $where == '' ? " Where a.created_at>='" . $thismonth . "'" : $where . " Where a.created_at>='" . $thismonth . "'";
                         break;
                 }
             }
             $select .= " " . $where . " group by a.wallet_id";
             $withdraw_fees = DB::select($select);
             $data['withdraw_fees'] = $withdraw_fees;
             return View::make('admin.statistics.statistic_fee_withdraw', $data);
             break;
         case 'add-page':
             $data['type'] = 'page';
             return View::make('admin.pages.add_post', $data);
             break;
         case 'add-news':
             $data['type'] = 'news';
             return View::make('admin.pages.add_post', $data);
             break;
         case 'all-page':
             $data['type'] = 'page';
             $record_per_page = 15;
             $total = Post::where('type', $data['type'])->count();
             if ($pager_page == '') {
                 $pager_page = 1;
             }
             $data['total_pages'] = ceil($total / $record_per_page);
             //15 user per page
             $data['cur_page'] = $pager_page;
             $offset_start = ($pager_page - 1) * $record_per_page;
             $posts = Post::where('type', $data['type'])->skip($offset_start)->take($record_per_page)->get();
             $data['posts'] = $posts;
             return View::make('admin.pages.all_posts', $data);
             break;
         case 'all-news':
             $data['type'] = 'news';
             $record_per_page = 15;
             $total = Post::where('type', $data['type'])->count();
             if ($pager_page == '') {
                 $pager_page = 1;
             }
             $data['total_pages'] = ceil($total / $record_per_page);
             //15 user per page
             $data['cur_page'] = $pager_page;
             $offset_start = ($pager_page - 1) * $record_per_page;
             $posts = Post::where('type', $data['type'])->skip($offset_start)->take($record_per_page)->get();
             $data['posts'] = $posts;
             return View::make('admin.pages.all_posts', $data);
             break;
         case 'users':
             $record_per_page = 15;
             $total_users = User::count();
             if ($pager_page == '') {
                 $pager_page = 1;
             }
             $data['total_pages'] = ceil($total_users / $record_per_page);
             //15 user per page
             $data['cur_page'] = $pager_page;
             $offset_start = ($pager_page - 1) * $record_per_page;
             //$offset_end = ($pager_page*$record_per_page)-1;
             $users = User::skip($offset_start)->take($record_per_page)->get()->toArray();
             foreach ($users as $key => $value) {
                 $user = USer::find($value['id']);
                 $users[$key]['roles'] = $user->roles->toArray();
                 //echo "<pre>roles:"; print_r($user->roles->toArray()); echo "</pre>";
             }
             //echo "<pre>"; print_r($users); echo "</pre>";
             $roles = Role::get();
             $data['users'] = $users;
             $data['roles'] = $roles;
             return View::make('admin.user.manage_users', $data);
             break;
         case 'orders':
             $record_per_page = 15;
             if ($pager_page == '') {
                 $pager_page = 1;
             }
             $data['cur_page'] = $pager_page;
             $offset_start = ($pager_page - 1) * $record_per_page;
             //$offset_end = ($pager_page*$record_per_page)-1;
             $select = "select a.*, b.wallet_from as `from`, b.wallet_to as `to`, c.username from orders a left join market b on a.market_id=b.id left join users c on a.user_id=c.id";
             $select_count = "select count(*) as total from orders a";
             $where = '';
             if (isset($_GET['do_filter'])) {
                 if ($where == '') {
                     if (!empty($_GET['market'])) {
                         $where = $where == '' ? " Where a.market_id='" . $_GET['market'] . "'" : $where . " AND a.market_id='" . $_GET['market'] . "'";
                     }
                 }
                 if ($_GET['status'] != '') {
                     $where = $where == '' ? " Where a.status='" . $_GET['status'] . "'" : $where . " AND a.status='" . $_GET['status'] . "'";
                 }
                 if ($_GET['type'] != '') {
                     $where = $where == '' ? " Where a.type='" . $_GET['type'] . "'" : $where . " AND a.type='" . $_GET['type'] . "'";
                 }
             }
             $select_count = $select_count . " " . $where . " order by `created_at` desc";
             $total_records = DB::select($select_count);
             //echo "<pre>total_records: "; print_r($total_records); echo "</pre>"; exit;
             $data['total_pages'] = ceil($total_records[0]->total / $record_per_page);
             $select .= " " . $where . " order by `created_at` desc limit " . $offset_start . "," . $record_per_page;
             $ordershistory = DB::select($select);
             $data['ordershistories'] = $ordershistory;
             return View::make('admin.orders', $data);
             break;
         case 'trade-histories':
             $record_per_page = 15;
             if ($pager_page == '') {
                 $pager_page = 1;
             }
             $data['cur_page'] = $pager_page;
             $offset_start = ($pager_page - 1) * $record_per_page;
             $select = "select a.*, b.wallet_from as `from`, b.wallet_to as `to`,c.username as seller, d.username as buyer from trade_history a left join market b on a.market_id=b.id left join users c on a.seller_id=c.id left join users d on a.buyer_id=d.id";
             $select_count = "select count(*) as total from trade_history a";
             $where = '';
             if (isset($_GET['do_filter'])) {
                 if ($where == '') {
                     if (!empty($_GET['market'])) {
                         $where = $where == '' ? " Where a.market_id='" . $_GET['market'] . "'" : $where . " AND a.market_id='" . $_GET['market'] . "'";
                     }
                 }
                 if ($_GET['type'] != '') {
                     $where = $where == '' ? " Where a.type='" . $_GET['type'] . "'" : $where . " AND a.type='" . $_GET['type'] . "'";
                 }
                 if ($_GET['time'] != '') {
                     switch ($_GET['time']) {
                         case 'today':
                             $where = $where == '' ? " Where a.created_at>='" . date("Y-m-d") . "'" : $where . " Where a.created_at>='" . date("Y-m-d") . "'";
                             break;
                         case 'thisweek':
                             $thisweek = date('Y-m-d', strtotime('this week'));
                             $where = $where == '' ? " Where a.created_at>='" . $thisweek . "'" : $where . " Where a.created_at>='" . $thisweek . "'";
                             break;
                         case 'thismonth':
                             $thismonth = date('Y-m-1', strtotime('this month'));
                             $where = $where == '' ? " Where a.created_at>='" . $thismonth . "'" : $where . " Where a.created_at>='" . $thismonth . "'";
                             break;
                     }
                 }
             }
             $select_count = $select_count . " " . $where . " order by `created_at` desc";
             $total_records = DB::select($select_count);
             //echo "<pre>total_records: "; print_r($total_records); echo "</pre>"; exit;
             $data['total_pages'] = ceil($total_records[0]->total / $record_per_page);
             $select .= " " . $where . " order by `created_at` desc limit " . $offset_start . "," . $record_per_page;
             $trades = DB::select($select);
             $data['tradehistories'] = $trades;
             return View::make('admin.trade_histories', $data);
             break;
         case 'coins-voting':
             $coinvotes = DB::table('coin_votes')->get();
             $wallet = Wallet::where('type', 'BTC')->first();
             if (isset($wallet->id)) {
                 try {
                     $wallet->connectJsonRPCclient($wallet->wallet_username, $wallet->wallet_password, $wallet->wallet_ip, $wallet->port);
                     foreach ($coinvotes as $key => $value) {
                         $num_vote = Vote::where('coinvote_id', '=', $value->id)->count();
                         //echo "<pre>getreceivedbyaccount"; print_r($wallet->getReceivedByAddress($value->btc_address)); echo "</pre>";//$value->label_address
                         $btc_payment = $wallet->getReceivedByAddress($value->btc_address);
                         //'12X9jVe4S8pAqJ7EoKN7B4YwMQpzfgArtX'
                         $num_payment = floor($btc_payment / 0.0001);
                         //echo "btc_payment: ".$btc_payment;
                         //echo "<br>num_payment: ".$num_payment;
                         $coinvotes[$key]->balance = $num_payment;
                         $coinvotes[$key]->num_vote = $num_vote + $num_payment;
                     }
                 } catch (Exception $e) {
                     $data['error_message'] = "Not connect to this";
                     //'Caught exception: '.$e->getMessage()."\n";  //
                 }
                 //echo "<pre>coinvotes"; print_r($coinvotes); echo "</pre>";
                 $data['coinvotes'] = $coinvotes;
             } else {
                 $data['not_wallet'] = "Please add BTC wallet before add the vote coin.";
             }
             return View::make('admin.coins_voting', $data);
             break;
         case 'funds':
             $wallets = Wallet::leftjoin('fee_withdraw', 'fee_withdraw.wallet_id', '=', 'wallets.id')->orderby('type')->get();
             $balances = array();
             $fee_withdraws = array();
             foreach ($wallets as $wallet) {
                 try {
                     $wallet->connectJsonRPCclient($wallet->wallet_username, $wallet->wallet_password, $wallet->wallet_ip, $wallet->port);
                     $balances[$wallet->id] = $wallet->getBalance();
                     $fee_withdraws[$wallet->id] = $wallet->getTxFee();
                     UserAddressDeposit::insert(array('user_id' => $user->id, 'wallet_id' => $wallet->id, 'addr_deposit' => $address));
                 } catch (Exception $e) {
                     $data['error_message'] = 'Caught exception: ' . $e->getMessage() . "\n";
                     //"Not connect to this wallet";//'Caught exception: '.$e->getMessage()."\n";
                 }
             }
             $data['wallets'] = $wallets;
             $data['balances'] = $balances;
             $data['fee_withdraws'] = $fee_withdraws;
             //echo "<pre>fee_withdraws"; print_r($fee_withdraws); echo "</pre>";
             return View::make('admin.funds', $data);
             break;
         case 'withdraws-queue':
             $record_per_page = 20;
             if ($pager_page == '') {
                 $pager_page = 1;
             }
             $data['cur_page'] = $pager_page;
             $offset_start = ($pager_page - 1) * $record_per_page;
             if (isset($_GET['do_filter'])) {
                 $withdraws = Withdraw::leftjoin('users', 'users.id', '=', 'withdraws.user_id');
                 if ($_GET['wallet_id'] != '') {
                     $withdraws->where('wallet_id', $_GET['wallet_id']);
                 }
                 if ($_GET['status'] != '') {
                     $withdraws->where('status', $_GET['status']);
                 }
                 if ($_GET['username'] != '') {
                     $withdraws->where('users.username', $_GET['username']);
                 }
                 $withdraws->select('withdraws.*', 'users.username', 'users.id as user_id');
             } else {
                 $withdraws = Withdraw::leftjoin('users', 'users.id', '=', 'withdraws.user_id')->select('withdraws.*', 'users.username');
             }
             $total_records = $withdraws->get();
             //echo "<br>total_records: ".count($total_records);
             $data['total_pages'] = ceil(count($total_records) / $record_per_page);
             //echo "<br>total_records: ".$data['total_pages'];
             $withdraws = $withdraws->skip($offset_start)->take($record_per_page)->orderby("created_at", "desc")->get();
             $wallets = Wallet::orderby('type')->get()->toArray();
             $new_wallet = array();
             foreach ($wallets as $key => $value) {
                 $new_wallet[$value['id']] = $value;
             }
             $data['wallets'] = $new_wallet;
             $data['withdraws'] = $withdraws;
             $data['users'] = User::orderBy('username')->get();
             return View::make('admin.withdraws_queue', $data);
             break;
         case 'deposits-queue':
             $record_per_page = 20;
             if ($pager_page == '') {
                 $pager_page = 1;
             }
             $data['cur_page'] = $pager_page;
             $offset_start = ($pager_page - 1) * $record_per_page;
             if (isset($_GET['do_filter'])) {
                 $deposits = Deposit::leftjoin('users', 'users.id', '=', 'deposits.user_id');
                 if ($_GET['wallet_id'] != '') {
                     $deposits->where('wallet_id', $_GET['wallet_id']);
                 }
                 if ($_GET['status'] != '') {
                     $deposits->where('paid', $_GET['status']);
                 }
                 if ($_GET['username'] != '') {
                     $deposits->where('users.username', $_GET['username']);
                 }
                 $deposits->select('deposits.*', 'users.username', 'users.id as user_id');
             } else {
                 $deposits = Deposit::leftjoin('users', 'users.id', '=', 'deposits.user_id')->select('deposits.*', 'users.username');
             }
             $total_records = $deposits->get();
             //echo "<br>total_records: ".count($total_records);
             $data['total_pages'] = ceil(count($total_records) / $record_per_page);
             //echo "<br>total_records: ".$data['total_pages'];
             $deposits = $deposits->skip($offset_start)->take($record_per_page)->orderby("created_at", "desc")->get();
             $wallets = Wallet::orderby('type')->get()->toArray();
             $new_wallet = array();
             foreach ($wallets as $key => $value) {
                 $new_wallet[$value['id']] = $value;
             }
             $data['wallets'] = $new_wallet;
             $data['deposits'] = $deposits;
             $data['users'] = User::orderBy('username')->get();
             return View::make('admin.deposits_queue', $data);
             break;
         case 'wallets':
             $record_per_page = 15;
             $total_users = Wallet::count();
             if ($pager_page == '') {
                 $pager_page = 1;
             }
             $data['total_pages'] = ceil($total_users / $record_per_page);
             //15 user per page
             $data['cur_page'] = $pager_page;
             $offset_start = ($pager_page - 1) * $record_per_page;
             $wallets = Wallet::skip($offset_start)->take($record_per_page)->orderby('name')->get();
             $data['wallets'] = $wallets;
             return View::make('admin.wallet.manage_wallets', $data);
             break;
         case 'markets':
             $record_per_page = 15;
             $total_users = Market::count();
             if ($pager_page == '') {
                 $pager_page = 1;
             }
             $data['total_pages'] = ceil($total_users / $record_per_page);
             //15 user per page
             $data['cur_page'] = $pager_page;
             $offset_start = ($pager_page - 1) * $record_per_page;
             $markets = Market::skip($offset_start)->take($record_per_page)->get();
             $data['markets'] = $markets;
             $wallets_temp = Wallet::orderby('type')->get();
             $wallets = array();
             foreach ($wallets_temp as $wallet) {
                 $wallets[$wallet->id] = $wallet;
             }
             $data['wallets'] = $wallets;
             return View::make('admin.manage_markets', $data);
             break;
         case 'balance-wallets':
             $record_per_page = 15;
             $total_users = Wallet::count();
             if ($pager_page == '') {
                 $pager_page = 1;
             }
             $data['total_pages'] = ceil($total_users / $record_per_page);
             //15 user per page
             $data['cur_page'] = $pager_page;
             $offset_start = ($pager_page - 1) * $record_per_page;
             $wallets = Wallet::skip($offset_start)->take($record_per_page)->orderby('name')->get();
             $amount_transaction = array();
             $balances = array();
             foreach ($wallets as $wallet) {
                 //get total deposit
                 $total_deposit = Deposit::where('wallet_id', $wallet->id)->where('paid', 1)->sum('amount');
                 $total_withdraw = Withdraw::where('wallet_id', $wallet->id)->where('status', 1)->sum('receive_amount');
                 $amount_transaction[$wallet->id] = array('total_amount_deposit' => $total_deposit, 'total_amount_withdraw' => $total_withdraw);
                 try {
                     $wallet->connectJsonRPCclient($wallet->wallet_username, $wallet->wallet_password, $wallet->wallet_ip, $wallet->port);
                     $balances[$wallet->id] = $wallet->getBalance();
                 } catch (Exception $e) {
                     $balances[$wallet->id] = Lang::get('messages.cannot_connect');
                 }
             }
             $data['wallets'] = $wallets;
             $data['amount_transaction'] = $amount_transaction;
             $data['balances'] = $balances;
             return View::make('admin.wallet.manage_wallets_balance', $data);
             break;
         case "login-histories":
             $record_per_page = 15;
             if ($pager_page == '') {
                 $pager_page = 1;
             }
             $data['cur_page'] = $pager_page;
             $offset_start = ($pager_page - 1) * $record_per_page;
             //$offset_end = ($pager_page*$record_per_page)-1;
             $select = "select a.*, b.username from login_history a left join users b on a.user_id=b.id";
             $select_count = "select count(*) as total from login_history as a";
             $where = '';
             if (isset($_GET['do_filter'])) {
                 if ($where == '') {
                     if (!empty($_GET['user'])) {
                         $where = $where == '' ? " Where a.user_id='" . $_GET['user'] . "'" : $where . " AND a.user='******'user'] . "'";
                     }
                 }
             }
             $select_count = $select_count . " " . $where;
             $total_records = DB::select($select_count);
             //echo "<pre>total_records: "; print_r($total_records); echo "</pre>"; exit;
             $data['total_pages'] = ceil($total_records[0]->total / $record_per_page);
             $select .= " " . $where . " order by `date` desc limit " . $offset_start . "," . $record_per_page;
             $login_histories = DB::select($select);
             $data['login_histories'] = $login_histories;
             $users = User::orderby('username')->get();
             $data['users'] = $users;
             return View::make('admin.user.login_histories', $data);
             break;
         case 'method-deposit':
             $record_per_page = 15;
             $total_users = MethodDepositCurrency::count();
             if ($pager_page == '') {
                 $pager_page = 1;
             }
             $data['total_pages'] = ceil($total_users / $record_per_page);
             //15 user per page
             $data['cur_page'] = $pager_page;
             $offset_start = ($pager_page - 1) * $record_per_page;
             $MethodDepositCurrency = MethodDepositCurrency::skip($offset_start)->take($record_per_page)->get();
             $data['MethodDepositCurrency'] = $MethodDepositCurrency;
             return View::make('admin.method-deposit-currency.manage_method_deposit', $data);
             break;
         case 'method-withdraw':
             $record_per_page = 15;
             $total_users = MethodWithdrawCurrency::count();
             if ($pager_page == '') {
                 $pager_page = 1;
             }
             $data['total_pages'] = ceil($total_users / $record_per_page);
             //15 user per page
             $data['cur_page'] = $pager_page;
             $offset_start = ($pager_page - 1) * $record_per_page;
             $MethodWithdrawCurrency = MethodWithdrawCurrency::skip($offset_start)->take($record_per_page)->get();
             $data['MethodWithdrawCurrency'] = $MethodWithdrawCurrency;
             return View::make('admin.method-withdraw-currency.manage_method_withdraw', $data);
             break;
         default:
             $setting = new Setting();
             //$data['bg_color']=$setting->getSetting('bg_color','');
             $data['site_mode'] = $setting->getSetting('site_mode', 0);
             //$data['bg_file']=$setting->getSetting('bg_file','');
             $data['disable_withdraw'] = $setting->getSetting('disable_withdraw', 0);
             $data['recaptcha_publickey'] = $setting->getSetting('recaptcha_publickey', '');
             $data['recaptcha_privatekey'] = $setting->getSetting('recaptcha_privatekey', '');
             $data['amount_btc_per_vote'] = $setting->getSetting('amount_btc_per_vote', 0.0001);
             //pusher app
             $data['pusher_app_id'] = $setting->getSetting('pusher_app_id', '');
             $data['pusher_app_key'] = $setting->getSetting('pusher_app_key', '');
             $data['pusher_app_secret'] = $setting->getSetting('pusher_app_secret', '');
             //default_market
             $m_default = Market::where('active', 1)->orderBy('id')->first();
             $market_default_id = isset($m_default->id) ? $m_default->id : 0;
             $data['default_market'] = $setting->getSetting('default_market', $market_default_id);
             //setting points
             $data['disable_points'] = $setting->getSetting('disable_points', 0);
             $data['point_per_btc'] = $setting->getSetting('point_per_btc', 1);
             $data['percent_point_reward_trade'] = $setting->getSetting('percent_point_reward_trade', 0);
             $data['percent_point_reward_referred_trade'] = $setting->getSetting('percent_point_reward_referred_trade', 0);
             $data['max_amount_funds'] = $setting->getSetting('max_amount_funds', 1000);
             //echo "<pre>data: "; print_r($data); echo "</pre>"; exit;
             return View::make('admin.setting', $data);
             break;
     }
 }