Exemplo n.º 1
0
 /**
  * Store a newly created resource in storage.
  *
  * @param  Request  $request
  * @return Response
  */
 public function store()
 {
     if (!Request::has('_id', 'type')) {
         return failure('参数错误');
     }
     $type = Request::input('type', 1);
     $id = Request::input('_id');
     $withdraw = UserWithdraw::find($id);
     if (!$withdraw) {
         return failure('该条数据不存在');
     }
     $user = User::find($withdraw->user_id);
     if (!$user) {
         return failure('该用户不存在');
     }
     if ($type) {
         $r = $withdraw->setSuccess($user);
     } else {
         $r = $withdraw->setFailure($user);
     }
     if ($r) {
         return success('提现成功');
     }
     return failure('提现失败');
 }
Exemplo n.º 2
0
 /**
  * 检查登录是否成功
  *
  * @date   2015-10-09
  * @return [type]     [description]
  */
 public function checkLogin()
 {
     if (!Request::has('username', 'password')) {
         return failure('请输入用户名或密码');
     }
     // $rules = [
     //     'captcha' => 'required|captcha',
     // ];
     // $validator = Validator::make(Request::all(), $rules);
     // if ($validator->fails()) {
     //     return $this->failure('验证码错误');
     // }
     $admin = Admin::where('username', Request::input('username'))->first();
     if (!$admin) {
         return failure('用户不存在');
     }
     if (!Hash::check(Request::input('password'), $admin->password)) {
         return failure('用户名或密码错误');
     }
     $admin->increment('sign_in_cnt');
     $admin->last_sign_in_at = Carbon::now();
     $admin->last_sign_in_ip = Request::getClientIp();
     $admin->save();
     Auth::loginUsingId($admin->user_id);
     return success('登录成功');
 }
Exemplo n.º 3
0
/**
 * Prints the WordPress-standard success and/or failure bar when a message is stored
 * in either of success() or failure().
 */
function success_and_failure()
{
    foreach (array('success' => success(), 'failure' => failure()) as $class => $message) {
        if (is_admin() && $message) {
            ?>
				<div class="updated fade <?php 
            echo $class;
            ?>
" id="message" style="background-color: <?php 
            $class == 'success' ? 'rgb(255, 251, 204)' : '#AB6F74';
            ?>
;">
					<p><?php 
            echo $message;
            ?>
</p></div><br />
			<?php 
        } else {
            if ($message) {
                ?>
				<div class="<?php 
                echo $class;
                ?>
">
					<p><?php 
                echo $message;
                ?>
</p>
				</div>
			<?php 
            }
        }
    }
}
Exemplo n.º 4
0
function api($method, $params)
{
    $json = rawapi($method, $params);
    if ($json["result"] === "failure") {
        failure($json["reason"]);
    }
    return $json;
}
Exemplo n.º 5
0
 /**
  * Show the form for editing the specified resource.
  *
  * @param  int  $id
  * @return Response
  */
 public function edit($id)
 {
     $recharge = UserRecharge::find($id);
     if (!$recharge) {
         return failure('数据不存在');
     }
     if ($recharge->fail()) {
         return success('处理成功');
     }
     return failure('处理失败');
 }
Exemplo n.º 6
0
 public function update()
 {
     $id = Request::input('id');
     $adminBank = AdminBank::find($id);
     if (!$adminBank) {
         return failure('不存在该条记录');
     }
     if (!$adminBank->toggleStatus()) {
         return failure('修改状态失败');
     }
     return success('状态变更成功');
 }
function failureClear($_Link, $p, $id)
{
    if ($id > 0 && !empty($id)) {
        $updateQuery = "UPDATE jobs SET job_status = 999 WHERE job_id = " . $id;
        $res = mysqli_query($_Link, $updateQuery);
        $queryAppend = '';
        if (isset($p) && $p != '') {
            $queryAppend = " AND cp = '" . $p . "'";
        }
        echo failure($_Link, $queryAppend);
    }
}
Exemplo n.º 8
0
 public function insert()
 {
     $adminUser = Auth::user();
     $username = Request::input('username');
     if (User::where('username', $username)->exists()) {
         return failure('该用户存在');
     }
     $user = User::saveData(['username' => Request::input('username'), 'password' => Hash::make(Request::input('password')), 'nickname' => Request::input('username'), 'qq' => Request::input('qq'), 'type' => Request::input('type'), 'fandian' => Request::input('fandian'), 'parent_id' => $adminUser->id, 'ancestry' => $adminUser->username . '>' . Request::input('username'), 'ancestry_depth' => $adminUser->ancestry_depth . ',' . $adminUser->id, 'level' => 1, 'register_ip' => Request::getClientIp()]);
     if (!$user) {
         return failure('添加会员失败');
     }
     return success('添加会员成功');
 }
