Exemple #1
0
 /**
  * Parses a signed_request and validates the signature.
  *
  * @param string $signedRequest A signed token
  * @param string $appSecret
  *
  * @return array The payload inside it or null if the sig is wrong
  */
 public static function decode($signedRequest, $appSecret)
 {
     if (!$signedRequest || strpos($signedRequest, '.') === false) {
         Debugger::log('Signed request is invalid! ' . json_encode($signedRequest), 'facebook');
         return NULL;
     }
     list($encoded_sig, $payload) = explode('.', $signedRequest, 2);
     // decode the data
     $sig = Helpers::base64UrlDecode($encoded_sig);
     $data = Json::decode(Helpers::base64UrlDecode($payload), Json::FORCE_ARRAY);
     if (!isset($data['algorithm']) || strtoupper($data['algorithm']) !== Configuration::SIGNED_REQUEST_ALGORITHM) {
         Debugger::log("Unknown algorithm '{$data['algorithm']}', expected " . Configuration::SIGNED_REQUEST_ALGORITHM, 'facebook');
         return NULL;
     }
     // check sig
     $expected_sig = hash_hmac('sha256', $payload, $appSecret, $raw = TRUE);
     if (strlen($expected_sig) !== strlen($sig)) {
         Debugger::log('Bad Signed JSON signature! Expected ' . self::dump($expected_sig) . ', but given ' . self::dump($sig), 'facebook');
         return NULL;
     }
     $result = 0;
     for ($i = 0; $i < strlen($expected_sig); $i++) {
         $result |= ord($expected_sig[$i]) ^ ord($sig[$i]);
     }
     if ($result !== 0) {
         Debugger::log('Bad Signed JSON signature! Expected ' . self::dump($expected_sig) . ', but given ' . self::dump($sig), 'facebook');
         return NULL;
     }
     return $data;
 }
 /**
  * @param  Exception
  * @return void
  */
 public function renderDefault($exception)
 {
     if ($exception) {
         $data = array('error_msg' => $exception->getMessage(), 'upd_process_id' => 'ErrorPresenter::renderDefault()');
         if (isset($this->lastLogItem) && is_object($this->lastLogItem)) {
             $this->logger->updateLogVisit($this->lastLogItem->id, $data);
         }
     }
     if ($this->isAjax()) {
         // AJAX request? Just note this error in payload.
         $this->payload->error = TRUE;
         $this->terminate();
     } elseif ($exception instanceof NA\BadRequestException || $exception instanceof HQ\UnauthorizedAccessException) {
         $code = $exception->getCode();
         if ($exception instanceof HQ\UnauthorizedAccessException) {
             // Unathorized access in admin
             $this->setView("admin403");
         } else {
             // load template 403.latte or 404.latte or ... 4xx.latte
             $this->setView(in_array($code, array(403, 404, 405, 410, 500)) ? $code : '4xx');
         }
         // log to access.log
         Debugger::log("HTTP code {$code}: {$exception->getMessage()} in {$exception->getFile()}:{$exception->getLine()}", 'access');
     } else {
         $this->setView('500');
         // load template 500.latte
         $this->logger->logError($exception, 'exception', 'ErrorPresenter::LOG_EXCEPTION');
     }
 }
 protected function createComponentAddSetting()
 {
     $form = new Form();
     $form->addText('key', 'Klíč')->setRequired('Zadejte klíč nastavení');
     $form->addText('value', 'Hodnota')->setRequired('Zadejte hodnotu nastavení');
     $form->addSubmit('send', 'Zapsat');
     $form->onSuccess[] = function (Form $f) {
         try {
             $val = $f->values;
             $this->settings->set($val->key, $val->value);
             $this->settings->push();
             //Write
             $this->logger->log('System', 'edit', "%user% změnila(a) nastavení");
             $msg = $this->flashMessage("Nastavení bylo zapsáno", 'success');
             $msg->title = 'Yehet!';
             $msg->icon = 'check';
             $this->redirect('this');
         } catch (\PDOException $e) {
             \Nette\Diagnostics\Debugger::log($e);
             $msg = $this->flashMessage("Něco se podělalo. Zkuste to prosím později.", 'danger');
             $msg->title = 'Oh shit!';
             $msg->icon = 'warning';
         }
     };
     return $form;
 }
