Exemplo n.º 1
0
 public function startup()
 {
     parent::startup();
     $this->absoluteUrls = TRUE;
     $admin_config = ConfigAdapterIni::load(APP_DIR . '/config/admin.ini');
     foreach ($admin_config['admin'] as $var => $value) {
         Environment::setVariable($var, $value);
     }
     Environment::setVariable('themesDir', 'themes');
     $method = $this->getRequest()->getMethod();
     if ($method == 'GET') {
         $data = $method = $this->getRequest()->getParams();
         if (isset($data['rsd'])) {
             header('Content-Type: text/xml');
             $this->view = 'rsd';
         } elseif (isset($data['wlw'])) {
             header('Content-Type: text/xml');
             $this->view = 'wlw';
         }
     } else {
         if (!isset($HTTP_RAW_POST_DATA)) {
             $HTTP_RAW_POST_DATA = file_get_contents('php://input');
         }
         $data = $HTTP_RAW_POST_DATA;
         file_put_contents('xmlrpc.txt', $data, FILE_APPEND);
         $this->formatCallbacks($this->methods);
         $server = new IXR_Server($this->methods, $data);
     }
 }
Exemplo n.º 2
0
 /**
  * merges config files of each module imported via config.ini[modules] to one file and loads it
  * considering current environment [dev, production, ...] - separate config file for each
  * uses Nette/Cache for invalidation when one (or more) of config files changed
  *
  * @param string|null  filepath
  * @return Config
  */
 public static function load($baseConfigFile = null)
 {
     if ($baseConfigFile === null) {
         $baseConfigFile = Environment::expand(Environment::getConfigurator()->defaultConfigFile);
     }
     $envName = Environment::getName();
     Environment::setVariable('tempDir', VAR_DIR . '/cache');
     $cache = Environment::getCache('config');
     $key = "config[{$envName}]";
     if (!isset($cache[$key])) {
         // najviac casu zabera load, tak az tu, ked ho je treba
         $appConfig = Environment::loadConfig($baseConfigFile);
         $configs = array(Config::fromFile($baseConfigFile, $envName)->toArray());
         $configPaths = array($baseConfigFile);
         foreach ($appConfig->modules as $c) {
             $configPaths[] = $path = MODULES_DIR . "/{$c}Module/config.ini";
             if (file_exists($path)) {
                 $configs[] = Config::fromFile($path, $envName)->toArray();
             }
         }
         $arrayConfig = call_user_func_array('array_merge_recursive', $configs);
         $cache->save($key, $arrayConfig, array('files' => $configPaths));
     }
     return Environment::loadConfig(new Config($cache[$key]));
 }
Exemplo n.º 3
0
 private function checkAndRegisterLang()
 {
     if (Environment::getConfig('langs')->multipleLangs) {
         //		dump( Environment::getHttpRequest()->getUri() );
         if ($this->getParam("lang") && LangsModel::isAllowed($this->getParam("lang"))) {
             $this->lang = $this->getParam("lang");
         } else {
             $this->redirect(301, ":Front:Homepage:", array('lang' => Environment::getVariable("lang")));
         }
     }
     $this->template->lang = $this->lang;
     Environment::setVariable('lang', $this->lang);
 }
Exemplo n.º 4
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.º 5
0
<h1>Nette\Templates\CurlyBracketsFilter & snippets test</h1>

<pre>
<?php 
require_once '../../Nette/loader.php';
/*use Nette\Debug;*/
/*use Nette\Environment;*/
/*use Nette\Templates\Template;*/
class MockControl extends Control
{
    public function getSnippetId($name = NULL)
    {
        return 'sni__' . $name;
    }
}
function printSource($s)
{
    echo $s;
}
Environment::setVariable('tempDir', dirname(__FILE__) . '/tmp');
$template = new Template();
$template->setFile(dirname(__FILE__) . '/templates/curly-brackets-snippet.phtml');
$template->registerFilter('Nette\\Templates\\CurlyBracketsFilter::invoke');
$template->registerFilter('printSource');
$template->control = new MockControl();
$template->render();
Exemplo n.º 6
0
<h1>Nette\Environment services test</h1>

