/** * Returns kills in json format according to the specified parameters * * @static * @param array $parameters * @return array */ public static function getKills($parameters = array()) { $ip = IP::get(); $userAgent = @$_SERVER["HTTP_USER_AGENT"]; Log::log("API Fetch: " . $_SERVER["REQUEST_URI"] . " (" . $ip . " / " . $userAgent . ")"); $tables = array(); $orWhereClauses = array(); $andWhereClauses = array(); Filters::buildFilters($tables, $orWhereClauses, $andWhereClauses, $parameters, true); $tables = array_unique($tables); //if (sizeof($tables) > 1) throw new Exception("Advanced multi-table searching is currently disabled"); if (sizeof($tables) == 0) { $tables[] = "zz_participants p"; } if (sizeof($tables) == 2) { $tablePrefix = "k"; } else { $tablePrefix = substr($tables[0], strlen($tables[0]) - 1, 1); } $query = "select distinct {$tablePrefix}.killID from "; $query .= implode(" left join ", array_unique($tables)); if (sizeof($tables) == 2) { $query .= " on (k.killID = p.killID) "; } if (sizeof($andWhereClauses) || sizeof($orWhereClauses)) { $query .= " where "; if (sizeof($orWhereClauses) > 0) { $andOr = array_key_exists("combined", $parameters) && $parameters["combined"] == true ? " or " : " and "; $query .= " ( " . implode($andOr, $orWhereClauses) . " ) "; if (sizeof($andWhereClauses)) { $query .= " and "; } } if (sizeof($andWhereClauses)) { $query .= implode(" and ", $andWhereClauses); } } if (array_key_exists("limit", $parameters) && $parameters["limit"] < 200) { $limit = $parameters["limit"]; $offset = 0; } else { $limit = 200; // Hardcoded, yes. This number should never change. -- Squizz $page = array_key_exists("page", $parameters) ? (int) $parameters["page"] : 1; $offset = ($page - 1) * $limit; } $orderDirection = array_key_exists("orderDirection", $parameters) ? $parameters["orderDirection"] : "desc"; $query .= " order by {$tablePrefix}.dttm {$orderDirection} limit {$offset}, {$limit}"; $cacheTime = 3600; $kills = Db::query($query, array(), $cacheTime); return self::getJSON($kills, $parameters); }
/** * @param string $username * @param string $password * @param bool $autoLogin * * @return bool */ public static function setLogin($username, $password, $autoLogin) { global $cookie_name, $cookie_time, $cookie_ssl, $baseAddr, $app; $hash = Password::genPassword($password); if ($autoLogin) { $hash = $username . '/' . hash('sha256', $username . $hash . time()); $validTill = date('Y-m-d H:i:s', time() + $cookie_time); $userID = Db::queryField('SELECT id FROM zz_users WHERE username = :username', 'id', array(':username' => $username), 30); $userAgent = $_SERVER['HTTP_USER_AGENT']; $ip = IP::get(); Db::execute('INSERT INTO zz_users_sessions (userID, sessionHash, validTill, userAgent, ip) VALUES (:userID, :sessionHash, :validTill, :userAgent, :ip)', array(':userID' => $userID, ':sessionHash' => $hash, ':validTill' => $validTill, ':userAgent' => $userAgent, ':ip' => $ip)); $app->setEncryptedCookie($cookie_name, $hash, time() + $cookie_time, '/', $baseAddr, $cookie_ssl, true); } $_SESSION['loggedin'] = $username; return true; }
/** * @param string $username * @param string $password * @param bool $autoLogin * @return bool */ public static function setLogin($username, $password, $autoLogin) { global $cookie_name, $cookie_time, $cookie_ssl, $baseAddr, $app; $hash = Password::genPassword($password); if ($autoLogin) { $hash = $username . "/" . hash("sha256", $username . $hash . time()); $validTill = date("Y-m-d H:i:s", time() + $cookie_time); $userID = Db::queryField("SELECT id FROM zz_users WHERE username = :username", "id", array(":username" => $username), 0); $userAgent = $_SERVER["HTTP_USER_AGENT"]; $ip = IP::get(); Db::execute("INSERT INTO zz_users_sessions (userID, sessionHash, validTill, userAgent, ip) VALUES (:userID, :sessionHash, :validTill, :userAgent, :ip)", array(":userID" => $userID, ":sessionHash" => $hash, ":validTill" => $validTill, ":userAgent" => $userAgent, ":ip" => $ip)); $app->setEncryptedCookie($cookie_name, $hash, time() + $cookie_time, "/", $baseAddr, $cookie_ssl, true); } $_SESSION["loggedin"] = $username; return true; }
/** * Returns kills in json format according to the specified parameters. * * @static * * @param array $parameters * * @return array */ public static function getKills($parameters = array()) { global $debug; $ip = IP::get(); $userAgent = @$_SERVER['HTTP_USER_AGENT']; if ($debug) { Log::log('API Fetch: ' . $_SERVER['REQUEST_URI'] . ' (' . $ip . ' / ' . $userAgent . ')'); } if (isset($parameters['limit']) && $parameters['limit'] > 200) { $parameters['limit'] = 200; } if (isset($parameters['page'])) { $parameters['limit'] = 200; } if (!isset($parameters['limit'])) { $parameters['limit'] = 200; } $kills = Kills::getKills($parameters, true, false); return self::getJSON($kills, $parameters); }
} if ($message) { $html .= sprintf('<div><strong>Message:</strong> %s</div>', $message); } if ($file) { $html .= sprintf('<div><strong>File:</strong> %s</div>', $file); } if ($line) { $html .= sprintf('<div><strong>Line:</strong> %s</div>', $line); } if ($trace) { $html .= '<h4>Trace</h4>'; $html .= sprintf('<pre>%s</pre>', $trace); } $date = date("Y-m-d H:i:s"); $url = $_SERVER["REQUEST_URI"]; $ip = IP::get(); try { Db::execute("INSERT INTO zz_errors (id, error, message, url, ip) VALUES (:id, :error, :message, :url, :ip) ON DUPLICATE KEY UPDATE ip = :ip, date = :date", array(":id" => $codeHash, ":error" => $html, ":message" => $message, ":url" => $url, ":ip" => $ip, ":date" => $date)); $app->render("error.html", array("code" => $codeHash, "errorMessage" => $message, "error" => $html)); } catch (Exception $ex) { $html = "<html>"; $html .= "<head>"; $html .= "<title>Oh noes an error!</title>"; $html .= "</head>"; $html .= "<body>"; $html .= $e->getMessage(); $html .= "</body>"; $html .= "</html>"; echo $html; }
public static function scrapeCheck() { global $apiWhiteList, $apiRequestsPrDay; if (!$apiRequestsPrDay) { $maxRequestsPerDay = 17280; } else { $maxRequestsPerDay = $apiRequestsPrDay; } $ip = substr(IP::get(), 0, 64); if (!in_array($ip, $apiWhiteList)) { $count = Db::queryField("select count(*) count from zz_analytics where ip = :ip and uri like '/api/%' and dttm >= date_sub(now(), interval 24 hour)", "count", array(":ip" => $ip), 0); if ($count > $maxRequestsPerDay) { $date = date("Y-m-d H:i:s"); $cachedUntil = date("Y-m-d H:i:s", time() + 3600); if (stristr($_SERVER["REQUEST_URI"], "xml")) { $data = "<?xml version=\"1.0\" encoding=\"UTF-8\"?" . ">"; // separating the ? and > allows vi to still color format code nicely $data .= "<eveapi version=\"2\" zkbapi=\"1\">"; $data .= "<currentTime>{$date}</currentTime>"; $data .= "<result>"; $data .= "<error>You have too many API requests in the last 24 hours. You are allowed a maximum of {$maxRequestsPerDay} requests.</error>"; $data .= "</result>"; $data .= "<cachedUntil>{$cachedUntil}</cachedUntil>"; $data .= "</eveapi>"; header("Content-type: text/xml; charset=utf-8"); } else { header("Content-type: application/json; charset=utf-8"); $data = json_encode(array("Error" => "You have too many API requests in the last 24 hours. You are allowed a maximum of {$maxRequestsPerDay} requests.", "cachedUntil" => $cachedUntil)); } header("X-Bin-Request-Count: " . $count); header("X-Bin-Max-Requests: " . $maxRequestsPerDay); header("Retry-After: " . $cachedUntil . " GMT"); header("HTTP/1.1 429 Too Many Requests"); header("Etag: " . md5(serialize($data))); echo $data; die; } header("X-Bin-Request-Count: " . $count); header("X-Bin-Max-Requests: " . $maxRequestsPerDay); } }
// http requests should already be prevented, but use this just in case // also prevents sessions from being created without ssl if (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] != 'https') { $uri = @$_SERVER['REQUEST_URI']; header("Location: https://zkillboard.com{$uri}"); die; } $timer = new Timer(); // Starting Slim Framework $app = new \Slim\Slim($config); // Session session_set_save_handler(new RedisSessionHandler(), true); session_cache_limiter(false); session_start(); $visitors = new RedisTtlCounter('ttlc:visitors', 300); $visitors->add(IP::get()); $requests = new RedisTtlCounter('ttlc:requests', 300); $requests->add(uniqid()); $load = getLoad(); // Check if the user has autologin turned on if ($load < 20 && !User::isLoggedIn()) { User::autoLogin(); } if ($load >= 20) { $uri = @$_SERVER['REQUEST_URI']; if ($uri != '') { $contents = $redis->get("cache:{$uri}"); if ($contents !== false) { echo $contents; exit; }
/** * Adds a key to the database. * * @static * @param int $keyID * @param string $vCode * @param null|string $label * @return string */ public static function addKey($keyID, $vCode, $label = null) { $userID = User::getUserID(); if ($userID == null) { $userID = 0; } $exists = Db::queryRow("SELECT userID, keyID, vCode FROM zz_api WHERE keyID = :keyID AND vCode = :vCode", array(":keyID" => $keyID, ":vCode" => $vCode), 0); if ($exists == null) { // Insert the api key Db::execute("replace into zz_api (userID, keyID, vCode, label) VALUES (:userID, :keyID, :vCode, :label)", array(":userID" => $userID, ":keyID" => $keyID, ":vCode" => $vCode, ":label" => $label)); } else { if ($exists["userID"] == 0) { // Someone already gave us this key anonymously, give it to this user Db::execute("UPDATE zz_api SET userID = :userID, label = :label WHERE keyID = :keyID", array(":userID" => $userID, ":label" => $label, ":keyID" => $keyID)); return "keyID {$keyID} previously existed in our database but has now been assigned to you."; } else { return "keyID {$keyID} is already in the database..."; } } $pheal = Util::getPheal($keyID, $vCode); $result = $pheal->accountScope->APIKeyInfo(); $key = $result->key; $keyType = $key->type; if ($keyType == "Account") { $keyType = "Character"; } $ip = IP::get(); Log::log("API: {$keyID} has been added. Type: {$keyType} ({$ip})"); return "Success, your {$keyType} key has been added."; }
User::autoLogin(); } // Theme $viewtheme = null; if (User::isLoggedIn()) { $viewtheme = UserConfig::get("viewtheme"); } $app->config(array("templates.path" => $baseDir . "templates/" . ($viewtheme ? $viewtheme : "bootstrap"))); // Error handling $app->error(function (\Exception $e) use($app) { include "view/error.php"; }); // Load the routes - always keep at the bottom of the require list ;) include "routes.php"; // Load twig stuff include "twig.php"; // Send debug info to chrome logger if ($debug) { ChromePhp::log($_SERVER); ChromePhp::log("Cache Used: " . Cache::getClass()); ChromePhp::log("Queries: " . Db::getQueryCount()); ChromePhp::log("IP Server sees: " . IP::get()); ChromePhp::log("Page generation time (Minus queries): " . Util::pageTimer()); } // Run the thing! $app->run(); if ($newRelic) { // New Relic hhvm_newrelic_transaction_set_name($uri); hhvm_newrelic_transaction_end(); }