Ejemplo n.º 1
1
 /**
  * logs failed request api call including options and error message
  *
  * @param string $scope
  * @param string $name
  * @param array $opts
  * @param string $message
  * @return boolean
  */
 public function errorLog($scope, $name, $opts, $message)
 {
     // stop measure the response time
     $this->stop();
     $this->logger->error(sprintf('failed: %s to %s (%2.4fs), message: %s', Config::getInstance()->http_post ? 'POST' : 'GET', $this->formatUrl($scope, $name, $opts), $this->responseTime, $message));
     return true;
 }
Ejemplo n.º 2
0
 /**
  * @param integer $keyID
  * @param string $vCode
  */
 public static function getPheal($keyID = null, $vCode = null)
 {
     global $phealCacheLocation, $apiServer, $baseAddr, $ipsAvailable;
     \Pheal\Core\Config::getInstance()->http_method = "curl";
     \Pheal\Core\Config::getInstance()->http_user_agent = "API Fetcher for http://{$baseAddr}";
     if (!empty($ipsAvailable)) {
         $max = count($ipsAvailable) - 1;
         $ipID = mt_rand(0, $max);
         \Pheal\Core\Config::getInstance()->http_interface_ip = $ipsAvailable[$ipID];
     }
     \Pheal\Core\Config::getInstance()->http_post = false;
     \Pheal\Core\Config::getInstance()->http_keepalive = true;
     // default 15 seconds
     \Pheal\Core\Config::getInstance()->http_keepalive = 10;
     // KeepAliveTimeout in seconds
     \Pheal\Core\Config::getInstance()->http_timeout = 30;
     if ($phealCacheLocation != null) {
         \Pheal\Core\Config::getInstance()->cache = new \Pheal\Cache\FileStorage($phealCacheLocation);
     }
     \Pheal\Core\Config::getInstance()->log = new PhealLogger();
     \Pheal\Core\Config::getInstance()->api_customkeys = true;
     \Pheal\Core\Config::getInstance()->api_base = $apiServer;
     if ($keyID != null && $vCode != null) {
         $pheal = new \Pheal\Pheal($keyID, $vCode);
     } else {
         $pheal = new \Pheal\Pheal();
     }
     return $pheal;
 }
Ejemplo n.º 3
0
 /**
  * @param int    $keyID
  * @param string $vCode
  */
 public static function getPheal($keyID = null, $vCode = null, $overRide = false)
 {
     if ($overRide == false) {
         return;
     }
     global $apiServer, $baseAddr, $ipsAvailable;
     if (!$overRide) {
         if (php_sapi_name() == 'cli') {
             exit;
         }
         return;
         // Web requests shouldn't be hitting the API...
     }
     \Pheal\Core\Config::getInstance()->http_method = 'curl';
     \Pheal\Core\Config::getInstance()->http_user_agent = "API Fetcher for http://{$baseAddr}";
     if (!empty($ipsAvailable)) {
         $max = count($ipsAvailable) - 1;
         $ipID = mt_rand(0, $max);
         \Pheal\Core\Config::getInstance()->http_interface_ip = $ipsAvailable[$ipID];
     }
     \Pheal\Core\Config::getInstance()->http_post = false;
     \Pheal\Core\Config::getInstance()->http_keepalive = true;
     // default 15 seconds
     \Pheal\Core\Config::getInstance()->http_keepalive = 10;
     // KeepAliveTimeout in seconds
     \Pheal\Core\Config::getInstance()->http_timeout = 30;
     \Pheal\Core\Config::getInstance()->api_customkeys = true;
     \Pheal\Core\Config::getInstance()->api_base = $apiServer;
     if ($keyID !== null && $vCode !== null) {
         $pheal = new \Pheal\Pheal($keyID, $vCode);
     } else {
         $pheal = new \Pheal\Pheal();
     }
     return $pheal;
 }
