Beispiel #1
0
 public function onPresenter(Application $application, IPresenter $presenter)
 {
     if (Debugger::$productionMode === FALSE && $this->changelogManager->haveFilesChanged() && $this->changelogManager->importNewChangelogData() && !$presenter instanceof ChangelogPresenter) {
         $this->httpResponse->redirect('/db-changelog');
         exit;
     }
 }
 /**
  * Povolí zápis cookies do IFRAMe a pokud má aplikace appNamespace, povolí vložení aplikace do IFRAMe
  */
 private function setHeaders()
 {
     $this->httpResponse->addHeader('P3P', 'CP="CAO PSA OUR"');
     if ($this->config["appNamespace"] !== FALSE) {
         $this->httpResponse->setHeader('X-Frame-Options', NULL);
     }
 }
Beispiel #3
0
 private function processRequest()
 {
     if ($this->httpRequest->isPost() && $this->httpRequest->isAjax() && $this->httpRequest->getHeader(self::XHR_HEADER)) {
         $data = json_decode(file_get_contents('php://input'), true);
         if ($data && isset($data[self::AJAX_ACTION_KEY])) {
             switch ($data[self::AJAX_ACTION_KEY]) {
                 case self::AJAX_ACTION_LOAD:
                     $message = $data[self::AJAX_MESSAGE_KEY];
                     if (!$this->translator->hasTranslation($message)) {
                         throw new \Exception();
                     }
                     $data = array('translation' => $this->translator->findTranslation($message));
                     $this->httpResponse->setContentType('application/json');
                     echo json_encode($data);
                     break;
                 case self::AJAX_ACTION_EDIT:
                     $message = $data[self::AJAX_MESSAGE_KEY];
                     $translation = $data[self::AJAX_TRANSLATION_KEY];
                     if (!$this->translator->hasTranslation($message)) {
                         throw new \Exception();
                     }
                     $info = $this->translator->getMessageInfo($message);
                     $data = $this->translator->_loadCategory($info['path'], $info['category']);
                     $data[$info['name']] = $translation;
                     $this->translator->getLoader()->save($info['path'], $info['category'], $this->translator->getLanguage(), $data);
                     $this->httpResponse->setContentType('application/json');
                     break;
                 default:
                     throw new \Exception();
                     break;
             }
         }
         exit;
     }
 }
Beispiel #4
0
 /**
  * sets identifying cookie to user and saves it to DB table `user`
  */
 public function setUserCookie()
 {
     $userCookie = $this->httpRequest->getCookie('rabbit_user');
     if ($userCookie === NULL) {
         $hash = md5(time());
         //saves cookie to user for 1 month since now
         $this->httpResponse->setCookie('rabbit_user', $hash, \Nette\Utils\DateTime::from('now')->modifyClone('+1 month'));
         //saves to DB
         $this->userRepository->insert(['hash' => $hash]);
     }
 }
 /**
  * Authenticate user
  * @param  string $username
  * @param  string $password
  * @return void
  */
 public function authenticate($username, $password)
 {
     $url = $this->httpRequest->url;
     if ($url->user !== $username || $url->password !== $password) {
         $this->httpResponse->setHeader('WWW-Authenticate', 'Basic realm="HTTP Authentication"');
         $this->httpResponse->setCode(Nette\Http\IResponse::S401_UNAUTHORIZED);
         echo '<h1>Authentication failed.</h1>';
         if ($this->exit_on_bad_credentials) {
             die;
         }
     }
 }
 public function run(Nette\Application\Request $request)
 {
     $dir = realpath($this->container->parameters['tempDir'] . '/webfiles');
     try {
         if (!$dir) {
             throw new Nette\Application\BadRequestException("File not found");
         }
         $filePath = $dir . '/' . $request->parameters['file'];
         $this->httpResponse->setContentType($request->parameters['type'] == 'js' ? 'text/javascript' : 'text/css', 'utf-8');
         return new vBuilder\Application\Responses\FileResponse($filePath, $request->parameters['file'], FALSE);
     } catch (Nette\Application\BadRequestException $e) {
         $this->httpResponse->setCode(404);
         return new Nette\Application\Responses\TextResponse("Not found");
     }
 }