Exemple #4
0
/**
 * @param string $message
 */
function l($message)
{
    $message = array_map(function ($message) {
        return !is_scalar($message) ? Nette\Utils\Json::encode($message) : $message;
    }, func_get_args());
    Nette\Diagnostics\Debugger::log(implode(', ', $message));
}
Exemple #5
0
 /**
  * @param  Exception
  * @return void
  */
 public function renderDefault($exception)
 {
     // this block is there due to nette caching issue 11
     // https://github.com/nette/caching/issues/11
     if ($exception instanceof Nette\InvalidStateException) {
         $temp = $this->context->parameters['tempDir'];
         //unlink($temp . '/btfj.dat');
         rename($temp . '/btfj.dat', $temp . '/btfj.dat' . microtime(TRUE));
     }
     if ($exception instanceof Nette\Application\BadRequestException) {
         $code = $exception->getCode();
         // load template 403.latte or 404.latte or ... 4xx.latte
         $this->setView(in_array($code, array(403, 404, 405, 410, 500)) ? $code : '4xx');
         // log to access.log
         Debugger::log("HTTP code {$code}: {$exception->getMessage()} in {$exception->getFile()}:{$exception->getLine()}", 'access');
     } else {
         $this->setView('500');
         // load template 500.latte
         Debugger::log($exception, Debugger::ERROR);
         // and log exception
     }
     if ($this->isAjax()) {
         // AJAX request? Note this error in payload.
         $this->payload->error = TRUE;
         $this->terminate();
     }
 }
 /**
  * @param $id
  * @param $status
  * @throws \Nette\Application\BadRequestException
  */
 public function actionView($id, $status = null)
 {
     $interpret = $this->interpreti->find($id);
     if ($status) {
         $this->template->status = $status;
     }
     if (!$interpret) {
         throw new Nette\Application\BadRequestException("Interpret does not exists!", 404);
     }
     if ($interpret->interpret_id) {
         $msg = $this->flashMessage("Přesměrováno z '{$interpret->nazev}'");
         $msg->title = "Alias";
         $this->redirect("this", array("id" => $interpret->interpret_id));
         //If is alias => redirect to real
     }
     $this->template->interpret = $interpret;
     //Register helper fot fetching song form last.fm
     $this->template->registerhelper('songImage', function ($song, $img = 0) {
         try {
             return $this->lastfm->call('Track.getInfo', ['track' => $song->name, 'artist' => $song->interpret_name])->track->album->image[$img]->{'#text'};
         } catch (Model\Lastfm\LastfmException $e) {
             return null;
         }
     });
     //Last.fm Interpret info (images)
     try {
         $this->template->lastfm = $this->lastfm->call('Artist.getInfo', ['artist' => $interpret->nazev])->artist;
     } catch (Model\Lastfm\LastfmException $e) {
         if ($this->settings->get('lastfm_enabled', false)) {
             Debugger::log($e);
         }
     }
 }
 /**
  * @param Method $element
  * @throws \Flame\Rest\Security\ForbiddenRequestException
  */
 public function authenticate(Method $element)
 {
     $referer = $this->getReferer();
     if (!in_array($referer, $this->allowedReferers)) {
         Debugger::log('Invalid HTTP REFERER header "' . $referer . '"', Debugger::DETECT);
         throw new ForbiddenRequestException();
     }
 }
Exemple #8
0
 /**
  * @param Method $element
  * @throws \Flame\Rest\Security\ForbiddenRequestException
  */
 public function authenticate(Method $element)
 {
     $ip = $this->getClientIp();
     if (!in_array($ip, $this->allowedIps)) {
         Debugger::log('Banned ip "' . $ip . '"', Debugger::DETECT);
         throw new ForbiddenRequestException();
     }
 }
 /**
  * Wrapper for Debugger::log() method
  * @param string $message
  * @param int $priority
  */
 public static function log($message, $priority = NDebugger::INFO)
 {
     NDebugger::log($message, $priority);
     if (!$message instanceof \Exception) {
         $message = new \Exception($message);
     }
     if (self::$sendErrors && $priority == NDebugger::ERROR) {
         Rollbar::report_message($message);
     }
 }
