예제 #1
0
 static function logException(\Exception $e)
 {
     $requestURI = Dispatcher::getInstance()->getCalledURL();
     $requestURILine = sprintf(static::$messageConfigs['default']['line'], 'Request URI', $requestURI);
     $message = static::computeMessage($e, static::$messageConfigs['default'], array($requestURILine));
     \ManiaLib\Utils\Logger::error($message);
 }
예제 #2
0
 function serverAudience($serverLogin, $unit = 'day', $from = '-6 days', $to = 'now')
 {
     $service = new \ManiaHost\Services\AnalyticsService();
     $data = $service->getServerAudience($serverLogin, $unit, $from, $to);
     \ManiaLib\Utils\Logger::info($data);
     $abscissa = array();
     $avgValues = array();
     $maxValues = array();
     foreach ($data as $value) {
         $abscissa[] = $value[0];
         $avgValues[] = $value[1];
         $maxValues[] = $value[2];
     }
     $barChart = new \Google\ImageCharts\BarChart();
     $barChart->setSize(600, 200);
     $barChart->setTitle('Average audience on ' . $serverLogin);
     $barChart->setAbscissaAxis($abscissa);
     $barChart->setData($avgValues);
     $avgGraphUrl = $barChart->getUrl();
     $barChart = new \Google\ImageCharts\BarChart();
     $barChart->setSize(600, 200);
     $barChart->setTitle('Audience max on ' . $serverLogin);
     $barChart->setAbscissaAxis($abscissa);
     $barChart->setData($maxValues);
     $maxGraphUrl = $barChart->getUrl();
     $this->response->avgGraphUrl = $avgGraphUrl;
     $this->response->maxGraphUrl = $maxGraphUrl;
 }
예제 #3
0
 function inc($key)
 {
     $key = str_replace('\\', '/', $key);
     if (!$this->memcached->increment($key)) {
         $message = sprintf('Memcache::increment() with key "%s" failed', $key);
         \ManiaLib\Utils\Logger::error($message);
     }
 }
예제 #4
0
 function preFilter()
 {
     if ($this->session->get(static::SESS_AUTH_KEY)) {
         return;
     }
     if ($this->request->get('code')) {
         if ($this->request->get(self::SESS_NONCE_KEY)) {
             if ($this->request->get(self::SESS_NONCE_KEY) != $this->session->get(self::SESS_NONCE_KEY)) {
                 $this->request->delete('code');
                 $this->request->delete(self::SESS_NONCE_KEY);
                 $this->request->redirect('');
                 return;
             }
         }
         $tries = $this->session->get(static::SESS_AUTH_KEY . '-tries', 0);
         $tries++;
         if ($tries > static::RETRY) {
             $this->session->delete(static::SESS_AUTH_KEY . '-tries');
             throw new \ManiaLib\Application\UserException('Authentication failed');
         }
         $this->session->set(static::SESS_AUTH_KEY . '-tries', $tries);
     }
     $config = Config::getInstance();
     $username = $config->username;
     $password = $config->password;
     $this->oauth2 = new \Maniaplanet\WebServices\ManiaConnect\Player($username, $password);
     try {
         $player = $this->oauth2->getPlayer();
     } catch (\Maniaplanet\WebServices\Exception $e) {
         \ManiaLib\Utils\Logger::info(sprintf("MPWS Exception: HTTP %d %s - %s %d", $e->getHTTPStatusCode(), $e->getHTTPStatusMessage(), $e->getMessage(), $e->getCode()));
         $this->response->errorManialink = $this->request->createLink();
         $this->response->errorButtonMessage = 'Try again';
         throw new \ManiaLib\Application\SilentUserException('Authentication failed', 0, $e);
     }
     if (!$player) {
         $nonce = md5(uniqid());
         $this->session->set(self::SESS_NONCE_KEY, $nonce);
         $this->request->set(self::SESS_NONCE_KEY, $nonce);
         $loginURL = $this->oauth2->getLoginURL(Config::getInstance()->scope, $this->request->createLink('.'));
         $this->request->redirectAbsolute($loginURL);
         return;
     }
     $this->request->delete('code');
     $this->request->delete(self::SESS_NONCE_KEY);
     $this->session->set('login', $player->login);
     $this->session->set('nickname', $player->nickname);
     $this->session->set('path', $player->path);
     $this->session->set(static::SESS_AUTH_KEY, 1);
     $this->session->delete(static::SESS_AUTH_KEY . '-tries');
 }