Beispiel #7
0
 /**
  * Translate given string
  * @param string $message
  * @param int $form plural form (positive number)
  * @return string
  */
 public function translate($message, $form = 1)
 {
     $this->loadDictonary();
     $message = (string) $message;
     $message_plural = NULL;
     if (is_array($form) && $form !== NULL) {
         $message_plural = current($form);
         $form = (int) end($form);
     } elseif (is_numeric($form)) {
         $form = (int) $form;
         if ($form < 2) {
             $message_plural = 0;
         } elseif ($form < 5) {
             $message_plural = 1;
         } else {
             $message_plural = 2;
         }
     } elseif (!is_int($form) || $form === NULL) {
         $form = 1;
     }
     if (!empty($message) && isset($this->dictionary[$message])) {
         $tmp = preg_replace('/([a-z]+)/', '$$1', "n={$form};" . $this->metadata[$this->dictionary[$message]['file']]['Plural-Forms']);
         eval($tmp);
         $message = $this->dictionary[$message]['translation'];
         if (!empty($message)) {
             $message = is_array($message) && $message_plural !== NULL && isset($message[$message_plural]) ? $message[$message_plural] : $message;
         }
     } else {
         if ($this->debugMode === true && (!$this->httpResponse->isSent() || $this->sessionStorage)) {
             if (!isset($this->sessionStorage->newStrings[$this->lang])) {
                 $this->sessionStorage->newStrings[$this->lang] = array();
             }
             $this->sessionStorage->newStrings[$this->lang][$message] = empty($message_plural) ? array($message) : array($message, $message_plural);
         }
         if ($form > 1 && !empty($message_plural)) {
             $message = $message_plural;
         }
     }
     if (is_array($message)) {
         $message = current($message);
     }
     $args = func_get_args();
     if (count($args) > 1) {
         array_shift($args);
         if (is_array(current($args)) || current($args) === NULL) {
             array_shift($args);
         }
         if (count($args) == 1 && is_array(current($args))) {
             $args = current($args);
         }
         $message = str_replace(array('%label', '%name', '%value'), array('#label', '#name', '#value'), $message);
         if (count($args) > 0 && $args != NULL) {
             $message = vsprintf($message, $args);
         }
         $message = str_replace(array('#label', '#name', '#value'), array('%label', '%name', '%value'), $message);
     }
     return $message;
 }
Beispiel #8
0
 public function onResponse(NA\Application $application, NA\IResponse $response)
 {
     if ($this->config["panel"]["ajax"] && $application->getPresenter() instanceof \Nette\Application\UI\Presenter && $application->getPresenter()->isAjax()) {
         $debug = ["count" => count($this->_getElapsed())];
         if ($debug["count"]) {
             ob_start();
             include __DIR__ . "/panel/templates/results.phtml";
             $debug["template"] = ob_get_clean();
         }
         $data = base64_encode(json_encode($debug));
         // Workaround for Chrome header limit as https://github.com/Seldaek/monolog/issues/172
         if (strlen($data) > 240 * 1024) {
             $debug["template"] = "Incomplete logs, chrome header size limit reached!";
             $data = base64_encode(json_encode($debug));
         }
         $this->response->setHeader(self::HEADER_PREFIX, $data);
     }
 }
Beispiel #9
0
 /**
  * 
  * @param Scripter $scripter
  * @param Response $response
  * @param Request $request
  */
 public static function register_shutdown(Scripter $scripter, Response $response, Request $request)
 {
     register_shutdown_function(function () use($scripter, $response, $request) {
         $page = ob_get_contents();
         ob_end_clean();
         $header_type = $response->getHeader("Content-Type");
         if ($header_type && strpos($header_type, "text/html") === 0 && !$request->isAjax()) {
             $scripter->cache->removeNotUseFile();
             preg_match('/(?:<head[^>]*>)(.*?)<\\/head>/s', $page, $matches);
             if (isset($matches[1])) {
                 $replace = $matches[1];
                 $matches[1] .= '<script type="text/javascript" src="' . '/' . $scripter->config->url_path_name . '/' . $scripter->getPageName() . '/js' . '"></script>';
                 $matches[1] .= '<link rel="stylesheet" href="' . '/' . $scripter->config->url_path_name . '/' . $scripter->getPageName() . '/css' . '">';
                 $page = str_replace($replace, $matches[1], $page);
             }
         }
         echo $page;
     });
 }
Beispiel #10
0
 public function renderAuthFtp()
 {
     if ($this->httpRequest->getMethod() != "POST") {
         $this->error('Neplatná metoda.', 403);
     }
     $this->httpResponse->setContentType('text/plain', 'UTF-8');
     $username = $this->httpRequest->getPost('username', '');
     $password = $this->httpRequest->getPost('password', '');
     $s = $this->share->findOneBy(array('var' => $username, 'var2' => $password));
     $out = array();
     if (!$s) {
         $out[] = 'auth_ok:0';
     } else {
         $out[] = 'auth_ok:1';
         $out[] = 'uid:' . Model\Share::shareuid;
         $out[] = 'gid:' . Model\Share::sharegid;
         $out[] = 'dir:' . Model\Share::dataBaseUrl . $s->folder->name . '/';
     }
     $out[] = 'end';
     $this->send($out);
 }
