Exemplo n.º 1
0
 public function detectTo($params)
 {
     if (Environment::isProduction()) {
         return Configure::read('Mail.addresses.admin');
     } else {
         return Configure::read('Mail.addresses.debug');
     }
 }
Exemplo n.º 2
0
     $js = new JavaScriptLoader();
     $js->tempUri = Environment::getVariable("baseUri") . "js";
     $js->tempPath = WWW_DIR . "/js";
     $js->sourcePath = WWW_DIR;
     $js->joinFiles = Environment::isProduction();
     if (Environment::isProduction()) {
         //$js->filters[] = array($this, "packJs");
     }
     return $js;
 }
 protected function createComponentJs()
 {
Exemplo n.º 3
0
 public static function enable($mode = NULL, $logDirectory = NULL, $email = NULL)
 {
     error_reporting(E_ALL | E_STRICT);
     if (is_bool($mode)) {
         self::$productionMode = $mode;
     } elseif (is_string($mode)) {
         $mode = preg_split('#[,\\s]+#', "{$mode} 127.0.0.1 ::1");
     }
     if (is_array($mode)) {
         self::$productionMode = !isset($_SERVER['REMOTE_ADDR']) || !in_array($_SERVER['REMOTE_ADDR'], $mode, TRUE);
     }
     if (self::$productionMode === self::DETECT) {
         if (class_exists('Environment')) {
             self::$productionMode = Environment::isProduction();
         } elseif (isset($_SERVER['SERVER_ADDR']) || isset($_SERVER['LOCAL_ADDR'])) {
             $addrs = array();
             if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
                 $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;
         }
     }
     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');
     }
     if (function_exists('ini_set')) {
         ini_set('display_errors', !self::$productionMode);
         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')) {
         throw new NotSupportedException('Function ini_set() must be enabled.');
     }
     if ($email) {
         if (!is_string($email)) {
             throw new InvalidArgumentException('E-mail 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;
     }
 }
Exemplo n.º 4
0
 *
 * Development Mode:
 * 	1: Errors and warnings shown, model caches refreshed, flash messages halted.
 * 	2: As in 1, but also with full debug messages and SQL output.
 *
 * In production mode, flash messages redirect after a time interval.
 * In development mode, you need to click the flash message to continue.
 */
require_once APP . 'plugins' . DS . 'environment' . DS . 'libs' . DS . 'environment.php';
Environment::initialize(array('develop_server' => 'example.com', 'develop_domains' => array('hiromi'), 'production_server' => 'example.net', 'production_domains' => array('www')));
if (Environment::isProduction()) {
    Configure::write('debug', 0);
} else {
    Configure::write('debug', 2);
}
define('__SSL__REDIRECT', Environment::isProduction());
/**
 * CakePHP Log Level:
 *
 * In case of Production Mode CakePHP gives you the possibility to continue logging errors.
 *
 * The following parameters can be used:
 *  Boolean: Set true/false to activate/deactivate logging
 *    Configure::write('log', true);
 *
 *  Integer: Use built-in PHP constants to set the error level (see error_reporting)
 *    Configure::write('log', E_ERROR | E_WARNING);
 *    Configure::write('log', E_ALL ^ E_NOTICE);
 */
Configure::write('log', true);
/**
Exemplo n.º 5
0
 /**
  * @return RobotLoader
  */
 public static function createRobotLoader($options)
 {
     $loader = new 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;
 }
Exemplo n.º 6
0
 /**
  * @return bool
  */
 protected function isProduction()
 {
     return Environment::isProduction();
 }
Exemplo n.º 7
0
        $uri->path = String::fixEncoding($uri->path);
        $uri->scriptPath = '/';
        $req = new HttpRequest();
        $req->setUri($uri);
        return $req;
    }
    $serviceLocator = Environment::getServiceLocator();
    $httpReqServiceName = 'Nette\\Web\\IHttpRequest';
    $serviceLocator->removeService($httpReqServiceName);
    $serviceLocator->addService($httpReqServiceName, createHttpRequestService());
}
// Step 3: Configure application
// 3a) get and setup a front controller
$application = Environment::getApplication();
$application->errorPresenter = 'Front:Error';
if (Environment::isProduction() && Debug::$productionMode) {
    $application->catchExceptions = true;
} else {
    $application->catchExceptions = false;
}
dibi::connect(Environment::getConfig("database"));
// Step 4: Setup application router
$routes = array();
/* MENU ITEMS */
$routes[] = new Route('<lang [a-z]{2}>/<id>/', array('module' => 'Front', 'presenter' => 'Page', 'action' => 'default', 'id' => array(Route::FILTER_IN => callback('MenuSeoModel::findIdByUri'), Route::FILTER_OUT => callback('MenuSeoModel::findUriById')), 'lang' => NULL));
// setup CLI mode
if (Environment::isConsole()) {
    Debug::$productionMode = false;
    // to allow 'dump' render output
    $application->allowedMethods = false;
    $routes[] = new CliRouter(array('action' => 'Console:Default:default'));
Exemplo n.º 8
0
 /**
  * Enables displaying or logging errors and exceptions.
  * @param  bool          enable production mode? (NULL means autodetection)
  * @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($productionMode = NULL, $logFile = NULL, $email = NULL)
 {
     if (version_compare(PHP_VERSION, '5.2.1') === 0) {
         throw new NotSupportedException(__METHOD__ . ' is not supported in PHP 5.2.1');
         // PHP bug #40815
     }
     error_reporting(E_ALL | E_STRICT);
     // production/development mode detection
     if (is_bool($productionMode)) {
         self::$productionMode = $productionMode;
     }
     if (self::$productionMode === self::DETECT) {
         if (class_exists('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('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::$consoleMode);
         ini_set('log_errors', (bool) self::$logFile);
     } elseif (ini_get('log_errors') != (bool) self::$logFile || ini_get('display_errors') != !self::$productionMode && ini_get('display_errors') !== (self::$productionMode ? 'stderr' : 'stdout')) {
         throw new NotSupportedException('Function ini_set() must be enabled.');
     }
     self::$sendEmails = $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);
     }
     set_exception_handler(array(__CLASS__, 'exceptionHandler'));
     set_error_handler(array(__CLASS__, 'errorHandler'));
     register_shutdown_function(array(__CLASS__, 'shutdownHandler'));
     self::$enabled = TRUE;
     if (is_int($productionMode)) {
         // back compatibility
         //trigger_error('Debug::enable($errorLevel) is deprecated; Remove $errorLevel parameter.', E_USER_WARNING);
     }
 }
Exemplo n.º 9
0
 /**
  * Dispatch a HTTP request to a front controller.
  * @return void
  */
 public function run()
 {
     $httpRequest = $this->getHttpRequest();
     $httpResponse = $this->getHttpResponse();
     $httpRequest->setEncoding('UTF-8');
     $httpResponse->setHeader('X-Powered-By', 'Nette Framework');
     if (Environment::getVariable('baseUri') === NULL) {
         Environment::setVariable('baseUri', $httpRequest->getUri()->getBasePath());
     }
     // autostarts session
     $session = $this->getSession();
     if (!$session->isStarted() && $session->exists()) {
         $session->start();
     }
     // check HTTP method
     if ($this->allowedMethods) {
         $method = $httpRequest->getMethod();
         if (!in_array($method, $this->allowedMethods, TRUE)) {
             $httpResponse->setCode(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 "<meta name='robots' content='noindex'>\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 {
                     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);
 }
Exemplo n.º 10
0
 /**
  * Dispatch a HTTP request to a front controller.
  */
 public function run()
 {
     $httpRequest = $this->getHttpRequest();
     $httpResponse = $this->getHttpResponse();
     $httpRequest->setEncoding('UTF-8');
     $httpResponse->setHeader('X-Powered-By', 'Nette Framework');
     if (Environment::getVariable('baseUri') === NULL) {
         Environment::setVariable('baseUri', $httpRequest->getUri()->basePath);
     }
     // check HTTP method
     $method = $httpRequest->getMethod();
     if ($this->allowedMethods) {
         if (!in_array($method, $this->allowedMethods, TRUE)) {
             $httpResponse->setCode(IHttpResponse::S501_NOT_IMPLEMENTED);
             $httpResponse->setHeader('Allow', implode(',', $this->allowedMethods));
             $method = htmlSpecialChars($method);
             die("<h1>Method {$method} is not implemented</h1>");
         }
     }
     // dispatching
     $request = NULL;
     $hasError = 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->modify('name', $presenter);
             } catch (InvalidPresenterException $e) {
                 throw new BadRequestException($e->getMessage(), 404, $e);
             }
             $this->presenter = new $class($request);
             // Instantiate topmost service locator
             $this->presenter->setServiceLocator(new ServiceLocator($this->serviceLocator));
             // Execute presenter
             $this->presenter->run();
             break;
         } catch (RedirectingException $e) {
             // not error, presenter redirects to new URL
             $httpResponse->redirect($e->getUri(), $e->getCode());
             break;
         } catch (ForwardingException $e) {
             // not error, presenter forwards to new request
             $request = $e->getRequest();
         } catch (AbortException $e) {
             // not error, application is correctly terminated
             unset($e);
             break;
         } catch (Exception $e) {
             // fault barrier
             if ($this->catchExceptions === NULL) {
                 $this->catchExceptions = Environment::isProduction();
             }
             if (!$this->catchExceptions) {
                 throw $e;
             }
             $this->onError($this, $e);
             if ($hasError) {
                 $e = new ApplicationException('An error occured while executing error-presenter', 0, $e);
             } elseif ($this->errorPresenter) {
                 $hasError = TRUE;
                 $request = new PresenterRequest($this->errorPresenter, PresenterRequest::FORWARD, array('exception' => $e));
                 continue;
             }
             if ($e instanceof BadRequestException) {
                 if (!$httpResponse->isSent()) {
                     $httpResponse->setCode($e->getCode());
                 }
                 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>";
                 break;
             } else {
                 if (!$httpResponse->isSent()) {
                     $httpResponse->setCode(500);
                 }
                 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>";
                 break;
             }
         }
     } while (1);
     $this->onShutdown($this, isset($e) ? $e : NULL);
 }