Exemple #10
0
/**
 * Nette\Diagnostics\Debugger::log() shortcut.
 */
function dlog($var = NULL)
{
    if (func_num_args() === 0) {
        Debugger::log(new Exception(), 'dlog');
    }
    foreach (func_get_args() as $arg) {
        Debugger::log($arg, 'dlog');
    }
    return $var;
}
 public function renderDefault($exception)
 {
     if ($this->isAjax()) {
         $this->payload->error = TRUE;
         $this->terminate();
     } elseif ($exception instanceof Nette\Application\BadRequestException) {
         $this->setView('404');
     } else {
         $this->setView('500');
         Debugger::log($exception, Debugger::ERROR);
     }
 }
Exemple #12
0
 /**
  * @return Application\IResponse
  */
 public function run(Application\Request $request)
 {
     $e = $request->parameters['exception'];
     if ($e instanceof Application\BadRequestException) {
         $code = $e->getCode();
     } else {
         $code = 500;
         Debugger::log($e, Debugger::ERROR);
     }
     ob_start();
     require __DIR__ . '/templates/error.phtml';
     return new Application\Responses\TextResponse(ob_get_clean());
 }
 public function actionDefault()
 {
     try {
         $this->db->beginTransaction();
         $this->db->table('addons_resources')->delete();
         foreach ($this->db->table('addons') as $addon) {
             $this->updateAddon($addon);
         }
         $this->db->commit();
     } catch (\PDOException $e) {
         Debugger::log($e);
         $this->db->rollBack();
     }
 }
Exemple #14
0
 public function __destruct()
 {
     // Pokud mam rozpracovanou nejakou objednavku a nebyla prave ulozena do DB,
     // tak si ji ulozim do session
     if (isset($this->_order) && !$this->_order->orderSent()) {
         // Musim zachytavat vyjimky a logovat je, protoze pri destructu uz je stranka
         // vyrenderovana a nelze zobrazit chybove hlaseni
         try {
             $this->_order->save();
         } catch (\Exception $e) {
             Nette\Diagnostics\Debugger::log($e);
             Nette\Diagnostics\Debugger::log('Error saving shop order into session because of ' . get_class($e) . ': ' . md5($e), Nette\Diagnostics\Debugger::CRITICAL);
         }
     }
 }
Exemple #15
0
 /**
  * @param  Exception
  * @return void
  */
 public function renderDefault($exception)
 {
     if ($this->isAjax()) {
         // AJAX request? Just note this error in payload.
         $this->payload->error = TRUE;
         $this->terminate();
     }
     $code = $exception->getCode();
     Debugger::log("HTTP code {$code}: {$exception->getMessage()} in {$exception->getFile()}:{$exception->getLine()}", 'access');
     if (in_array($code, array(403, 404, 500))) {
         $page = $this->pageRepository->findOneBy(array('special' => $code));
         if ($page) {
             $this->forward(':Cms:Pages:Text:Route:', array('routeId' => $page->mainRoute->id, 'pageId' => $page->id));
         }
     }
 }
Exemple #16
0
 /**
  * @param  Exception
  * @return void
  */
 public function renderDefault($exception)
 {
     if ($this->isAjax()) {
         // AJAX request? Just note this error in payload.
         $this->payload->error = TRUE;
         $this->terminate();
     } elseif ($exception instanceof NA\BadRequestException) {
         $code = $exception->getCode();
         $this->setView(in_array($code, array(403, 404, 405, 410, 500)) ? $code : '4xx');
         // load template 403.latte or 404.latte or ... 4xx.latte
     } else {
         $this->setView('500');
         // load template 500.latte
         Debugger::log($exception, Debugger::ERROR);
         // and log exception
     }
 }
 /**
  * @param  Exception
  * @return void
  */
 public function renderDefault($exception)
 {
     if ($this->isAjax()) {
         // AJAX request? Just note this error in payload.
         $this->payload->error = TRUE;
         $this->terminate();
     } elseif ($exception instanceof Nette\Application\BadRequestException) {
         $code = $exception->getCode();
         // load template 403.latte or 404.latte or ... 4xx.latte
         $this->setView(in_array($code, array(403, 404, 405, 410, 500)) ? $code : '4xx');
         // log to access.log
         Debugger::log("HTTP code {$code}: {$exception->getMessage()} in {$exception->getFile()}:{$exception->getLine()}", 'access');
     } else {
         $this->setView('500');
         // load template 500.latte
         Debugger::log($exception, Debugger::ERROR);
         // and log exception
     }
 }