Ejemplo n.º 4
0
 public static function bootstrap()
 {
     // Configure Pheal
     PhealConfig::getInstance()->cache = new \Pheal\Cache\FileStorage(storage_path() . '/cache/phealcache/');
     PhealConfig::getInstance()->access = new \Pheal\Access\StaticCheck();
     PhealConfig::getInstance()->log = new \Pheal\Log\FileStorage(storage_path() . '/logs/');
     PhealConfig::getInstance()->api_customkeys = true;
     PhealConfig::getInstance()->http_method = 'curl';
     // Build a meaningful User-Agent for CCP should they need to contact someone
     $user_agent = 'SeAT ' . \Config::get('seat.version') . ' API Fetcher at ' . \Config::get('app.url');
     // Add the Url
     // If the administrative_contact is set, add this to the User-Agent, else use the
     // default mail_from in the settings
     if (Settings::getSetting('administrative_contact') == null) {
         $user_agent .= ' Install mail_from: ' . \Config::get('mail.from.name') . ' <' . \Config::get('mail.from.address') . '>';
     } else {
         $user_agent .= ' Administrative Contact: ' . Settings::getSetting('administrative_contact');
     }
     // Set the newly compiled User-Agent
     PhealConfig::getInstance()->http_user_agent = $user_agent;
     // Should the EVE api be determined as 'down', set the cache value for 'eve_api_down'
     // with a expiration of 30 minutes. We will also decrement the current error count
     // by 10 to allow for some calls to happen after the value has expired out of
     // cache
     if (\Cache::get('eve_api_error_count') >= \Config::get('seat.error_limit')) {
         \Cache::put('eve_api_down', true, 30);
         \Cache::decrement('eve_api_error_count', 10);
     }
     // Check if the EVE Api has been detected as 'down'.
     if (\Cache::has('eve_api_down')) {
         throw new Exception\APIServerDown();
     }
     // Disable the Laravel query log. Some of the API calls do.. a lot of queries :P
     \DB::connection()->disableQueryLog();
 }
Ejemplo n.º 5
0
 /**
  * Set the actual config instance, based on it creates a client instance
  */
 private function init()
 {
     if (!isset($this->config)) {
         $this->config = Config::getInstance();
         $this->client = new Client($this->generateClientConfiguration());
     }
 }
Ejemplo n.º 6
0
 /**
  * Bootstrap the application services.
  *
  * @return void
  */
 public function boot()
 {
     // Pheal setup (for XML API)
     PhealConfig::getInstance()->cache = new PredisStorage();
     PhealConfig::getInstance()->access = new StaticCheck();
     PhealConfig::getInstance()->http_user_agent = 'Reset app by Ortho Loess, hosted at ' . config('app.url');
     PhealConfig::getInstance()->api_base = config('xml_api.root', "https://api.eveonline.com/");
 }
Ejemplo n.º 7
0
 public function __construct(\Pheal\Cache\CanCache $cache = null, \Pheal\Access\CanCheck $access = null)
 {
     if ($cache) {
         \Pheal\Core\Config::getInstance()->cache = $cache;
     }
     if ($access) {
         \Pheal\Core\Config::getInstance()->access = $access;
     }
 }
Ejemplo n.º 8
0
 /**
  *
  */
 protected static function setupPheal()
 {
     // configure logging
     self::$logger = new Logger(Config::Instance()->log_name);
     self::$logger->pushHandler(Config::Instance()->log_handler);
     // only setup cache folders the first time the api setup method is called
     if (self::$scopeType === null) {
         PhealConfig::getInstance()->access = new PhealAccessStaticCheck();
         PhealConfig::getInstance()->http_user_agent = Config::Instance()->user_agent;
     }
 }
 public function setUp()
 {
     $this->runCommand('doctrine:database:drop', array('--connection' => 'eveapi', '--force' => true));
     $this->runCommand('doctrine:database:create', array('--connection' => 'eveapi', '--no-interaction' => true));
     $out = $this->runCommand('doctrine:migrations:migrate', array('--em' => 'eveapi', '--no-interaction' => true));
     $this->assertContains('++ migrated', $out, 'Doctrine Migrations Failed');
     $this->assertNotContains('Exception', $out, 'Doctrine Migrations Failed');
     $this->entityManager = $this->get('doctrine.orm.eveapi_entity_manager');
     $phealConfig = Config::getInstance();
     $phealConfig->cache = new ForcedFileStorage(__DIR__ . '/../Fixtures/Api/');
 }
