/**
  * Funkce pro odeslání GET požadavku bez čekání na získání odpovědi
  * @param string $url
  * @throws \Exception
  */
 public static function sendBackgroundGetRequest($url)
 {
     $url = new Url($url);
     $host = $url->getHost();
     if (empty($host)) {
         $host = 'localhost';
     }
     #region parametry připojení
     switch ($url->getScheme()) {
         case 'https':
             $scheme = 'ssl://';
             $port = 443;
             break;
         case 'http':
         default:
             $scheme = '';
             $port = 80;
     }
     $urlPort = $url->getPort();
     if (!empty($urlPort)) {
         $port = $urlPort;
     }
     #endregion
     $fp = @fsockopen($scheme . $host, $port, $errno, $errstr, self::REQUEST_TIMEOUT);
     if (!$fp) {
         Debugger::log($errstr, ILogger::ERROR);
         throw new \Exception($errstr, $errno);
     }
     $path = $url->getPath() . ($url->getQuery() != "" ? '?' . $url->getQuery() : '');
     fputs($fp, "GET " . $path . " HTTP/1.0\r\nHost: " . $host . "\r\n\r\n");
     fputs($fp, "Connection: close\r\n");
     fputs($fp, "\r\n");
 }
Esempio n. 2
0
 /**
  * @param array $configs
  * @return Nette\DI\Container
  */
 protected function createContainer(array $configs = [])
 {
     $sl = $this->parentCreateContainer($configs);
     /** @var DbConnectionMock $db */
     $db = $sl->getByType('Doctrine\\DBAL\\Connection');
     if (!$db instanceof DbConnectionMock) {
         $serviceNames = $sl->findByType('Doctrine\\DBAL\\Connection');
         throw new \LogicException(sprintf('The service %s should be instance of Kdyby\\TesterExtras\\DbConnectionMock, to allow lazy schema initialization', reset($serviceNames)));
     }
     $db->onConnect[] = function (Connection $db) use($sl) {
         if ($this->databaseName !== NULL) {
             return;
         }
         try {
             if (!method_exists($this, 'doSetupDatabase')) {
                 throw new \LogicException(sprintf("Method %s:%s is not implemented", get_class($this), __FUNCTION__));
             }
             $this->doSetupDatabase($db);
         } catch (\Exception $e) {
             Tracy\Debugger::log($e, Tracy\Debugger::ERROR);
             Assert::fail($e->getMessage());
         }
     };
     return $sl;
 }
 /**
  * Provide auto merge
  */
 public function actionDefault()
 {
     $payload = $this->httpRequest->getRawBody();
     if (!$payload) {
         Debugger::log('No payload data', Debugger::ERROR);
         $this->terminate();
     }
     $data = json_decode($payload, true);
     if (!$data) {
         Debugger::log('json_decode error', Debugger::ERROR);
         $this->terminate();
     }
     if ($data['object_kind'] != 'note') {
         Debugger::log('Only notes object kind processing now. *' . $data['object_kind'] . '* given', Debugger::ERROR);
         $this->terminate();
     }
     $projectId = isset($data['merge_request']['source_project_id']) ? $data['merge_request']['source_project_id'] : false;
     $mergeRequestId = isset($data['merge_request']['id']) ? $data['merge_request']['id'] : false;
     if (!$projectId || !$mergeRequestId) {
         Debugger::log('projectId or mergeRequestId missing', Debugger::ERROR);
         $this->terminate();
     }
     $project = $this->projectRepository->findByGitlabId($projectId);
     if (!$project) {
         Debugger::log('Project ' . $projectId . ' is not allowed to auto merge', Debugger::ERROR);
         $this->terminate();
     }
     $mr = $this->gitlabClient->api('mr')->show($projectId, $mergeRequestId);
     $mergeRequest = $this->mergeRequestBuilder->create($mr, $data);
     if ($mergeRequest->canBeAutoMerged($project->positive_votes)) {
         $this->gitlabClient->api('mr')->merge($projectId, $mergeRequestId, 'Auto merged');
     }
 }
 private function handleRequest(React\Http\Request $request, React\Http\Response $response)
 {
     try {
         $container = $this->containerFactory->createContainer();
         /** @var HttpRequestFactory $requestFactory */
         $requestFactory = $container->getByType(HttpRequestFactory::class);
         $requestFactory->setFakeHttpRequest($this->createNetteHttpRequest($request));
         /** @var CliRouter $router */
         $cliRouter = $container->getService('console.router');
         $cliRouter->setIsCli(FALSE);
         /** @var Nette\Application\Application $application */
         $application = $container->getByType(Nette\Application\Application::class);
         array_unshift($application->onError, function () {
             throw new AbortException();
         });
         ob_start();
         $application->run();
         $responseBody = ob_get_contents();
         ob_end_clean();
         $response->writeHead(200, array('Content-Type' => 'text/html; charset=utf-8'));
         $response->end($responseBody);
     } catch (\Exception $e) {
         Debugger::log($e, Debugger::EXCEPTION);
         $response->writeHead(500, array('Content-Type' => 'text/plain'));
         $response->end('Internal Server Error');
     }
 }