Exemple #18
0
 public function handleDelete($id)
 {
     try {
         $page = $this->pages->find($id);
         if (!$page) {
             throw new \PDOException("Row #{$id} not exists!");
         }
         $page->delete();
         $this->logger->log('CMS', 'delete', "%user% smazala(a) stránku {$page->name}");
         $msg = $this->flashMessage("Stránka smazána", 'success');
         $msg->title = 'A je venku!';
         $msg->icon = 'trash-o';
     } catch (\PDOException $e) {
         $msg = $this->flashMessage("Někde nastala chyba.", 'danger');
         $msg->title = 'Oh shit!';
         $msg->icon = 'exclamation-triangle';
         \Nette\Diagnostics\Debugger::log($e, \Nette\Diagnostics\Debugger::ERROR);
     }
     $this->redirect('this');
 }
 public function sendMessageFormSubmitted($form)
 {
     /** validate date inputs */
     $values = $form->getValues();
     try {
         $to = $this->context->parameters['email']['from'];
         $this->sendMail($values->email, $to, "Message from user", 'message', array('text' => $values->text, 'from' => $values->email));
         $this->sendMail($to, $values->email, "Confirmation", 'messageConfirm', array('text' => $values->text, 'from' => $values->email));
     } catch (Exception $e) {
         $this->flashMessage("Při odesílání došlo k chybě! Omlouváme se, ale posílání vzkazů je asi rozbité. :(", 'error');
         \Nette\Diagnostics\Debugger::log('Email cannot be sent! ' . $e->getMessage());
     }
     $this->flashMessage("Váš vzkaz byl odeslán", 'success');
     if (!$this->isAjax()) {
         $this->redirect('this');
     } else {
         $form->setValues(array(), TRUE);
         $this->invalidateControl('sidebar');
     }
 }
Exemple #20
0
 /**
  * @param \Symfony\Component\Console\Input\InputInterface $input
  * @param \Symfony\Component\Console\Output\OutputInterface $output
  * @return int
  * @throws \Exception
  */
 public function run(InputInterface $input = NULL, OutputInterface $output = NULL)
 {
     try {
         return parent::run($input, $output);
     } catch (\Exception $e) {
         if ($output instanceof ConsoleOutputInterface) {
             $this->renderException($e, $output->getErrorOutput());
         } else {
             $this->renderException($e, $output);
         }
         if ($file = Debugger::log($e, Debugger::ERROR)) {
             $output->writeln(sprintf('<error>  (Tracy output was stored in %s)  </error>', basename($file)));
             $output->writeln('');
             if (Debugger::$browser) {
                 exec(Debugger::$browser . ' ' . escapeshellarg($file));
             }
         }
         return min((int) $e->getCode(), 255);
     }
 }
Exemple #21
0
 public function handleDelete($id)
 {
     $user = $this->users->getUser($id);
     if (!$user) {
         $msg = $this->flashMessage("Tenhle uživatel neexistuje.", 'danger');
         $msg->title = 'Oh shit!';
         $msg->icon = 'warning';
         $this->redirect('this');
     }
     try {
         $user->delete();
         $this->logger->log('User', 'delete', "%user% smazala(a) uživatele {$user->username}");
         $msg = $this->flashMessage("Uživatel '{$user->username}' úspěšně smazán.", 'success');
         $msg->title = 'Yehet!';
         $msg->icon = 'check';
     } catch (\PDOException $ex) {
         \Nette\Diagnostics\Debugger::log($ex);
         $msg = $this->flashMessage("Něco se podělalo. Zkuzte to prosím později.", 'danger');
         $msg->title = 'Oh shit!';
         $msg->icon = 'warning';
     }
     $this->redirect('this');
 }