Ejemplo n.º 10
0
 /**
  * @param Pheal $pheal
  * @param Userbot $userbot
  */
 function __construct(Userbot $userbot)
 {
     $this->pheal = new Pheal();
     $this->userbot = $userbot;
     if (env('PHEAL_CACHE') == 'database') {
         $dbSettings = config('database.connections.mysql');
         PhealConfig::getInstance()->cache = new \Pheal\Cache\PdoStorage($dbSettings['driver'] . ':host=' . $dbSettings['host'] . ';dbname=' . $dbSettings['database'], $dbSettings['username'], $dbSettings['password']);
     } else {
         //PhealConfig::getInstance()->cache = new \Pheal\Cache\FileStorage(storage_path().'/app/phealCache/');
         PhealConfig::getInstance()->cache = new \Pheal\Cache\PredisStorage();
     }
     PhealConfig::getinstance()->access = new \Pheal\Access\StaticCheck();
 }
Ejemplo n.º 11
0
 /**
  * @return \Pheal\Pheal
  */
 public static function setup_pheal()
 {
     $config = Config::getInstance();
     // Configure Pheal
     $config->cache = new NullStorage();
     $config->log = new NullLogStorage();
     $config->api_customkeys = true;
     $config->http_method = 'curl';
     $config->http_timeout = 60;
     // TODO: Setup the identifying User-Agent
     $config->http_user_agent = 'SeAT Test Suite Client';
     return new Pheal();
 }
Ejemplo n.º 12
0
 private function configurePheal(Kernel $kernel, $userAgent, LoggerInterface $logger)
 {
     $config = Config::getInstance();
     $cacheDir = $kernel->getCacheDir() . '/pheal/';
     if (!is_dir($cacheDir)) {
         if (false === @mkdir($cacheDir, 0777, true)) {
             throw new \RuntimeException(sprintf('Could not create cache directory "%s".', $cacheDir));
         }
     }
     $config->cache = new HashedNameFileStorage($cacheDir);
     $config->access = new StaticCheck();
     $config->rateLimiter = new FileLockRateLimiter($cacheDir);
     $config->log = new PsrLogger($logger);
     $config->http_user_agent = $userAgent;
 }
Ejemplo n.º 13
0
 public function configurePheal(array $bundle_config)
 {
     $config = Config::getInstance();
     if (!is_dir($bundle_config['cache_dir'])) {
         if (false === @mkdir($bundle_config['cache_dir'], 0777, true)) {
             throw new \RuntimeException(sprintf('Could not create cache directory "%s".', $bundle_config['cache_dir']));
         }
     }
     $config->cache = new HashedNameFileStorage($bundle_config['cache_dir']);
     $config->access = new StaticCheck();
     $config->rateLimiter = new FileLockRateLimiter($bundle_config['cache_dir']);
     $config->log = new PsrLogger($bundle_config['logger']);
     $config->http_user_agent = $bundle_config['user_agent'];
     $config->http_ssl_verifypeer = $bundle_config['verify_peer'];
 }
Ejemplo n.º 14
0
 /**
  * @param RenaApp $app
  */
 function __construct(RenaApp $app)
 {
     $this->app = $app;
     Config::getInstance()->http_method = "curl";
     Config::getInstance()->http_user_agent = $app->baseConfig->getConfig("userAgent", "site", "API DataGetter from projectRena (karbowiak@gmail.com)");
     Config::getInstance()->http_post = false;
     Config::getInstance()->http_keepalive = 10;
     // 10 seconds keep alive
     Config::getInstance()->http_timeout = 30;
     Config::getInstance()->cache = new \Pheal\Cache\RedisStorage(array("host" => $app->baseConfig->getConfig("host", "redis", "127.0.0.1"), "port" => $app->baseConfig->getConfig("port", "redis", 6379), "persistent" => true, "auth" => null, "prefix" => "Pheal"));
     $psrLogger = new \Monolog\Logger("PhealLogger");
     $psrLogger->pushHandler(new \Monolog\Handler\StreamHandler(__DIR__ . "/../../logs/pheal.log", Logger::INFO));
     Config::getInstance()->log = new \Pheal\Log\PsrLogger($psrLogger);
     Config::getInstance()->api_customkeys = true;
     Config::getInstance()->api_base = $app->baseConfig->getConfig("apiServer", "ccp", "https://api.eveonline.com/");
     Config::getInstance()->rateLimiter = new \Pheal\RateLimiter\FileLockRateLimiter(__DIR__ . "/../../cache", 100, 60, 30);
 }
