/** * Gets upload directory path * @return string */ function getUploadedFilesTemporaryPath() { if (!Queues::$uploadsTempDir) { Queues::$uploadsTempDir = Environment::expand("%tempDir%" . DIRECTORY_SEPARATOR . "uploads-MFU"); } if (!file_exists(Queues::$uploadsTempDir)) { mkdir(Queues::$uploadsTempDir, 0777, true); } if (!is_writable(Queues::$uploadsTempDir)) { Queues::$uploadsTempDir = Environment::expand("%tempDir%"); } if (!is_writable(Queues::$uploadsTempDir)) { throw new InvalidStateException("Directory for temp files is not writable!"); } return Queues::$uploadsTempDir; }
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() . "."); } } } }
/** * Loads global configuration from file and process it. * @param string|Nette\Config\Config file name or Config object * @return Nette\Config\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); } // process environment variables if ($config->variable instanceof Config) { foreach ($config->variable as $key => $value) { Environment::setVariable($key, $value); } } // expand variables $iterator = new \RecursiveIteratorIterator($config); foreach ($iterator as $key => $value) { $tmp = $iterator->getDepth() ? $iterator->getSubIterator($iterator->getDepth() - 1)->current() : $config; $tmp[$key] = Environment::expand($value); } // process services $runServices = array(); $context = Environment::getContext(); if ($config->service instanceof Config) { foreach ($config->service as $key => $value) { $key = strtr($key, '-', '\\'); // limited INI chars if (is_string($value)) { $context->removeService($key); $context->addService($key, $value); } else { if ($value->factory) { $context->removeService($key); $context->addService($key, $value->factory, isset($value->singleton) ? $value->singleton : TRUE, (array) $value->option); } elseif (isset($this->defaultServices[$key])) { $context->removeService($key); $context->addService($key, $this->defaultServices[$key], 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 (clone $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) { $context->getService($name); } return $config; }
/** * 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; }
/** * Creates and returns mPDF object * @param PDFResponse $response * @return mPDFExtended */ public function createMPDF() { /* if(!self::$mPDFPath) { self::$mPDFPath = dirname(__FILE__)."/mpdf/mpdf.php"; } */ $mpdfPath = \Nette\Environment::expand(self::$mPDFPath); define('_MPDF_PATH', dirname($mpdfPath) . "/"); require $mpdfPath; //\Nette\Debug::barDump($mpdfPath); $margins = $this->getMargins(); // [ float $margin_header , float $margin_footer [, string $orientation ]]]]]]) $mpdf = new \mPDF('utf-8', $this->pageFormat, '', '', $margins["left"], $margins["right"], $margins["top"], $margins["bottom"], $margins["header"], $margins["footer"], $this->pageOrientation); return $mpdf; }
/** * Loads configuration from file and process it. * @return void */ public function loadConfig($file, $section = NULL) { if ($file === NULL) { $file = $this->defaultConfigFile; } $container = $this->container; $file = $container->expand($file); if (!is_file($file)) { $file = preg_replace('#\\.neon$#', '.ini', $file); // back compatibility } if ($section === NULL) { if (PHP_SAPI === 'cli') { $section = Environment::CONSOLE; } else { $section = $container->params['productionMode'] ? Environment::PRODUCTION : Environment::DEVELOPMENT; } } $cache = new Cache($container->templateCacheStorage, 'Nette.Configurator'); $cacheKey = array((array) $container->params, $file, $section); $cached = $cache->load($cacheKey); if ($cached) { require $cached['file']; fclose($cached['handle']); return; } $config = Nette\Config\Config::fromFile($file, $section); $code = "<?php\n// source file {$file}\n\n"; // back compatibility with singular names foreach (array('service', 'variable') as $item) { if (isset($config[$item])) { trigger_error(basename($file) . ": Section '{$item}' is deprecated; use plural form '{$item}s' instead.", E_USER_WARNING); $config[$item . 's'] = $config[$item]; unset($config[$item]); } } // add expanded variables while (!empty($config['variables'])) { $old = $config['variables']; foreach ($config['variables'] as $key => $value) { try { $code .= $this->generateCode('$container->params[?] = ?', $key, $container->params[$key] = $container->expand($value)); unset($config['variables'][$key]); } catch (Nette\InvalidArgumentException $e) { } } if ($old === $config['variables']) { throw new InvalidStateException("Unable to expand variables: " . implode(', ', array_keys($old)) . "."); } } unset($config['variables']); // process services if (isset($config['services'])) { foreach ($config['services'] as $key => &$def) { if (preg_match('#^Nette\\\\.*\\\\I?([a-zA-Z]+)$#', strtr($key, '-', '\\'), $m)) { // back compatibility $m[1][0] = strtolower($m[1][0]); trigger_error(basename($file) . ": service name '{$key}' has been renamed to '{$m['1']}'", E_USER_WARNING); $key = $m[1]; } if (is_scalar($def)) { $def = array('class' => $def); } if (method_exists(get_called_class(), "createService{$key}")) { $container->removeService($key); if (!isset($def['factory']) && !isset($def['class'])) { $def['factory'] = array(get_called_class(), "createService{$key}"); } } if (isset($def['option'])) { $def['arguments'][] = $def['option']; } if (!empty($def['run'])) { $def['tags'] = array('run'); } } $builder = new DI\ContainerBuilder(); $code .= $builder->generateCode($config['services']); unset($config['services']); } // expand variables array_walk_recursive($config, function (&$val) { $val = Environment::expand($val); }); // PHP settings if (isset($config['php'])) { foreach ($config['php'] as $key => $value) { if (is_array($value)) { // back compatibility - flatten INI dots foreach ($value as $k => $v) { $code .= $this->configurePhp("{$key}.{$k}", $v); } } else { $code .= $this->configurePhp($key, $value); } } unset($config['php']); } // define constants if (isset($config['const'])) { foreach ($config['const'] as $key => $value) { $code .= $this->generateCode('define', $key, $value); } unset($config['const']); } // set modes - back compatibility if (isset($config['mode'])) { trigger_error(basename($file) . ": Section 'mode' is deprecated; use 'params' instead.", E_USER_WARNING); foreach ($config['mode'] as $mode => $state) { $code .= $this->generateCode('$container->params[?] = ?', $mode . 'Mode', (bool) $state); } unset($config['mode']); } // other foreach ($config as $key => $value) { $code .= $this->generateCode('$container->params[?] = ' . (is_array($value) ? 'Nette\\ArrayHash::from(?)' : '?'), $key, $value); } // pre-loading $code .= self::preloadEnvironment($container); // auto-start services $code .= 'foreach ($container->getServiceNamesByTag("run") as $name => $foo) { $container->getService($name); }' . "\n"; $cache->save($cacheKey, $code, array(Cache::FILES => $file)); Nette\Utils\LimitedScope::evaluate($code, array('container' => $container)); }
// Step 1: Load Nette Framework // this allows load Nette Framework classes automatically so that // you don't have to litter your code with 'require' statements require_once LIBS_DIR . '/Nette/loader.php'; // Step 2: Configure environment // 2a) enable Nette\Debug for better exception and error visualisation Debug::$strictMode = true; Debug::enable(); // 2b) load configuration from config.ini file Environment::loadConfig(); // 2c) check if directory /app/temp is writable if (@file_put_contents(Environment::expand('%tempDir%/_check'), '') === FALSE) { throw new Exception("Make directory '" . Environment::getVariable('tempDir') . "' writable!"); } // 2d) setup sessions //$session = Environment::getSession(); //$session->start(); // Step 3: Setup application router $application = Environment::getApplication(); $router = $application->getRouter(); $router[] = new SimpleRouter(array("presenter" => "AutoUse")); // Step 5: Run the application! $application->run();