Exemple #22
0
	/**
	 * @param \Exception
	 */
	public static function _exceptionHandler(\Exception $exception)
	{
		if (PHP_SAPI == 'cli' && static::$browser) {
			try {
				Debugger::log($exception);

				$hash = md5($exception);
				$path = Debugger::$logDirectory;
				foreach (new \DirectoryIterator($path) as $entry) {
					if (strpos($entry, $hash)) {
						$path .= "/" . $entry;
						break;
					}
				}

				if ($path != Debugger::$logDirectory) {
					exec(sprintf(static::$browser, escapeshellarg('file://' . $path)));
					static::$browser = NULL;
				}
			} catch (\Exception $e) {
				echo $e->getMessage();
			}
		}
	}
Exemple #23
0
 /**
  * @param  Exception
  * @return void
  */
 public function renderDefault($exception)
 {
     if ($exception instanceof Nette\Application\BadRequestException) {
         if ($exception instanceof vBuilder\Application\UnsupportedBrowserException) {
             $this->setView('unsupportedBrowser');
         } else {
             $code = $exception->getCode();
             $this->setView(in_array($code, array(403, 404)) ? $code : 'default');
             // log to access.log
             Debugger::log("HTTP code {$code}: {$exception->getMessage()} in {$exception->getFile()}:{$exception->getLine()}", 'access');
         }
     } elseif ($exception instanceof vBuilder\Application\UnderConstructionException) {
         $this->setView('underConstruction');
     } else {
         $this->setView('default');
         Debugger::log($exception, Debugger::ERROR);
         // and log exception
     }
     if ($this->isAjax()) {
         // AJAX request? Note this error in payload.
         $this->payload->error = TRUE;
         $this->terminate();
     }
 }
 /**
  * @param \Nette\Security\IIdentity
  * @return \NetteAddons\Forms\Form
  */
 public function create(IIdentity $user)
 {
     $form = new Form();
     $form->addHidden('token', Strings::random());
     $form->addText('url', 'Repository URL', NULL, 256)->setAttribute('autofocus', TRUE)->setRequired();
     $form['url']->addRule(Form::PATTERN, 'Sorry, we currently support only packagist.', '(https?\\://)?packagist\\.org/packages/([a-z0-9]+(?:-[a-z0-9]+)*)/([a-z0-9]+(?:-[a-z0-9]+)*)');
     $form->addSubmit('sub', 'Load');
     $manager = $this->manager;
     $validators = $this->validators;
     $form->onSuccess[] = function (Form $form) use($manager, $validators, $user) {
         $values = $form->getValues();
         try {
             $addonEntity = $this->packagistImporter->getAddon($values['url']);
             if (!$validators->isComposerFullNameUnique($addonEntity->getComposerFullName())) {
                 $form->addError("Addon with composer name '{$addonEntity->getComposerFullName()}' already exists.");
                 return;
             }
             $addon = new Addon();
             // Back compatability
             $addon->composerFullName = $addonEntity->getComposerFullName();
             $addon->userId = $user->getId();
             $addon->shortDescription = $addonEntity->getPerex();
             $addon->type = Addon::TYPE_COMPOSER;
             $addon->defaultLicense = array();
             $addon->resources[AddonResources::RESOURCE_GITHUB] = $addonEntity->getGithub();
             $addon->resources[AddonResources::RESOURCE_PACKAGIST] = $addonEntity->getPackagist();
             $manager->storeAddon($values->token, $addon);
         } catch (\NetteAddons\Model\Importers\AddonVersionImporters\AddonNotFoundException $e) {
             $form['url']->addError("Package with URL '{$values->url}' does not exist.");
         } catch (\Exception $e) {
             $form['url']->addError('Importing failed. Try again later.');
             Debugger::log($e, Debugger::WARNING);
         }
     };
     return $form;
 }
