/** * @param string $targetString The string from the config file * @param the $map A reference to the map object (redundant) * @param the $mapItem A reference to the object this target is attached to * @return array invalue, outvalue, unix timestamp that the data was valid */ function ReadData($targetString, &$map, &$mapItem) { $data[IN] = null; $data[OUT] = null; $data_time = 0; $matches = 0; if (preg_match("/^time:(.*)\$/", $targetString, $matches)) { $timezone = $matches[1]; $offset = "now"; if (preg_match("/^([^:]+):(.*)\$/", $timezone, $matches2)) { $timezone = $matches2[1]; $offset = $matches2[2]; // test that the offset is valid $timestamp = strtotime($offset); if ($timestamp === false || $timestamp === -1) { warn("Time ReadData: Offset String ({$offset}) is bogus - ignoring [WMTIME03]\n"); $offset = "now"; } } $timezone_l = strtolower($timezone); if (array_key_exists($timezone_l, $this->timezones)) { $tz = $this->timezones[$timezone_l]; wm_debug("Time ReadData: Timezone exists: {$tz}\n"); $dateTime = new DateTime($offset, new DateTimeZone($tz)); $mapItem->add_note("time_time12", $dateTime->format("h:i")); $mapItem->add_note("time_time12ap", $dateTime->format("h:i A")); $mapItem->add_note("time_time24", $dateTime->format("H:i")); $mapItem->add_note("time_timet", $dateTime->format("U")); $mapItem->add_note("time_timezone", $tz); $data[IN] = $dateTime->format("H"); $data[OUT] = $dateTime->format("i"); $data_time = time(); $matches++; } if ($matches == 0) { wm_warn("Time ReadData: Couldn't recognize {$timezone} as a valid timezone name [WMTIME02]\n"); } } else { // some error code to go in here wm_warn("Time ReadData: Couldn't recognize {$targetString} \n"); } wm_debug("Time ReadData: Returning (" . WMUtility::valueOrNull($data[IN]) . "," . WMUtility::valueOrNull($data[OUT]) . ",{$data_time})\n"); return array($data[IN], $data[OUT], $data_time); }
function ReadData($targetstring, &$map, &$item) { $data[IN] = NULL; $data[OUT] = NULL; $data_time = 0; $itemname = $item->name; $matches = 0; if (preg_match("/^time:(.*)\$/", $targetstring, $matches)) { $timezone = $matches[1]; $timezone_l = strtolower($timezone); $timezone_identifiers = DateTimeZone::listIdentifiers(); foreach ($timezone_identifiers as $tz) { if (strtolower($tz) == $timezone_l) { debug("Time ReadData: Timezone exists: {$tz}\n"); $dateTime = new DateTime("now", new DateTimeZone($tz)); $item->add_note("time_time12", $dateTime->format("h:i")); $item->add_note("time_time12ap", $dateTime->format("h:i A")); $item->add_note("time_time24", $dateTime->format("H:i")); $item->add_note("time_timezone", $tz); $data[IN] = $dateTime->format("H"); $data_time = time(); $data[OUT] = $dateTime->format("i"); $matches++; } } if ($matches == 0) { warn("Time ReadData: Couldn't recognize {$timezone} as a valid timezone name [WMTIME02]\n"); } } else { // some error code to go in here warn("Time ReadData: Couldn't recognize {$targetstring} \n"); } debug("Time ReadData: Returning (" . ($data[IN] === NULL ? 'NULL' : $data[IN]) . "," . ($data[OUT] === NULL ? 'NULL' : $data[OUT]) . ",{$data_time})\n"); return array($data[IN], $data[OUT], $data_time); }
function preTestPost(ISblamPost $p) { $text = preg_replace('/\\[:..:\\]\\s+/', ' ', $p->getRawContent()); if (strlen($text) < 40) { $text .= $p->getAuthorURI(); } if (strlen($text) < 40) { $text .= $p->getAuthorEmail(); } if (strlen($text) < 40) { $text .= $p->getAuthorName(); } if (strlen($text) < 20) { $text .= $p->getAuthorIP(); } if (strlen($text) < 10) { $this->checksum = NULL; return; } $text = preg_replace(array('/[.,\\s!:;()-]+/', '/([a-f0-9]{1,3}[a-f]{1,6}[0-9]{1,6})+/', '/\\d\\d{1,8}/'), array(' ', 'H', 'D'), strtolower($text)); d($text, 'normalized text'); $this->length = strlen($text); $this->checksum = md5($text); if (!$this->db->exec(sprintf("/*maxtime5*/INSERT INTO dupes (checksum,count,expires,ip) VALUES(UNHEX('%s'),1,%d,%u)\n\t\t\tON DUPLICATE KEY UPDATE count = 1 + IF(expires < %d,CEIL(count/10),count), expires = GREATEST(expires + 3600*6, %d)", $this->checksum, time() + 3600 * 18, ip2long($p->getAuthorIP()), time(), time() + 3600 * 18))) { warn($this->db->errorInfo()); } }
private function convertToArray($dat) { if (!function_exists('mb_convert_encoding') || !($conv = mb_convert_encoding($dat, "UTF-8", "UTF-8,ISO-8859-2,Windows-1252"))) { $conv = @iconv("UTF-8", "UTF-8", $dat); if ($conv === false || strlen($conv) < strlen($dat) * 0.9) { $conv = @iconv("ISO-8859-2", "UTF-8//IGNORE", $dat); if ($conv === false || strlen($conv) < strlen($dat)) { warn($conv, "A total failure, not even ISO!"); $conv = utf8_encode($dat); } else { d($conv, "got iso converted"); } } else { d($conv, "got UTF-8 converted"); } } $dat = strtr($conv, array('ą' => 'ą', 'ę' => 'ę', 'ó' => 'ó', 'ż' => 'ż', 'ś' => 'ś', 'ć' => 'ć', 'ź' => 'ź', 'ń' => 'ń', 'Ą' => 'Ą', 'Ę' => 'Ę', 'Ó' => 'Ó', 'Ż' => 'Ż', 'Ś' => 'Ś', 'Ć' => 'Ć', 'Ź' => 'Ź', 'Ń' => 'Ń')); $dat = explode("", $dat); $cnt = count($dat); $fields = array(); for ($i = 1; $i < $cnt; $i += 2) { $fields[$dat[$i - 1]] = $dat[$i]; } return $fields; }
function ReadData($targetstring, &$map, &$item) { $data[IN] = NULL; $data[OUT] = NULL; $data_time = 0; if (preg_match("/^!(.*)\$/", $targetstring, $matches)) { $command = $matches[1]; debug("ExternalScript ReadData: Running {$command}\n"); // run the command here if (($pipe = popen($command, "r")) === false) { warn("ExternalScript ReadData: Failed to run external script. [WMEXT01]\n"); } else { $i = 0; while ($i < 5 && !feof($pipe)) { $lines[$i++] = fgets($pipe, 1024); } pclose($pipe); if ($i == 5) { $data[IN] = floatval($lines[0]); $data[OUT] = floatval($lines[1]); $item->add_hint("external_line1", $lines[0]); $item->add_hint("external_line2", $lines[1]); $item->add_hint("external_line3", $lines[2]); $item->add_hint("external_line4", $lines[3]); $data_time = time(); } else { warn("ExternalScript ReadData: Not enough lines read from external script ({$i} read, 4 expected) [WMEXT02]\n"); } } } debug("ExternalScript ReadData: Returning (" . ($data[IN] === NULL ? 'NULL' : $data[IN]) . "," . ($data[OUT] === NULL ? 'NULL' : $data[OUT]) . ",{$data_time})\n"); return array($data[IN], $data[OUT], $data_time); }
/** * @param string $targetString The string from the config file * @param the $map A reference to the map object (redundant) * @param the $mapItem A reference to the object this target is attached to * @return array invalue, outvalue, unix timestamp that the data was valid */ function ReadData($targetString, &$map, &$mapItem) { $data[IN] = null; $data[OUT] = null; $data_time = 0; if (preg_match("/^time:(.*)\$/", $targetString, $matches)) { $timezone = $matches[1]; $offset = "now"; if (preg_match("/^([^:]+):(.*)\$/", $timezone, $matches2)) { $timezone = $matches2[1]; $offset = $matches2[2]; // test that the offset is valid $timestamp = strtotime($offset); if ($timestamp === false || $timestamp === -1) { warn("Time ReadData: Offset String ({$offset}) is bogus - ignoring [WMTIME03]\n"); $offset = "now"; } } list($required_time, $timezone_name) = $this->getTimeForTimeZone($timezone, $offset); $data = $this->populateTimeData($mapItem, $required_time, $timezone_name); $data_time = time(); } else { // some error code to go in here wm_warn("Time ReadData: Couldn't recognize {$targetString} \n"); } wm_debug("Time ReadData: Returning (" . WMUtility::valueOrNull($data[IN]) . "," . WMUtility::valueOrNull($data[OUT]) . ",{$data_time})\n"); return array($data[IN], $data[OUT], $data_time); }
function ReadData($targetstring, &$map, &$item) { $data[IN] = NULL; $data[OUT] = NULL; $data_time = 0; if (preg_match("/^dbplug:([^:]+)\$/", $targetstring, $matches)) { $database_user = $map->get_hint('dbplug_dbuser'); $database_pass = $map->get_hint('dbplug_dbpass'); $database_name = $map->get_hint('dbplug_dbname'); $database_host = $map->get_hint('dbplug_dbhost'); $key = mysql_real_escape_string($matches[1]); $SQL = "select in,out from table where host={$key} LIMIT 1"; if (mysql_connect($database_host, $database_user, $database_pass)) { if (mysql_select_db($database_name)) { $result = mysql_query($SQL); if (!$result) { warn("dbsample ReadData: Invalid query: " . mysql_error() . "\n"); } else { $row = mysql_fetch_assoc($result); $data[IN] = $row['in']; $data[OUT] = $row['out']; } } else { warn("dbsample ReadData: failed to select database: " . mysql_error() . "\n"); } } else { warn("dbsample ReadData: failed to connect to database server: " . mysql_error() . "\n"); } $data_time = now(); } debug("RRD ReadData: Returning (" . ($data[IN] === NULL ? 'NULL' : $data[IN]) . "," . ($data[OUT] === NULL ? 'NULL' : $data[IN]) . ",{$data_time})\n"); return array($data[IN], $data[OUT], $data_time); }
private function collectArtDirectories($path) { global $config; $this->directories[] = $path . '/'; if (count($this->directories) % 3 == 0) { echo '.'; } $dir = @opendir($path); if (!$dir) { if ($config['art.error.when.missing']) { error("Unable to locate art directory: {$path}"); } echo "\n"; warn("Unable to locate art directory: {$path}"); return; } $dirs = array(); while (false !== ($file = readdir($dir))) { if ($file == '.' || $file == '..') { continue; } if (!is_dir($path . '/' . $file)) { continue; } $dirs[] = $path . '/' . $file; } closedir($dir); foreach ($dirs as $path) { $this->collectArtDirectories($path); } }
function authenticate($params) { assert(isset($params['user']) && isset($params['pass'])); $contactId = $params['user']; $token = $params['pass']; $contact = DatabaseHelper::getInstance()->getContactByIdentifier($contactId, $identifier); if ($contact) { info(__METHOD__ . ': Contact ' . $contact['Id'] . ' succesfully authenticated'); return array('Id' => $contact['Id'], 'Role' => $contact['Role']); } else { warn(__METHOD__ . ': Authentication failed for contact "' . $contactId . '" and token "' . $identifier . '"'); return false; } }
protected function readConfig(array $ini) { if (!empty($ini['tlds'])) { SblamURI::init($ini['tlds'], $this->services->getDB()); } else { warn('tlds not given!'); } if (!empty($ini['dns'])) { AsyncDNS::init(preg_split('![\\s,]+!', $ini['dns'], NULL, PREG_SPLIT_NO_EMPTY)); } else { warn('dns not given!'); } foreach ($ini as $name => $settings) { if (!is_array($settings) || $name == 'db') { continue; } if (!empty($settings['disabled']) || isset($settings['enabled']) && !$settings['enabled']) { /*d($name,'disabled');*/ continue; } try { include_once "tests/" . strtolower($name) . ".php"; $classname = "SblamTest" . ucfirst($name); if (!class_exists($classname)) { warn($name, "Problem loading test plugin"); } $info = call_user_func(array($classname, 'info')); if (!empty($info['remote']) && isset($ini['remote']) && !$ini['remote']) { d($info, 'Its a remote service, remote disabled, skipping'); continue; } if (!empty($info['unsupported'])) { d($info, 'unsupported in this configuration'); continue; } $test = new $classname($settings, $this->services); if (!$test instanceof ISblamTest) { warn($test, 'Not a test'); continue; } //d($classname,"instantiated"); $this->addTest($test, isset($settings['phase']) ? $settings['phase'] : 10); } catch (Exception $e) { warn($e, "Failed to initialize plugin {$name}"); } } return true; }
public function initInternal() { $this->_regions = DatabaseHelper::getInstance()->getRegions(); if (isset($_GET['regionSelector']) && array_key_exists($_GET['regionSelector'], $this->_regions)) { $this->_currentRegion = $this->_regions[$_GET['regionSelector']]; // Set the cookie for 14 days if (!setcookie('region', $_GET['regionSelector'], time() + TWO_WEEKS, getConfiguration('public.path') . '/')) { warn(__METHOD__ . ': Could not set cookie for user! Output already exists.'); } unset($_GET['region']); } else { if (isset($_COOKIE['region']) && array_key_exists($_COOKIE['region'], $this->_regions)) { $this->_currentRegion = $this->_regions[$_COOKIE['region']]; // Update cookie expiry time setcookie('region', $_COOKIE['region'], time() + TWO_WEEKS, getConfiguration('public.path') . '/'); } else { $this->_currentRegion = $this->_regions[self::getDefaultRegion()]; } } info(__METHOD__ . ' region selected: ' . $this->_currentRegion['Id'] . ' (' . $this->_currentRegion['Name'] . ')'); }
private function severity($ip) { $rev = SblamURI::gethostbyaddr($ip); if (is_array($rev)) { warn($rev, "gethostbyaddr returned array!?"); $rev = reset($rev); } if (!$rev) { return 3; } if (preg_match('/(^|[.-])(vp[sn]|srv)[.\\d-]|(^|\\.)(colo|dedi?)[-.]|dedic|resell|serv(er|[.\\d-])|^ns\\d*\\.|^mail\\d*\\.|multicast|invalid|unknown/', $rev)) { return 2; } if (preg_match('/internetdsl\\.|static/', $rev) || preg_match('/^[^\\d]+$/', $rev) || strlen($rev) < 10) { return 1.5; } if (preg_match('/^nat[\\d.-]|cache|proxy|gprs[^a-z]|dynamic|\\.dhcp\\.|\\.sta\\.|ppp[\\d.-]|\\.dyn\\.|(^|[.-])adsl[.0-9-]/', $rev)) { return 0.8; } return 1; }
function authenticate($params) { assert('isset($params["email"]) && isset($params["password"])'); // TODO: A primitive brute-force defense? // We must call buildEmail as we may have explicitely added the // domain suffix during registration $email = Utils::buildEmail($params['email']); $pass = $params['password']; // Created a hashed hexadecimal string, use the salt if possible $hashed = Utils::hashPassword($pass); $contact = DatabaseHelper::getInstance()->getContactByEmail($email); if ($contact !== false) { if ($contact['Identifier'] === $hashed) { info(__METHOD__ . ': Contact ' . $contact['Id'] . ' succesfully authenticated'); return array('Id' => $contact['Id'], 'Role' => $contact['Role']); } else { warn(__METHOD__ . ': Contact ' . $contact['Id'] . ' failed to authorize: wrong password'); } } return false; }
public function addDecklist (Decklist $decklist) { global $config; if (!$this->decklistOnlyOutput) $this->addCards($decklist->cards); if ($this->decklistOnlyOutput || $config['render.decklist']) { $count = count($decklist->cards); if ($count <= 75) { // 75 or less and we assume this is a standard 60 card deck with upto a 15 // card sideboard. $decklistRenderer = new DecklistRenderer(); $decklistRenderer->cards = $decklist->cards; $decklistRenderer->writer = $this; $decklistRenderer->outputDir = $config['output.directory']; $decklistRenderer->outputName = 'Decklist - ' . $decklist->name; $this->renderers[] = $decklistRenderer; } else { // Enough cards for a multi page list. $cardsPerDeckpage = isset($config['output.decklist.cardsperpage']) ? $config['output.decklist.cardsperpage'] : 50; echo "\n"; warn('Large/Highlander deck detected, going to ' . $cardsPerDeckpage . ' card per page lists.'); $cardsRendered = 0 ; while ($cardsRendered < $count) { // slice out each card block. $cardPage = array_slice($decklist->cards, $cardsRendered, $cardsPerDeckpage); $decklistRenderer = new DecklistRenderer(); $decklistRenderer->cards = $cardPage; $decklistRenderer->wholeDeck = $decklist->cards; $decklistRenderer->writer = $this; $decklistRenderer->outputDir = $config['output.directory']; $decklistRenderer->outputName = 'Decklist - ' . $decklist->name . ' page ' . (floor($cardsRendered / $cardsPerDeckpage) + 1); $this->renderers[] = $decklistRenderer; $cardsRendered += $cardsPerDeckpage; } } } }
function index() { $pdo = $this->services->getDB(); $sblam = $this->getSblam(); // inits urls $table = 'plonker'; // FIXME: read config! $accumulate = array(); $max = 10; while ($max--) { foreach ($pdo->query("SELECT ip,added from {$table} where flags=0 order by rand() limit 2000") as $r) { try { $ip = long2ip($r['ip']); $rev = preg_replace('!(\\d+)\\.(\\d+)\\.(\\d+)\\.(\\d+)!', '\\4.\\3.\\2.\\1.dul.dnsbl.sorbs.net', $ip); $r['rev1'] = $rev; SblamURI::gethostbynameasync($rev); $rev = preg_replace('!(\\d+)\\.(\\d+)\\.(\\d+)\\.(\\d+)!', '\\4.\\3.\\2.\\1.korea.services.net', $ip); $r['rev2'] = $rev; SblamURI::gethostbynameasync($rev); $accumulate[] = $r; usleep(50000); if (count($accumulate) >= 20) { foreach ($accumulate as $r) { $res = SblamURI::gethostbyname($r['rev1']) ? 'dul' : 'nodul'; $res .= ',' . (SblamURI::gethostbyname($r['rev2']) ? 'wild' : 'nowild'); $q = "update {$table} set flags = '{$res}', added = added where ip = {$r['ip']}"; d($q); if (!$pdo->query($q)) { warn($pdo->errorInfo()); } } $accumulate = array(); } } catch (Exception $e) { } } } return array('redirect' => '/admin/plonker'); }
private function initInternal() { $this->locales = DatabaseHelper::getInstance()->getLocales(); if (isset($_GET['lang']) && array_key_exists($_GET['lang'], $this->locales)) { $this->locale = $this->locales[$_GET['lang']]; // Set the cookie for 14 days if (!setcookie('lang', $_GET['lang'], time() + TWO_WEEKS, getConfiguration('public.path') . '/')) { warn(__METHOD__ . ': Could not set cookie for user! Output already exists.'); } unset($_GET['lang']); } else { if (isset($_COOKIE['lang']) && array_key_exists($_COOKIE['lang'], $this->locales)) { $this->locale = $this->locales[$_COOKIE['lang']]; // Update cookie expiry time setcookie('lang', $_COOKIE['lang'], time() + TWO_WEEKS, getConfiguration('public.path') . '/'); } else { $this->locale = $this->locales[self::getDefaultLocale()]; } } info(__METHOD__ . ' locale selected: ' . $this->locale['Name'] . ' (' . $this->locale['Locale'] . ')'); setlocale(LC_ALL, $this->locale['Locale']); putenv('LC_ALL=' . $this->locale['Locale']); }
function testPost(ISblamPost $p) { // whitelist only direct connection (because other can be forged) and only when there aren't any objectionable hosts there $out = array(); $firstIP = true; $whitelisted = false; foreach ($p->getAuthorIPs() as $ip) { $rev = SblamURI::gethostbyaddr($ip); if (!$rev) { continue; } if (is_array($rev)) { warn($rev, 'gethostbyaddr returned array'); $rev = reset($rev); } // WTF? if (preg_match('!(?:\\.|^)(?:' . $this->isps . ')$!', $rev)) { $out[] = array(0.5, self::CERTAINITY_LOW, "Sent from blacklisted ISP ({$rev})"); } else { if ($firstIP && preg_match('!\\.(?:' . $this->whitelist . ')$!', $rev)) { $whitelisted = true; } else { if (preg_match('!\\.(?:' . $this->blacklist . ')$!', $rev)) { $out[] = array(0.35, self::CERTAINITY_LOW, "Sent from blacklisted TLD ({$rev})"); } } } $firstIP = false; } if (!count($out) && $whitelisted) { return array(-0.25, self::CERTAINITY_LOW, "Sent from whitelisted TLD ({$rev})"); } if (count($out)) { return $out; } }
} if ($rowuser["reputation"] >= 1) { $rep = "<a href=index.php?page=reputationpage > Reputace <img src='images/rep/reputation_pos.gif' border='0' alt='" . $setrep["good_level"] . "' title='" . $setrep["good_level"] . "' /></a>"; } if ($rowuser["reputation"] <= -1) { $rep = "<a href=index.php?page=reputationpage > Reputace <img src='images/rep/reputation_neg.gif'border='0' alt='" . $setrep["bad_level"] . "' title='" . $setrep["bad_level"] . "' /></a>"; } if ($rowuser["reputation"] >= 101) { $rep = "<a href=index.php?page=reputationpage > Reputace <img src='images/rep/reputation_highpos.gif' border='0' alt='" . $setrep["best_level"] . "' title='" . $setrep["best_level"] . "' /></a>"; } if ($rowuser["reputation"] <= -101) { $rep = "<a href=index.php?page=reputationpage > Reputace <img src='images/rep/reputation_highneg.gif'border='0' alt='" . $setrep["worse_level"] . "' title='" . $setrep["worse_level"] . "' /></a>"; } } // DT end reputation system print "<td class=\"blocklist\" align=\"center\" style=\"text-align:left;\">" . $language["WELCOME_BACK"] . "<a href='index.php?page=userdetails&id=" . $CURUSER["uid"] . "'> " . user_with_color($CURUSER["username"], $CURUSER["prefixcolor"], $CURUSER["suffixcolor"]) . get_user_icons($CURUSER) . warn($CURUSER) . $rra . $upr . $udo . $udob . $ubir . $umal . $ufem . $uban . $uwar . $upar . $ubot . $utrmu . $utrmo . $uvimu . $uvimo . $ufrie . $ujunk . $ustaf . $usys . " </a> \n"; if ($CURUSER["announce"] == "yes") { print "<td class=\"blocklist\" align=\"left\" style=\"text-align:left;\"><a href=\"index.php?page=announcement&uid=" . $CURUSER["uid"] . "\"><img src=\"images/ann.png\"></a></td>\n"; } print "<td class=\"blocklist\" align=\"left\" style=\"text-align:left;\">" . $rep . " \n"; print "<td class=\"blocklist\" align=\"left\" style=\"text-align:left;\">" . $col . "<font color='{$freec}'>{$till}" . ucfirst($post) . "</font> {$pic}</td>\n"; print "<td class=\"blocklist\" align=\"left\" style=\"text-align:center;\"><a class=\"mainmenu\" href=\"logout.php\"><img src=\"images/logout.png \" /></a></td>\n"; ?> </tr> </table> <?php if (!$CURUSER || $CURUSER["view_torrents"] == "no") { // do nothing } else { if ($XBTT_USE) { $res = get_result("select count(*) as tot, sum(f.seeds)+sum(ifnull(x.seeders,0)) as seeds, sum(f.leechers)+sum(ifnull(x.leechers,0)) as leechs FROM {$TABLE_PREFIX}files f LEFT JOIN xbt_files x ON f.bin_hash=x.info_hash", true, $btit_settings['cache_duration']);
function addURIs(array $links, $isspam, $howmuch = 1) { $parsed = array(); foreach ($links as $l) { try { $this->addURI($parsed, new SblamURI($l)); } catch (Exception $e) { warn($e); } } if (count($parsed)) { return $this->db->add(array_keys($parsed), $isspam, $howmuch); } return false; }
public function render() { echo $this->outputName . '...'; $canvas = imagecreatetruecolor(736, 1050); $settings = $this->getSettings(); $black = imagecolorallocate($canvas, 0, 0, 0); imagefill($canvas, 0, 0, $black); imagefilledrectangle($canvas, 12, 14, 736 - 12, 1050 - 14, imagecolorallocate($canvas, 255, 255, 255)); imageline($canvas, 20, 62, 716, 62, $black); // Compute the number of colored mana symbols. $symbolsCount = array("R" => 0, "G" => 0, "U" => 0, "B" => 0, "W" => 0); $allCards = isset($this->wholeDeck) ? $this->wholeDeck : $this->cards; foreach ($allCards as $card) { foreach ($card->getCostSymbols() as $symbols) { for ($i = 0, $n = strlen($symbols); $i < $n; $i++) { $symbol = $symbols[$i]; if (isset($symbolsCount[$symbol])) { $symbolsCount[$symbol]++; } } } } $symbolsTotal = 0; foreach ($symbolsCount as $count) { $symbolsTotal += $count; } // Draw deck colors. $symbolsLeft = $settings['colors.right']; if ($symbolsTotal > 0) { asort($symbolsCount); foreach ($symbolsCount as $symbol => $count) { // Draw either a large symbol or smaller one, based on the percentage of the color in the deck. if ($count / $symbolsTotal >= 0.15) { list($width) = $this->drawSymbol(null, 0, 0, 40, $symbol, false, true); $symbolsLeft -= $width; $this->drawSymbol($canvas, $settings['colors.top'], $symbolsLeft, 40, $symbol, true, true); } else { if ($count > 0) { list($width) = $this->drawSymbol(null, 0, 0, 25, $symbol, false, true); $symbolsLeft -= $width; $this->drawSymbol($canvas, $settings['colors.top'] + 15, $symbolsLeft, 25, $symbol, true, true); } } $symbolsLeft -= 5; } } // Draw title. $this->drawText($canvas, $settings['title.x'], $settings['title.y'], $symbolsLeft - $settings['title.x'], str_replace('Decklist - ', '', $this->outputName), $this->font('title')); // Draw legality icons. list($legality, $maindeckLegality, $illegalSideboardCards) = $this->writer->formatDB->getLegality($this->cards, $settings['decklist.debug.legality']); $y = $settings["legality.top"]; $x = $settings["legality.left"]; foreach ($legality as $format => $isLegal) { if ($isLegal) { $imageName = "legal"; } else { if ($maindeckLegality[$format]) { $imageName = "caution"; } else { $imageName = "illegal"; } } switch ($format) { case "Vintage (T1)": $format = "t1"; break; case "Legacy (T1.5)": $format = "t15"; break; case "Extended (T1.x)": $format = "t1x"; break; case "Standard (T2)": $format = "t2"; break; } $legalityImage = @imagecreatefrompng("images/decklist/{$imageName} {$format}.png"); if (!$legalityImage) { error("Legality image not found: {$imageName} {$format}.png"); } imagecopy($canvas, $legalityImage, $x, $y, 0, 0, 25, 25); imagedestroy($legalityImage); $x += 35; } // Compute card qty in main deck and sideboard. $maindeckCards = array(); $n = count($this->cards); if ($n >= 75) { $n -= 15; } for ($i = 0; $i < $n; $i++) { $card = $this->cards[$i]; $title = strtolower($card->title); if (!@$maindeckCards[$title]) { $maindeckCards[$title] = 0; } $maindeckCards[$title]++; } $sideboardCards = array(); for ($n = count($this->cards); $i < $n; $i++) { $card = $this->cards[$i]; $title = strtolower($card->title); if (!@$sideboardCards[$title]) { $sideboardCards[$title] = 0; } $sideboardCards[$title]++; } echo '.'; // Draw main deck cards. $baselineStart = $settings['cards.top'] + $this->font('cards')->getHeight(); $left = $settings['cards.column.1.left']; $right = $settings['cards.column.1.right']; $baseline = $baselineStart; foreach ($maindeckCards as $title => $qty) { if ($baseline > $settings['cards.bottom']) { if ($left == $settings['cards.column.2.left']) { break; } $left = $settings['cards.column.2.left']; $right = $settings['cards.column.2.right']; $baseline = $baselineStart; } $baseline = $this->drawTitle($canvas, $left, $baseline, $right, $qty, $title, $this->font('cards')); } // Sideboard goes on the second column, or after a blank line if already on the second column. if ($left == $settings['cards.column.1.left']) { $left = $settings['cards.column.2.left']; $right = $settings['cards.column.2.right']; $baseline = $baselineStart; } else { $baseline += $this->font('cards')->getLineHeight(); } // Draw sideboard cards. foreach ($sideboardCards as $title => $qty) { if ($baseline > $settings['cards.bottom']) { if ($left == $settings['cards.column.2.left']) { break; } $left = $settings['cards.column.2.left']; $right = $settings['cards.column.2.right']; $baseline = $baselineStart; } $color = in_array($title, $illegalSideboardCards) ? 'color:130,130,130' : null; $baseline = $this->drawTitle($canvas, $left, $baseline, $right, $qty, $title, $this->font('cards', $color)); } if ($baseline > $settings['cards.bottom'] && $left == $settings['cards.column.2.left']) { echo "\n"; warn('Not all cards fit on the decklist card.'); } // Draw card count. $count = count($this->cards); if ($count >= 75) { $count = $count - 15 . "/15"; } $count = "({$count})"; $width = $this->getTextWidth($count, $this->font('count')); $this->drawText($canvas, $settings['count.right'] - $width, $settings['count.y'], null, $count, $this->font('count')); echo "\n"; return $canvas; }
<?php require_once './libs/password_hashing.php'; $user = $_POST["user"]; $warnings = validate($user, ["first_name" => "required", "last_name" => "required", "email" => ["required", "email"], "roles" => ["required", "array"], "password" => "required"]); if ($user["password"] !== $user["confirm_password"]) { array_push($warnings, ["password" => "password_mismatch"]); } warn($warnings); $firstName = $user["first_name"]; $lastName = $user["last_name"]; $email = $user["email"]; $roles = 0; foreach ($user["roles"] as $role) { $roles = $roles + pow(2, $role - 1); } $password = password_hash($user["password"], PASSWORD_DEFAULT); $created_at = date("Y-m-d H:i:s"); $created_by = $_SESSION["id"]; $createUser = $db->prepare("INSERT INTO users (first_name, last_name, email, password, roles, created_by, created_at, updated_by, updated_at)\r\n VALUES (:firstName, :lastName, :email, :password, :roles, :created_by, :created_at, :updated_by, :updated_at)"); # If user with the same email exists but is removed, then revive the user with the new info $findExistingUser = $db->prepare("SELECT id FROM users WHERE email=:email LIMIT 1"); $reviveUser = $db->prepare("UPDATE users SET first_name=:firstName, last_name=:lastName, password=:password, roles=:roles, updated_at=:updated_at, updated_by=:updated_by, status='active' WHERE id=:id"); try { $existingUser = query("SELECT id FROM users WHERE email=:email LIMIT 1", [":email" => $email]); if (isset($existingUser["id"])) { query("UPDATE users SET first_name=:firstName, last_name=:lastName, password=:password, roles=:roles, updated_at=:updated_at, updated_by=:updated_by, status='active' WHERE id=:id", [":id" => $existingUser["id"], ":firstName" => $firstName, ":lastName" => $lastName, ":password" => $password, ":roles" => $roles, ":updated_by" => $created_by, ":updated_at" => $created_at]); output(["status" => "success"]); exit; } else { query("INSERT INTO users (first_name, last_name, email, password, roles, created_by, created_at, updated_by, updated_at) VALUES (:firstName, :lastName, :email, :password, :roles, :created_by, :created_at, :updated_by, :updated_at)", [":firstName" => $firstName, ":lastName" => $lastName, ":email" => $email, ":password" => $password, ":roles" => $roles, ":created_by" => $created_by, ":created_at" => $created_at, ":updated_by" => $created_by, ":updated_at" => $created_at]);
status("checking server setup..."); $f = fopen("/proc/loadavg", "r"); if ($f) { $buffer = ''; if (!feof($f)) { $buffer = fgets($f, 1024); } fclose($f); $loads = explode(" ", $buffer); if (strlen($buffer) == 0 || $loads <= 0) { //how likly is it to be 0 fail("unable to read loadavg value - REQUIRED on non windows systems"); } } else { fail("loadavg check failed - REQUIRED on non windows systems"); } } else { warn("possible windows system detected: site will skip loadavg check - NOT RECOMMENDED"); } ////////////////////////////////////////////////////////////////// #todo? Database check... (and connect to sphinx/memcache etc...) ////////////////////////////////////////////////////////////////// // END OF TESTING // We show some diagnostics if any tests failed... status("completed"); if (!$ok) { echo "<br><br><br><br>"; phpinfo(); } else { echo "<li style=\"color:green;font-weight:bold;\">Server is correctly configured to run Geograph!</li>"; }
<? $verfile = "/usr/napc/conf/rptgui_version"; if( file_exists($verfile) ) { $verh = fopen($verfile, 'r') or warn("Unable to open version file $verfile"); if ( ! isset($verh) ) { echo "Unable to open CSV file $verfile"; exit; } $ver_data = fread($verh, filesize($verfile)); fclose($verh); echo " Report Generator v{$ver_data}. Copyright @ 2007"; } ?>
<?php include "../env.php"; include APP_PATH . "/Bootstrap.php"; if (ENV !== ENV_DEVELOPMENT && (!Utils::IsXhrRequest() || !AuthHandler::isSessionExisting())) { die; } $contactId = AuthHandler::getLoggedInUserId(); if (!$contactId) { warn("Toggle activate command sent while no user is logged in"); die; } try { $server = DatabaseHelper::getInstance(); $ride = $server->getRideProvidedByContactId($contactId); if (!$ride) { throw new Exception("No ride found for contact {$contactId}"); } $rideId = $ride['Id']; if ($ride['Active'] == RIDE_ACTIVE) { // Hidden status is always status + 2 $newStatus = RIDE_INACTIVE; $msg = _("Ride de-activated. From now on, this ride will not appear in the search results."); } else { if ($ride['Active'] == RIDE_INACTIVE) { $newStatus = RIDE_ACTIVE; $msg = _("Ride activated. You are back in business!"); } else { throw new Exception("Illegal status"); } }
$private = "<img src=\"images/greengo.gif\" title=\"public\">"; } if ($row_user["profileview"] == 1) { $private = "<img src=\"images/private2.png\" title=\"private\">"; } $users[$i]["private"] = $private; //private profile MrFix // DT arcade if ($row_user["trophy"] == 0) { $rra = ""; } if ($row_user["trophy"] == 1) { $rra = "<img src='images/crown.gif' alt='Arcade King' title='Arcade King' />"; } // DT arcade $users[$i]["username"] = "******"index.php?page=userdetails&id=" . $row_user["id"] . "\">" . unesc($row_user["prefixcolor"]) . unesc($row_user["username"]) . $udo . $udob . $ubir . $umal . $ufem . $uban . $uwar . $upar . $ubot . $utrmu . $utrmo . $uvimu . $uvimo . $ufrie . $ujunk . $ustaf . $usys . $banp . $imm . get_user_icons($row_user) . warn($row_user) . booted($row_user) . $upr . $rra . unesc($row_user["suffixcolor"]) . "</a>"; $users[$i]["userlevel"] = $row_user["level"]; $users[$i]["joined"] = $joined; $users[$i]["lastconnect"] = $lastconnect; $users[$i]["flag"] = $flag; //user ratio if ($row_user["profileview"] == 0 || $CURUSER["uid"] == $row_user["id"]) { if (intval($row_user["downloaded"]) > 0) { $ratio = number_format($row_user["uploaded"] / $row_user["downloaded"], 2); } else { $ratio = '∞'; } } else { $ratio = "<img src=\"images/private2.png\" title=\"private\">"; } $users[$i]["ratio"] = $ratio;
function post_index($max = 12500, $batchsize = 300) { if ($this->is_active()) { die("Another process is active!"); } $this->ping(); ignore_user_abort(true); $batchsize = max(5, intval($batchsize)); $pdo = $this->services->getDB(); $pdo->exec("truncate bayeswordsh_s"); $pdo->exec("truncate linkswordsh_s"); $base = new SblamBase($pdo); $bayes = new SblamTestBayes(array(), $this->services); $done = 0; $failures = 0; $wait = 0; $maxspam = 600; while ($max--) { $this->ping(); $sort = rand() & 64 ? 'DESC' : ''; $doneinbatch = 0; foreach ($pdo->query("/*maxtime20*/SELECT id FROM posts_meta\n WHERE (added IS NULL OR added = 0) AND (manualspam IS NOT NULL OR (abs(spamscore)>20 AND spamcert > 90)) AND spamscore < {$maxspam}\n ORDER BY id {$sort} LIMIT {$batchsize}")->fetchAll(PDO::FETCH_ASSOC) as $res) { $doneinbatch++; $post = $base->getPostById($res['id']); if (!$post) { $failures++; warn($res['id'], "Can't find post"); continue; } $poststarttime = microtime(true); $this->ping(); list($spamscore, $spamcert) = $post->getSpamScore(); $howmuch = 1; if (!$post->bayesadded && ($post->manualspam !== NULL || abs($spamscore) > 0.9)) { $isspam = $post->manualspam !== NULL ? $post->manualspam : ($spamscore > 0 ? 1 : 0); if ($post->manualspam !== NULL && $post->manualspam == 0 || $spamscore < -2.5) { $howmuch = 3; } if (!$bayes->addPost($post, $isspam, $howmuch)) { $failures++; warn("Failed to add post " . $post->getPostId()); continue; } if (!$pdo->exec("/*maxtime15*/UPDATE posts_meta set added=1{$howmuch}\n WHERE (added=0 or added is null) and id= '" . addslashes($post->getPostId()) . "'")) { warn($post->getPostId(), "update of post failed"); break; } } $done++; $postchecktime = microtime(true) - $poststarttime; $load = sys_getloadavg(); $load = max($load[0] - 0.4, $load[1] / 2, $load[2] / 3, 0); if ($load < 1) { $load /= 3; } elseif ($load >= 2.2) { $load *= 3; } $load = max($load, $postchecktime); $wait += $load; $this->ping(); echo "#{$done}; {$failures} fail; id{$res['id']}; score {$spamscore} * {$howmuch}; load {$load}; wait " . round(0.1 * $wait, 1) . "\n<br>"; flush(); usleep(100000 * $load); } if (!$doneinbatch) { sleep(5); $maxspam += 40 + $maxspam / 10; if ($maxspam > 1500) { break; } } else { if ($maxspam > 400) { $maxspam -= 10; } } } $this->ended(); return array('done' => $done, 'failed' => $failures, 'waited' => round(0.1 * $wait), 'waitperpost' => round(0.1 * $wait / $done, 2)); }
/** @return 0 on not-found, false on error, str or array on success. */ function getResult($blocking = true) { $res = $this->getRawResult($blocking); if ($res) { $out = array(); foreach ($res->answer as $rr) { if ($rr instanceof Net_DNS_RR_A) { $out[] = $rr->address; } elseif ($rr instanceof Net_DNS_RR_PTR) { return $rr->ptrdname; } elseif ($rr instanceof Net_DNS_RR_NS) { $out[] = $rr->nsdname; } elseif ($rr instanceof Net_DNS_RR_CNAME) { $temp = gethostbynamel($rr->cname); if ($temp) { $out = array_merge($out, $temp); } } else { warn($rr, "Unusable record type"); } } if ($this->resolverskey) { unset(self::$resolvers[$this->resolverskey]); } return $out; } return $res; }
} else { $torrenttpl->set("INSERT_COMMENT", false, TRUE); } $comments = array(); $count = 0; foreach ($subres as $subrow) { $level = get_result("SELECT level FROM {$TABLE_PREFIX}users_level WHERE id_level='{$subrow['id_level']}'", true, $btit_settings['cache_duration']); $lvl = $level[0]; if (!$subrow[uid]) { $title = "orphaned"; } elseif (!"{$subrow['custom_title']}") { $title = "" . $lvl['level'] . ""; } else { $title = unesc($subrow["custom_title"]); } $comments[$count]["user"] = "******"index.php?page=userdetails&id=" . $subrow["uid"] . "\">" . unesc($subrow["user"]) . warn($row) . "</a>"; $comments[$count]["user"] .= "</a><br/> " . $title; $comments[$count]["date"] = date("d/m/Y H.i.s", $subrow["data"] - $offset); $comments[$count]["elapsed"] = "(" . get_elapsed_time($subrow["data"]) . " ago)"; $comments[$count]["avatar"] = "<img onload=\"resize_avatar(this);\" src=\"" . ($subrow["avatar"] && $subrow["avatar"] != "" ? htmlspecialchars($subrow["avatar"]) : "{$STYLEURL}/images/default_avatar.gif") . "\" alt=\"\" />"; $comments[$count]["ratio"] = "<img src=\"images/arany.png\"> " . (intval($subrow['downloaded']) > 0 ? number_format($subrow['uploaded'] / $subrow['downloaded'], 2) : "---"); $comments[$count]["uploaded"] = "<img src=\"images/speed_up.png\"> " . makesize($subrow["uploaded"]); $comments[$count]["downloaded"] = "<img src=\"images/speed_down.png\"> " . makesize($subrow["downloaded"]); // only users able to delete torrents can delete comments... if ($CURUSER["delete_torrents"] == "yes") { $comments[$count]["delete"] = "<a onclick=\"return confirm('" . str_replace("'", "\\'", $language["DELETE_CONFIRM"]) . "')\" href=\"index.php?page=comment&id=" . $row["info_hash"] . "&cid=" . $subrow["id"] . "&action=delete\">" . image_or_link("{$STYLEPATH}/images/delete.png", "", $language["DELETE"]) . "</a>"; } $comments[$count]["comment"] = format_comment($subrow["text"]); $count++; } unset($subrow);
/** * Get an assoziative array [Chromosome] => [length]. Used by regions.php. * @param $db compara * @param $species_name species name in compara syntax eg. rattus_norvegicus */ function getChromosomesAndLengths($db, $species_name) { $sqlChromosomes = 'SELECT d.name, d.length ' . 'FROM dnafrag as d ' . ' INNER JOIN genome_db as g on ( ' . ' g.genome_db_id = d.genome_db_id ' . ' AND g.genome_db_id = (select genome_db_id from genome_db where name = "' . $species_name . '") ' . ' AND d.coord_system_name = "chromosome"' . ')'; $resultChromosomes = $db->query($sqlChromosomes) or trigger_error('Query failed: ' . $db->error); if (!$resultChromosomes->num_rows) { warn('getChromosomesAndLengths(): No cromosomes found to species with name: "' . $species_name . '"!'); return array(); } $chrs = array(); while ($row = $resultChromosomes->fetch_assoc()) { $n = $row['name']; $chrs["{$n}"] = $row['length']; } $resultChromosomes->close(); return $chrs; }
/** * Read in the routes.json config * * @return array Assoc array of decoded JSON config */ function getRoutes() { // Read in the JSON_CONFIG_FILE if (!($data = @file_get_contents($GLOBALS['JSON_CONFIG_FILE']))) { warn("No config data found in {$GLOBALS['JSON_CONFIG_FILE']}, or file is not readable"); return null; } // Remove comments from the JSON string before we parse it // Comments aren't technically part of the JSON spec but especially when hand-editing config files, // it's real nice to have them. // // This is a very simple parser, it just removes // comments and doesn't pay attention // to any sort of spacing etc. That's OK since the string "//" should never appear in // our config anyway, as simple as it currently is. $data = preg_replace(",\\s*//.*,", "", $data); // logMessage("JSON data after preg_replace:\n", $data); // DEBUG // decode the JSON into an object $json = json_decode($data); if ($json === null) { warn("Cannot parse json data in {$GLOBALS['JSON_CONFIG_FILE']}"); return null; } // Convert the JSON object into an assoc array $vars = expectObjectGetArray($json, "Invalid data contained in {$GLOBALS['JSON_CONFIG_FILE']}"); // Make sure at the VERY LEAST there are remotes defined in this array if (!isset($vars['remotes'])) { warn("No remotes specified in {$GLOBALS['JSON_CONFIG_FILE']}, treating config as empty"); return null; } return $vars; }