Esempio n. 1
0
 public static function createEntityManager($database)
 {
     $config = new Doctrine\ORM\Configuration();
     // annotations
     $annotationDriver = $config->newDefaultAnnotationDriver(array(APP_DIR . '/Model', NEURON_DIR . '/Model'));
     $config->setMetadataDriverImpl($annotationDriver);
     // proxy
     $config->setProxyNamespace('Neuron\\Proxy');
     $config->setProxyDir(TEMP_DIR);
     // cache
     $cache = Environment::isProduction() ? new NetteDoctrineCache() : new Doctrine\Common\Cache\ArrayCache();
     $config->setMetadataCacheImpl($cache);
     $config->setQueryCacheImpl($cache);
     // debugbar
     $config->setSQLLogger(Doctrine2Panel::getAndRegister());
     // entity manager
     $em = Doctrine\ORM\EntityManager::create((array) $database, $config);
     $evm = $em->getEventManager();
     $evm->addEventSubscriber(new Doctrine\DBAL\Event\Listeners\MysqlSessionInit("utf8", "utf8_czech_ci"));
     $evm->addEventSubscriber(new ValidationSubscriber());
     $evm->addEventSubscriber(new CacheSubscriber());
     $neonParser = new \Nette\NeonParser();
     $aliases = $neonParser->parse(file_get_contents(APP_DIR . "/entityClassAliases.neon"));
     $evm->addEventSubscriber(new \Neuron\Model\Doctrine\EntityClassAliasesSubscriber($aliases));
     return $em;
 }
Esempio n. 2
0
 /**
  * @param Nette\Web\IHttpRequest $httpRequest
  * @return Nette\Application\PresenterRequest|NULL
  */
 public function match(\Nette\Http\IRequest $httpRequest)
 {
     /** @var $appRequest \Nette\Application\Request */
     $appRequest = parent::match($httpRequest);
     // doplněno: pokud match vrátí NULL, musíme také vrátit NULL
     if (!$appRequest) {
         return $appRequest;
     }
     // musím si přeložit host, kvůli localhostu to není dané
     if (strpos($httpRequest->url->host, '.localhost') !== false && !\Nette\Environment::isProduction()) {
         // jsme na localhostu
         $host = substr($httpRequest->url->host, 0, strripos($httpRequest->url->host, '.localhost'));
         // musíme si doménu osamostatnit od .localhost
         $host = str_replace('_', '.', $host);
         // na lokálu mám místo teček podtržení
     } else {
         // jsme na produkci
         $host = $httpRequest->url->host;
     }
     // zkusím zda je soubor již v cache
     if (is_file(WEB_DIR . '/' . $host . '/cache' . $httpRequest->url->path)) {
         return new Nette\Application\Request('Frontend', 'POST', array('action' => 'cache', 'file' => WEB_DIR . '/' . $host . '/cache' . $httpRequest->url->path));
     }
     /*
     if ($params = $this->doFilterParams($this->getRequestParams($appRequest), $appRequest, self::WAY_IN)) {
     	return $this->setRequestParams($appRequest, $params);
     }
     */
     // $pages = $this->context->createPages();
     $data = array('action' => 'default');
     return new Nette\Application\Request('Frontend', 'POST', $data);
 }
Esempio n. 3
0
 public function __construct(\Nette\IComponentContainer $parent = null, $name = null)
 {
     parent::__construct($parent, $name);
     $this->setJoinFiles(Environment::isProduction());
     $this->setTempUri(Environment::getVariable("baseUri") . "data/webtemp");
     $this->setTempPath(WWW_DIR . "/data/webtemp");
     $this->setSourcePath(WWW_DIR . "/js");
     $presenter = Environment::getApplication()->getPresenter();
     $this->filters[] = new VariablesFilter(array("baseUri" => Environment::getVariable("baseUri"), "texylaPreviewPath" => $presenter->link(":Texyla:preview"), "texylaFilesPath" => $presenter->link(":Texyla:listFiles"), "texylaFilesUploadPath" => $presenter->link(":Texyla:upload")));
     if (Environment::isProduction()) {
         $this->filters[] = "JSMin::minify";
     }
     $this->init();
 }