<pre>
<?php 
require_once '../../Nette/loader.php';
/*use Nette\Debug;*/
/*use Nette\Environment;*/
echo "Environment::getHttpResponse\n";
$obj = Environment::getHttpResponse();
Debug::dump($obj->class);
echo "Environment::getApplication\n";
$obj = Environment::getApplication();
Debug::dump($obj->class);
echo "Environment::getCache(...)\n";
Environment::setVariable('tempDir', __FILE__);
$obj = Environment::getCache('my');
Debug::dump($obj->class);
/* in PHP 5.3
echo "Environment::getXyz(...)\n";
Environment::setServiceAlias('Nette\Web\IUser', 'xyz');
$obj = Environment::getXyz();
Debug::dump($obj->class);
*/
Exemplo n.º 7
0
     $theme = Environment::getVariable('theme');
     $appDir = Environment::getVariable('appDir');
     $path = '/' . str_replace(':', 'Module/', $presenter);
     $pathP = substr_replace($path, '/' . $themesDir . '/' . $theme . '/templates', strrpos($path, '/'), 0);
     $list = array("{$appDir}{$pathP}/@{$layout}.phtml", "{$appDir}{$pathP}.@{$layout}.phtml");
     while (($path = substr($path, 0, strrpos($path, '/'))) !== FALSE) {
         $list[] = "{$appDir}{$path}" . '/' . $themesDir . '/' . $theme . '/templates/' . "@{$layout}.phtml";
     }
     return $list;
 }
 private function setupThemePath()
 {
     $presenter = $this->getName();
     $parts = explode(':', $presenter);
     Environment::setVariable('moduleDir', $parts[0] . 'Module');
     $themesDir = Environment::getVariable('themesDir');
Exemplo n.º 8
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.º 9
0
 /**
  * Loads global configuration from file and process it.
  * @param  string|Nette\Config\Config  file name or Config object
  * @param  bool
  * @return Nette\Config\Config
  */
 public function loadConfig($file, $useCache)
 {
     if ($useCache === NULL) {
         $useCache = Environment::isLive();
     }
     $cache = $useCache && $this->cacheKey ? Environment::getCache('Nette.Environment') : NULL;
     $name = Environment::getName();
     $cacheKey = Environment::expand($this->cacheKey);
     if (isset($cache[$cacheKey])) {
         Environment::swapState($cache[$cacheKey]);
         $config = Environment::getConfig();
     } else {
         if ($file instanceof Config) {
             $config = $file;
             $file = NULL;
         } else {
             if ($file === NULL) {
                 $file = $this->defaultConfigFile;
             }
             $file = Environment::expand($file);
             $config = Config::fromFile($file, $name, 0);
         }
         // process environment variables
         if ($config->variable instanceof Config) {
             foreach ($config->variable as $key => $value) {
                 Environment::setVariable($key, $value);
             }
         }
         if (PATH_SEPARATOR !== ';' && isset($config->set->include_path)) {
             $config->set->include_path = str_replace(';', PATH_SEPARATOR, $config->set->include_path);
         }
         $config->expand();
         $config->setReadOnly();
         // process services
         $locator = Environment::getServiceLocator();
         if ($config->service instanceof Config) {
             foreach ($config->service as $key => $value) {
                 $locator->addService($value, strtr($key, '-', '\\'));
             }
         }
         // save cache
         if ($cache) {
             $state = Environment::swapState(NULL);
             $state[0] = $config;
             // TODO: better!
             $cache->save($cacheKey, $state, array(Cache::FILES => $file));
         }
     }
     // check temporary directory - TODO: discuss
     /*
     $dir = Environment::getVariable('tempDir');
     if ($dir && !(is_dir($dir) && is_writable($dir))) {
     	trigger_error("Temporary directory '$dir' is not writable", E_USER_NOTICE);
     }
     */
     // process ini settings
     if ($config->set instanceof Config) {
         foreach ($config->set as $key => $value) {
             $key = strtr($key, '-', '.');
             if (function_exists('ini_set')) {
                 ini_set($key, $value);
             } else {
                 switch ($key) {
                     case 'include_path':
                         set_include_path($value);
                         break;
                     case 'iconv.internal_encoding':
                         iconv_set_encoding('internal_encoding', $value);
                         break;
                     case 'mbstring.internal_encoding':
                         mb_internal_encoding($value);
                         break;
                     case 'date.timezone':
                         date_default_timezone_set($value);
                         break;
                     case 'error_reporting':
                         error_reporting($value);
                         break;
                     case 'ignore_user_abort':
                         ignore_user_abort($value);
                         break;
                     case 'max_execution_time':
                         set_time_limit($value);
                         break;
                     default:
                         throw new NotSupportedException('Required function ini_set() is disabled.');
                 }
             }
         }
     }
     // define constants
     if ($config->const instanceof Config) {
         foreach ($config->const as $key => $value) {
             define($key, $value);
         }
     }
     // set modes
     if (isset($config->mode)) {
         foreach ($config->mode as $mode => $state) {
             Environment::setMode($mode, $state);
         }
     }
     return $config;
 }
Exemplo n.º 10
0
 function loadConfig($file)
 {
     $name = Environment::getName();
     if ($file instanceof Config) {
         $config = $file;
         $file = NULL;
     } else {
         if ($file === NULL) {
             $file = $this->defaultConfigFile;
         }
         $file = Environment::expand($file);
         $config = Config::fromFile($file, $name);
     }
     if ($config->variable instanceof Config) {
         foreach ($config->variable as $key => $value) {
             Environment::setVariable($key, $value);
         }
     }
     $iterator = new RecursiveIteratorIterator($config);
     foreach ($iterator as $key => $value) {
         $tmp = $iterator->getDepth() ? $iterator->getSubIterator($iterator->getDepth() - 1)->current() : $config;
         $tmp[$key] = Environment::expand($value);
     }
     $runServices = array();
     $locator = Environment::getServiceLocator();
     if ($config->service instanceof Config) {
         foreach ($config->service as $key => $value) {
             $key = strtr($key, '-', '\\');
             if (is_string($value)) {
                 $locator->removeService($key);
                 $locator->addService($key, $value);
             } else {
                 if ($value->factory) {
                     $locator->removeService($key);
                     $locator->addService($key, $value->factory, isset($value->singleton) ? $value->singleton : TRUE, (array) $value->option);
                 }
                 if ($value->run) {
                     $runServices[] = $key;
                 }
             }
         }
     }
     if (!$config->php) {
         $config->php = $config->set;
         unset($config->set);
     }
     if ($config->php instanceof Config) {
         if (PATH_SEPARATOR !== ';' && isset($config->php->include_path)) {
             $config->php->include_path = str_replace(';', PATH_SEPARATOR, $config->php->include_path);
         }
         foreach (clone $config->php as $key => $value) {
             if ($value instanceof Config) {
                 unset($config->php->{$key});
                 foreach ($value as $k => $v) {
                     $config->php->{"{$key}.{$k}"} = $v;
                 }
             }
         }
         foreach ($config->php as $key => $value) {
             $key = strtr($key, '-', '.');
             if (!is_scalar($value)) {
                 throw new InvalidStateException("Configuration value for directive '{$key}' is not scalar.");
             }
             if ($key === 'date.timezone') {
                 date_default_timezone_set($value);
             }
             if (function_exists('ini_set')) {
                 ini_set($key, $value);
             } else {
                 switch ($key) {
                     case 'include_path':
                         set_include_path($value);
                         break;
                     case 'iconv.internal_encoding':
                         iconv_set_encoding('internal_encoding', $value);
                         break;
                     case 'mbstring.internal_encoding':
                         mb_internal_encoding($value);
                         break;
                     case 'date.timezone':
                         date_default_timezone_set($value);
                         break;
                     case 'error_reporting':
                         error_reporting($value);
                         break;
                     case 'ignore_user_abort':
                         ignore_user_abort($value);
                         break;
                     case 'max_execution_time':
                         set_time_limit($value);
                         break;
                     default:
                         if (ini_get($key) != $value) {
                             throw new NotSupportedException('Required function ini_set() is disabled.');
                         }
                 }
             }
         }
     }
     if ($config->const instanceof Config) {
         foreach ($config->const as $key => $value) {
             define($key, $value);
         }
     }
     if (isset($config->mode)) {
         foreach ($config->mode as $mode => $state) {
             Environment::setMode($mode, $state);
         }
     }
     foreach ($runServices as $name) {
         $locator->getService($name);
     }
     return $config;
 }
Exemplo n.º 11
0
if (!function_exists('date_default_timezone_set')) {
    function date_default_timezone_set($timezone)
    {
        ini_set('date.timezone', $timezone);
    }
}
date_default_timezone_set(require Environment::expand('%timezoneFile%'));
// debugging
Debug::enable(NULL, BASE_DIR . '/error.log', Environment::expand('%adminEmail%'));
// paths
Environment::setVariable('themeDir', Environment::expand('%baseDir%/themes'));
Environment::setVariable('templatesDir', Environment::expand('%themeDir%/%theme%'));
Environment::setVariable('tempDir', Environment::expand('%baseDir%/tmp'));
Environment::setVariable('themeBaseUri', Environment::expand('%baseUri%/themes/%theme%'));
Environment::setVariable('mediaDir', Environment::expand('%baseDir%/media'));
Environment::setVariable('mediaBaseUri', Environment::expand('%baseUri%/media'));
set_include_path(LIB_DIR . PATH_SEPARATOR . get_include_path());
Html::$xhtml = FALSE;
SafeStream::register();
setlocale(LC_ALL, require Environment::expand('%localeFile%'));
Zend_Search_Lucene::setDefaultSearchField('description');
// configure locale
require_once LIB_DIR . '/tr.php';
$available = array();
foreach (glob(APP_DIR . '/locale/' . '*.php') as $_) {
    $available[substr(substr($_, strlen(APP_DIR . '/locale/')), 0, 2)] = $_;
}
tr::$locale = Environment::getHttpRequest()->detectLanguage(array_keys($available));
if (tr::$locale) {
    list(tr::$plurals[tr::$locale], tr::$table[tr::$locale]) = (require $available[tr::$locale]);
}
Exemplo n.º 12
0
 /**
  * Loads global configuration from file and process it.
  * @param  string|Nette\Config\Config  file name or Config object
  * @return Config
  */
 public function loadConfig($file)
 {
     $name = Environment::getName();
     if ($file instanceof Config) {
         $config = $file;
         $file = NULL;
     } else {
         if ($file === NULL) {
             $file = $this->defaultConfigFile;
         }
         $file = Environment::expand($file);
         $config = Config::fromFile($file, $name, 0);
     }
     // process environment variables
     if ($config->variable instanceof Config) {
         foreach ($config->variable as $key => $value) {
             Environment::setVariable($key, $value);
         }
     }
     $config->expand();
     // process services
     $locator = Environment::getServiceLocator();
     if ($config->service instanceof Config) {
         foreach ($config->service as $key => $value) {
             $locator->addService($value, strtr($key, '-', '\\'));
         }
     }
     // check temporary directory - TODO: discuss
     /*
     $dir = Environment::getVariable('tempDir');
     if ($dir && !(is_dir($dir) && is_writable($dir))) {
     	trigger_error("Temporary directory '$dir' is not writable", E_USER_NOTICE);
     }
     */
     // process ini settings
     if ($config->set instanceof Config) {
         if (PATH_SEPARATOR !== ';' && isset($config->set->include_path)) {
             $config->set->include_path = str_replace(';', PATH_SEPARATOR, $config->set->include_path);
         }
         foreach ($config->set as $key => $value) {
             $key = strtr($key, '-', '.');
             // old INI compatibility
             if (!is_scalar($value)) {
                 throw new InvalidStateException("Configuration value for directive '{$key}' is not scalar.");
             }
             if (function_exists('ini_set')) {
                 ini_set($key, $value);
             } else {
                 switch ($key) {
                     case 'include_path':
                         set_include_path($value);
                         break;
                     case 'iconv.internal_encoding':
                         iconv_set_encoding('internal_encoding', $value);
                         break;
                     case 'mbstring.internal_encoding':
                         mb_internal_encoding($value);
                         break;
                     case 'date.timezone':
                         date_default_timezone_set($value);
                         break;
                     case 'error_reporting':
                         error_reporting($value);
                         break;
                     case 'ignore_user_abort':
                         ignore_user_abort($value);
                         break;
                     case 'max_execution_time':
                         set_time_limit($value);
                         break;
                     default:
                         if (ini_get($key) != $value) {
                             // intentionally ==
                             throw new NotSupportedException('Required function ini_set() is disabled.');
                         }
                 }
             }
         }
     }
     // define constants
     if ($config->const instanceof Config) {
         foreach ($config->const as $key => $value) {
             define($key, $value);
         }
     }
     // set modes
     if (isset($config->mode)) {
         foreach ($config->mode as $mode => $state) {
             Environment::setMode($mode, $state);
         }
     }
     $config->setReadOnly();
     return $config;
 }
Exemplo n.º 13
0
<?php

require LIBS_DIR . '/nette-dev/loader.php';
require LIBS_DIR . '/debug.php';
require LIBS_DIR . '/Mokuji/Mokuji.php';
//enable Debugging
//Environment::setMode(Environment::DEVELOPMENT);
//Debug::enable(Debug::DEVELOPMENT);
//load configuration
Environment::loadConfig(APP_DIR . '/config/config.ini');
Environment::setVariable('website', WEBSITE);
db::connect(Environment::getConfig('database'));
//get Application
Environment::getSession()->start();
$app = Environment::getApplication();
$app->catchExceptions = FALSE;
$app->run();
Exemplo n.º 14
0
 public function formatTemplateFiles($presenter, $view)
 {
     $parts = explode(':', $presenter);
     Environment::setVariable('moduleDir', $parts[0] . 'Module');
     $themesDir = Environment::getVariable('themesDir');
     $theme = Environment::getVariable('theme');
     $appDir = Environment::getVariable('appDir');
     $path = '/' . str_replace(':', 'Module/', $presenter);
     $pathP = substr_replace($path, '/' . $themesDir . '/' . $theme . '/templates', strrpos($path, '/'), 0);
     $this->pathToTheme = substr($pathP, 0, strrpos($pathP, '/'));
     $this->pathToTheme = substr($this->pathToTheme, 0, strrpos($this->pathToTheme, '/'));
     $path = substr_replace($path, '/' . $themesDir . '/' . $theme . '/templates', strrpos($path, '/'));
     return array("{$appDir}{$pathP}/{$view}.phtml", "{$appDir}{$pathP}.{$view}.phtml", "{$appDir}{$path}/@global.{$view}.phtml");
 }
Exemplo n.º 15
0
        $uri = $this->mycontrol->link('this?x=1&round=1#frag');
        echo "3.12 {$uri}\n\n";
        $uri = $this->mycontrol->link('//this?x=1&round=1#frag');
        echo "3.13 {$uri}\n\n";
    }
    /**
     * @view: default
     */
    public function handleBuy($x = 1, $y = 1)
    {
    }
}
class OtherPresenter extends TestPresenter
{
}
class Submodule_OtherPresenter extends TestPresenter
{
}
Environment::setVariable('appDir', dirname(__FILE__));
$httpRequest = Environment::getHttpRequest();
$uri = clone $httpRequest->getUri();
$uri->scriptPath = '/index.php';
$uri->host = 'localhost';
$httpRequest->setUri($uri);
$application = Environment::getApplication();
$application->setRouter(new SimpleRouter());
$request = new PresenterRequest('Test', HttpRequest::GET, array());
TestPresenter::$invalidLinkMode = TestPresenter::INVALID_LINK_WARNING;
$presenter = new TestPresenter($request);
$presenter->autoCanonicalize = FALSE;
$presenter->run();
Exemplo n.º 16
0
/*use Nette\Environment;*/
echo "Getting variable 'foo':\n";
Debug::dump(Environment::getVariable('foo'));
try {
    echo "Getting variable 'tempDir':\n";
    Debug::dump(Environment::getVariable('tempDir'));
} catch (Exception $e) {
    echo get_class($e), ': ', $e->getMessage(), "\n\n";
}
echo "Defining constant 'APP_DIR':\n";
define('APP_DIR', '/myApp');
echo "Getting variable 'appDir':\n";
Debug::dump(Environment::getVariable('appDir'));
echo "Getting variable 'tempDir' #2:\n";
Debug::dump(Environment::getVariable('tempDir'));
echo "Setting variable 'test'...\n";
Environment::setVariable('test', '%appDir%/test');
echo "Getting variable 'test':\n";
Debug::dump(Environment::getVariable('test'));
echo "Getting variables:\n";
Debug::dump(Environment::getVariables());
try {
    echo "Setting circular variables...\n";
    Environment::setVariable('bar', '%foo%');
    Environment::setVariable('foo', '%foobar%');
    Environment::setVariable('foobar', '%bar%');
    echo "Getting circular variable:\n";
    Debug::dump(Environment::getVariable('bar'));
} catch (Exception $e) {
    echo get_class($e), ': ', $e->getMessage(), "\n\n";
}
Exemplo n.º 17
0
 /**
  * Loads global configuration from file and process it.
  * @param  string|Config  file name or Config object
  * @return Config
  */
 public function loadConfig($file)
 {
     $name = Environment::getName();
     if ($file instanceof Config) {
         $config = $file;
         $file = NULL;
     } else {
         if ($file === NULL) {
             $file = $this->defaultConfigFile;
         }
         $file = Environment::expand($file);
         $config = Config::fromFile($file, $name, 0);
     }
     // process environment variables
     if ($config->variable instanceof Config) {
         foreach ($config->variable as $key => $value) {
             Environment::setVariable($key, $value);
         }
     }
     $config->expand();
     // process services
     $runServices = array();
     $locator = Environment::getServiceLocator();
     if ($config->service instanceof Config) {
         foreach ($config->service as $key => $value) {
             $key = strtr($key, '-', '\\');
             // limited INI chars
             if (is_string($value)) {
                 $locator->removeService($key);
                 $locator->addService($key, $value);
             } else {
                 if ($value->factory) {
                     $locator->removeService($key);
                     $locator->addService($key, $value->factory, isset($value->singleton) ? $value->singleton : TRUE, (array) $value->option);
                 }
                 if ($value->run) {
                     $runServices[] = $key;
                 }
             }
         }
     }
     // process ini settings
     if (!$config->php) {
         // backcompatibility
         $config->php = $config->set;
         unset($config->set);
     }
     if ($config->php instanceof Config) {
         if (PATH_SEPARATOR !== ';' && isset($config->php->include_path)) {
             $config->php->include_path = str_replace(';', PATH_SEPARATOR, $config->php->include_path);
         }
         foreach ($config->php as $key => $value) {
             // flatten INI dots
             if ($value instanceof Config) {
                 unset($config->php->{$key});
                 foreach ($value as $k => $v) {
                     $config->php->{"{$key}.{$k}"} = $v;
                 }
             }
         }
         foreach ($config->php as $key => $value) {
             $key = strtr($key, '-', '.');
             // backcompatibility
             if (!is_scalar($value)) {
                 throw new InvalidStateException("Configuration value for directive '{$key}' is not scalar.");
             }
             if ($key === 'date.timezone') {
                 // PHP bug #47466
                 date_default_timezone_set($value);
             }
             if (function_exists('ini_set')) {
                 ini_set($key, $value);
             } else {
                 switch ($key) {
                     case 'include_path':
                         set_include_path($value);
                         break;
                     case 'iconv.internal_encoding':
                         iconv_set_encoding('internal_encoding', $value);
                         break;
                     case 'mbstring.internal_encoding':
                         mb_internal_encoding($value);
                         break;
                     case 'date.timezone':
                         date_default_timezone_set($value);
                         break;
                     case 'error_reporting':
                         error_reporting($value);
                         break;
                     case 'ignore_user_abort':
                         ignore_user_abort($value);
                         break;
                     case 'max_execution_time':
                         set_time_limit($value);
                         break;
                     default:
                         if (ini_get($key) != $value) {
                             // intentionally ==
                             throw new NotSupportedException('Required function ini_set() is disabled.');
                         }
                 }
             }
         }
     }
     // define constants
     if ($config->const instanceof Config) {
         foreach ($config->const as $key => $value) {
             define($key, $value);
         }
     }
     // set modes
     if (isset($config->mode)) {
         foreach ($config->mode as $mode => $state) {
             Environment::setMode($mode, $state);
         }
     }
     // auto-start services
     foreach ($runServices as $name) {
         $locator->getService($name);
     }
     $config->freeze();
     return $config;
 }
Exemplo n.º 18
0
<pre>
<?php 
require_once '../../Nette/loader.php';
/*use Nette\Caching\Cache;*/
/*use Nette\Environment;*/
/*use Nette\Debug;*/
$tmpDir = dirname(__FILE__) . '/tmp';
foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($tmpDir), RecursiveIteratorIterator::CHILD_FIRST) as $entry) {
    // delete all files
    if ($entry->isDir()) {
        @rmdir($entry);
    } else {
        @unlink($entry);
    }
}
Environment::setVariable('tempDir', $tmpDir);
$key = '';
$value = array();
for ($i = 0; $i < 32; $i++) {
    $key .= chr($i);
    $value[] = chr($i) . chr(255 - $i);
}
$cache = Environment::getCache();
echo "Is cached?\n";
Debug::dump(isset($cache[$key]));
echo "Cache content:\n";
Debug::dump($cache[$key]);
echo "Writing cache...\n";
$cache[$key] = $value;
$cache->release();
echo "Is cached?\n";
Exemplo n.º 19
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.º 20
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);
 }