Beispiel #11
0
 /**
  * Destroy the current session
  */
 public function destroySession()
 {
     $this->accessToken = NULL;
     $this->signedRequest = NULL;
     $this->user = NULL;
     $this->session->clearAll();
     // Javascript sets a cookie that will be used in getSignedRequest that we need to clear if we can
     $cookieName = $this->config->getSignedRequestCookieName();
     if (array_key_exists($cookieName, $this->httpRequest->getCookies())) {
         $this->httpResponse->deleteCookie($cookieName, '/', $this->getBaseDomain());
         unset($_COOKIE[$cookieName]);
     }
 }
 /**
  * Saves the JWT Access Token into HTTP cookie.
  */
 private function saveJWTCookie()
 {
     if (empty($this->jwtData)) {
         $this->response->deleteCookie(self::COOKIE_NAME);
         return;
     }
     if ($this->generateIat) {
         $this->jwtData['iat'] = DateTime::from('NOW')->format('U');
     }
     // Unset JTI if there was any
     unset($this->jwtData['jti']);
     if ($this->generateJti) {
         // Generate new JTI
         $this->jwtData['jti'] = hash('sha256', serialize($this->jwtData) . Random::generate(10));
     }
     // Encode the JWT and set the cookie
     $jwt = $this->jwtService->encode($this->jwtData, $this->privateKey, $this->algorithm);
     $this->response->setCookie(self::COOKIE_NAME, $jwt, $this->expirationTime);
     $this->cookieSaved = true;
     // Set cookie saved flag to true, so loadJWTCookie() doesn't rewrite our data
 }
Beispiel #13
0
 /**
  * Set cookie with social login service
  * @param $socialServiceName Social service name for
  */
 protected function setSocialLoginCookie($socialServiceName)
 {
     $this->httpResponse->setCookie($this->cookieName, $socialServiceName, 0);
 }
Beispiel #14
0
 /**
  * @return Nette\Http\Response
  */
 public static function createServiceHttpResponse()
 {
     $response = new Nette\Http\Response();
     if (!$response->isSent()) {
         $response->setContentType('text/html', 'utf-8');
     }
     return $response;
 }