Ejemplo n.º 15
0
 function __construct()
 {
     // Configure Pheal
     Config::getInstance()->cache = new FileCache(WORKING_DIR . '/tmp/cache/');
     Config::getInstance()->access = new StaticCheck();
     Config::getInstance()->log = new FileLog(WORKING_DIR . '/tmp/log/');
     Config::getInstance()->http_ssl_verifypeer = false;
     Config::getInstance()->http_user_agent = USER_AGENT;
     // Load and configure classes
     $this->pheal = new Pheal(API_KEYID, API_VCODE);
     $this->cache = new Cacher();
     $options = $this->GetClientOptions();
     $guzzle = new Client($options);
     $this->slack = new ApiClient(SLACK_TOKEN, $guzzle);
     $this->payload = new ChatPostMessagePayload();
     $this->payload->setChannel(SLACK_CHANNEL);
     $this->payload->setUsername(SLACK_USERNAME);
 }
Ejemplo n.º 16
0
 /**
  * Set the configuration parameters for Pheal
  */
 public function __construct()
 {
     // Just return the instance if we have already
     // configured it
     if ($this->instance !== null) {
         return $this->instance;
     }
     // Get a Pheal 'instance'
     $config = Config::getInstance();
     // Configure Pheal
     $config->access = new EveApiAccess();
     $config->cache = new HashedNameFileStorage(config('eveapi.config.pheal.cache_path'));
     $config->log = new PsrLogger($this->getPhealLogger());
     $config->fetcher = app('Pheal\\Fetcher\\Guzzle');
     $config->api_customkeys = true;
     $config->http_timeout = 60;
     // Compile a user-agent string
     $config->http_user_agent = 'eveseat/' . config('eveapi.config.version') . ' ' . Seat::get('admin_contact');
     // Set the instance
     $this->instance = $config;
     return $this->instance;
 }
Ejemplo n.º 17
0
 /**
  * returns formatted url for logging
  *
  * @param string $scope
  * @param string $name
  * @param array $opts
  * @param bool $truncateKey
  * @return string
  */
 protected function formatUrl($scope, $name, $opts, $truncateKey = true)
 {
     // create url
     $url = Config::getInstance()->api_base . $scope . '/' . $name . '.xml.aspx';
     // truncacte apikey for log safety
     if ($truncateKey && count($opts)) {
         if (isset($opts['apikey'])) {
             $opts['apikey'] = substr($opts['apikey'], 0, 16) . '...';
         }
         if (isset($opts['vCode'])) {
             $opts['vCode'] = substr($opts['vCode'], 0, 16) . '...';
         }
     }
     // add post data
     if (Config::getInstance()->http_post) {
         $url .= ' DATA: ' . http_build_query($opts, '', '&');
     } elseif (count($opts)) {
         // add data to url
         $url .= '?' . http_build_query($opts, '', '&');
     }
     return $url;
 }