Esempio n. 5
0
 /**
  * @param WorkedHours $workedHours
  * @return WorkedHours
  * @throws \DibiException
  */
 public function setupWorkedHours(WorkedHours $workedHours)
 {
     $values = ['workStart' => $workedHours->workStart->getTime(), 'workEnd' => $workedHours->workEnd->getTime(), 'lunch' => $workedHours->lunch->getTime(), 'otherHours' => $workedHours->otherHours->getTime()];
     try {
         $this->connection->query('LOCK TABLES worked_hours WRITE');
         $data = $this->connection->query('SELECT workedHoursID AS id FROM worked_hours
              WHERE %and', $values)->fetch();
         if ($data === false) {
             $this->connection->query('INSERT INTO [worked_hours]', $values);
             $id = $this->connection->getInsertId();
         } else {
             $id = $data['id'];
         }
         $this->connection->query('UNLOCK TABLES');
         if (!$workedHours->isDetached()) {
             $workedHours->detach();
         }
         $workedHours->makeAlive($this->entityFactory, $this->connection, $this->mapper);
         $workedHours->attach($id);
         return $workedHours;
     } catch (\DibiException $e) {
         $this->connection->query('UNLOCK TABLES');
         Debugger::log($e, Debugger::ERROR);
         throw $e;
     }
 }
Esempio n. 6
0
 /**
  * Nette render default method
  *
  * @return void
  */
 public function renderDefault()
 {
     $start = microtime(true);
     $this->sendCorsHeaders();
     $hand = $this->getHandler();
     $handler = $hand['handler'];
     $authorization = $hand['authorization'];
     if ($this->checkAuth($authorization) === false) {
         return;
     }
     $params = $this->processParams($handler);
     if ($params === false) {
         return;
     }
     try {
         $response = $handler->handle($params);
         $code = $response->getCode();
     } catch (Exception $exception) {
         $response = new JsonApiResponse(500, ['status' => 'error', 'message' => 'Internal server error']);
         $code = $response->getCode();
         Debugger::log($exception, Debugger::EXCEPTION);
     }
     $end = microtime(true);
     if ($this->context->findByType('Tomaj\\NetteApi\\Logger\\ApiLoggerInterface')) {
         $this->logRequest($this->context->getByType('Tomaj\\NetteApi\\Logger\\ApiLoggerInterface'), $code, $end - $start);
     }
     // output to nette
     $this->getHttpResponse()->setCode($code);
     $this->sendResponse($response);
 }
 /**
  * @param  Exception
  * @return void
  * @throws Nette\Application\AbortException
  */
 public function actionDefault($exception)
 {
     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');
         if (Debugger::isEnabled()) {
             // 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
         if (Debugger::isEnabled()) {
             Debugger::log($exception, Debugger::ERROR);
             // and log exception
         }
     }
     $this->template->exception = $exception;
     if ($this->isAjax()) {
         // AJAX request? Note this error in payload.
         $this->payload->error = true;
         $this->terminate();
     }
 }
Esempio n. 8
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 ' . Dumper::toText($expected_sig) . ', but given ' . Dumper::toText($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 ' . Dumper::toText($expected_sig) . ', but given ' . Dumper::toText($sig), 'facebook');
         return NULL;
     }
     return $data;
 }
