/** * Constractor creates connection and checks/creates tables stucture */ public function __construct() { $dibiConfig = dibi::getConnection()->getConfig(); $dbname = isset($dibiConfig['dbname']) ? $dibiConfig['dbname'] : $dibiConfig['database']; $config = array('driver' => 'sqlite', 'profiler' => Environment::getConfig('perform')->storage_profiler, 'database' => realpath(Environment::getConfig('perform')->modelCache) . '/' . $dbname . '-storage.sdb'); parent::__construct($config, 'storage'); if (!$this->getDatabaseInfo()->hasTable('fields')) { $this->query('CREATE TABLE [fields] ([id] INTEGER NOT NULL PRIMARY KEY, [name] VARCHAR(100) NOT NULL, [table] VARCHAR(50) NOT NULL, [hash] VARCHAR(32) NOT NULL, [type] VARCHAR(50)); CREATE UNIQUE INDEX [fields_idx] on [fields] ( [name], [table]);'); } if (!$this->getDatabaseInfo()->hasTable('tables')) { $this->query('CREATE TABLE [tables] ( [id] INTEGER NOT NULL PRIMARY KEY, [name] VARCHAR(100) NOT NULL UNIQUE, [hash] VARCHAR(32) NOT NULL);'); } if (!$this->getDatabaseInfo()->hasTable('views')) { $this->query('CREATE TABLE [views] ( [id] INTEGER NOT NULL PRIMARY KEY, [name] VARCHAR(100) NOT NULL UNIQUE, [hash] VARCHAR(32) NOT NULL);'); } if (!$this->getDatabaseInfo()->hasTable('indexes')) { $this->query('CREATE TABLE [indexes] ([id] INTEGER NOT NULL PRIMARY KEY, [name] VARCHAR(100) NOT NULL, [table] VARCHAR(50) NOT NULL, [hash] VARCHAR(32) NOT NULL, [unique] BOOLEAN); CREATE UNIQUE INDEX [indexes_idx] on [indexes] ( [name], [table]);'); } }
public function __construct() { $this->config['useAcl'] = Environment::getConfig('global')->useAcl; // init hasher $this->config['hasher'] = Environment::getConfig('hasher'); $this->hasher = BaseHasher::create($this->config['hasher']->type, $this->config['hasher']); }
public function sendPassFormSubmitted($form) { $values = $form->getValues(); $user = $this->model->findByEmail($values['email']); if (!$user->id) { // $this->flashMessage('Účet so zadaným e-mailom neexistuje', self::FLASH_MESSAGE_ERROR); $this->flashMessage('Provided email does not exist in the system', self::FLASH_MESSAGE_ERROR); $this->redirect('this'); } else { $token = $this->model->allowTemporaryLogin($user->id, $values['email'], $this->tempLoginTokenExpiration); // send email with url for temporary login try { $email_template = $this->createTemplate(); $email_template->setFile(__DIR__ . '/../templates/email.phtml'); $email_template->completeName = $user->completeName; $email_template->tempLoginUri = $this->link('//tempLogin', array('tempLoginToken' => $token)); $mail = new Mail(); $mail->setFrom(Environment::getConfig("contact")->forgottenPassEmail); $mail->addTo($values['email']); $mail->setSubject('Password Assistance'); $mail->setHtmlBody($email_template); $mail->send(); } catch (DibiDriverException $e) { $this->flashMessage(OPERATION_FAILED, self::FLASH_MESSAGE_ERROR); $this->redirect('this'); } catch (InvalidStateException $e) { // $this->flashMessage('Email sa nepodarilo odoslať, skúste znova o pár sekúnd', self::FLASH_MESSAGE_ERROR); $this->flashMessage('Email could NOT be sent. Please try again in a moment', self::FLASH_MESSAGE_ERROR); $this->redirect('this'); } // $this->flashMessage('Na zadaný e-mail boli odoslané prihlasovacie údaje', self::FLASH_MESSAGE_SUCCESS); $this->flashMessage('E-mail with detailed information has been sent to ' . $values['email'], self::FLASH_MESSAGE_SUCCESS); $this->redirect('this'); } }
/** * Convert * * Loads HTML and passes to getMarkdown() * * @param $html * * @return string The Markdown version of the html */ public function convert($html) { if ($html === '' && $this->environment->getConfig()->getOption('suppress_errors')) { return ''; } $document = $this->createDOMDocument($html); // Work on the entire DOM tree (including head and body) if (!($root = $document->getElementsByTagName('html')->item(0))) { throw new \InvalidArgumentException('Invalid HTML was provided'); } $rootElement = new Element($root); $this->convertChildren($rootElement); // Store the now-modified DOMDocument as a string $markdown = $document->saveHTML(); $markdown = $this->sanitize($markdown); return $markdown; }
public function __construct() { //db::connect(); $config = Environment::getConfig(); $this->prefix = ''; $this->startup(); $this->__after_startup(); }
/** * Constructor */ public function __construct() { /* check if modelCacheDir valid */ $this->modelCacheDir = realpath(Environment::getConfig('perform')->modelCache); if (!file_exists($this->modelCacheDir) and !mkdir($this->modelCacheDir, 0777, true)) { throw new Exception("Unable to create model cache directory '{$this->modelCacheDir}'."); } if (!is_writable($this->modelCacheDir)) { throw new Exception("Model cache directory '{$this->modelCacheDir}' is not writable."); } }
public static function connect($settings = array(), $connection_name = null) { $config = Environment::getConfig(); foreach ($config['database'] as $connection_name => $settings) { try { dibi::connect($settings, $connection_name); if ($settings['profiler'] == true) { dibi::getProfiler()->setFile(APP_DIR . '/log/db.txt'); } } catch (DibiException $e) { echo get_class($e), ': ', $e->getMessage(), "\n"; } } }
public static function initialize() { $conf = Environment::getConfig('database'); $connection = dibi::connect($conf[$conf->engine]); if ($conf->engine == 'sqlite') { $connection->getDriver()->registerFunction('regexp', 'Sqlite::regexp', 2); } elseif ($conf->engine == 'postgre') { dibi::addSubst('', '::'); } if ($conf->profiler) { $profiler = is_numeric($conf->profiler) || is_bool($conf->profiler) ? new DibiProfiler(array()) : new $conf->profiler(); $profiler->setFile(Environment::expand('%logDir%') . '/sql.log'); $connection->setProfiler($profiler); } }
protected static function setupHooks() { $db_config = Environment::getConfig('database'); define('TABLE_ACL', $db_config->tables->acl); define('TABLE_PRIVILEGES', $db_config->tables->acl_privileges); define('TABLE_ASSERTIONS', $db_config->tables->acl_assertions); define('TABLE_RESOURCES', $db_config->tables->acl_resources); define('TABLE_ROLES', $db_config->tables->acl_roles); define('TABLE_USERS', $db_config->tables->users); define('TABLE_USERS_ROLES', $db_config->tables->users_2_roles); $acl_config = Environment::getConfig('acl'); define('ACL_RESOURCE', $acl_config->resource); define('ACL_PRIVILEGE', $acl_config->privilege); define('ACL_CACHING', $acl_config->cache); define('ACL_PROG_MODE', $acl_config->programmer_mode); }
function createHttpRequestService() { $config = Environment::getConfig('httpRequest'); // params can be taken from config or command line if needed $uri = new UriScript(); $uri->scheme = 'http'; $uri->port = Uri::$defaultPorts['http']; $uri->host = $config->host; $uri->path = $config->path; // $uri->path = '/'; $uri->canonicalize(); $uri->path = String::fixEncoding($uri->path); $uri->scriptPath = '/'; $req = new HttpRequest(); $req->setUri($uri); return $req; }
public function okClicked($button) { $arr = $button->getForm()->getValues(); $username = $arr['userName']; $password = $arr['password']; $user = Environment::getUser(); // zaregistrujeme autentizační handler $credits = (array) Environment::getConfig('admin'); $user->setAuthenticationHandler(new SimpleAuthenticator(array($credits['username'] => $credits['password']))); try { // pokusíme se přihlásit uživatele... $user->authenticate($username, $password); $this->redirect(':Admin:Default:'); } catch (AuthenticationException $e) { $this->error = $e->getMessage(); $this->redirect('this'); } }
public function run() { $this->cache = Environment::getCache('Application'); $modules = Environment::getConfig('modules'); if (!empty($modules)) { foreach ($modules as $module) { $this->loadModule($module); } } $this->setupRouter(); // $this->setupHooks(); // Requires database connection $this->onRequest[] = array($this, 'setupPermission'); // ... // Run the application! parent::run(); $this->cache->release(); }
/** * Autoloader factory. * @return Acl */ public static function factory() { $expire = 24 * 60 * 60; // 1 den $driver = Environment::getConfig('database')->driver; try { $key = 'acl'; $cache = Environment::getCache('application/acl'); if (isset($cache[$key])) { // serving from cache return $cache[$key]; } else { $acl = new self(); $cache->save($key, $acl, array('expire' => $expire, 'tags' => array('system', 'acl'))); return $acl; } } catch (Exception $e) { $acl = new self(); //$cache->save($key, $acl, array('expire' => $expire)); return $acl; } }
public function authenticate(array $credentials) { $login = $credentials['username']; $password = $this->phash($credentials['password']); $super_admin = Environment::getConfig('admin'); if ($login == $super_admin['login']) { if ($password == $super_admin['password']) { $super_admin_info['name'] = 'super admin'; $row = new DibiRow($super_admin_info); } else { throw new AuthenticationException("Invalid password.", self::INVALID_CREDENTIAL); } } else { $row = db::select('*')->from('[:admin:users]')->where('login = %s', $login)->fetch(); if (!$row) { throw new AuthenticationException("Login '{$login}' not found.", self::IDENTITY_NOT_FOUND); } if ($row->password !== $password) { throw new AuthenticationException("Invalid password.", self::INVALID_CREDENTIAL); } } return new Identity($row->name); }
<h1>Nette\Environment config test</h1> <pre> <?php require_once '../../Nette/loader.php'; /*use Nette\Debug;*/ /*use Nette\Environment;*/ class Factory { static function createService($options) { Debug::dump(__METHOD__); Debug::dump($options); return (object) NULL; } } echo "Loading config:\n"; Environment::setName(Environment::PRODUCTION); Environment::loadConfig('config.ini'); echo "Variable foo:\n"; Debug::dump(Environment::getVariable('foo')); echo "Constant HELLO_WORLD:\n"; Debug::dump(constant('HELLO_WORLD')); echo "php.ini config:\n"; Debug::dump(Environment::getConfig('php')); echo "Database config:\n"; Debug::dump(Environment::getConfig('database')); echo "is production mode?\n"; Debug::dump(Environment::isProduction());
/** * Setups path to data file and load that file as DOMDocument * * Instantiate using {@link getInstance()}; Storage is a singleton! * * @return void */ protected function __construct() { $this->path = Environment::getConfig('variable')->dataFile; $this->loadFile(); }
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); }
protected function startup() { parent::startup(); $this->model = new SolutionsModel(); $this->config = Environment::getConfig('solutions'); }
public static function initialize() { dibi::connect(Environment::getConfig('database')); }
/** * Getter for Cache instance * Creates instance if called for the first time * Creates MemcachedStorage if extension memcache exists * Otherwise FileStorage Cache is created * Triggers notice if config variable advertisememcached in perform block is not set to false * @return Cache */ public static function getCache() { if (!self::$cache) { $config = Environment::getConfig('perform'); if (extension_loaded('memcache')) { self::$cache = new Cache(new MemcachedStorage($config->memcache_host, $config->memcache_port, $config->cache_prefix)); $namespace = self::$cache; $namespace['test'] = true; if ($namespace['test'] === true) { return self::$cache; } } self::$cache = Environment::getCache($config->cache_prefix); if ($config->advertisememcached) { trigger_error("FileCache enabled, use Memcached if possible. Turn off this warning by setting advertisememcached to false", E_USER_WARNING); } } return self::$cache; }
<?php require_once dirname(__FILE__) . '/protected/config/environment.php'; $environment = new Environment(Environment::DEVELOPMENT); // change the following paths if necessary $yii = CORE_FOLDER . '/yii/framework/yii.php'; $globals = CMS_FOLDER . '/globals.php'; defined('YII_DEBUG') or define('YII_DEBUG', $environment->getDebug()); defined('YII_TRACE_LEVEL') or define('YII_TRACE_LEVEL', $environment->getTraceLevel()); require_once $yii; require_once $globals; Yii::setPathOfAlias('common', COMMON_FOLDER); Yii::setPathOfAlias('cms', CMS_FOLDER); Yii::setPathOfAlias('cmswidgets', CMS_WIDGETS); Yii::createWebApplication($environment->getConfig())->run();
/** * Initializes a Curl object * * <strike>Sets the $cookieFile to "curl_cookie.txt" in the current directory</strike> * Also sets the $userAgent to $_SERVER['HTTP_USER_AGENT'] if it exists, 'Curl/PHP '.PHP_VERSION.' (http://curl.kdyby.org/)' otherwise * * @param string $url */ public function __construct($url = Null) { if (is_string($url) and strlen($url) > 0) { $this->setUrl($url); } // $this->cookieFile(dirname(__FILE__).DIRECTORY_SEPARATOR.'curl_cookie.txt'); $this->setUserAgent(isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : 'Curl/PHP ' . PHP_VERSION . ' (http://curl.kdyby.org/)'); if (class_exists('Environment')) { $config = Environment::getConfig('curl'); foreach ((array) $config as $option => $value) { if ($option == 'cookieFile') { $this->setCookieFile($value); } elseif ($option == 'downloadFolder') { $this->setDownloadFolder($value); } elseif ($option == 'referer') { $this->setReferer($value); } elseif ($option == 'userAgent') { $this->setUserAgent($value); } elseif ($option == 'followRedirects') { $this->setFollowRedirects($value); } elseif ($option == 'returnTransfer') { $this->setReturnTransfer($value); } elseif (is_array($this->{$option})) { foreach ((array) $value as $key => $set) { $this->{$option}[$key] = $set; } } else { $this->{$option} = $value; } } } }
/** * 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; }
<?php /** * Nette TreeView example bootstrap file. * * @copyright Copyright (c) 2010 Roman Novák * @package nette-treeview */ // 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 LIBS_DIR . '/Nette/loader.php'; // Step 2: Configure environment // 2a) enable Nette\Debug for better exception and error visualisation Debug::enable(false); Debug::enableProfiler(); // 2b) load configuration from config.ini file Environment::loadConfig(); Environment::getSession()->start(); dibi::connect(Environment::getConfig('database')); // Step 3: Configure application // 3a) get and setup a front controller $application = Environment::getApplication(); //$application->errorPresenter = 'Error'; $application->catchExceptions = false; // Step 4: Setup application router $router = $application->getRouter(); $router[] = new Route('index.php', array('presenter' => 'Homepage', 'action' => 'default'), Route::ONE_WAY); $router[] = new Route('<presenter>/<action>/<id>', array('presenter' => 'Homepage', 'action' => 'default', 'id' => NULL)); // Step 5: Run the application! $application->run();
public function __construct() { $this->fontsPath = Environment::getConfig('variable')->fontsPath; $this->graphsPath = Environment::getConfig('variable')->graphsPath; }
protected function sendRegBasicEmail($values) { $template = new Template(APP_DIR . "/templates/mails/basicRegMail.phtml"); $template->registerFilter(new LatteFilter()); $template->setTranslator($this->getTranslator()); $template->homepageLink = $this->link("//:Front:Files:list"); $template->login = $values['username']; $template->password = $values['password']; $template->title = $this->translate('Registration'); $mail = new Mail(); $mail->addTo($values['email']); $mail->setFrom(Environment::getConfig("contact")->registrationEmail); $mail->setSubject($template->title); $mail->setHTMLbody($template); $mail->send(); $this->flashMessage('E-mail has been sent to provided e-mail address.', self::FLASH_MESSAGE_SUCCESS); }
/** * Get method to retreive single result and fill model * @param mixed * @return DibiResult */ public function load() { if ($args = func_get_args()) { $this->where($args); } $result = $this->getDataSource()->fetch(); if (Environment::getConfig('perform')->profiler) { PerfORMController::addSql(dibi::$sql); } $this->getModel()->fill($result); return $result ? $this->getModel() : false; }
/** * @return Configuration */ public function getConfig() { return $this->environment->getConfig(); }
/** * Gets SK ITCBundle Code Generator PHPUnit Abstract Generator Generator Config Array Hash * * @return ArrayHash */ public function getConfig() { if (NULL == $this->config) { $config = Environment::getConfig(); $this->setConfig($config); } return $this->config; }