예제 #5
0
 /**
  * @return RecordSet
  */
 function execute($query)
 {
     $mtime = microtime(true);
     if (func_num_args() > 1) {
         $query = call_user_func_array('sprintf', func_get_args());
     }
     $query = $this->instrumentQuery($query);
     $result = mysqli_query($this->connection, $query);
     if (!$result) {
         throw new QueryException(mysqli_error($this->connection) . ': ' . $query, mysqli_errno($this->connection));
     }
     if ($this->config->queryLog) {
         $mtime2 = round((microtime(true) - $mtime) * 1000);
         $message = str_pad($mtime2 . ' ms', 10, ' ') . $query;
         \ManiaLib\Utils\Logger::info($message);
     }
     if ($this->config->slowQueryLog) {
         $mtime2 = round((microtime(true) - $mtime) * 1000);
         if ($mtime2 > $this->config->slowQueryThreshold) {
             $message = str_pad($mtime2 . ' ms', 10, ' ') . $query;
             \ManiaLib\Utils\Logger::info($message);
         }
     }
     return new RecordSet($result);
 }
예제 #6
0
 function run()
 {
     if (file_exists($this->getPHPConfigFilename())) {
         require_once $this->getPHPConfigFilename();
     } else {
         $key = Cache::getPrefix() . get_called_class();
         $cache = $this->getCache();
         $values = $cache->fetch($key);
         if ($values === false) {
             $values = $this->loadFile($this->getINIConfigFilename());
             if (is_dir($this->getINIConfigDirectory())) {
                 foreach (glob($this->getINIConfigDirectory() . '*.ini') as $filename) {
                     $values = array_merge($values, $this->loadFile($filename));
                 }
             }
             $cache->add($key, $values, 600);
             $cached = true;
         }
         $this->arrayToSingletons($values);
         if (isset($cached)) {
             \ManiaLib\Utils\Logger::log('Config cached at ' . $key);
         }
     }
 }
예제 #7
0
 /**
  * @param string $path
  * @param bool $recursive
  * @param bool $isLaps
  * @param string[] $mapTypes
  * @param string $environment
  * @param int $offset
  * @param int $length
  * @return Map[]
  */
 function getList($path, $recursive = false, $isLaps = false, array $mapTypes = array(), $environment = '', $offset = null, $length = null)
 {
     $workPath = DedicatedFileService::securePath($this->mapDirectory . $path);
     $mapTypes = array_map('strtolower', $mapTypes);
     $maps = array();
     $path = str_ireplace('\\', '/', $path);
     $files = scandir($workPath);
     foreach ($files as $filename) {
         if (is_dir($workPath . '/' . $filename)) {
             if ($filename == '.' || $filename == '..') {
                 continue;
             }
             $file = new Directory();
             $file->filename = $filename;
             $file->path = $path;
             if ($recursive) {
                 $file->children = $this->getList($path . $filename . '/', $recursive, $isLaps, $mapTypes, $environment);
                 if ($file->children) {
                     $maps[] = $file;
                 }
             } else {
                 $maps[] = $file;
             }
         } else {
             if (preg_match('/\\.map\\.gbx$/ui', substr($filename, -8))) {
                 try {
                     $file = $this->get($filename, $path);
                     if ((!$isLaps || $isLaps && $file->nbLaps != 0) && (!$environment || $environment && $environment == $file->environment) && (!$mapTypes || $mapTypes && in_array(strtolower($file->type), $mapTypes, true))) {
                         $maps[] = $file;
                     }
                 } catch (\Exception $e) {
                     \ManiaLib\Utils\Logger::user('Cannot parse `' . $path . $filename . '`');
                 }
             }
         }
     }
     usort($maps, array(__CLASS__, 'compareFiles'));
     if ($offset !== null) {
         return array_slice($maps, $offset, $length);
     }
     return $maps;
 }