Esempio n. 9
0
 public function renderDefault()
 {
     $this->template->anyVariable = 'any value';
     //		$dao = $this->articles;
     $this->template->articles = $this->articles->getArticles()->findAll();
     $posts = $this->EntityManager->getRepository(Posts::getClassName());
     $this->template->posts = $posts->findAll();
     $this->template->myparametr = $this->context->parameters['first_parametr'];
     //		$this->template->test = $this->doSomeRefactoring('Hello world from blog');
     //		$post = new Posts();
     //		$post->title = 'New title';
     //		$post->text = 'New text New textNew text';
     //		$post->created_at = new \Nette\Utils\DateTime;
     //
     //
     //		$this->EntityManager->persist($post);
     //		$this->EntityManager->flush();
     //		$dao = $this->EntityManager->getRepository(Posts::getClassName());
     //		$dao->setTitle('test');
     //		$dao->__call('set', ['title' => 'my title']);
     //		dump($dao->__isset('title'));
     //		$dao->__set('title', 'test');
     try {
         $this->checkNum(2);
         \Tracy\Debugger::barDump('If you see this, the number is 1 or below');
     } catch (Nette\Application\BadRequestException $e) {
         Debugger::log('Message: ' . $e->getMessage());
         var_dump($e->getMessage());
     }
     //		finally {
     //			\Tracy\Debugger::barDump('Got here Finally');
     //		}
 }
 /**
  * Callback for ForgottenPasswordForm onSuccess event.
  * @param Form      $form
  * @param ArrayHash $values
  */
 public function formSucceeded(Form $form, $values)
 {
     $user = $this->userManager->findByEmail($values->email);
     if (!$user) {
         $form->addError('No user with given email found');
         return;
     }
     $password = Nette\Utils\Random::generate(10);
     $this->userManager->setNewPassword($user->id, $password);
     try {
         // !!! Never send passwords through email !!!
         // This is only for demonstration purposes of Notejam.
         // Ideally, you can create a unique link where user can change his password
         // himself for limited amount of time, and then send the link.
         $mail = new Nette\Mail\Message();
         $mail->setFrom('*****@*****.**', 'Notejamapp');
         $mail->addTo($user->email);
         $mail->setSubject('New notejam password');
         $mail->setBody(sprintf('Your new password: %s', $password));
         $this->mailer->send($mail);
     } catch (Nette\Mail\SendException $e) {
         Debugger::log($e, Debugger::EXCEPTION);
         $form->addError('Could not send email with new password');
     }
 }
Esempio n. 11
0
 /**
  * Default form handler
  */
 public function process()
 {
     /** @var ArrayHash $values */
     $values = $this->values;
     try {
         $this->onBeforeProcess($this, $values);
         if (isset($values->id)) {
             $this->onBeforeUpdate($this, $values);
             $arr = (array) $values;
             unset($arr['id']);
             $row = $this->selection->wherePrimary($values->id)->fetch();
             $row->update($arr);
             $this->onAfterUpdate($row, $this, $values);
         } else {
             $this->onBeforeInsert($this, $values);
             $row = $this->selection->insert($values);
             $this->onAfterInsert($row, $this, $values);
         }
         $this->onAfterProcess($row, $this, $values);
     } catch (\PDOException $e) {
         $this->addError($e->getMessage());
         dump($e);
         Debugger::log($e);
     }
 }
 private function setSystemSettings()
 {
     try {
         $this->systemSettings = $this->systemSettingsFacade->findAll();
     } catch (EntitiesNotFoundException $ex) {
         \Tracy\Debugger::log($ex);
         $this->systemSettings = null;
     }
 }