Esempio n. 4
0
 public function __construct(\Nette\IComponentContainer $parent = null, $name = null)
 {
     parent::__construct($parent, $name);
     $this->setSourcePath(WWW_DIR . "/css");
     $this->setTempUri(Environment::getVariable("baseUri") . "data/webtemp");
     $this->setTempPath(WWW_DIR . "/data/webtemp");
     $this->setJoinFiles(Environment::isProduction());
     $this->fileFilters[] = new Webloader\LessFilter();
     if (Environment::isProduction()) {
         $this->filters[] = function ($code) {
             return cssmin::minify($code, "remove-last-semicolon");
         };
     }
     $this->init();
 }
Esempio n. 5
0
 /**
  * Invoke filter
  *
  * @param string $code
  * @param \Lohini\WebLoader\WebLoader $loader
  * @param string $file
  * @return string
  */
 public function __invoke($code, \Lohini\WebLoader\WebLoader $loader, $file = NULL)
 {
     if ($file === NULL || !in_array(\Nette\Utils\Strings::lower(pathinfo($file, PATHINFO_EXTENSION)), [\PHPSass\File::SASS, \PHPSass\File::SCSS])) {
         return $code;
     }
     $so = ['style' => \PHPSass\Renderers\Renderer::STYLE_COMPRESSED, 'syntax' => pathinfo($file, PATHINFO_EXTENSION), 'load_paths' => [dirname($file)]];
     if (class_exists('PHPSass\\Extensions\\Compass')) {
         $so['functions'] = \PHPSass\Extensions\Compass::getFunctions('Compass');
         $so['extensions'] = ['Compass'];
         $so['load_paths'][] = dirname(\Nette\Reflection\ClassType::from('PHPSass\\Extensions\\Compass')->getFileName());
     }
     if (!\Nette\Environment::isProduction()) {
         $so['debug'] = TRUE;
         $so['debug_info'] = TRUE;
         $so['style'] = \PHPSass\Renderers\Renderer::STYLE_NESTED;
     }
     $filter = new \PHPSass\Parser($so);
     return $filter->toCss($file, TRUE);
 }
 public function handleFormSuccess(Form $form)
 {
     $data = $form->getValues();
     // Let's pass our data to template
     $this->template->values = $data;
     $queueId = uniqid();
     // Moving uploaded files
     foreach ($data["upload"] as $file) {
         // $file je instance HttpUploadedFile
         $newFilePath = \Nette\Environment::expand("%appDir%") . "/../uploadedFilesDemo/q{" . $queueId . "}__f{" . rand(10, 99) . "}__" . $file->getName();
         // V produkčním módu nepřesunujeme soubory...
         if (!\Nette\Environment::isProduction()) {
             if ($file->move($newFilePath)) {
                 $this->flashMessage("File " . $file->getName() . " was successfully moved!");
             } else {
                 $this->flashMessage("Error while moving file " . $file->getName() . ".");
             }
         }
     }
 }
Esempio n. 7
0
 /**
  * @return bool
  */
 protected function isProduction()
 {
     return Nette\Environment::isProduction();
 }