Exemplo n.º 11
0
$loader->register();
/** 2e) load extension methods */
if (is_file(APP_DIR . '/extensions.php')) {
    include_once APP_DIR . '/extensions.php';
}
/** 2f) enable DebugBar */
if ($mode == Debug::DEVELOPMENT) {
    Debug::$showBar = TRUE;
}
/** 2g) Session setup [optional] */
if (Environment::getVariable('sessionDir') !== NULL && !is_writable(Environment::getVariable('sessionDir'))) {
    die("Make directory '" . realpath(Environment::getVariable('sessionDir')) . "' writable!");
}
$session = Environment::getSession();
$session->setSavePath(Environment::getVariable('sessionDir'));
// Step 3: Configure application
/** 3a) Setup Application, ErrorPresenter & exceptions catching */
$application = Environment::getApplication();
Presenter::$invalidLinkMode = Environment::isProduction() ? Presenter::INVALID_LINK_SILENT : Presenter::INVALID_LINK_EXCEPTION;
Environment::setVariable('host', Environment::getHttpRequest()->getUri()->host);
/** 3b) establish database connection and initialize services */
$application->onStartup[] = 'Services::initialize';
$application->onStartup[] = 'BaseModel::initialize';
$application->onShutdown[] = 'BaseModel::disconnect';
// Step 4: Setup application router
$router = $application->getRouter();
$router[] = new Route('index.php', array('presenter' => 'Example', 'action' => 'default'), Route::ONE_WAY);
$router[] = new Route('<presenter>/<action>/', array('presenter' => 'Example', 'action' => 'default'));
$router[] = new SimpleRouter('Example:default');
// Step 5: Run the application!
$application->run();
Exemplo n.º 12
0
<?php