예제 #8
0
 function preFilter()
 {
     $version = self::getVersion();
     $minVersion = Config::getInstance()->minVersion;
     if ($version !== null && $minVersion !== null) {
         $versionTimestamp = self::version2timestamp($version);
         $minVersionTimestamp = self::version2timestamp($minVersion);
         if ($versionTimestamp < $minVersionTimestamp) {
             \ManiaLib\Utils\Logger::user('Maniaplanet not up-to-date: ' . $version);
             call_user_func(self::$errorPageCallback);
             exit;
         }
     }
 }
예제 #9
0
 /**
  * Executes a HTTP request on the API.
  *
  * The usage of the $ressource and $params parameters is similar to the use
  * of the sprintf() function. You can PUT sprintf() placeholders in the
  * $ressource, and the first elements of the $params array will be
  * urlencode'd and sprintf()'ed in the ressource. The last element of the
  * $params array will be serialized and used for request body if using
  * POST or PUT methods.
  *
  * Examples:
  * <code>
  * $obj->execute('GET', '/stuff/%s/', array('foobar')); // => /stuff/foobar/
  * $obj->execute('GET', '/stuff/%s/', array('foo bar')); // => /stuff/foo%20bar/
  * $obj->execute('GET', '/stuff/%s/%d/', array('foobar', 1)); // => /stuff/foobar/1/
  * $obj->execute('POST', '/stuff/', array($someDataToPost)); // => /stuff/
  * $obj->execute('POST', '/stuff/%s/', array('foobar', $someDataToPost)); // => /stuff/foobar/
  * </code>
  *
  * @param string $method The HTTP method to use. Only GET, POST, PUT and DELETE are supported for now.
  * @param string $ressource The ressource (path after the URL + query string)
  * @param array $params The parameters
  * @return mixed The unserialized API response
  * @throws \Maniaplanet\WebServices\Exception
  */
 protected function execute($method, $ressource, array $params = array())
 {
     $this->lastException = null;
     $url = $this->APIURL . $ressource;
     // If we need a request body, it's the last element of the params array
     // Otherwise it's null
     if ($method == 'POST' || $method == 'PUT') {
         $data = array_pop($params);
         if ($this->serializeCallback) {
             $data = call_user_func($this->serializeCallback, $data);
         }
     } else {
         $data = null;
     }
     // The rest of the params array is urlencode'd and sprintf'ed
     // into the ressource itself
     if ($params) {
         $params = array_map('urlencode', $params);
         array_unshift($params, $url);
         $url = call_user_func_array('sprintf', $params);
     }
     // Let's prepare the CURL request options and HTTP header
     $options = array();
     $header = array();
     $header['accept'] = 'Accept: ' . $this->accept;
     $header['content-type'] = 'Content-type: ' . $this->contentType;
     $header = array_merge($header, $this->headers);
     switch ($method) {
         case 'GET':
             // Nothing to do
             break;
         case 'POST':
             $options[CURLOPT_POST] = true;
             $options[CURLOPT_POSTFIELDS] = $data;
             break;
         case 'PUT':
             $fh = fopen('php://temp', 'rw');
             fwrite($fh, $data);
             rewind($fh);
             $options[CURLOPT_PUT] = true;
             $options[CURLOPT_INFILE] = $fh;
             $options[CURLOPT_INFILESIZE] = strlen($data);
             break;
         case 'DELETE':
             $options[CURLOPT_POST] = true;
             $options[CURLOPT_POSTFIELDS] = '';
             $options[CURLOPT_CUSTOMREQUEST] = 'DELETE';
             break;
         default:
             throw new \InvalidArgumentException('Unsupported HTTP method: ' . $method);
     }
     $options[CURLOPT_URL] = $url;
     $options[CURLOPT_HTTPHEADER] = $header;
     if ($this->enableAuth && $this->username) {
         $options[CURLOPT_HTTPAUTH] = CURLAUTH_BASIC;
         $options[CURLOPT_USERPWD] = $this->username . ':' . $this->password;
     }
     $options[CURLOPT_TIMEOUT] = 10;
     $options[CURLOPT_CONNECTTIMEOUT] = 10;
     $options[CURLOPT_RETURNTRANSFER] = true;
     $options[CURLOPT_USERAGENT] = 'maniaplanet-ws-sdk/' . self::VERSION;
     $options[CURLOPT_SSL_VERIFYHOST] = 0;
     $options[CURLOPT_SSL_VERIFYPEER] = 0;
     try {
         $ch = curl_init();
         curl_setopt_array($ch, $options);
         $responseBody = curl_exec($ch);
         $responseBodyRaw = $responseBody;
         $responseInfo = curl_getinfo($ch);
         // Instrumentation
         $this->lastRequestExecTime = round($responseInfo['total_time'] * 1000);
         if ($this->slowRequestThreshold) {
             if (class_exists('\\ManiaLib\\Utils\\Logger') && $this->lastRequestExecTime > $this->slowRequestThreshold) {
                 $message = sprintf('%s ms: %s %s', $this->lastRequestExecTime, $method, $url);
                 \ManiaLib\Utils\Logger::info($message);
             }
         }
         $curlError = curl_error($ch);
         $curlErrorNo = curl_errno($ch);
         curl_close($ch);
     } catch (\Exception $e) {
         if ($ch) {
             curl_close($ch);
         }
         throw $e;
     }
     if ($responseInfo['http_code'] == 200) {
         if ($responseBody) {
             if ($this->unserializeCallback) {
                 $responseBody = call_user_func($this->unserializeCallback, $responseBody);
             }
         }
         return $responseBody;
     } else {
         $message = $curlError;
         $code = $curlErrorNo;
         $statusCode = $responseInfo['http_code'];
         $statusMessage = null;
         if (array_key_exists($statusCode, self::$HTTPStatusCodes)) {
             $statusMessage = self::$HTTPStatusCodes[$statusCode];
         }
         if ($responseBody) {
             if ($this->unserializeCallback) {
                 $responseBody = call_user_func($this->unserializeCallback, $responseBody);
             }
             if (is_object($responseBody)) {
                 if (property_exists($responseBody, 'message')) {
                     $message = $responseBody->message;
                 } elseif (property_exists($responseBody, 'error')) {
                     $message = $responseBody->error;
                 }
                 if (property_exists($responseBody, 'code')) {
                     $code = $responseBody->message;
                 }
             }
         }
         $exception = new Exception($message, $code, $statusCode, $statusMessage);
         if ($this->throwExceptions) {
             throw $exception;
         } else {
             $this->lastException = $exception;
             return false;
         }
     }
 }
예제 #10
0
 function payExtend($idRent, $duration)
 {
     \ManiaLib\Utils\Logger::info((int) $idRent);
     $transactionObject = $this->session->getStrict('transaction-' . $this->session->login);
     $transactionService = new \ManiaHost\Services\TransactionService();
     if (!$transactionService->isPaid($transactionObject)) {
         throw new \ManiaLib\Application\UserException('You have to pay to rent the server');
     }
     $rentService = new \ManiaHost\Services\RentService();
     $rent = $rentService->get($idRent);
     \ManiaLib\Utils\Logger::info($rent);
     $rent->duration += $duration;
     $rentService->updateRent($rent);
     $this->request->redirectArgList('/rent/');
 }
예제 #11
0
 function delete($key)
 {
     if (!apc_delete($key)) {
         \ManiaLib\Utils\Logger::error('apc_delete(' . $key . ') failed');
     }
 }