Esempio n. 8
0
 /**
  * Enables displaying or logging errors and exceptions.
  * @param  mixed         production, development mode, autodetection or IP address(es) whitelist.
  * @param  string        error log directory; enables logging in production mode, FALSE means that logging is disabled
  * @param  string        administrator email; enables email sending in production mode
  * @return void
  */
 public static function enable($mode = NULL, $logDirectory = NULL, $email = NULL)
 {
     error_reporting(E_ALL | E_STRICT);
     // production/development mode detection
     if (is_bool($mode)) {
         self::$productionMode = $mode;
     } elseif (is_string($mode)) {
         // IP addresses
         $mode = preg_split('#[,\\s]+#', "{$mode} 127.0.0.1 ::1");
     }
     if (is_array($mode)) {
         // IP addresses whitelist detection
         self::$productionMode = !isset($_SERVER['REMOTE_ADDR']) || !in_array($_SERVER['REMOTE_ADDR'], $mode, TRUE);
     }
     if (self::$productionMode === self::DETECT) {
         if (class_exists('Nette\\Environment')) {
             self::$productionMode = Environment::isProduction();
         } elseif (isset($_SERVER['SERVER_ADDR']) || isset($_SERVER['LOCAL_ADDR'])) {
             // IP address based detection
             $addrs = array();
             if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
                 // proxy server detected
                 $addrs = preg_split('#,\\s*#', $_SERVER['HTTP_X_FORWARDED_FOR']);
             }
             if (isset($_SERVER['REMOTE_ADDR'])) {
                 $addrs[] = $_SERVER['REMOTE_ADDR'];
             }
             $addrs[] = isset($_SERVER['SERVER_ADDR']) ? $_SERVER['SERVER_ADDR'] : $_SERVER['LOCAL_ADDR'];
             self::$productionMode = FALSE;
             foreach ($addrs as $addr) {
                 $oct = explode('.', $addr);
                 if ($addr !== '::1' && (count($oct) !== 4 || $oct[0] !== '10' && $oct[0] !== '127' && ($oct[0] !== '172' || $oct[1] < 16 || $oct[1] > 31) && ($oct[0] !== '169' || $oct[1] !== '254') && ($oct[0] !== '192' || $oct[1] !== '168'))) {
                     self::$productionMode = TRUE;
                     break;
                 }
             }
         } else {
             self::$productionMode = !self::$consoleMode;
         }
     }
     // logging configuration
     if (is_string($logDirectory) || $logDirectory === FALSE) {
         self::$logDirectory = $logDirectory;
     } else {
         self::$logDirectory = defined('APP_DIR') ? APP_DIR . '/../log' : getcwd() . '/log';
     }
     if (self::$logDirectory) {
         ini_set('error_log', self::$logDirectory . '/php_error.log');
     }
     // php configuration
     if (function_exists('ini_set')) {
         ini_set('display_errors', !self::$productionMode);
         // or 'stderr'
         ini_set('html_errors', FALSE);
         ini_set('log_errors', FALSE);
     } elseif (ini_get('display_errors') != !self::$productionMode && ini_get('display_errors') !== (self::$productionMode ? 'stderr' : 'stdout')) {
         // intentionally ==
         throw new \NotSupportedException('Function ini_set() must be enabled.');
     }
     if ($email) {
         if (!is_string($email)) {
             throw new \InvalidArgumentException('Email address must be a string.');
         }
         self::$email = $email;
     }
     if (!defined('E_DEPRECATED')) {
         define('E_DEPRECATED', 8192);
     }
     if (!defined('E_USER_DEPRECATED')) {
         define('E_USER_DEPRECATED', 16384);
     }
     if (!self::$enabled) {
         register_shutdown_function(array(__CLASS__, '_shutdownHandler'));
         set_exception_handler(array(__CLASS__, '_exceptionHandler'));
         set_error_handler(array(__CLASS__, '_errorHandler'));
         self::$enabled = TRUE;
     }
 }
Esempio n. 9
0
 /**
  * Invalid link handler. Descendant can override this method to change default behaviour.
  * @param  InvalidLinkException
  * @return string
  * @throws InvalidLinkException
  */
 protected function handleInvalidLink($e)
 {
     if (self::$invalidLinkMode === NULL) {
         self::$invalidLinkMode = Environment::isProduction() ? self::INVALID_LINK_SILENT : self::INVALID_LINK_WARNING;
     }
     if (self::$invalidLinkMode === self::INVALID_LINK_SILENT) {
         return '#';
     } elseif (self::$invalidLinkMode === self::INVALID_LINK_WARNING) {
         return 'error: ' . $e->getMessage();
     } else {
         // self::INVALID_LINK_EXCEPTION
         throw $e;
     }
 }
Esempio n. 10
0
 /**
  * @return Nette\Loaders\RobotLoader
  */
 public static function createRobotLoader($options)
 {
     $loader = new Nette\Loaders\RobotLoader();
     $loader->autoRebuild = isset($options['autoRebuild']) ? $options['autoRebuild'] : !Environment::isProduction();
     $loader->setCacheStorage(Environment::getService('Nette\\Caching\\ICacheStorage'));
     if (isset($options['directory'])) {
         $loader->addDirectory($options['directory']);
     } else {
         foreach (array('appDir', 'libsDir') as $var) {
             if ($dir = Environment::getVariable($var, NULL)) {
                 $loader->addDirectory($dir);
             }
         }
     }
     $loader->register();
     return $loader;
 }