Exemple #25
0
 private function getJson($cnt_attempts = 0)
 {
     if (!$this->nextPage || $this->nextPage == "") {
         $query = "/" . $this->gid . "/feed";
     } else {
         $query = str_replace('https://graph.facebook.com', '', $this->nextPage);
     }
     // trying download next json, it is possible to make 5 attempts per one query
     try {
         $result = $this->facebook->api($query);
     } catch (Exception $e) {
         echo "{$cnt_attempts} attempt per query ({$query}).";
         if ($cnt_attempts > 5) {
             echo "5 attempts per query ({$query}) are exhausted. Stopping whole script.";
             Debugger::log("{$e} on query: {$query}");
             $this->terminate();
         }
         echo 'Caught exception: ', $e->getMessage(), " ... repeating query ({$query})\n";
         return $this->getJson(++$cnt_attempts);
     }
     if (isset($result['paging']['next'])) {
         $this->nextPage = $result['paging']['next'];
     } else {
         $this->nextPage = null;
     }
     $this->cnt_downloaded++;
     return $result;
 }
Exemple #26
0
 /**
  * @return Token
  */
 private function fetchNewToken()
 {
     $request = $this->requestFactory->createRequest('login', $this->consumer->exportToArray())->setMethod(Request::POST);
     try {
         $response = Json::decode($this->getCurlSender()->send($request)->getResponse());
         return new Token($response->token, $this->consumer->getAppId(), new DateTime($response->expiration));
     } catch (CurlException $e) {
         Debugger::log('Cannot fetch new token: ' . $e->getMessage(), 'logistics');
         throw $e;
     }
 }
 /**
  * @param string $id
  *
  * @return bool
  */
 public function remove($id)
 {
     try {
         $key = $this->formatKey($id);
         $this->client->multi(function (RedisClient $client) use($key) {
             $client->del($key);
             $client->unlock($key);
         });
         unset($this->ssIds[$key]);
         return TRUE;
     } catch (Exception $e) {
         Debugger::log($e, 'redis-session');
         return FALSE;
     }
 }
 /**
  * Dispatch a HTTP request to a front controller.
  *
  * @return void
  */
 public function run()
 {
     $request = null;
     $repeatedError = false;
     do {
         try {
             if (count($this->requests) > self::$maxLoop) {
                 throw new ApplicationException('Too many loops detected in application life cycle.');
             }
             if (!$request) {
                 $this->onStartup($this);
                 $request = $this->router->match($this->httpRequest);
                 if (!$request instanceof Request) {
                     $request = null;
                     throw new BadRequestException('No route for HTTP request.');
                 }
                 if (strcasecmp($request->getPresenterName(), $this->errorPresenter) === 0) {
                     throw new BadRequestException('Invalid request. Presenter is not achievable.');
                 }
             }
             $this->requests[] = $request;
             $this->onRequest($this, $request);
             // Instantiate presenter
             $presenterName = $request->getPresenterName();
             try {
                 $this->presenter = $this->presenterFactory->createPresenter($presenterName);
             } catch (InvalidPresenterException $e) {
                 throw new BadRequestException($e->getMessage(), 404, $e);
             }
             $this->presenterFactory->getPresenterClass($presenterName);
             $request->setPresenterName($presenterName);
             $request->freeze();
             // Execute presenter
             $response = $this->presenter->run($request);
             if ($response) {
                 $this->onResponse($this, $response);
             }
             // Send response
             if ($response instanceof Responses\ForwardResponse) {
                 $request = $response->getRequest();
                 continue;
             } elseif ($response instanceof IResponse) {
                 $response->send($this->httpRequest, $this->httpResponse);
             }
             break;
         } catch (\Exception $e) {
             // fault barrier
             $this->onError($this, $e);
             if (!$this->catchExceptions) {
                 $this->onShutdown($this, $e);
                 throw $e;
             }
             if ($repeatedError) {
                 $e = new ApplicationException('An error occurred while executing error-presenter', 0, $e);
             }
             if (!$this->httpResponse->isSent()) {
                 $this->httpResponse->setCode($e instanceof BadRequestException ? $e->getCode() : 500);
             }
             if (!$repeatedError && $this->errorPresenter) {
                 $repeatedError = true;
                 if ($this->presenter instanceof UI\Presenter) {
                     try {
                         $this->presenter->forward(":{$this->errorPresenter}:", array('exception' => $e));
                     } catch (AbortException $foo) {
                         $request = $this->presenter->getLastCreatedRequest();
                     }
                 } else {
                     $request = new Request($this->errorPresenter, Request::FORWARD, array('exception' => $e));
                 }
                 // continue
             } else {
                 // default error handler
                 if ($e instanceof BadRequestException) {
                     $code = $e->getCode();
                 } else {
                     $code = 500;
                     Nette\Diagnostics\Debugger::log($e, Nette\Diagnostics\Debugger::ERROR);
                 }
                 require __DIR__ . '/templates/error.phtml';
                 break;
             }
         }
     } while (1);
     $this->onShutdown($this, isset($e) ? $e : null);
 }