// Load Nette Framework
require LIBS_DIR . '/Nette/loader.php';
// Configure environment
Debug::enable();
Environment::loadConfig();
// Configure application
$application = Environment::getApplication();
$application->errorPresenter = 'Error';
$application->catchExceptions = Environment::isProduction();
// Setup router
$router = $application->getRouter();
$router[] = new Route('index.php', array('presenter' => 'Default', 'action' => 'default'), Route::ONE_WAY);
$router[] = new Route('<presenter>/<action>/<id>', array('presenter' => 'Default', 'action' => 'default', 'id' => NULL));
//RoutingDebugger::enable();
// Run application!
$application->run();
Exemplo n.º 13
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
     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(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
                 if ($e instanceof BadRequestException) {
                     $code = $e->getCode();
                 } else {
                     $code = 500;
                     Debug::log($e);
                 }
                 echo "<!DOCTYPE html><meta name=robots content=noindex><meta name=generator content='Nette Framework'>\n\n";
                 echo "<style>body{color:#333;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";
                 static $messages = array(0 => array('Oops...', 'Your browser sent a request that this server could not understand or process.'), 403 => array('Access Denied', 'You do not have permission to view this page. Please try contact the web site administrator if you believe you should be able to view this page.'), 404 => array('Page Not Found', 'The page you requested could not be found. It is possible that the address is incorrect, or that the page no longer exists. Please try the search engine to find what you are looking for.'), 405 => array('Method Not Allowed', 'The requested method is not allowed for the URL.'), 410 => array('Page Not Found', 'The page you requested has been taken off the site. We apologize for the inconvenience.'), 500 => array('Server Error', 'We\'re sorry! The server encountered an internal error and was unable to complete your request. Please try again later.'));
                 $message = isset($messages[$code]) ? $messages[$code] : $messages[0];
                 echo "<title>{$message['0']}</title>\n\n<h1>{$message['0']}</h1>\n\n<p>{$message['1']}</p>\n\n";
                 if ($code) {
                     echo "<p><small>{$code} error</small></p>";
                 }
                 break;
             }
         }
     } while (1);
     $this->onShutdown($this, isset($e) ? $e : NULL);
 }