Exemplo n.º 9
0
/**
 * @param $goption
 * @param $coption
 * @param $cparams
 */
function command_install($goption, $coption, $cparams)
{
    global $modslib;
    global $prefs;
    global $mods_server;
    $deps = $modslib->find_deps($prefs['mods_dir'], $mods_server, $cparams);
    if (count($deps['unavailable'])) {
        $err = "Sorry, theses packages are required but not available:\n";
        foreach ($deps['unavailable'] as $mod) {
            $err .= " - " . $mod->modname . "\n";
        }
        failure($err);
    }
    if (count($deps['conflicts'])) {
        $err = "Sorry, theses packages are required but conflicts:\n";
        foreach ($deps['conflicts'] as $mod) {
            $err .= " - " . $mod->modname . "\n";
        }
        failure($err);
    }
    if (count($deps['wanted'])) {
        echo "You asked to install these mods:\n";
        foreach ($deps['wanted'] as $mod) {
            echo "  " . $mod->modname . "\n";
        }
    }
    if (count($deps['toinstall'])) {
        echo "The following packages will be installed:\n";
        foreach ($deps['toinstall'] as $mod) {
            echo "  " . $mod->modname . " (" . $mod->revision . ")\n";
        }
    }
    if (count($deps['toupgrade'])) {
        echo "The following packages will be upgraded:\n";
        foreach ($deps['toupgrade'] as $meat) {
            echo "  " . $meat['to']->modname . " (" . $meat['to']->revision . ") (from version " . $meat['from']->revision . ")\n";
        }
    }
    if (count($deps['suggests'])) {
        echo "Suggested packages:\n";
        foreach ($deps['suggests'] as $mod) {
            echo "  " . $mod->modname . "\n";
        }
    }
    $res = ask("Would you like to continue (y/N) ? ");
    if ($res != 'y') {
        echo "Good bye\n";
        exit(0);
    }
    $modslib->install_with_deps($prefs['mods_dir'], $mods_server, $deps);
}
Exemplo n.º 10
0
 public function update()
 {
     if (!Request::has('_id', 'title', 'content', 'status')) {
         return failure('参数错误');
     }
     $notice = Notice::find(Request::input('_id'));
     $notice->title = Request::input('title');
     $notice->content = Request::input('content');
     $notice->status = Request::input('status');
     if ($notice->save()) {
         return success('修改成功');
     }
     return failure('修改失败');
 }
Exemplo n.º 11
0
 public function addBank()
 {
     if (!Request::has('bank', 'name', 'account')) {
         return failure('参数错误');
     }
     $bank = Bank::find(Request::input('bank'));
     if (!$bank) {
         return failure('银行不存在');
     }
     $adminBank = AdminBank::add($bank, Request::input('name'), Request::input('account'), Request::input('address'));
     if (!$adminBank) {
         return failure('添加银行失败');
     }
     return success('添加银行成功');
 }
Exemplo n.º 12
0
 /**
  * 修改昵称
  *  
  * @date   2015-09-19
  * @return [type]     [description]
  */
 public function update()
 {
     if (!Request::has('action')) {
         return failure('非法操作');
     }
     $user = Auth::user();
     if (Request::input('action') == 'nickname') {
         $nickname = Request::input('nickname');
         if (!$nickname) {
             return $this->failure('昵称不能为空');
         }
         $user->nickname = $nickname;
         $user->save();
         return success('修改成功');
     }
     if (Request::input('action') == 'passwd') {
         $old_pass = Request::input('old_pass');
         $new_pass = Request::input('new_pass');
         if (!Hash::check($old_pass, $user->password)) {
             return failure('密码错误');
         }
         if (Hash::check($new_pass, $user->payment_password)) {
             return failure('登陆密码不能和支付密码一样');
         }
         $user->password = Hash::make($new_pass);
         if (!$user->save()) {
             return failure('密码修改失败');
         }
         return success('密码修改成功');
     }
     if (Request::input('action') == 'coinpasswd') {
         $old_bank = Request::input('old_bank');
         $new_bank = Request::input('new_bank');
         if (!$user->payment_password == '') {
             if (!Hash::check($old_bank, $user->payment_password)) {
                 return failure('资金密码错误');
             }
         }
         if (Hash::check($new_bank, $user->password)) {
             return failure('支付密码不能和登陆密码一样');
         }
         $user->payment_password = Hash::make($new_bank);
         if (!$user->save()) {
             return failure('支付密码修改失败');
         }
         return success('支付密码修改成功');
     }
 }