Exemple #29
0
 /**
  * Dispatch a HTTP request to a front controller.
  * @return void
  */
 public function run()
 {
     $httpRequest = $this->context->httpRequest;
     $httpResponse = $this->context->httpResponse;
     // check HTTP method
     if ($this->allowedMethods) {
         $method = $httpRequest->getMethod();
         if (!in_array($method, $this->allowedMethods, TRUE)) {
             $httpResponse->setCode(Nette\Http\IResponse::S501_NOT_IMPLEMENTED);
             $httpResponse->setHeader('Allow', implode(',', $this->allowedMethods));
             echo '<h1>Method ' . htmlSpecialChars($method) . ' is not implemented</h1>';
             return;
         }
     }
     // dispatching
     $request = NULL;
     $repeatedError = FALSE;
     do {
         try {
             if (count($this->requests) > self::$maxLoop) {
                 throw new ApplicationException('Too many loops detected in application life cycle.');
             }
             if (!$request) {
                 $this->onStartup($this);
                 // routing
                 $router = $this->getRouter();
                 // enable routing debugger
                 Diagnostics\RoutingPanel::initialize($this, $httpRequest);
                 $request = $router->match($httpRequest);
                 if (!$request instanceof Request) {
                     $request = NULL;
                     throw new BadRequestException('No route for HTTP request.');
                 }
                 if (strcasecmp($request->getPresenterName(), $this->errorPresenter) === 0) {
                     throw new BadRequestException('Invalid request. Presenter is not achievable.');
                 }
             }
             $this->requests[] = $request;
             $this->onRequest($this, $request);
             // Instantiate presenter
             $presenterName = $request->getPresenterName();
             try {
                 $this->presenter = $this->getPresenterFactory()->createPresenter($presenterName);
             } catch (InvalidPresenterException $e) {
                 throw new BadRequestException($e->getMessage(), 404, $e);
             }
             $this->getPresenterFactory()->getPresenterClass($presenterName);
             $request->setPresenterName($presenterName);
             $request->freeze();
             // Execute presenter
             $response = $this->presenter->run($request);
             $this->onResponse($this, $response);
             // Send response
             if ($response instanceof Responses\ForwardResponse) {
                 $request = $response->getRequest();
                 continue;
             } elseif ($response instanceof IResponse) {
                 $response->send($httpRequest, $httpResponse);
             }
             break;
         } catch (\Exception $e) {
             // fault barrier
             $this->onError($this, $e);
             if (!$this->catchExceptions) {
                 $this->onShutdown($this, $e);
                 throw $e;
             }
             if ($repeatedError) {
                 $e = new ApplicationException('An error occurred while executing error-presenter', 0, $e);
             }
             if (!$httpResponse->isSent()) {
                 $httpResponse->setCode($e instanceof BadRequestException ? $e->getCode() : 500);
             }
             if (!$repeatedError && $this->errorPresenter) {
                 $repeatedError = TRUE;
                 if ($this->presenter instanceof UI\Presenter) {
                     try {
                         $this->presenter->forward(":{$this->errorPresenter}:", array('exception' => $e));
                     } catch (AbortException $foo) {
                         $request = $this->presenter->getLastCreatedRequest();
                     }
                 } else {
                     $request = new Request($this->errorPresenter, Request::FORWARD, array('exception' => $e));
                 }
                 // continue
             } else {
                 // default error handler
                 if ($e instanceof BadRequestException) {
                     $code = $e->getCode();
                 } else {
                     $code = 500;
                     Nette\Diagnostics\Debugger::log($e, Nette\Diagnostics\Debugger::ERROR);
                 }
                 require __DIR__ . '/templates/error.phtml';
                 break;
             }
         }
     } while (1);
     $this->onShutdown($this, isset($e) ? $e : NULL);
 }