Esempio n. 13
0
 /**
  * Odchytí výjimku, v případě, že je program v produkčním modu, je výjimka zalogována a komponentě předána Flash
  * Message. Pokud ne, je vyhozena dál.
  * @param \Exception $exception
  * @param string $message
  * @throws \Exception
  */
 protected function catchException(\Exception $exception, $message = "global.errors.action-error")
 {
     if (\Tracy\Debugger::$productionMode) {
         \Tracy\Debugger::log($exception->getMessage(), \Tracy\Logger::EXCEPTION);
         $this->flashMessage($this->t($message), "danger");
     } else {
         throw $exception;
     }
 }
Esempio n. 14
0
 public function renderDefault()
 {
     try {
         $this->template->articles = $this->articleFacade->findAllVisible($this->paginator->getPageLimit());
     } catch (EntityNotFoundException $ex) {
         \Tracy\Debugger::log($ex);
         $this->template->articles = false;
     }
 }
Esempio n. 15
0
 /**
  * Odchytí výjimku v rámci zpracování formuláře, v případě, že je program v produkčním modu, je výjimka zalogována
  * a formuláře přidána chyba. Pokud ne, je vyhozena dál.
  * @param \Exception $exception
  * @param Nette\Application\UI\Form $form
  * @param string $message
  * @throws \Exception
  */
 protected function catchFormError(\Exception $exception, \Nette\Application\UI\Form $form, $message = "global.errors.action-error")
 {
     if (\Tracy\Debugger::$productionMode) {
         \Tracy\Debugger::log($exception->getMessage(), \Tracy\Logger::EXCEPTION);
         $form->addError($this->t($message));
     } else {
         throw $exception;
     }
 }
Esempio n. 16
0
 public function save(Statistic $statistic)
 {
     try {
         $this->mapper->insert($statistic);
     } catch (UniqueConstraintViolationException $ex) {
         \Tracy\Debugger::log($ex);
         $this->mapper->update($statistic);
     }
 }
Esempio n. 17
0
 public function update(User $user)
 {
     try {
         $this->db->table(self::TABLE_NAME)->where(self::COLUMN_ID, $user->id)->update(array(self::COLUMN_EMAIL => $user->email, self::COLUMN_FIRST_NAME => $user->firstName, self::COLUMN_LAST_NAME => $user->lastName, self::COLUMN_REGISTERED_AT => $user->registeredAt, self::COLUMN_ACTIVE => $user->active, self::COLUMN_BLOCKED => $user->blocked, self::COLUMN_HASH => $user->hash, self::COLUMN_TOKEN => $user->token, self::COLUMN_VALIDITY => $user->validity, self::COLUMN_ROLE => $user->role, self::COLUMN_URL => $user->url));
         return $user->id;
     } catch (UniqueConstraintViolationException $ex) {
         \Tracy\Debugger::log($ex);
         throw new DuplicateEmailException();
     }
 }
Esempio n. 18
0
 /**
  * Tracy\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;
 }
Esempio n. 19
0
 function handleReply($text, $comment)
 {
     try {
         $project_id = $this->projectManager->accepted($this->user->id)->id;
         $response = $this->commentingService->reply($this->user->id, $project_id, $text, $comment);
         $this->sendResponse($response);
     } catch (Model\CommentingException $e) {
         Debugger::log($e);
     }
 }
Esempio n. 20
0
 /**
  * @param \stekycz\Cronner\ITimestampStorage $timestampStorage
  * @param \stekycz\Cronner\CriticalSection $criticalSection
  * @param int|null $maxExecutionTime It is used only when Cronner runs
  * @param bool $skipFailedTask
  */
 public function __construct(ITimestampStorage $timestampStorage, CriticalSection $criticalSection, $maxExecutionTime = NULL, $skipFailedTask = TRUE)
 {
     $this->setTimestampStorage($timestampStorage);
     $this->criticalSection = $criticalSection;
     $this->setMaxExecutionTime($maxExecutionTime);
     $this->setSkipFailedTask($skipFailedTask);
     $this->onTaskError[] = function (Cronner $cronner, Exception $exception) {
         Debugger::log($exception, Debugger::ERROR);
     };
 }