Esempio n. 11
0
 /**
  * Enables displaying or logging errors and exceptions.
  * @param  mixed         production, development mode, autodetection or IP address(es).
  * @param  string        error log file (FALSE disables logging in production mode)
  * @param  array|string  administrator email or email headers; enables email sending in production mode
  * @return void
  */
 public static function enable($mode = NULL, $logFile = NULL, $email = NULL)
 {
     error_reporting(E_ALL | E_STRICT);
     // production/development mode detection
     if (is_bool($mode)) {
         self::$productionMode = $mode;
     } elseif (is_string($mode)) {
         // IP adresses
         $mode = preg_split('#[,\\s]+#', $mode);
     }
     if (is_array($mode)) {
         // IP adresses
         self::$productionMode = !isset($_SERVER['REMOTE_ADDR']) || !in_array($_SERVER['REMOTE_ADDR'], $mode, TRUE);
     }
     if (self::$productionMode === self::DETECT) {
         if (class_exists('Nette\\Environment')) {
             self::$productionMode = Environment::isProduction();
         } elseif (isset($_SERVER['SERVER_ADDR']) || isset($_SERVER['LOCAL_ADDR'])) {
             // IP address based detection
             $addr = isset($_SERVER['SERVER_ADDR']) ? $_SERVER['SERVER_ADDR'] : $_SERVER['LOCAL_ADDR'];
             $oct = explode('.', $addr);
             self::$productionMode = $addr !== '::1' && (count($oct) !== 4 || $oct[0] !== '10' && $oct[0] !== '127' && ($oct[0] !== '172' || $oct[1] < 16 || $oct[1] > 31) && ($oct[0] !== '169' || $oct[1] !== '254') && ($oct[0] !== '192' || $oct[1] !== '168'));
         } else {
             self::$productionMode = !self::$consoleMode;
         }
     }
     // logging configuration
     if (self::$productionMode && $logFile !== FALSE) {
         self::$logFile = 'log/php_error.log';
         if (class_exists('Nette\\Environment')) {
             if (is_string($logFile)) {
                 self::$logFile = Environment::expand($logFile);
             } else {
                 try {
                     self::$logFile = Environment::expand('%logDir%/php_error.log');
                 } catch (\InvalidStateException $e) {
                 }
             }
         } elseif (is_string($logFile)) {
             self::$logFile = $logFile;
         }
         ini_set('error_log', self::$logFile);
     }
     // php configuration
     if (function_exists('ini_set')) {
         ini_set('display_errors', !self::$productionMode);
         // or 'stderr'
         ini_set('html_errors', !self::$logFile && !self::$consoleMode);
         ini_set('log_errors', FALSE);
     } elseif (ini_get('display_errors') != !self::$productionMode && ini_get('display_errors') !== (self::$productionMode ? 'stderr' : 'stdout')) {
         // intentionally ==
         throw new \NotSupportedException('Function ini_set() must be enabled.');
     }
     self::$sendEmails = self::$logFile && $email;
     if (self::$sendEmails) {
         if (is_string($email)) {
             self::$emailHeaders['To'] = $email;
         } elseif (is_array($email)) {
             self::$emailHeaders = $email + self::$emailHeaders;
         }
     }
     if (!defined('E_DEPRECATED')) {
         define('E_DEPRECATED', 8192);
     }
     if (!defined('E_USER_DEPRECATED')) {
         define('E_USER_DEPRECATED', 16384);
     }
     register_shutdown_function(array(__CLASS__, '_shutdownHandler'));
     set_exception_handler(array(__CLASS__, '_exceptionHandler'));
     set_error_handler(array(__CLASS__, '_errorHandler'));
     self::$enabled = TRUE;
 }
Esempio n. 12
0
 /**
  * @return Nette\Loaders\RobotLoader
  */
 public static function createRobotLoader($options)
 {
     $loader = new Nette\Loaders\RobotLoader();
     $loader->autoRebuild = !Environment::isProduction();
     //$loader->setCache(Environment::getCache('Nette.RobotLoader'));
     $dirs = isset($options['directory']) ? $options['directory'] : array(Environment::getVariable('appDir'), Environment::getVariable('libsDir'));
     $loader->addDirectory($dirs);
     $loader->register();
     return $loader;
 }
Esempio n. 13
0
 public function onSubmit(Form $form)
 {
     $data = $form->getValues();
     // Předáme data do šablony
     $this->template->values = $data;
     $queueId = uniqid();
     \dibi::begin();
     $gallery_id = $this->gallery->insert(array("name" => $data["name"]));
     // Přesumene uploadované soubory
     foreach ($data["upload"] as $file) {
         // $file je instance HttpUploadedFile
         $newFilePath = FILESTORAGE_DIR . "/q{" . $queueId . "}__f{" . rand(10, 99) . "}__" . $file->getName();
         // V produkčním módu nepřesunujeme soubory...
         if (!Environment::isProduction()) {
             if ($file->move($newFilePath)) {
                 $this->flashMessage("Soubor " . $file->getName() . " byl úspěšně přesunut!");
             } else {
                 $this->flashMessage("Při přesouvání souboru " . $file->getName() . " nastala chyba! Pro více informací se podívejte do logů.");
             }
         }
         $this->files->insert($file);
         $this->gallery->addFile($gallery_id, $file_id);
         dump($file);
     }
     \dibi::commit();
 }
 /**
  * Cleans cache
  */
 public static function cleanCache()
 {
     if (!Environment::isProduction() or rand(1, 100) < 5) {
         self::getQueuesModel()->cleanup();
     }
 }