Exemple #30
0
 /**
  * Makes an HTTP request. This method can be overridden by subclasses if
  * developers want to do fancier things or use something other than curl to
  * make the request.
  *
  * @param string $url The URL to make the request to
  * @param array $params The parameters to use for the POST body
  * @param resource $ch Initialized curl handle
  *
  * @throws Facebook\FacebookApiException
  * @return string The response text
  */
 protected function makeRequest($url, array $params, $ch = NULL)
 {
     if (isset($this->cache[$cacheKey = md5(serialize(array($url, $params)))])) {
         return $this->cache[$cacheKey];
     }
     $url = new UrlScript($url);
     $method = strtoupper(isset($params['method']) ? $params['method'] : 'GET');
     $this->onRequest((string) $url, $params);
     $ch = $ch ?: curl_init();
     $opts = $this->curlOptions;
     if ($this->fb->config->graphVersion !== '' && $this->fb->config->graphVersion !== 'v1.0') {
         // v2.0 or later
         unset($params['method']);
         if ($method === 'GET') {
             $url->appendQuery($params);
             $params = array();
         }
         if ($method === 'DELETE' || $method === 'PUT') {
             $opts[CURLOPT_CUSTOMREQUEST] = $method;
         }
         if ($method !== 'GET') {
             $opts[CURLOPT_POSTFIELDS] = $params;
         }
         $opts[CURLOPT_HTTPHEADER][] = 'Accept-Encoding: *';
     } else {
         // BC
         $opts[CURLOPT_POSTFIELDS] = $this->fb->config->fileUploadSupport ? $params : http_build_query($params, NULL, '&');
         // disable the 'Expect: 100-continue' behaviour. This causes CURL to wait
         // for 2 seconds if the server does not support this header.
         $opts[CURLOPT_HTTPHEADER][] = 'Expect:';
     }
     $opts[CURLOPT_URL] = (string) $url;
     // execute request
     curl_setopt_array($ch, $opts);
     $result = curl_exec($ch);
     // provide certificate if needed
     if (curl_errno($ch) == CURLE_SSL_CACERT || curl_errno($ch) === CURLE_SSL_CACERT_BADFILE) {
         Debugger::log('Invalid or no certificate authority found, using bundled information', 'facebook');
         $this->curlOptions[CURLOPT_CAINFO] = CertificateHelper::getCaInfoFile();
         curl_setopt($ch, CURLOPT_CAINFO, CertificateHelper::getCaInfoFile());
         $result = curl_exec($ch);
     }
     // With dual stacked DNS responses, it's possible for a server to
     // have IPv6 enabled but not have IPv6 connectivity.  If this is
     // the case, curl will try IPv4 first and if that fails, then it will
     // fall back to IPv6 and the error EHOSTUNREACH is returned by the
     // operating system.
     if ($result === FALSE && empty($opts[CURLOPT_IPRESOLVE])) {
         $matches = array();
         if (preg_match('/Failed to connect to ([^:].*): Network is unreachable/', curl_error($ch), $matches)) {
             if (strlen(@inet_pton($matches[1])) === 16) {
                 Debugger::log('Invalid IPv6 configuration on server, Please disable or get native IPv6 on your server.', 'facebook');
                 $this->curlOptions[CURLOPT_IPRESOLVE] = CURL_IPRESOLVE_V4;
                 curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
                 $result = curl_exec($ch);
             }
         }
     }
     $info = curl_getinfo($ch);
     if (isset($info['request_header'])) {
         list($info['request_header']) = self::parseHeaders($info['request_header']);
     }
     $info['method'] = $method;
     if ($result === FALSE) {
         $e = new Facebook\FacebookApiException(array('error_code' => curl_errno($ch), 'error' => array('message' => curl_error($ch), 'type' => 'CurlException')));
         curl_close($ch);
         $this->onError($e, $info);
         throw $e;
     }
     if (!$result && isset($info['redirect_url'])) {
         $result = Json::encode(array('url' => $info['redirect_url']));
     }
     $info['headers'] = self::parseHeaders(substr($result, 0, $info['header_size']));
     $result = trim(substr($result, $info['header_size']));
     $this->onSuccess($result, $info);
     curl_close($ch);
     return $this->cache[$cacheKey] = $result;
 }