Exemplo n.º 13
0
 public function loginTo()
 {
     $rules = ['captcha' => 'required|captcha'];
     $validator = Validator::make(Request::all(), $rules);
     if ($validator->fails()) {
         return failure('验证码错误');
     }
     if (Auth::attempt(['username' => Request::input('username'), 'password' => Request::input('passwd')])) {
         $user = Auth::user();
         $user->last_sign_in_ip = ip2long(Request::getClientIp());
         $user->last_sign_in_at = Carbon::now();
         $user->sign_in_cnt += 1;
         $user->user_tokens = md5($user->username);
         $user->save();
         return success('登录成功');
     }
     return failure('用户名或密码错误');
 }
Exemplo n.º 14
0
function file_re($file, $pattern, $all = true)
{
    static $path;
    $path or $path = isset($_SERVER['argv'][1]) ? $_SERVER['argv'][1] . '/include/curl/' : "/usr/local/include/curl/";
    if ($content = file_get_contents($path . $file)) {
        if ($all) {
            if (preg_match_all($pattern, $content, $matches, PREG_SET_ORDER)) {
                return $matches;
            }
        } else {
            if (preg_match($pattern, $content, $matches)) {
                return $matches;
            }
        }
        trigger_error("no match in {$file} for {$pattern}");
    }
    failure();
}
Exemplo n.º 15
0
function check_game()
{
    global $bot;
    // Check if we have now been assigned a game.
    $res = pg_query_params('SELECT
       b.game,
       b.cards,

       g.bot1,
       g.bot2,
       g.bid1,
       g.bid2
     FROM
       bots AS b JOIN games AS g
     ON
       b.game=g.id
     WHERE
       b.id=$1;', [$bot["id"]]);
    if ($res === FALSE) {
        failure("Failed to query the database to check whether you have been assigned a game.");
    }
    if (pg_affected_rows($res) !== 1) {
        return;
    }
    $row = pg_fetch_assoc($res);
    pg_free_result($res);
    // If our bid is null, we can return successfully and not confuse the bot.
    if ($row["bot1"] === $bot["id"] && !is_null($row["bid1"]) || $row["bot2"] === $bot["id"] && !is_null($row["bid2"])) {
        failure("You have already started playing a game, #{$row['game']}, and must finish it before attempting to start a new game.");
    }
    // Parse the cards the bot has been dealt into an array.
    $cards = explode(",", substr($row["cards"], 1, -1));
    // Determine our opponent.
    if ($row["bot1"] === $bot["id"]) {
        $opponent = (int) $row["bot2"];
    } else {
        $opponent = (int) $row["bot1"];
    }
    // Return the game information to the client.
    pg_query("BEGIN;");
    reset_timeout("session");
    success(["cards" => $cards, "game" => (int) $row["game"], "opponent" => $opponent]);
}
Exemplo n.º 16
0
// Retrieve the password hash for the bot.
$res = pg_query_params('SELECT id,password FROM bots WHERE name=$1;', [$req["name"]]);
if ($res === FALSE) {
    failure("Failed to query the database for the existence of your name.");
}
if (pg_affected_rows($res) !== 1) {
    failure("The 'name' you provided, '{$req['name']}', has not been registered.");
}
$row = pg_fetch_assoc($res);
$id = (int) $row["id"];
$pass = $row["password"];
pg_free_result($res);
// Validate the password from the request against the database.
if (!password_verify($req["password"], $pass)) {
    failure("The 'password' you provided did not match the one given during registration.");
}
// Generate a shoddy but workable session identifier.
$sess = md5($req["name"] . openssl_random_pseudo_bytes(128));
// Record the session in the database.
$res = pg_query_params('UPDATE bots SET session=$1, session_timeout=now()+\'30 minutes\'::interval WHERE name=$2;', [$sess, $req["name"]]);
if ($res === FALSE || pg_affected_rows($res) !== 1) {
    failure("Failed to record your session in the database.");
}
pg_free_result($res);
// Extract the full session information from the database.
$bot = get_session($sess);
// Be sure that we don't have an active game.
forfeit();
// Return successfully.
reset_timeout("session");
success(["session" => $sess, "id" => $id]);
Exemplo n.º 17
0
// ---------------------------------------------------------------------------
// Error checking
// ---------------------------------------------------------------------------
if (!isset($_SESSION['users_id'])) {
    failure('Invalid user id');
}
if (!isset($_POST['id']) || !filter_var($_POST['id'], FILTER_VALIDATE_INT) || $_POST['id'] < 1) {
    failure('Invalid bookmark id');
}
$id = $_POST['id'];
// ---------------------------------------------------------------------------
// Secondary error checking
// ---------------------------------------------------------------------------
$bm = new suxBookmarks();
if (!$bm->getByID($id)) {
    failure('Invalid bookmark ' . $id);
}
// ---------------------------------------------------------------------------
// Go
// ---------------------------------------------------------------------------
$module = 'bookmarks';
$link = 'link__bookmarks__users';
$col = 'bookmarks';
// Get image names from template config
$tpl = new suxTemplate($module);
$tpl->configLoad('my.conf', $module);
$image = $tpl->getConfigVars('imgUnsubscribed');
$db = suxDB::get();
$query = "SELECT COUNT(*) FROM {$link} WHERE {$col}_id = ? AND users_id = ? ";
$st = $db->prepare($query);
$st->execute(array($id, $_SESSION['users_id']));
Exemplo n.º 18
0
        //Make the webrequest
        //Only if we have a valid url
        if (valid_url($url, true)) {
            // Load Requests Library
            include 'requests/Requests.php';
            Requests::register_autoloader();
            $headers = array('Content-Type' => 'application/json');
            $response = Requests::post($url, $headers, json_encode($obj));
            if ($response->success) {
                success('<string>' . $response->status_code . '</string>');
            } else {
                failure($response->status_code);
            }
        } else {
            //since the url was invalid, we return 400 (Bad Request)
            failure(400);
        }
}
/** Copied from wordpress */
function success($innerXML)
{
    $xml = <<<EOD
<?xml version="1.0"?>
<methodResponse>
  <params>
    <param>
      <value>
      {$innerXML}
      </value>
    </param>
  </params>
Exemplo n.º 19
0
 /**
  * Saves this instance of the model to the database.
  */
 final function save()
 {
     if ($this->_is_valid) {
         $props = $this->get_properties();
         if (isset($props['id']) && $props['id']) {
             $id = $props['id'];
             unset($props['id']);
             $this->db->where('id', $id);
             $this->db->update($this->get_table(), $props);
         } else {
             unset($props['id']);
             $this->db->insert($this->get_table(), $props);
             $this->id = $this->db->insert_id();
         }
         if ($message = $this->db->_error_message()) {
             failure($message);
             return false;
         }
         return true;
     } else {
         return false;
     }
 }
Exemplo n.º 20
0
$res = pg_query_params('SELECT bot1, bot2, bid1, bid2 FROM games WHERE id=$1;', [$bot["game"]]);
if ($res === FALSE) {
    failure("Failed to query the database to check whether you have bid in this game.");
}
if (pg_affected_rows($res) !== 1) {
    failure("The 'game' attached to your session, '{$bot['game']}', was not found.");
}
$row = pg_fetch_assoc($res);
pg_free_result($res);
// Check which player the bot is in this game.
if ($row["bot1"] === $bot["id"]) {
    $col = "bid1";
} elseif ($row["bot2"] === $bot["id"]) {
    $col = "bid2";
} else {
    failure("The 'game' attached to your session, '{$bot['game']}', does not have you recorded as a player. Contact Mak about this error.");
}
// Check if a bid has already been made.
if (!is_null($row[$col])) {
    failure("You have already bid '{$row[$col]}' in this game, and changing your bid is not permitted.");
}
// Register our bid.
$res = pg_query_params('UPDATE games SET ' . $col . '=$1 WHERE id=$2;', [$req["bid"], $bot["game"]]);
if ($res === FALSE || pg_affected_rows($res) !== 1) {
    failure("Failed to update the database to add your bid to this game.");
}
pg_free_result($res);
// Return successfully.
reset_timeout("game");
reset_timeout("session");
success([]);
Exemplo n.º 21
0
         break;
     case 'logBloodPressure':
         list($date, $systolic, $diastolic, $time) = explode(",", $body);
         $date = dateconverter($date);
         $xml = $fitbit->logBloodPressure($date, $systolic, $diastolic, $time);
         success('<string>' . $response->status_code . '</string>');
         break;
     case 'logGlucose':
         list($date, $tracker, $glucose, $hba1c, $time) = explode(",", $body);
         $date = dateconverter($date);
         $xml = $fitbit->logGlucose($date, $tracker, $glucose, $hba1c, $time);
         success('<string>' . $response->status_code . '</string>');
         break;
     default:
         //__log("$obj->{$data->name}: Failure 404");
         failure(404);
         break;
 }
 /*
 				//Make the webrequest
 				//Only if we have a valid url
 				if (valid_url($url, true)) {
 					// Load Requests Library
 					include('requests/Requests.php');
 					Requests::register_autoloader();
 
 					$headers  = array(
 						'Content-Type' => 'application/json'
 					);
 					$response = Requests::post($url, $headers, json_encode($obj));
 
Exemplo n.º 22
0
function get_session($sess)
{
    $res = pg_query_params('SELECT
       id,
       name,
       password,
       session,
       EXTRACT(EPOCH FROM (now() - session_timeout)) AS session_timeout,
       game,
       EXTRACT(EPOCH FROM (now() - game_timeout)) AS game_timeout,
       cards
     FROM bots
     WHERE session=$1
     LIMIT 1;', [$sess]);
    if ($res === FALSE) {
        panic("Failed to query the database for the existence of your session.");
    }
    if (pg_affected_rows($res) !== 1) {
        failure("The session you provided, '{$sess}', is not currently active.");
    }
    $row = pg_fetch_assoc($res);
    pg_free_result($res);
    return $row;
}
Exemplo n.º 23
0
// ---------------------------------------------------------------------------
// Error checking
// ---------------------------------------------------------------------------
if (!isset($_SESSION['users_id'])) {
    failure('Invalid user id');
}
if (!isset($_POST['id']) || !filter_var($_POST['id'], FILTER_VALIDATE_INT) || $_POST['id'] < 1) {
    failure('Invalid feed id');
}
$id = $_POST['id'];
// ---------------------------------------------------------------------------
// Secondary error checking
// ---------------------------------------------------------------------------
$feed = new suxRSS();
if (!$feed->getFeedByID($id)) {
    failure('Invalid feed');
}
// ---------------------------------------------------------------------------
// Go
// ---------------------------------------------------------------------------
$module = 'feeds';
$link = 'link__rss_feeds__users';
$col = 'rss_feeds';
// Get image names from template config
$tpl = new suxTemplate($module);
$tpl->configLoad('my.conf', $module);
$image = $tpl->getConfigVars('imgUnsubscribed');
$db = suxDB::get();
$query = "SELECT COUNT(*) FROM {$link} WHERE {$col}_id = ? AND users_id = ? ";
$st = $db->prepare($query);
$st->execute(array($id, $_SESSION['users_id']));
Exemplo n.º 24
0
    failure("The 'name' must be between 1 and 40 characters, inclusive, but a name of length {$len} was given.");
}
// Confirm that the password is acceptable length.
$len = strlen($req["password"]);
if ($len < 1 || $len > 255) {
    failure("The 'password' must be between 1 and 255 characters, inclusive, but a name of length {$len} was given.");
}
// Confirm that the name contains acceptable characters.
if (preg_match("/[^-_a-z0-9]/i", $req["name"])) {
    failure("The 'name' must be composed of only letters, numbers, hyphens, and underscores.");
}
// Check that the name is available.
$res = pg_query_params('SELECT name FROM bots WHERE name=$1 LIMIT 1;', [$req["name"]]);
if ($res === FALSE) {
    failure("Failed to query the database for the existence of your name.");
}
if (pg_affected_rows($res) !== 0) {
    failure("The 'name' you requested, '{$req['name']}', has already been registered.");
}
pg_free_result($res);
// Hash the password.
$pass = password_hash($req["password"], PASSWORD_DEFAULT);
// Register the bot.
$res = pg_query_params('INSERT into bots (name, password) values ($1, $2) RETURNING id;', [$req["name"], $pass]);
if ($res === FALSE || pg_affected_rows($res) !== 1) {
    failure("Failed to register your bot into the database.");
}
$row = pg_fetch_assoc($res);
pg_free_result($res);
// Return successfully.
success(["id" => (int) $row["id"]]);
Exemplo n.º 25
0
function grabComics($grab_uri, $output_uri)
{
    $num = 0;
    $fetched = 0;
    // How many we actually retreived
    // create a cURL handle
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_BINARYTRANSFER, TRUE);
    // We're grabbing images
    curl_setopt($ch, CURLOPT_FILETIME, TRUE);
    // We want the modify date
    curl_setopt($ch, CURLOPT_HEADER, FALSE);
    // We don't want headers with the output
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    // Don't output return
    // First, define our vars
    $info = NULL;
    $filename = NULL;
    global $extsToTry;
    global $maxSkip;
    $curSkip = 0;
    $sql = "SELECT value FROM `config` WHERE `key`='extsToTry'";
    $result = verify_query($sql);
    $row = mysql_fetch_assoc($result);
    $extsToTry = explode(',', $row['value']);
    mysql_free_result($result);
    $sql = "SELECT value FROM `config` WHERE `key`='maxSkip'";
    $result = verify_query($sql);
    $row = mysql_fetch_assoc($result);
    $maxSkip = $row['value'];
    mysql_free_result($result);
    while (true) {
        // Break inside
        // First we'll check if we have this file already
        $alreadyFetched = FALSE;
        foreach ($extsToTry as $ext) {
            $filename = sprintf('./%05d.%s', $num, $ext);
            if (file_exists($output_uri . $filename)) {
                $alreadyFetched = TRUE;
                break;
            }
        }
        if ($alreadyFetched === TRUE) {
            $num++;
            $curSkip = 0;
            continue;
        }
        // Now to fetch it from the site
        foreach ($extsToTry as $ext) {
            $filename = sprintf('./%05d.%s', $num, $ext);
            curl_setopt($ch, CURLOPT_URL, $grab_uri . $filename);
            // The URL of course
            $ret = curl_exec($ch);
            $info = curl_getinfo($ch);
            if ($info['http_code'] == 200) {
                break;
            }
            // Found it on this ext
        }
        if ($info['http_code'] == 404) {
            if ($curSkip <= $maxSkip) {
                $curSkip++;
                $num++;
                continue;
                // Goto next
            } else {
                // Else we've hit the end
                $num -= $curSkip + 1;
                echo "<h1>Success</h1><br />\nFetched {$fetched} comics for {$grab_uri}. There are {$num} comics for this series now.<br />\n";
                break;
            }
        } elseif ($info['http_code'] != 200) {
            failure("Received http code " . $info['http_code'] . " for {$grab_uri}.<br />\n");
            break;
        }
        $curSkip = 0;
        $fh = fopen($output_uri . $filename, "w");
        if ($fh === FALSE) {
            failure("Unable to open output file {$output_uri}{$filename}.<br />\n");
            break;
        }
        $bytes = fwrite($fh, $ret);
        fclose($fh);
        if ($bytes == FALSE) {
            failure("Error writing file {$output_uri}{$filename}.<br />\n");
            break;
        }
        $success = touch($output_uri . $filename, intval($info['filetime']));
        // Set modified date
        if ($success === FALSE) {
            echo "WARNING: Failed to touch file {$output_uri}{$filename}.<br />\n";
        }
        echo "Successfully wrote {$filename}.<br />\n";
        $num++;
        $fetched++;
    }
    // close cURL resource, and free up system resources
    curl_close($ch);
}
Exemplo n.º 26
0
        $status = "<p class=\"alert alert-success\">This bot is current online, and playing game <a href=\"/stats/game/by-id/{$bot['game']}/\">{$bot['game']}</a>.</p>";
    } else {
        $status = "<p class=\"alert alert-success\">This bot is current online.</p>";
    }
} else {
    $status = "<p class=\"alert alert-danger\">This bot is currently offline.</p>";
}
// Find game statistics.
$res = pg_query_params('SELECT
     (SELECT COUNT(*) FROM games WHERE ((bot1=$1 OR bot2=$1)) AND ((bot1=$1 AND score1>score2) OR (bot2=$1 AND score2>score1))) AS wins,
     (SELECT COUNT(*) FROM games WHERE ((bot1=$1 OR bot2=$1)) AND ((bot1=$1 AND score1<score2) OR (bot2=$1 AND score2<score1))) AS losses,
     (SELECT COUNT(*) FROM games WHERE ((bot1=$1 OR bot2=$1)) AND ((bot1=$1 AND score1=score2) OR (bot2=$1 AND score2=score1))) AS ties,
     (SELECT COUNT(*) FROM games WHERE ((bot1=$1 OR bot2=$1)) AND forfeited_by IS NOT NULL) AS forfeits,
     (SELECT COUNT(*) FROM games WHERE ((bot1=$1 OR bot2=$1))) AS total;', [$bot["id"]]);
if ($res === FALSE) {
    failure("Unable to query the database for the statistics on the games {$bot['name']} has played.");
}
$row = pg_fetch_assoc($res);
pg_free_result($res);
function pct($m, $n)
{
    if ($n == 0) {
        $p = 0;
    } else {
        $p = $m / $n * 100;
    }
    return number_format($p, 2, '.', '');
}
$html = file_get_contents("bot.html");
$html = str_replace("{{bot-name}}", $bot["name"], $html);
$html = str_replace("{{bot-id}}", $bot["id"], $html);
    echo "        'certificate_authority' => " . success($ssl_result ? 'true' : 'false') . PHP_EOL;
    echo "    )" . PHP_EOL;
    echo "));" . PHP_EOL;
} elseif ($compatiblity === REQUIREMENTS_MIN_MET) {
    echo success('Bottom Line: Yes, you can!') . PHP_EOL;
    echo PHP_EOL;
    echo 'Your PHP environment is ready to go! There are a couple of minor features that' . PHP_EOL . 'you won\'t be able to take advantage of, but nothing that\'s a show-stopper.' . PHP_EOL;
    echo PHP_EOL;
    echo info('Recommended settings for config.inc.php') . PHP_EOL;
    echo PHP_EOL;
    echo "CFCredentials::set(array(" . PHP_EOL;
    echo "    '@default' => array(" . PHP_EOL;
    echo "        'key' => 'aws-key'," . PHP_EOL;
    echo "        'secret' => 'aws-secret'," . PHP_EOL;
    echo "        'default_cache_config' => ";
    if ($apc_ok) {
        echo success('\'apc\'');
    } elseif ($xcache_ok) {
        echo success('\'xcache\'');
    } elseif ($file_ok) {
        echo success('\'/path/to/cache/folder\'');
    }
    echo "," . PHP_EOL;
    echo "        'certificate_authority' => " . ($ssl_result ? 'false' : 'true') . PHP_EOL;
    echo "    )" . PHP_EOL;
    echo "));" . PHP_EOL;
} else {
    echo failure('Bottom Line: We\'re sorry...') . PHP_EOL;
    echo 'Your PHP environment does not support the minimum requirements for the ' . PHP_EOL . 'AWS SDK for PHP.' . PHP_EOL;
}
echo PHP_EOL;
function test_net_ping($os, $result, $expect)
{
    $ping = Net_Ping_Result::factory($result, $os);
    if (PEAR::isError($ping)) {
        echo failure($os, "factory(): " . $ping->getMessage());
    }
    if ($expect['min'] !== $ping->getMin()) {
        echo failure($os, "getMin()");
    }
    if ($expect['avg'] !== $ping->getAvg()) {
        echo failure($os, "getAvg()");
    }
    if ($expect['max'] !== $ping->getMax()) {
        echo failure($os, "getMax()");
    }
    if ($expect['stddev'] !== $ping->getStddev()) {
        echo failure($os, "getStddev()");
    }
    if ($os !== $ping->getSystemName()) {
        echo failure($os, "getSystemName()");
    }
    if ($expect['ttl'] !== $ping->getTTL()) {
        echo failure($os, "getTTL()");
    }
    if (!is_array($ping->getICMPSequence())) {
        echo failure($os, "getICMPSequence()");
    }
    if ($expect['transmitted'] !== $ping->getTransmitted()) {
        echo failure($os, "getTransmitted()");
    }
    if ($expect['received'] !== $ping->getReceived()) {
        echo failure($os, "getReceived()");
    }
    if ($expect['bytesperreq'] !== $ping->getBytesPerRequest()) {
        echo failure($os, "getBytesPerRequest()");
    }
    if ($expect['bytestotal'] !== $ping->getBytesTotal()) {
        echo failure($os, "getBytesTotal()");
    }
    if ($expect['targetip'] !== $ping->getTargetIp()) {
        echo failure($os, "getTargetIp()");
    }
    if ($expect['loss'] !== $ping->getLoss()) {
        echo failure($os, "getLoss()");
    }
    unset($ping);
}
Exemplo n.º 29
0
        $status2 = "<p class=\"alert alert-success\">The bot named '{$bot2['name']}' is current online, and playing game <a href=\"/stats/game/by-id/{$bot2['game']}/\">{$bot2['game']}</a>.</p>";
    } else {
        $status2 = "<p class=\"alert alert-success\">The bot named '{$bot2['name']}' is current online.</p>";
    }
} else {
    $status2 = "<p class=\"alert alert-danger\">The bot named '{$bot2['name']}' is currently offline.</p>";
}
// Find game statistics.
$res = pg_query_params('SELECT
     (SELECT COUNT(*) FROM games WHERE ((bot1=$1 AND bot2=$2) OR (bot1=$2 AND bot2=$1)) AND ((bot1=$1 AND score1>score2) OR (bot2=$1 AND score2>score1))) AS wins,
     (SELECT COUNT(*) FROM games WHERE ((bot1=$1 AND bot2=$2) OR (bot1=$2 AND bot2=$1)) AND ((bot1=$1 AND score1<score2) OR (bot2=$1 AND score2<score1))) AS losses,
     (SELECT COUNT(*) FROM games WHERE ((bot1=$1 AND bot2=$2) OR (bot1=$2 AND bot2=$1)) AND ((bot1=$1 AND score1=score2) OR (bot2=$1 AND score2=score1))) AS ties,
     (SELECT COUNT(*) FROM games WHERE ((bot1=$1 AND bot2=$2) OR (bot1=$2 AND bot2=$1)) AND forfeited_by IS NOT NULL) AS forfeits,
     (SELECT COUNT(*) FROM games WHERE ((bot1=$1 AND bot2=$2) OR (bot1=$2 AND bot2=$1))) AS total;', [$bot1["id"], $bot2["id"]]);
if ($res === FALSE || pg_affected_rows($res) === 0) {
    failure("Unable to query the database for the statistics on the games {$bot1['name']} and {$bot2['name']} have played together.");
}
$row = pg_fetch_assoc($res);
pg_free_result($res);
function pct($m, $n)
{
    if ($n == 0) {
        $p = 0;
    } else {
        $p = $m / $n * 100;
    }
    return number_format($p, 2, '.', '');
}
$html = file_get_contents("versus.html");
$html = str_replace("{{name1}}", $bot1["name"], $html);
$html = str_replace("{{name2}}", $bot2["name"], $html);
Exemplo n.º 30
0
function add_to_file($step, $where, $what, $filename, $regexp = false)
{
    echo "Step {$step}: ";
    if ($content = @file_get_contents($filename)) {
        $content = str_replace("\r\n", "\n", $content);
        //If $what isn't in the file
        if (strpos($content, $what) === false) {
            //Add it
            if ($regexp === false) {
                $content = str_replace($where, $where . "\n" . $what, $content);
            } else {
                $content = preg_replace($where, "\$0\n" . $what, $content);
            }
            //If $what now is in the file
            if (strpos($content, $what) !== false) {
                //Try to save the file
                if ($f = @fopen($filename, 'wb')) {
                    fwrite($f, $content);
                    fclose($f);
                    success("hooked");
                } else {
                    failure("Error 3: '{$filename}' couldn't be opened for modification.\n" . 'Please change its access rights (chmod 777) and try again, then change access rights back to normal.');
                }
            } else {
                failure("Error 4: '{$where}' wasn't found in '{$filename}', so '{$what}' couldn't be inserted in it.");
            }
        } else {
            success("already hooked");
        }
    } else {
        failure("Error 6: '{$filename}' couldn't be found or read.");
    }
}