Exemplo n.º 14
0
 /**
  * @return bool
  */
 public function isProduction()
 {
     return $this->envObj->isProduction();
 }
Exemplo n.º 15
0
 public function testIsProduction()
 {
     $this->assertIdentical(Environment::isProduction('/virtual/www.example.com'), true);
     $this->assertIdentical(Environment::isProduction('/virtual/monsat.example.com'), false);
     $this->assertIdentical(Environment::isProduction('/virtual/www.example.jp'), false);
 }
Exemplo n.º 16
0
 protected function createComponentCss($name)
 {
     $css = new CssLoader($this, $name);
     // cesta na disku ke zdroji
     $css->sourcePath = WWW_DIR . "/css";
     // cesta na webu k cílovému adresáři
     $css->tempUri = Environment::getVariable("baseUri") . "webtemp";
     // cesta na disku k cílovému adresáři
     $css->tempPath = WWW_DIR . "/webtemp";
     // při development módu vypne spojování souborů
     $css->joinFiles = Environment::isProduction();
     if (Environment::isProduction()) {
         //	    	die('hui');
         $css->filters[] = function ($code) {
             return CssMin::minify($code);
         };
     } else {
         $css->throwExceptions = true;
     }
     // proměnné filtru je možné nastavit buď přímo v konstruktoru
     //	    $filter = new VariablesFilter(array(
     //	        "cervena" => "red",
     //	        "zelena" => "green",
     //	    ));
     //	    $css->filters[] = $filter;
     return $css;
 }
Exemplo n.º 17
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('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('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;
 }
Exemplo n.º 18
0
<h1>Nette\Environment mode test</h1>

<pre>
<?php 
require_once '../../Nette/loader.php';
/*use Nette\Debug;*/
/*use Nette\Environment;*/
echo "Is console?\n";
Debug::dump(Environment::isConsole());
echo "Is production mode?\n";
Debug::dump(Environment::isProduction());
define('DEBUG_MODE', FALSE);
echo "Is debugging?\n";
Debug::dump(Environment::isDebugging());
echo "Setting mode...\n";
Environment::setMode('debug', 123);
echo "Is debugging?\n";
Debug::dump(Environment::isDebugging());
Exemplo n.º 19
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: ' . htmlSpecialChars($e->getMessage());
     } else {
         // self::INVALID_LINK_EXCEPTION
         throw $e;
     }
 }
Exemplo n.º 20
0
 protected function setupHooks()
 {
     if (Environment::isProduction() && isset($this->cache['hooks'])) {
         $this->hooks = $this->cache['hooks'];
     } else {
         $this->hooks = new SiteHooks();
         foreach ($this->modules as $module) {
             $module->setupHooks($this->hooks);
         }
         $this->cache->save('hooks', $this->hooks);
     }
 }