Beispiel #15
0
 /**
  * @return $this
  */
 public function configure()
 {
     $this->httpResponse->addHeader(self::HEADER_ORIGIN, $this->getOrigin());
     $this->httpResponse->addHeader(self::HEADER_HEADERS, $this->getHeaders());
     $this->httpResponse->addHeader(self::HEADER_METHODS, $this->getMethods());
 }
 /**
  * Upload signal
  */
 public function handleUpload()
 {
     // HTTP headers for no cache etc
     $httpResponse = new Response();
     $httpResponse->setHeader("Expires", "Mon, 26 Jul 1997 05:00:00 GMT");
     $httpResponse->setHeader("Last-Modified", gmdate("D, d M Y H:i:s") . " GMT");
     $httpResponse->setHeader("Cache-Control", "no-store, no-cache, must-revalidate, post-check=0, pre-check=0");
     $httpResponse->setHeader("Pragma", "no-cache");
     $response = array("jsonrpc" => "2.0", "result" => "", "id" => "id", "type" => "");
     if ($this->system->parameters["readonly"]) {
         $response["result"] = "Read-only mode enabled, files can not be uploaded!";
         $response["type"] = "error";
         $this->presenter->sendResponse(new JsonResponse($response));
     }
     $fileSize = $this->system->filesystem->getSize($_FILES["file"]["tmp_name"]);
     if ($this->getFreeSpace() < $fileSize) {
         $response["result"] = "Disk space is full!";
         $response["type"] = "error";
         $this->presenter->sendResponse(new JsonResponse($response));
     }
     $actualDir = $this->system->session->actualdir;
     $targetDir = $this->getAbsolutePath($actualDir);
     if (!is_dir($targetDir)) {
         $response["result"] = "Target directory '{$actualDir}' not found!";
         $response["type"] = "error";
         $this->presenter->sendResponse(new JsonResponse($response));
     }
     // Settings
     $maxFileAge = 60 * 60;
     // Temp file age in seconds
     // Get parameters
     $chunk = isset($_REQUEST["chunk"]) ? $_REQUEST["chunk"] : 0;
     $chunks = isset($_REQUEST["chunks"]) ? $_REQUEST["chunks"] : 0;
     $fileName = isset($_REQUEST["name"]) ? $_REQUEST["name"] : "";
     $fileName = $this->system->filesystem->safeFilename($fileName);
     // Make sure the fileName is unique but only if chunking is disabled
     if ($chunks < 2 && is_file("{$targetDir}/{$fileName}")) {
         $ext = strrpos($fileName, ".");
         $fileName_a = substr($fileName, 0, $ext);
         $fileName_b = substr($fileName, $ext);
         $count = 1;
         while (is_file("{$targetDir}/{$fileName_a}" . "_{$count}" . $fileName_b)) {
             $count++;
         }
         $fileName = $fileName_a . "_{$count}" . $fileName_b;
     }
     // Remove old temp files
     if (is_dir($targetDir) && ($dir = opendir($targetDir))) {
         while (($file = readdir($dir)) !== false) {
             // Remove temp files if they are older than the max age
             $filePath = "{$targetDir}/{$file}";
             if (preg_match("/\\.tmp\$/", $file) && filemtime($filePath) < time() - $maxFileAge) {
                 unlink($filePath);
             }
         }
         closedir($dir);
     } else {
         $response["result"] = "Failed to open temp directory!";
         $response["type"] = "error";
         $this->presenter->sendResponse(new JsonResponse($response));
     }
     // Look for the content type header
     if (isset($_SERVER["HTTP_CONTENT_TYPE"])) {
         $contentType = $_SERVER["HTTP_CONTENT_TYPE"];
     }
     if (isset($_SERVER["CONTENT_TYPE"])) {
         $contentType = $_SERVER["CONTENT_TYPE"];
     }
     // Handle non multipart uploads older WebKit versions didn"t support multipart in HTML5
     if (strpos($contentType, "multipart") !== false) {
         if (isset($_FILES["file"]["tmp_name"]) && is_uploaded_file($_FILES["file"]["tmp_name"])) {
             // Open temp file
             $out = fopen($targetDir . DIRECTORY_SEPARATOR . $fileName, $chunk == 0 ? "wb" : "ab");
             if (!$out) {
                 $response["result"] = "Failed to open output stream!";
                 $response["type"] = "error";
                 $this->presenter->sendResponse(new JsonResponse($response));
             }
             // Read binary input stream and append it to temp file
             $in = fopen($_FILES["file"]["tmp_name"], "rb");
             if (!$in) {
                 $response["result"] = "Failed to open output stream!";
                 $response["type"] = "error";
                 $this->presenter->sendResponse(new JsonResponse($response));
             }
             while ($buff = fread($in, 4096)) {
                 fwrite($out, $buff);
             }
             fclose($out);
             fclose($in);
             unlink($_FILES["file"]["tmp_name"]);
         } else {
             $response["result"] = "Failed to move uploaded file!";
             $response["type"] = "error";
             $this->presenter->sendResponse(new JsonResponse($response));
         }
     } else {
         // Open temp file
         $out = fopen($targetDir . DIRECTORY_SEPARATOR . $fileName, $chunk == 0 ? "wb" : "ab");
         if (!$out) {
             $response["result"] = "Failed to open output stream!";
             $response["type"] = "error";
             $this->presenter->sendResponse(new JsonResponse($response));
         }
         // Read binary input stream and append it to temp file
         $in = fopen("php://input", "rb");
         if (!$in) {
             $response["result"] = "Failed to open input stream!";
             $response["type"] = "error";
             $this->presenter->sendResponse(new JsonResponse($response));
         }
         while ($buff = fread($in, 4096)) {
             fwrite($out, $buff);
         }
         fclose($out);
         fclose($in);
     }
     if ($this->system->parameters["cache"]) {
         $this->system->caching->deleteItem(array("content", $targetDir));
     }
     $response["result"] = "Successfuly uploaded.";
     $response["type"] = "info";
     $this->presenter->sendResponse(new JsonResponse($response));
 }
Beispiel #17
0
 /**
  * Action - Allows to redirect to a Url.
  * @param string  $uri  Endpoint URI
  */
 protected function actionRedirect($uri)
 {
     // Redirect to giben Uri address
     $this->response->redirect($uri);
 }
Beispiel #18
0
 /**
  * @param string|int|DateTime $time
  *
  * @return self
  */
 public function setExpiration($time)
 {
     if (!$time) {
         $this->setHeader('Cache-Control', 's-maxage=0, max-age=0, must-revalidate');
         $this->setHeader('Expires', 'Mon, 23 Jan 1978 10:00:00 GMT');
         return $this;
     }
     $time = DateTime::from($time);
     $this->setHeader('Cache-Control', 'max-age=' . ($time->format('U') - time()));
     $this->setHeader('Expires', HttpResponse::date($time));
     return $this;
 }
Beispiel #19
0
 public function delete($name, $path = null, $domain = null, $secure = null)
 {
     $this->_response->deleteCookie($name, $path, $domain, $secure);
 }