Esempio n. 15
0
 /**
  * Dispatch a HTTP request to a front controller.
  * @return void
  */
 public function run()
 {
     $httpRequest = $this->getHttpRequest();
     $httpResponse = $this->getHttpResponse();
     $httpRequest->setEncoding('UTF-8');
     if (Environment::getVariable('baseUri') === NULL) {
         Environment::setVariable('baseUri', $httpRequest->getUri()->getBasePath());
     }
     // autostarts session
     $session = $this->getSession();
     if (!$session->isStarted() && $session->exists()) {
         $session->start();
     }
     // enable routing debuggger
     Nette\Debug::addPanel(new RoutingDebugger($this->getRouter(), $httpRequest));
     // check HTTP method
     if ($this->allowedMethods) {
         $method = $httpRequest->getMethod();
         if (!in_array($method, $this->allowedMethods, TRUE)) {
             $httpResponse->setCode(Nette\Web\IHttpResponse::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);
                 // default router
                 $router = $this->getRouter();
                 if ($router instanceof MultiRouter && !count($router)) {
                     $router[] = new SimpleRouter(array('presenter' => 'Default', 'action' => 'default'));
                 }
                 // routing
                 $request = $router->match($httpRequest);
                 if (!$request instanceof PresenterRequest) {
                     $request = NULL;
                     throw new BadRequestException('No route for HTTP request.');
                 }
                 if (strcasecmp($request->getPresenterName(), $this->errorPresenter) === 0) {
                     throw new BadRequestException('Invalid request.');
                 }
             }
             $this->requests[] = $request;
             $this->onRequest($this, $request);
             // Instantiate presenter
             $presenter = $request->getPresenterName();
             try {
                 $class = $this->getPresenterLoader()->getPresenterClass($presenter);
                 $request->setPresenterName($presenter);
             } catch (InvalidPresenterException $e) {
                 throw new BadRequestException($e->getMessage(), 404, $e);
             }
             $request->freeze();
             // Execute presenter
             $this->presenter = new $class();
             $response = $this->presenter->run($request);
             // Send response
             if ($response instanceof ForwardingResponse) {
                 $request = $response->getRequest();
                 continue;
             } elseif ($response instanceof IPresenterResponse) {
                 $response->send();
             }
             break;
         } catch (\Exception $e) {
             // fault barrier
             if ($this->catchExceptions === NULL) {
                 $this->catchExceptions = Environment::isProduction();
             }
             $this->onError($this, $e);
             if (!$this->catchExceptions) {
                 $this->onShutdown($this, $e);
                 throw $e;
             }
             if ($repeatedError) {
                 $e = new ApplicationException('An error occured while executing error-presenter', 0, $e);
             }
             if (!$httpResponse->isSent()) {
                 $httpResponse->setCode($e instanceof BadRequestException ? $e->getCode() : 500);
             }
             if (!$repeatedError && $this->errorPresenter) {
                 $repeatedError = TRUE;
                 $request = new PresenterRequest($this->errorPresenter, PresenterRequest::FORWARD, array('exception' => $e));
                 // continue
             } else {
                 // default error handler
                 echo "<!DOCTYPE html><meta name=robots content=noindex>\n\n";
                 echo "<style>body{color:black;background:white;width:500px;margin:100px auto}h1{font:bold 47px/1.5 sans-serif;margin:.6em 0}p{font:21px/1.5 Georgia,serif;margin:1.5em 0}small{font-size:70%;color:gray}</style>\n\n";
                 if ($e instanceof BadRequestException) {
                     echo "<title>404 Not Found</title>\n\n<h1>Not Found</h1>\n\n<p>The requested URL was not found on this server.</p>";
                 } else {
                     Nette\Debug::processException($e, FALSE);
                     echo "<title>500 Internal Server Error</title>\n\n<h1>Server Error</h1>\n\n", "<p>The server encountered an internal error and was unable to complete your request. Please try again later.</p>";
                 }
                 echo "\n\n<hr>\n<small><i>Nette Framework</i></small>";
                 break;
             }
         }
     } while (1);
     $this->onShutdown($this, isset($e) ? $e : NULL);
 }