Ejemplo n.º 18
0
 $keyID = $row['keyID'];
 $vCode = $row['vCode'];
 $userID = $row['userID'];
 if (!isset($row['characters'])) {
     $row['characters'] = [];
 }
 $errorCode = (int) @$row['errorCode'];
 if ($errorCode == 0 || $errorCode == 221) {
     \Pheal\Core\Config::getInstance()->http_user_agent = "API Fetcher for https://{$baseAddr}";
     \Pheal\Core\Config::getInstance()->http_post = false;
     \Pheal\Core\Config::getInstance()->http_keepalive = true;
     // default 15 seconds
     \Pheal\Core\Config::getInstance()->http_keepalive = 10;
     // KeepAliveTimeout in seconds
     \Pheal\Core\Config::getInstance()->http_timeout = 30;
     \Pheal\Core\Config::getInstance()->api_customkeys = true;
     $pheal = new \Pheal\Pheal($keyID, $vCode);
     try {
         $apiKeyInfo = $pheal->ApiKeyInfo();
     } catch (Exception $ex) {
         $tqApis->remove($row);
         // Problem with api the key, remove it from rotation
         $errorCode = (int) $ex->getCode();
         if ($errorCode == 904) {
             Util::out("(apiProducer) 904'ed");
             exit;
         }
         if ($errorCode == 28) {
             Util::out('(apiProducer) API Server timeout');
             exit;
         }
<?php

use Pheal\Pheal;
use Pheal\Core\Config;
Config::getInstance()->cache = new \Pheal\Cache\PdoStorage('mysql:host=@db.host@;dbname=@db.name.ecp@', '@db.user@', '@db.pass@', 'phealng-cache', array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'@db.charset@\''));
Ejemplo n.º 20
0
 /**
  * method will ask caching class for valid xml, if non valid available
  * will make API call, and return the appropriate result
  *
  * @param string $scope api scope (examples: eve, map, server, ...)
  * @param string $name api method (examples: ServerStatus, Kills, Sovereignty, ...)
  * @param array $opts additional args (example.: characterID => 12345), shouldn't contain apikey/userid/keyid/vcode
  *
  * @throws \Pheal\Exceptions\ConnectionException
  * @throws \Pheal\Exceptions\PhealException
  * @throws \Pheal\Exceptions\HTTPException
  * @throws \Exception
  * @return \Pheal\Core\Result
  */
 private function requestXml($scope, $name, array $opts = array())
 {
     $opts = array_merge(Config::getInstance()->additional_request_parameters, $opts);
     // apikey/userid/keyid|vcode shouldn't be allowed in arguments and removed to avoid wrong cached api calls
     foreach ($opts as $k => $v) {
         if (in_array(strtolower($k), array('userid', 'apikey', 'keyid', 'vcode'))) {
             unset($opts[$k]);
         }
     }
     // prepare http arguments + url (to not modify original argument list for cache saving)
     $url = Config::getInstance()->api_base . $scope . '/' . $name . '.xml.aspx';
     $use_customkey = (bool) Config::getInstance()->api_customkeys;
     $http_opts = $opts;
     if ($this->userid) {
         $http_opts[$use_customkey ? 'keyID' : 'userid'] = $this->userid;
     }
     if ($this->key) {
         $http_opts[$use_customkey ? 'vCode' : 'apikey'] = $this->key;
     }
     // check access level if given (throws PhealAccessExpception if API call is not allowed)
     if ($use_customkey && $this->userid && $this->key && $this->keyType) {
         try {
             Config::getInstance()->access->check($scope, $name, $this->keyType, $this->accessMask);
         } catch (\Exception $e) {
             Config::getInstance()->log->errorLog($scope, $name, $http_opts, $e->getMessage());
             throw $e;
         }
     }
     // check cache first
     if (!($this->xml = Config::getInstance()->cache->load($this->userid, $this->key, $scope, $name, $opts))) {
         try {
             // start measure the response time
             Config::getInstance()->log->start();
             // rate limit
             Config::getInstance()->rateLimiter->rateLimit();
             $config = Config::getInstance();
             // request
             $this->xml = $config->fetcher->fetch($url, $http_opts);
             // stop measure the response time
             Config::getInstance()->log->stop();
             $element = @new \SimpleXMLElement($this->xml);
             // check if we could parse this
             if ($element === false) {
                 $errmsgs = '';
                 foreach (libxml_get_errors() as $error) {
                     $errmsgs .= $error->message . "\n";
                 }
                 throw new PhealException('XML Parser Error: ' . $errmsgs);
             }
             // archive+save only non-error api calls + logging
             if (!$element->error) {
                 Config::getInstance()->log->log($scope, $name, $http_opts);
                 Config::getInstance()->archive->save($this->userid, $this->key, $scope, $name, $opts, $this->xml);
             } else {
                 Config::getInstance()->log->errorLog($scope, $name, $http_opts, $element->error['code'] . ': ' . $element->error);
             }
             Config::getInstance()->cache->save($this->userid, $this->key, $scope, $name, $opts, $this->xml);
             // just forward HTTP Errors
         } catch (HTTPException $e) {
             throw $e;
             // ensure that connection exceptions are passed on
         } catch (ConnectionException $e) {
             throw $e;
             // other request errors
         } catch (\Exception $e) {
             // log + throw error
             Config::getInstance()->log->errorLog($scope, $name, $http_opts, $e->getCode() . ': ' . $e->getMessage());
             throw new PhealException('Original exception: ' . $e->getMessage(), $e->getCode(), $e);
         }
     } else {
         $element = @new \SimpleXMLElement($this->xml);
     }
     return new Result($element);
 }
Ejemplo n.º 21
0
<?php

require_once 'includes/header.php';
use Pheal\Pheal;
use Pheal\Core\Config;
Config::getInstance()->cache = new \Pheal\Cache\MemcacheStorage();
Config::getInstance()->access = new \Pheal\Access\StaticCheck();
// Getting the compliance type
if ($request['action'] == 'api') {
    if ($request['value'] == 'refresh') {
        $key = new ApiKey($_POST['keyID'], $_POST['vCode'], $_POST['uid'], $db);
        if ($key->getKeyStatus() == 1 and $key->getAccessMask() & MINIMUM_API) {
            $update = $key->updateApiKey();
            if ($update) {
                foreach ($key->getCharacters() as $character) {
                    $char = new Character($character['characterID'], $key->getKeyID(), $key->getVCode(), $key->getAccessMask(), $db, $user);
                    if ($char->getExistance() or $char->getExistance() == FALSE) {
                        $char->updateCharacterInfo();
                    }
                }
                $refresh = $key->refreshAPIKey();
                setAlert('success', 'API Key Refreshed', 'The API key has been successfully refreshed.');
            }
        } elseif (!($key->getAccessMask() & MINIMUM_API) and $key->getKeyStatus() == 1) {
            setAlert('danger', 'The API Key Does Not Meet Minimum Requirements', 'The required minimum Access Mask for API keys is ' . MINIMUM_API . '. Please create a new key using the Create Key link.');
        }
    }
    // We're doing API compliance
    $compliance_type = "API";
    // Getting a full API-pulled member list
    $pheal = new Pheal($settings->getCorpUserID(), $settings->getCorpVCode(), 'corp');
Ejemplo n.º 22
0
     $multi = $redis->multi();
     $multi->hSet("userID:api:{$userID}", $charID, true);
     $multi->expire("userID:api:{$userID}", 86400);
     $multi->setex("userID:api:{$userID}:{$charID}", 86400, serialize(['charID' => $charID, 'keyID' => $keyID, 'time' => time(), 'type' => $type]));
     $multi->exec();
 }
 $charCorp = $type == 'Corporation' ? 'corp' : 'char';
 $killsAdded = 0;
 \Pheal\Core\Config::getInstance()->http_method = 'curl';
 \Pheal\Core\Config::getInstance()->http_user_agent = "API Fetcher for https://{$baseAddr}";
 \Pheal\Core\Config::getInstance()->http_post = false;
 \Pheal\Core\Config::getInstance()->http_keepalive = 30;
 // KeepAliveTimeout in seconds
 \Pheal\Core\Config::getInstance()->http_timeout = 60;
 \Pheal\Core\Config::getInstance()->api_customkeys = true;
 \Pheal\Core\Config::getInstance()->api_base = 'https://api.eveonline.com/';
 $pheal = new \Pheal\Pheal($keyID, $vCode);
 $charCorp = $type == 'Corporation' ? 'corp' : 'char';
 $pheal->scope = $charCorp;
 $result = null;
 $params = array();
 $params['characterID'] = $charID;
 $result = null;
 try {
     $result = $pheal->KillMails($params);
 } catch (Exception $ex) {
     $errorCode = $ex->getCode();
     if ($errorCode == 904) {
         Util::out("(apiConsumer) 904'ed...");
         exit;
     }
Ejemplo n.º 23
0
<?php

use Pheal\Pheal;
use Pheal\Core\Config;
$phealConfig = Config::getInstance();
$phealConfig->access = new \Pheal\Access\StaticCheck();
$phealConfig->rateLimiter = new \Pheal\RateLimiter\FileLockRateLimiter('var/phealng');
$phealConfig->http_user_agent = "EVE Composition Planer";
$phealConfig->http_ssl_verifypeer = false;
Ejemplo n.º 24
0
 /**
  * logs failed request api call including options and error message
  *
  * @param string $scope
  * @param string $name
  * @param array $opts
  * @param string $message
  * @return boolean
  */
 public function errorLog($scope, $name, $opts, $message)
 {
     // stop measure the response time
     $this->stop();
     // get filename, return if disabled
     if (!($filename = $this->filename('error_log'))) {
         return false;
     }
     // remove htmltags, newlines, and coherent blanks
     $message = preg_replace("/(\\s\\s+|[\n\r])/", ' ', strip_tags($message));
     // log
     file_put_contents($filename, sprintf($this->options['error_format'], date('r'), Config::getInstance()->http_post ? 'POST' : 'GET', $this->responseTime, $this->formatUrl($scope, $name, $opts, $this->options['truncate_apikey']), $message), FILE_APPEND);
     return true;
 }
Ejemplo n.º 25
0
 /**
  * method will do the actual http call using curl libary.
  * you can choose between POST/GET via config.
  * will throw Exception if http request/curl times out or fails
  * @param String $url url beeing requested
  * @param array $opts an array of query paramters
  * @throws \Pheal\Exceptions\ConnectionException
  * @throws \Pheal\Exceptions\HTTPException
  * @return string raw http response
  */
 public function fetch($url, $opts)
 {
     // init curl
     if (!(is_resource(self::$curl) && get_resource_type(self::$curl) == 'curl')) {
         self::$curl = curl_init();
     }
     // custom user agent
     curl_setopt(self::$curl, CURLOPT_USERAGENT, 'PhealNG/' . Pheal::VERSION . ' ' . Config::getInstance()->http_user_agent);
     // custom outgoing ip address
     if (($http_interface_ip = Config::getInstance()->http_interface_ip) != false) {
         curl_setopt(self::$curl, CURLOPT_INTERFACE, $http_interface_ip);
     }
     // ignore ssl peer verification if needed
     if (substr($url, 0, 5) == 'https') {
         curl_setopt(self::$curl, CURLOPT_SSL_VERIFYPEER, Config::getInstance()->http_ssl_verifypeer);
         if (Config::getInstance()->http_ssl_verifypeer && Config::getInstance()->http_ssl_certificate_file !== false) {
             curl_setopt(self::$curl, CURLOPT_CAINFO, Config::getInstance()->http_ssl_certificate_file);
         }
     }
     // http timeout
     if (($http_timeout = Config::getInstance()->http_timeout) != false) {
         curl_setopt(self::$curl, CURLOPT_TIMEOUT, $http_timeout);
     }
     // use post for params
     if (count($opts) && Config::getInstance()->http_post) {
         curl_setopt(self::$curl, CURLOPT_POST, true);
         curl_setopt(self::$curl, CURLOPT_POSTFIELDS, $opts);
     } else {
         curl_setopt(self::$curl, CURLOPT_POST, false);
         // attach url parameters
         if (count($opts)) {
             $url .= '?' . http_build_query($opts, '', '&');
         }
     }
     // additional headers
     $headers = array();
     // enable/disable keepalive
     if (($http_keepalive = Config::getInstance()->http_keepalive) != false) {
         curl_setopt(self::$curl, CURLOPT_FORBID_REUSE, false);
         $http_keepalive = $http_keepalive === true ? 15 : (int) $http_keepalive;
         $headers[] = 'Connection: keep-alive';
         $headers[] = 'Keep-Alive: timeout=' . $http_keepalive . ', max=1000';
     } else {
         curl_setopt(self::$curl, CURLOPT_FORBID_REUSE, true);
     }
     // allow all encodings
     curl_setopt(self::$curl, CURLOPT_ENCODING, '');
     // curl defaults
     curl_setopt(self::$curl, CURLOPT_URL, $url);
     curl_setopt(self::$curl, CURLOPT_HTTPHEADER, $headers);
     curl_setopt(self::$curl, CURLOPT_RETURNTRANSFER, true);
     // call
     $result = curl_exec(self::$curl);
     $errno = curl_errno(self::$curl);
     $error = curl_error(self::$curl);
     // response http headers
     $httpCode = curl_getinfo(self::$curl, CURLINFO_HTTP_CODE);
     if (!Config::getInstance()->http_keepalive) {
         self::disconnect();
     }
     // http errors
     if ($httpCode >= 400) {
         // ccp is using error codes even if they send a valid application
         // error response now, so we have to use the content as result
         // for some of the errors. This will actually break if CCP ever uses
         // the HTTP Status for an actual transport related error.
         switch ($httpCode) {
             case 400:
             case 403:
             case 500:
             case 503:
                 return $result;
                 break;
             default:
         }
         throw new HTTPException($httpCode, $url);
     }
     // curl errors
     if ($errno) {
         throw new ConnectionException($error, $errno);
     } else {
         return $result;
     }
 }
Ejemplo n.º 26
0
 /**
  * method will do the actual http call using file()
  * @param String $url url beeing requested
  * @param array $opts an array of query paramters
  * @throws \Pheal\Exceptions\PhealException
  * @throws \Pheal\Exceptions\HTTPException
  * @return string raw http response
  */
 public function fetch($url, $opts)
 {
     // initialize this php abomination
     $php_errormsg = null;
     $options = array();
     $options['http'] = array();
     $options['http']['ignore_errors'] = true;
     // set custom user agent
     $options['http']['user_agent'] = 'PhealNG/' . Pheal::VERSION . ' ' . Config::getInstance()->http_user_agent;
     // set custom http timeout
     if (($http_timeout = Config::getInstance()->http_timeout) != false) {
         $options['http']['timeout'] = $http_timeout;
     }
     // ignore ssl peer verification if needed
     if (substr($url, 0, 5) == "https") {
         $options['ssl']['verify_peer'] = Config::getInstance()->http_ssl_verifypeer;
     }
     // use post for params
     if (count($opts) && Config::getInstance()->http_post) {
         $options['http']['method'] = 'POST';
         $options['http']['content'] = http_build_query($opts, '', '&');
     } elseif (count($opts)) {
         // else build url parameters
         $url .= "?" . http_build_query($opts, '', '&');
     }
     // set track errors. needed for $php_errormsg
     $oldTrackErrors = ini_get('track_errors');
     ini_set('track_errors', true);
     // create context with options and request api call
     // suppress the 'warning' message which we'll catch later with $php_errormsg
     if (count($options)) {
         $context = stream_context_create($options);
         $result = file_get_contents($url, false, $context);
     } else {
         $result = @file_get_contents($url);
     }
     // check for http errors via magic $http_response_header
     $httpCode = 200;
     if (isset($http_response_header[0])) {
         list($httpVersion, $httpCode, $httpMsg) = explode(' ', $http_response_header[0], 3);
     }
     // http errors
     if (is_numeric($httpCode) && $httpCode >= 400) {
         // ccp is using error codes even if they send a valid application
         // error response now, so we have to use the content as result
         // for some of the errors. This will actually break if CCP ever uses
         // the HTTP Status for an actual transport related error.
         switch ($httpCode) {
             case 400:
             case 403:
             case 500:
             case 503:
                 return $result;
                 break;
             default:
         }
         throw new \Pheal\Exceptions\HTTPException($httpCode, $url);
     }
     // throw error
     if ($result === false) {
         $message = $php_errormsg ? $php_errormsg : 'HTTP Request Failed';
         // set track_errors back to the old value
         ini_set('track_errors', $oldTrackErrors);
         throw new ConnectionException($message);
         // return result
     } else {
         // set track_errors back to the old value
         ini_set('track_errors', $oldTrackErrors);
         return $result;
     }
 }
Ejemplo n.º 27
0
Route::post('/apply', function () {
    // No point in getting an overly elaborate form validation going here.
    // Lets do this caveman style
    if (strlen(Input::get('keyID') <= 0) || !is_numeric(Input::get('keyID'))) {
        return View::make('ajax-form-errors')->withErrors(array('error' => 'The supplied keyID is invalid as its empty or not numeric!'));
    }
    if (strlen(Input::get('vCode')) <= 0 || strlen(Input::get('vCode')) != 64) {
        return View::make('ajax-form-errors')->withErrors(array('error' => 'The supplied vCode must be exactly 64 characters long'));
    }
    // Ok, looks like the key is valid! So, lets process it.
    PhealConfig::getInstance()->cache = new \Pheal\Cache\FileStorage(storage_path() . '/cache/phealcache/');
    PhealConfig::getInstance()->access = new \Pheal\Access\StaticCheck();
    PhealConfig::getInstance()->log = new \Pheal\Log\FileStorage(storage_path() . '/logs/');
    PhealConfig::getInstance()->http_user_agent = 'SeAT Recruitment Tool API Fetcher';
    PhealConfig::getInstance()->api_customkeys = true;
    PhealConfig::getInstance()->http_method = 'curl';
    $pheal = new Pheal(Input::get('keyID'), Input::get('vCode'));
    // Get API Key Information
    try {
        $key_info = $pheal->accountScope->APIKeyInfo();
    } catch (\Pheal\Exceptions\PhealException $e) {
        return View::make('ajax-form-errors')->withErrors(array('error' => $e->getCode() . ': ' . $e->getMessage()));
    }
    // Here, based on the type of key, we will either call some further information,
    // or just display what we have learned so far.
    if ($key_info->key->type == 'Corporation') {
        return View::make('ajax-form-errors')->withErrors(array('error' => 'It looks like you are trying to apply with a corporation key which simply wont work out.'));
    }
    // Get API Account Status Information
    try {
        $status_info = $pheal->accountScope->AccountStatus();