public function handleUpload() { $files = \Nette\Environment::getHttpRequest()->getFile("user_file"); foreach ($files as $file) { call_user_func($this->handler, $file); } }
/** * Sends a standard headers for file download * @param BaseFileDownload $file File * @param BaseDownloader $downloader Downloader of the file */ protected function sendStandardFileHeaders(BaseFileDownload $file, BaseDownloader $downloader = null) { $res = \Nette\Environment::getHttpResponse(); $req = \Nette\Environment::getHttpRequest(); //FDTools::clearHeaders($res); // Voláno už v FileDownload.php $res->setContentType($file->mimeType, "UTF-8"); $res->setHeader("X-File-Downloader", "File Downloader (http://filedownloader.projekty.mujserver.net)"); if ($downloader !== null) { $res->setHeader("X-FileDownloader-Actual-Script", $downloader->getReflection()->name); } $res->setHeader('Pragma', 'public'); // Fix for IE - Content-Disposition $res->setHeader('Content-Disposition', $file->getContentDisposition() . '; filename="' . FDTools::getContentDispositionHeaderData($file->transferFileName) . '"'); $res->setHeader('Content-Description', 'File Transfer'); $res->setHeader('Content-Transfer-Encoding', 'binary'); $res->setHeader('Connection', 'close'); $res->setHeader('ETag', FDTools::getETag($file->sourceFile)); $res->setHeader('Content-Length', FDTools::filesize($file->sourceFile)); // Cache control if ($file->enableBrowserCache) { $this->setupCacheHeaders($file); } else { $this->setupNonCacheHeaders($file); } }
/** * Handles uploaded files * forwards it to model */ public function handleUploads() { // Iterujeme nad přijatými soubory foreach (\Nette\Environment::getHttpRequest()->getFiles() as $name => $controlValue) { // MFU vždy posílá soubory v této struktuře: // // array( // "token" => "blablabla", // "files" => array( // 0 => HttpUploadedFile(...), // ... // ) // ) $isFormMFU = (is_array($controlValue) and isset($controlValue["files"]) and isset($_POST[$name]["token"])); if ($isFormMFU) { $token = $_POST[$name]["token"]; foreach ($controlValue["files"] as $file) { self::processFile($token, $file); } } // soubory, které se netýkají MFU nezpracujeme -> zpracuje si je standardním způsobem formulář } return true; // Skip all next }
/** * @return Template */ protected function createTemplate($file = null) { $template = new Template($file); $template->baseUrl = \Nette\Environment::getHttpRequest()->url->baseUrl; $template->basePath = rtrim($template->baseUrl, '/'); $template->interface = $this; $template->registerHelperLoader('Nette\\Templating\\Helpers::loader'); return $template; }
/** * Handles uploaded files * forwards it to model */ public function handleUploads() { if (!isset($_POST["token"])) { return; } /* @var $token string */ $token = $_POST["token"]; /* @var $file \Nette\Http\FileUpload */ foreach (Environment::getHttpRequest()->getFiles() as $file) { self::processFile($token, $file); } // Response to client echo "1"; // End the script exit; }
/** * Make relative url absolute * @param string image url * @param string single or double quote * @param string absolute css file path * @param string source path * @return string */ public static function absolutizeUrl($url, $quote, $cssFile, $sourcePath) { // is already absolute if (preg_match("/^([a-z]+:\\/)?\\//", $url)) { return $url; } $docroot = realpath(WWW_DIR); $basePath = rtrim(Environment::getHttpRequest()->getUrl()->getScriptPath(), '/'); // inside document root if (Strings::startsWith($cssFile, $docroot)) { $path = $basePath . substr(dirname($cssFile), strlen($docroot)) . DIRECTORY_SEPARATOR . $url; // outside document root } else { $path = $basePath . substr($sourcePath, strlen($docroot)) . DIRECTORY_SEPARATOR . $url; } //$path = self::cannonicalizePath($path); return $quote === '"' ? addslashes($path) : $path; }
public function setUrl($url) { $uriScript = new UriScript($url); $uriScript->setScriptPath(Environment::getHttpRequest()->getUri()->getScriptPath()); $httpRequest = new HttpRequest($uriScript); $presenterRequest = Environment::getApplication()->getRouter()->match($httpRequest); if ($presenterRequest === null || !String::startsWith($url, Environment::getVariable("baseUri"))) { $this->url = $url ?: null; $this->destination = null; $this->params = array(); } else { $presenter = $presenterRequest->getPresenterName(); $params = $presenterRequest->getParams(); $action = isset($params["action"]) ? $params["action"] : "default"; $module = isset($params["module"]) ? $params["module"] . ":" : ""; unset($params["action"]); $this->destination = "{$module}{$presenter}:{$action}"; $this->params = $params; $this->url = null; } }
/** * @return ITemplate */ protected function createTemplate($file = null) { $template = new Nette\Templating\FileTemplate($file); //$presenter = Environment::getApplication()->getPresenter(); $template->onPrepareFilters[] = array($this, 'templatePrepareFilters'); // default parameters //$template->control = $this; //$template->presenter = $presenter; $template->baseUrl = \Nette\Environment::getHttpRequest()->url->baseUrl; $template->basePath = rtrim($template->baseUrl, '/'); $template->baseModulePath = $template->basePath . '/modules/multipleFileUpload'; // flash message /*if ($presenter !== NULL && $presenter->hasFlashSession()) { $id = $this->getParamId('flash'); $template->flashes = $presenter->getFlashSession()->$id; } if (!isset($template->flashes) || !is_array($template->flashes)) { $template->flashes = array(); }*/ $template->registerHelperLoader('Nette\\Templating\\Helpers::loader'); return $template; }
/** * @return Nette\Web\IHttpRequest */ public function getRequest() { return Nette\Environment::getHttpRequest(); }
/** * Handle edit */ public function handleEdit() { if ($this->presenter->isAjax()) { $post = \Nette\Environment::getHttpRequest()->getPost(); foreach ($post as $column => $value) { if ($column == 'id' || $this['columns']->getComponent($column)->isEditable()) { continue; } throw new \Nette\Application\ForbiddenRequestException("Column {$column} is not editable"); } call_user_func($this->editHandler, $post); } }
/** * Download file! * @param BaseFileDownload $file */ function download(BaseFileDownload $transfer) { $this->currentTransfer = $transfer; $this->sendStandardFileHeaders($transfer, $this); @ignore_user_abort(true); // For onAbort event $req = Environment::getHttpRequest(); $res = Environment::getHttpResponse(); $filesize = $this->size = $transfer->sourceFileSize; $this->length = $this->size; // Content-length $this->start = 0; $this->end = $this->size - 1; /* ### Headers ### */ // Now that we've gotten so far without errors we send the accept range header /* At the moment we only support single ranges. * Multiple ranges requires some more work to ensure it works correctly * and comply with the spesifications: http://www.w3.org/Protocols/rfc2616/rfc2616-sec19.html#sec19.2 * * Multirange support annouces itself with: * header('Accept-Ranges: bytes'); * * Multirange content must be sent with multipart/byteranges mediatype, * (mediatype = mimetype) * as well as a boundry header to indicate the various chunks of data. */ //$res->setHeader("Accept-Ranges", "0-".$this->end); // single-part - now not accepted by mozilla $res->setHeader("Accept-Ranges", "bytes"); // multi-part (through Mozilla) // http://www.w3.org/Protocols/rfc2616/rfc2616-sec19.html#sec19.2 if ($req->getHeader("Range", false)) { try { $range_start = $this->start; $range_end = $this->end; // Extract the range string $rangeArray = explode('=', $req->getHeader("Range"), 2); $range = $rangeArray[1]; // Make sure the client hasn't sent us a multibyte range if (strpos($range, ',') !== false) { // (?) Shoud this be issued here, or should the first // range be used? Or should the header be ignored and // we output the whole content? throw new FileDownloaderException("HTTP 416", 416); } // If the range starts with an '-' we start from the beginning // If not, we forward the file pointer // And make sure to get the end byte if spesified if ($range[0] == '-') { // The n-number of the last bytes is requested $range_start = $this->size - (double) substr($range, 1); } else { $range = explode('-', $range); $range_start = $range[0]; $range_end = isset($range[1]) && is_numeric($range[1]) ? $range[1] : $this->size; } /** * Check the range and make sure it's treated according to the specs. * @link http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html */ // End bytes can not be larger than $end. $range_end = $range_end > $this->end ? $this->end : $range_end; // Validate the requested range and return an error if it's not correct. if ($range_start > $range_end || $range_start > $this->size - 1 || $range_end >= $this->size) { throw new FileDownloaderException("HTTP 416", 416); } // All is ok - so assign variables back $this->start = $range_start; $this->end = $range_end; $this->length = $this->end - $this->start + 1; // Calculate new content length } catch (FileDownloaderException $e) { if ($e->getCode() === 416) { $res->setHeader("Content-Range", "bytes {$this->start}-{$this->end}/{$this->size}"); FDTools::_HTTPError(416); } else { throw $e; } } $res->setCode(206); // Partial content } // End of if partial download // Notify the client the byte range we'll be outputting $res->setHeader("Content-Range", "bytes {$this->start}-{$this->end}/{$this->size}"); $res->setHeader("Content-Length", $this->length); /* ### Call callbacks ### */ $transfer->onBeforeOutputStarts($transfer, $this); if ($this->start > 0) { $transfer->onTransferContinue($transfer, $this); } else { $transfer->onNewTransferStart($transfer, $this); } /* ### Send file to browser - document body ### */ $buffer = FDTools::$readFileBuffer; $sleep = false; if (is_int($transfer->speedLimit) and $transfer->speedLimit > 0) { $sleep = true; $buffer = (int) round($transfer->speedLimit); } $this->sleep = $sleep; if ($buffer < 1) { throw new InvalidArgumentException("Buffer must be bigger than zero!"); } if ($buffer > FDTools::getAvailableMemory() - memory_get_usage()) { throw new InvalidArgumentException("Buffer is too big! (bigger than available memory)"); } $this->buffer = $buffer; $fp = fopen($transfer->sourceFile, "rb"); // TODO: Add flock() READ if (!$fp) { throw new InvalidStateException("Can't open file for reading!"); } if ($this->end === null) { $this->end = $filesize - 1; } if (fseek($fp, $this->start, SEEK_SET) === -1) { // Move file pointer to the start of the download // Can not move pointer to begining of the filetransfer if ($this->processByCUrl() === true) { // Request was hadled by curl, clean, exit $this->cleanAfterTransfer(); return; } // Use this hack (fread file to start position) $destPos = $this->position = PHP_INT_MAX - 1; if (fseek($fp, $this->position, SEEK_SET) === -1) { rewind($fp); $this->position = 0; throw new InvalidStateException("Can not move pointer to position ({$destPos})"); } $maxBuffer = 1024 * 1024; while ($this->position < $this->start) { $this->position += strlen(fread($fp, min($maxBuffer, $this->start - $this->position))); } } else { // We are at the begining $this->position = $this->start; } $this->processNative($fp, $sleep); $this->cleanAfterTransfer(); }
/** * @return Nette\Application\Application */ public static function createApplication() { if (Environment::getVariable('baseUri', NULL) === NULL) { Environment::setVariable('baseUri', Environment::getHttpRequest()->getUri()->getBasePath()); } $context = clone Environment::getContext(); $context->addService('Nette\\Application\\IRouter', 'Nette\\Application\\MultiRouter'); if (!$context->hasService('Nette\\Application\\IPresenterLoader')) { $context->addService('Nette\\Application\\IPresenterLoader', function () { return new Nette\Application\PresenterLoader(Environment::getVariable('appDir')); }); } $application = new Nette\Application\Application(); $application->setContext($context); $application->catchExceptions = Environment::isProduction(); return $application; }
/** * Get the user's browser information * * @return array */ public static function getUserBrowser() { $browser = ['userBrowser' => '', 'userVersion' => 0]; $userAgent = \Nette\Environment::getHttpRequest()->getHeader('user-agent'); // MSIE if (preg_match('/mozilla.*?MSIE ([0-9a-z\\+\\-\\.]+).*/si', $userAgent, $match)) { $browser['userBrowser'] = 'IE'; $browser['userVersion'] = $match[1]; } elseif (preg_match('/mozilla.*rv:([0-9a-z\\+\\-\\.]+).*gecko.*/si', $userAgent, $match)) { $browser['userBrowser'] = 'Gecko'; $browser['userVersion'] = $match[1]; } elseif (preg_match('/mozilla.*applewebkit\\/([0-9a-z\\+\\-\\.]+).*/si', $userAgent, $match)) { $browser['userBrowser'] = 'Webkit'; $browser['userVersion'] = $match[1]; } elseif (preg_match('/mozilla.*opera ([0-9a-z\\+\\-\\.]+).*/si', $userAgent, $match) || preg_match('/^opera\\/([0-9a-z\\+\\-\\.]+).*/si', $userAgent, $match)) { $browser['userBrowser'] = 'Opera'; $browser['userVersion'] = $match[1]; } elseif (preg_match('/mozilla.*applewebkit\\/([0-9a-z\\+\\-\\.]+).*mobile.*/si', $userAgent, $match)) { $browser['userBrowser'] = 'SafMob'; $browser['userVersion'] = $match[1]; } elseif (preg_match('/mozilla.*MSIE ([0-9a-z\\+\\-\\.]+).*Mac.*/si', $userAgent, $match)) { $browser['userBrowser'] = 'IEMac'; $browser['userVersion'] = $match[1]; } elseif (preg_match('/PPC.*IEMobile ([0-9a-z\\+\\-\\.]+).*/si', $userAgent, $match)) { $browser['userBrowser'] = 'IEMob'; $browser['userVersion'] = '1.0'; } elseif (preg_match('/mozilla.*konqueror\\/([0-9a-z\\+\\-\\.]+).*/si', $userAgent, $match)) { $browser['userBrowser'] = 'Konq'; $browser['userVersion'] = $match[1]; } elseif (preg_match('/mozilla.*PSP.*; ([0-9a-z\\+\\-\\.]+).*/si', $userAgent, $match)) { $browser['userBrowser'] = 'PSP'; $browser['userVersion'] = $match[1]; } elseif (preg_match('/mozilla.*NetFront\\/([0-9a-z\\+\\-\\.]+).*/si', $userAgent, $match)) { $browser['userBrowser'] = 'NetF'; $browser['userVersion'] = $match[1]; } // Round the version number to one decimal place if (($iDot = strpos($browser['userVersion'], '.')) > 0) { $browser['userVersion'] = substr($browser['userVersion'], 0, $iDot + 2); } return $browser; }
/** * Handles uploading files */ public static function handleUploads() { // Pokud už bylo voláno handleUploads -> skonči if (self::$handleUploadsCalled === true) { return; } else { self::$handleUploadsCalled = true; } $req = Environment::getHttpRequest(); // Workaround for: http://forum.nettephp.com/cs/3680-httprequest-getheaders-a-content-type $contentType = $req->getHeader("content-type"); if (!$contentType and isset($_SERVER["CONTENT_TYPE"])) { $contentType = $_SERVER["CONTENT_TYPE"]; } if ($req->getMethod() !== "POST") { return; } self::getQueuesModel()->initialize(); foreach (self::getUIRegistrator()->getInterfaces() as $interface) { // \Nette\Diagnostics\Debugger::log($interface->getReflection()->getName().": is this your upload? ".$interface->isThisYourUpload()); if ($interface->isThisYourUpload()) { $ret = $interface->handleUploads(); if ($ret === true) { break; } } } }
/** * Upload souboru */ public function actionUpload() { // check rights if (!$this->getUser()->isInRole("admin")) { $this->sendError("Access denied."); } // path $folder = Environment::getHttpRequest()->getPost("folder"); try { $folderPath = $this->getFolderPath($folder); } catch (InvalidArgumentException $e) { $this->sendError("Folder does not exist or is not writeable."); } // file $file = Environment::getHttpRequest()->getFile("file"); // check if ($file === null || !$file->isOk()) { $this->sendError("Upload error."); } // move $fileName = String::webalize($file->getName(), "."); $path = $folderPath . "/" . $fileName; if (@$file->move($path)) { @chmod($path, 0666); if ($file->isImage()) { $this->payload->filename = ($folder ? "{$folder}/" : "") . $fileName; $this->payload->type = "image"; } else { $this->payload->filename = $this->baseFolderUri . ($folder ? "{$folder}/" : "") . $fileName; $this->payload->type = "file"; } $this->sendResponse(new JsonResponse($this->payload, "text/plain")); } else { $this->sendError("Move failed."); } }
/** * @return Nette\Http\Session */ protected function getSession() { if (!$this->httpRequest) { $this->httpRequest = Nette\Environment::getHttpRequest(); } return Nette\Environment::getSession(); }
/** * Handles uploaded files * forwards it to model */ public function handleUploads() { /* @var $token string */ $token = Environment::getHttpRequest()->getQuery("token"); if (empty($token)) { return; } // HTTP headers for no cache etc header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); header("Cache-Control: no-store, no-cache, must-revalidate"); header("Cache-Control: post-check=0, pre-check=0", false); header("Pragma: no-cache"); // Settings $queueModel = MultipleFileUpload::getQueuesModel()->getQueue($token); $targetDir = $queueModel->getUploadedFilesTemporaryPath(); $cleanupTargetDir = false; // Remove old files $maxFileAge = 60 * 60; // Temp file age in seconds // 5 minutes execution time @set_time_limit(5 * 60); // Uncomment this one to fake upload time // usleep(5000); // Get parameters $chunk = isset($_REQUEST["chunk"]) ? $_REQUEST["chunk"] : 0; $chunks = isset($_REQUEST["chunks"]) ? $_REQUEST["chunks"] : 0; $fileName = isset($_REQUEST["name"]) ? $_REQUEST["name"] : ''; $fileNameOriginal = $fileName; $fileName = sha1($token . $chunks . $fileNameOriginal); $filePath = $targetDir . DIRECTORY_SEPARATOR . $fileName; // Clean the fileName for security reasons $fileName = preg_replace('/[^\\w\\._]+/', '', $fileName); // Make sure the fileName is unique but only if chunking is disabled if ($chunks < 2 && file_exists($targetDir . DIRECTORY_SEPARATOR . $fileName)) { $ext = strrpos($fileName, '.'); $fileName_a = substr($fileName, 0, $ext); $fileName_b = substr($fileName, $ext); $count = 1; while (file_exists($targetDir . DIRECTORY_SEPARATOR . $fileName_a . '_' . $count . $fileName_b)) { $count++; } $fileName = $fileName_a . '_' . $count . $fileName_b; } // Create target dir if (!file_exists($targetDir)) { @mkdir($targetDir); } // Remove old temp files if (is_dir($targetDir) && ($dir = opendir($targetDir))) { while (($file = readdir($dir)) !== false) { $filePathTemp = $targetDir . DIRECTORY_SEPARATOR . $file; // Remove temp files if they are older than the max age if (preg_match('/\\.tmp$/', $file) && filemtime($filePathTemp) < time() - $maxFileAge) { @unlink($filePathTemp); } } closedir($dir); } else { die('{"jsonrpc" : "2.0", "error" : {"code": 100, "message": "Failed to open temp directory."}, "id" : "id"}'); } // 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'])) { $tmpPath = $filePath . "-uploadTmp"; move_uploaded_file($_FILES['file']['tmp_name'], $tmpPath); // Open base restriction bugfix // Open temp file $out = fopen($filePath, $chunk == 0 ? "wb" : "ab"); if ($out) { // Read binary input stream and append it to temp file $in = fopen($tmpPath, "rb"); if ($in) { while ($buff = fread($in, 4096)) { fwrite($out, $buff); } } else { die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}'); } fclose($in); fclose($out); @unlink($tmpPath); } else { die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}'); } } else { die('{"jsonrpc" : "2.0", "error" : {"code": 103, "message": "Failed to move uploaded file."}, "id" : "id"}'); } } else { // Open temp file $out = fopen($filePath, $chunk == 0 ? "wb" : "ab"); if ($out) { // Read binary input stream and append it to temp file $in = fopen("php://input", "rb"); if ($in) { while ($buff = fread($in, 4096)) { fwrite($out, $buff); } } else { die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}'); } fclose($in); fclose($out); } else { die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}'); } } if ($chunk == 0) { $queueModel->addFileManually($fileName, $chunk + 1, $chunks); } $file = null; $nonChunkedTransfer = ($chunk == 0 and $chunks == 0); $lastChunk = $chunk + 1 == $chunks; if ($lastChunk or $nonChunkedTransfer) { // Hotovo $file = new \Nette\Http\FileUpload(array('name' => $fileNameOriginal, 'type' => "", 'size' => filesize($filePath), 'tmp_name' => $filePath, 'error' => UPLOAD_ERR_OK)); } if ($file or $chunk > 0) { $queueModel->updateFile($fileName, $chunk + 1, $file); } // Return JSON-RPC response die('{"jsonrpc" : "2.0", "result" : null, "id" : "id"}'); /* @var $file Nette\Http\FileUpload */ /* foreach(Environment::getHttpRequest()->getFiles() AS $file) { self::processFile($token, $file); } // Response to client echo "1"; // End the script exit; */ }
/** * Download the file! * @param IDownloader $downloader */ function download(IDownloader $downloader = null) { $req = Environment::getHttpRequest(); $res = Environment::getHttpResponse(); if (self::$closeSession) { $ses = Environment::getSession(); if ($ses->isStarted()) { $ses->close(); } } if ($this->getContentDisposition() == "inline" and is_null($this->enableBrowserCache)) { $this->enableBrowserCache = true; } else { $this->enableBrowserCache = false; } if ($downloader === null) { $downloaders = self::getFileDownloaders(); } else { $downloaders = array($downloader); } if (count($downloaders) <= 0) { throw new InvalidStateException("There is no registred downloader!"); } krsort($downloaders); $lastException = null; foreach ($downloaders as $downloader) { if ($downloader instanceof IDownloader and $downloader->isCompatible($this)) { try { FDTools::clearHeaders($res); // Delete all headers $this->transferredBytes = 0; $this->onBeforeDownloaderStarts($this, $downloader); $downloader->download($this); // Start download $this->onComplete($this, $downloader); die; // If all gone ok -> die } catch (FDSkypeMeException $e) { if ($res->isSent()) { throw new InvalidStateException("Headers are already sent! Can't skip downloader."); } else { continue; } } catch (Exception $e) { if (!$res->isSent()) { FDTools::clearHeaders($res); } throw $e; } } } // Pokud se soubor nějakým způsobem odešle - toto už se nespustí if ($lastException instanceof Exception) { FDTools::clearHeaders(Environment::getHttpResponse(), TRUE); throw $lastException; } if ($req->getHeader("Range")) { FDTools::_HTTPError(416); } else { $res->setCode(500); } throw new InvalidStateException("There is no compatible downloader (all downloader returns downloader->isComplatible()=false or was skipped)!"); }
/** * @return Nette\Application\Application */ public static function createApplication(array $options = NULL) { if (Environment::getVariable('baseUri', NULL) === NULL) { Environment::setVariable('baseUri', Environment::getHttpRequest()->getUri()->getBaseUri()); } $context = clone Environment::getContext(); $context->addService('Nette\\Application\\IRouter', 'Nette\Application\MultiRouter'); if (!$context->hasService('Nette\\Application\\IPresenterFactory')) { $context->addService('Nette\\Application\\IPresenterFactory', function() use ($context) { return new Nette\Application\PresenterFactory(Environment::getVariable('appDir'), $context); }); } $class = isset($options['class']) ? $options['class'] : 'Nette\Application\Application'; $application = new $class; $application->setContext($context); $application->catchExceptions = Environment::isProduction(); return $application; }
public function __construct() { $this->httpRequest = Environment::getHttpRequest(); }
/** * @return Nette\Web\IHttpRequest */ protected function getHttpRequest() { return class_exists('Nette\\Environment') ? Nette\Environment::getHttpRequest() : new Nette\Web\HttpRequest(); }
/** * Returns filename (but if IE fix the bug) * * @link http://cz2.php.net/manual/en/function.fpassthru.php#25801 * @author Unknown * @param string $basename Path to file or filename * @return string */ static function getContentDispositionHeaderData($basename) { $basename = basename($basename); $req = Environment::getHttpRequest(); $userAgent = $req->getHeader("User-Agent"); if ($userAgent and strstr($userAgent, "MSIE")) { // workaround for IE filename bug with multiple periods / multiple dots in filename // that adds square brackets to filename - eg. setup.abc.exe becomes setup[1].abc.exe $iefilename = preg_replace('/\\./', '%2e', $basename, substr_count($basename, '.') - 1); $basename = rawurlencode($basename); // Czech chars in filename } return $basename; }
/** * @param $presenter Presenter * @param $response PresenterResponse * @internal */ public function onShutdown($presenter, $response) { $this->response = $response; $application = Environment::getApplication(); $presenter = $application->getPresenter(); $request = $presenter->getRequest(); $httpRequest = Environment::getHttpRequest(); $entry = array(); if ($signal = $presenter->getSignal()) { $receiver = empty($signal[0]) ? $presenter->name : $signal[0]; $signal = $receiver . " :: " . $signal[1]; } if ($response !== NULL) { $rInfo = get_class($response); if ($response->getReflection()->hasMethod('getCode')) { $rInfo .= ' (' . $response->code . ')'; } } $entry['info']['presenter'] = $presenter->backlink(); $entry['info']['response'] = $response === NULL ? 'NO RESPONSE' : $rInfo; $entry['info']['uri'] = $httpRequest->getUrl(); $entry['info']['uriPath'] = $httpRequest->getUrl()->path; $entry['info']['request'] = $request->getMethod(); $entry['info']['signal'] = $signal; $entry['info']['time'] = number_format((microtime(TRUE) - Debugger::$time) * 1000, 1, '.', ' '); $entry['dumps']['HttpRequest'] = Helpers::clickableDump($httpRequest); $entry['dumps']['PresenterRequest'] = Helpers::clickableDump($request); $entry['dumps']['Presenter'] = Helpers::clickableDump($presenter); $entry['dumps']['PresenterResponse'] = Helpers::clickableDump($response); foreach (self::$dumps as $key => $dump) { if (is_numeric($key)) { $entry['dumps'][] = $dump; } else { $entry['dumps'][$key] = $dump; } } $session = Environment::getSession('debug/RequestsPanel'); if (!isset($session->logs)) { $session->logs = array(); } $session->logs[] = $entry; }
/** @return Nette\Templating\FileTemplate */ public function getTemplate() { $template = new Nette\Templating\FileTemplate(); $template->registerFilter(new Nette\Latte\Engine()); $template->registerHelper('json', function ($array) { return json_encode($array); }); $template->registerHelper('toArray', function ($array) { if ($array instanceof \Traversable) { $array = iterator_to_array($array); } return array_map(function ($object) { return $object->toArray(); }, $array); }); $template->setFile(__DIR__ . '/template.latte'); $template->basePath = Nette\Environment::getHttpRequest()->getUrl()->basePath; return $template; }
/** * @return Nette\Web\IHttpRequest */ protected function getHttpRequest() { return Nette\Environment::getHttpRequest(); }
/** * Returns current HTTP request. * * @author David Grudl * @return Nette\Web\HttpRequest */ protected function getHttpRequest() { return Env::getHttpRequest(); }