Esempio n. 21
0
 public function renderDefault($id)
 {
     try {
         $this->template->articles = $this->articleFacade->findByAuthor($id, $this->paginator->getPageLimit());
         $this->template->author = $this->userFacade->findOneById($id);
     } catch (EntityNotFoundException $ex) {
         \Tracy\Debugger::log($ex);
         $this->template->articles = false;
     }
 }
 public function runAndScream($function)
 {
     try {
         $function();
         exit(0);
     } catch (\Exception $e) {
         echo $e->getMessage() . "\n";
         \Tracy\Debugger::log($e);
     }
     exit(1);
 }
Esempio n. 23
0
 private function loadTags()
 {
     try {
         $tags = $this->tagFacade->findAll();
         foreach ($tags->items as $tag) {
             $this->tags[$tag->id] = Strings::lower($tag->name);
         }
     } catch (EntityNotFoundException $ex) {
         \Tracy\Debugger::log($ex);
     }
 }
Esempio n. 24
0
 /**
  * Odstraneni konkretniho clanku
  * @param \App\Model\Entities\Article $article
  * @return boolean
  */
 public function deleteArticle(Entities\Article $article)
 {
     try {
         $this->em->remove($article);
         $result = $this->em->flush();
     } catch (\Doctrine\ORM\ORMException $e) {
         Debugger::log($e, Debugger::INFO);
         $result = FALSE;
     }
     return $result;
 }
Esempio n. 25
0
 public function insert(Team $team)
 {
     try {
         $id = $this->db->table(self::TABLE_NAME)->insert(array(self::COLUMN_NAME => $team->name))->id;
     } catch (UniqueConstraintViolationException $ex) {
         \Tracy\Debugger::log($ex);
         $id = $this->findOneByName($team->name)->id;
     } finally {
         return $id;
     }
 }
Esempio n. 26
0
 public function startup()
 {
     parent::startup();
     $this->template->addFilter('ago', 'Helpers::timeAgoInWords');
     try {
         $this->template->categories = $this->categoryFacade->findVisible();
     } catch (EntitiesNotFoundException $ex) {
         \Tracy\Debugger::log($ex);
         $this->template->categories = null;
     }
 }
Esempio n. 27
0
 /**
  * Processing form
  * @param Form $form
  * @param ArrayHash $values
  */
 public function formSuccess($form, $values)
 {
     try {
         $data = $this->settingsRepository->fetch();
         $data ? $data->update($values) : $this->settingsRepository->insert($values);
     } catch (PDOException $e) {
         Debugger::log($e, Debugger::ERROR);
         $form->addError('Database error occurred');
         return;
     }
     $this->onSuccess();
 }
Esempio n. 28
0
 private function setUsers()
 {
     $this->users[0] = "Všichni autoři";
     try {
         $users = $this->userFacade->findAllEditorsAndChiefs();
         foreach ($users->items as $user) {
             $this->users[$user->id] = $user->lastName . " " . $user->firstName . " ({$user->role})";
         }
     } catch (EntityNotFoundException $ex) {
         \Tracy\Debugger::log($ex);
     }
 }
Esempio n. 29
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::EXCEPTION);
     }
     ob_start();
     require __DIR__ . '/templates/error.phtml';
     return new Application\Responses\TextResponse(ob_get_clean());
 }
Esempio n. 30
0
File: Cron.php Progetto: foowie/cron
 public function run()
 {
     foreach ($this->jobs as $job) {
         try {
             if (!$job instanceof IJob) {
                 throw new CronException('Job must implement interface IJob!');
             }
             $job->run();
         } catch (Exception $e) {
             Debugger::log($e, Debugger::ERROR);
         }
     }
 }