Example #1
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]));
 }
 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);
     }
 }
 /**
  * Data grid model constructor.
  * @param  string  table name
  * @param  string  primary key name
  * @return void
  */
 public function __construct($table = NULL, $primary = NULL)
 {
     parent::__construct($table, $primary);
     if (!isset($this->primary) && isset($this->table)) {
         try {
             $dbInfo = $this->connection->getDatabaseInfo();
             $this->primary = $dbInfo->getTable($this->table)->getPrimaryKey()->getName();
         } catch (Exception $e) {
             Debug::processException($e);
             throw new InvalidArgumentException("Model must have one primary key.");
         }
     }
     if ($this->connection->profiler) {
         $this->connection->getProfiler()->setFile(Environment::expand('%logDir%') . '/sql.log');
     }
 }
 public function onSendMailFormSubmit(Form $form)
 {
     if (!$form->isValid()) {
         return;
     }
     $active = FALSE;
     try {
         dibi::begin();
         $active = TRUE;
         mapper::order_emails()->insertOne(array('order_id' => $form['order_id']->getValue(), 'subject' => $form['subject']->getValue(), 'body' => $form['body']->getValue()));
         $mail = new Mail();
         $mail->setFrom(Environment::expand('%shopName% <%shopEmail%>'))->addTo($form['to']->getValue())->setSubject($form['subject']->getValue())->setBody($form['body']->getValue())->send();
         adminlog::log(__('Sent e-mail to "%s" with subject "%s"'), $form['to']->getValue(), $form['subject']->getValue());
         $this->redirect('this');
         $this->terminate();
     } catch (RedirectingException $e) {
         dibi::commit();
         throw $e;
     } catch (Exception $e) {
         if ($active) {
             dibi::rollback();
         }
         $form->addError(__('Cannot send e-mail.'));
     }
 }
 /**
  * A little componen factory
  * @param string
  */
 public function createComponent($name)
 {
     switch ($name) {
         case 'dataForm':
             $data = isset(Environment::getSession(SESSION_ORDER_NS)->data) ? Environment::getSession(SESSION_ORDER_NS)->data : array();
             $form = new AppForm($this, $name);
             // contacts
             $form->addGroup(__('Contacts'));
             $form->addText('email', __('E-mail:'))->setEmptyValue('@')->addRule(Form::FILLED, __('You have to enter your e-mail.'))->addRule(Form::EMAIL, __('This is not an e-mail address.'));
             $form->addText('phone', __('Phone number:'))->addRule(Form::FILLED, __('You have to enter your phone number.'))->addRule(Form::NUMERIC, __('Phone number has to be number.'));
             // payer
             $form->addGroup(__('Payer'));
             $form->addText('payer_name', __('Name:'))->addRule(Form::FILLED, __('You have to enter your name.'));
             $form->addText('payer_lastname', __('Last name:'))->addRule(Form::FILLED, __('You have to enter your last name.'));
             $form->addText('payer_company', __('Company:'));
             $form->addText('payer_street', __('Street:'))->addRule(Form::FILLED, __('You have to enter your street.'));
             $form->addText('payer_city', __('City:'))->addRule(Form::FILLED, __('You have to enter your city.'));
             $form->addText('payer_postcode', __('Post code:'))->addRule(Form::FILLED, __('You have to enter your post code.'))->addRule(Form::NUMERIC, __('Post code has to be number.'));
             $form->addCheckbox('same_delivery', __('deliver at same address (you do not need to fill Delivery address below)'))->setValue(TRUE);
             // delivery address
             $form->addGroup(__('Delivery address'));
             $form->addText('delivery_name', __('Name:'))->addConditionOn($form['same_delivery'], Form::EQUAL, FALSE)->addRule(Form::FILLED, __('You have to enter your name.'));
             $form->addText('delivery_lastname', __('Last name:'))->addConditionOn($form['same_delivery'], Form::EQUAL, FALSE)->addRule(Form::FILLED, __('You have to enter your last name.'));
             $form->addText('delivery_street', __('Street:'))->addConditionOn($form['same_delivery'], Form::EQUAL, FALSE)->addRule(Form::FILLED, __('You have to enter your street.'));
             $form->addText('delivery_city', __('City:'))->addConditionOn($form['same_delivery'], Form::EQUAL, FALSE)->addRule(Form::FILLED, __('You have to enter your city.'));
             $form->addText('delivery_postcode', __('Post code:'))->addConditionOn($form['same_delivery'], Form::EQUAL, FALSE)->addRule(Form::FILLED, __('You have to enter your post code.'))->addRule(Form::NUMERIC, __('Post code has to be number.'));
             // delivery type
             $form->addGroup(__('Delivery type'));
             $delivery_types = array();
             foreach (mapper::order_delivery_types()->findAll() as $delivery_type) {
                 $delivery_types[$delivery_type->getId()] = $delivery_type->getName() . Environment::expand(' (' . $delivery_type->getPrice() . ' %currency%)');
             }
             $form->addSelect('delivery_type', __('Type:'), $delivery_types);
             // payment type
             $form->addGroup(__('Payment type'));
             $payment_types = array();
             foreach (mapper::order_payment_types()->findAll() as $payment_type) {
                 $payment_types[$payment_type->getId()] = $payment_type->getName() . Environment::expand(' (' . $payment_type->getPrice() . ' %currency%)');
             }
             $form->addSelect('payment_type', __('Type:'), $payment_types);
             // comment
             $form->addGroup(__('Comment'));
             $form->addTextarea('comment', __('Comment:'));
             // submit
             $form->setCurrentGroup(NULL);
             $form->addSubmit('ok', '(3/3) ' . __('Complete order »'));
             $form['ok']->setRendered(TRUE);
             $form->onSubmit[] = array($this, 'onDataFormSubmit');
             // defaults
             if (isset(Environment::getSession(SESSION_ORDER_NS)->data)) {
                 $form->setDefaults(Environment::getSession(SESSION_ORDER_NS)->data);
             }
             break;
         default:
             parent::createComponent($name);
     }
 }
Example #6
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;
 }
 private function loadLocale($locale)
 {
     try {
         $this->locales[$locale] = new JsonLocale(Environment::expand($this->l10nDir) . '/' . $locale, $locale);
     } catch (FileNotFoundException $e) {
         throw new JsonTranslatorLocaleException('Failed to load locale ' . $locale . '.', 0, $e);
     }
 }
Example #8
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;
 }
Example #9
0
 public static function date($str)
 {
     return date(Environment::expand('%datetimeFormat%'), strtotime($str));
 }
Example #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;
 }
Example #11
0
<h1>Nette\Loaders\RobotLoader test</h1>

<pre>
<?php 
require_once '../../Nette/loader.php';
/*use Nette\Debug;*/
/*use Nette\Environment;*/
Environment::setVariable('tempDir', dirname(__FILE__) . '/tmp');
foreach (glob(Environment::expand('%tempDir%/*')) as $file) {
    unlink($file);
}
// delete all files
$loader = new RobotLoader();
$loader->addDirectory('../../Nette/');
$loader->addDirectory(dirname(__FILE__));
$loader->addDirectory(dirname(__FILE__));
// purposely doubled
$loader->register();
if (class_exists('TestClass')) {
    echo 'class TestClass successfully loaded';
}
Example #12
0
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]);
}
// connect to DB
dibi::connect(require Environment::expand('%dbFile%'));
// get app
$app = Environment::getApplication();
// routing
$router = $app->getRouter();
Route::setStyleProperty('action', Route::FILTER_TABLE, array(__('show-cart') => 'showCart', __('fill-data') => 'fillData', __('complete') => 'complete', __('commit') => 'commit'));
$router[] = new Route(__('order') . '/<action>/', array('presenter' => 'Front:Order'));
$router[] = new Route('admin/<presenter>/<action>/', array('module' => 'Back', 'presenter' => 'Dashboard', 'action' => 'default'));
$router[] = new Route(__('search') . ' ? q=<q .*> & ' . __('page') . '=<page \\d+>', array('presenter' => 'Front:Search', 'action' => 'default', 'page' => 1));
Route::addStyle('path', NULL);
Route::setStyleProperty('path', Route::PATTERN, '.*');
$router[] = new Route('<path>/ ? ' . __('page') . '=<page_number \\d+> & ' . __('letter') . '=<letter [A-Z]|#>', array('presenter' => 'Front:Show', 'action' => 'default', 'path' => '', 'page_number' => 1, 'letter' => NULL));
// run!
$app->run();
Example #13
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;
 }
 protected function createComponentOrdersGrid()
 {
     $model = new DatagridModel();
     $grid = new DataGrid();
     $translator = new GettextTranslator(Environment::expand('%templatesDir%/customersGrid.cs.mo'));
     $grid->setTranslator($translator);
     $renderer = new DataGridRenderer();
     $renderer->paginatorFormat = '%input%';
     // customize format of paginator
     $renderer->onCellRender[] = array($this, 'ordersGridOnCellRendered');
     $grid->setRenderer($renderer);
     $grid->itemsPerPage = 10;
     // display 10 rows per page
     $grid->displayedItems = array('all', 10, 20, 50);
     // items per page selectbox items
     $grid->rememberState = TRUE;
     $grid->timeout = '+ 7 days';
     // change session expiration after 7 days
     $grid->bindDataTable($model->getOrdersInfo());
     $grid->multiOrder = FALSE;
     // order by one column only
     $operations = array('delete' => 'delete', 'deal' => 'deal', 'print' => 'print', 'forward' => 'forward');
     // define operations
     // in czech for example: $operations = array('delete' => 'smazat', 'deal' => 'vyřídit', 'print' => 'tisk', 'forward' => 'předat');
     // or you can left translate values by translator adapter
     $callback = array($this, 'gridOperationHandler');
     $grid->allowOperations($operations, $callback, 'orderNumber');
     // allows checkboxes to do operations with more rows
     /**** add some columns ****/
     $grid->addColumn('customerName', 'Customer');
     $grid->addColumn('addressLine1', 'Address')->getHeaderPrototype()->addStyle('width: 180px');
     $grid->addColumn('city', 'City');
     $grid->addColumn('country', 'Country');
     $caption = Html::el('span')->setText('P')->title('Number of products on order')->class('link');
     $grid->addNumericColumn('productsCount', $caption)->getCellPrototype()->addStyle('text-align: center');
     $grid->addDateColumn('orderDate', 'Date', '%m/%d/%Y');
     // czech format: '%d.%m.%Y'
     $grid->addColumn('status', 'Status');
     $grid->addColumn('creditLimit', 'Credit')->getCellPrototype()->addStyle('text-align: center');
     /**** add some filters ****/
     $grid['customerName']->addFilter();
     $grid['addressLine1']->addFilter();
     $grid['city']->addSelectboxFilter()->translateItems(FALSE);
     $grid['country']->addSelectboxFilter()->translateItems(FALSE);
     $grid['productsCount']->addFilter();
     $grid['orderDate']->addDateFilter();
     $grid['status']->addSelectboxFilter();
     $grid['creditLimit']->addFilter();
     /**** default sorting and filtering ****/
     $grid['orderDate']->addDefaultSorting('desc');
     $grid['productsCount']->addDefaultFiltering('>2');
     /**** column content affecting ****/
     // by css styling
     $grid['orderDate']->getCellPrototype()->addStyle('text-align: center');
     $grid['status']->getHeaderPrototype()->addStyle('width: 60px');
     $grid['addressLine1']->getHeaderPrototype()->addStyle('width: 150px');
     $grid['city']->getHeaderPrototype()->addStyle('width: 90px');
     // by replacement of given pattern
     $el = Html::el('span')->addStyle('margin: 0 auto');
     $grid['status']->replacement['Shipped'] = clone $el->class("icon icon-shipped")->title("Shipped");
     $grid['status']->replacement['Resolved'] = clone $el->class("icon icon-resolved")->title("Resolved");
     $grid['status']->replacement['Cancelled'] = clone $el->class("icon icon-cancelled")->title("Cancelled");
     $grid['status']->replacement['On Hold'] = clone $el->class("icon icon-hold")->title("On Hold");
     $grid['status']->replacement['In Process'] = clone $el->class("icon icon-process")->title("In Process");
     $grid['status']->replacement['Disputed'] = clone $el->class("icon icon-disputed")->title("Disputed");
     $grid['status']->replacement[''] = clone $el->class("icon icon-no-orders")->title("Without orders");
     // by callback(s)
     $grid['creditLimit']->formatCallback[] = 'Helpers::currency';
     /**** add some actions ****/
     $grid->addActionColumn('Actions')->getHeaderPrototype()->addStyle('width: 98px');
     $icon = Html::el('span');
     $grid->addAction('Copy', 'Customer:copy', clone $icon->class('icon icon-copy'));
     $grid->addAction('Detail', 'Customer:detail', clone $icon->class('icon icon-detail'));
     $grid->addAction('Edit', 'Customer:edit', clone $icon->class('icon icon-edit'));
     $grid->addAction('Delete', 'Customer:delete', clone $icon->class('icon icon-del'));
     return $grid;
 }
Example #15
0
 /**
  * Expand all variables.
  * @return void
  */
 public function expand()
 {
     if ($this->readOnly) {
         throw new NotSupportedException('Configuration is read-only.');
     }
     $data = $this->getArrayCopy();
     foreach ($data as $key => $val) {
         if (is_string($val)) {
             $data[$key] = Environment::expand($val);
         } elseif ($val instanceof self) {
             $val->expand();
         }
     }
     $this->setArray($data);
 }
Example #16
0
 /**
  * Enables displaying or logging errors and exceptions.
  * @param  int   error reporting level
  * @param  bool|string  log to file?
  * @param  array|string  send emails?
  * @return void
  */
 public static function enable($level = E_ALL, $logErrors = NULL, $sendEmails = FALSE)
 {
     if (version_compare(PHP_VERSION, '5.2.1') === 0) {
         throw new NotSupportedException(__METHOD__ . ' is not supported in PHP 5.2.1');
         // PHP bug #40815
     }
     // Environment auto-detection
     if ($logErrors === NULL && class_exists('Environment')) {
         $logErrors = Environment::isLive();
     }
     // Firebug detection
     if (self::$useFirebug === NULL) {
         self::$useFirebug = function_exists('json_encode') && !$logErrors && isset($_SERVER['HTTP_USER_AGENT']) && strpos($_SERVER['HTTP_USER_AGENT'], 'FirePHP/');
     }
     if ($level !== NULL) {
         error_reporting($level);
     }
     if (function_exists('ini_set')) {
         ini_set('display_startup_errors', !$logErrors);
         ini_set('display_errors', !$logErrors);
         // or 'stderr'
         ini_set('html_errors', self::$html);
         ini_set('log_errors', (bool) $logErrors);
     } elseif ($logErrors) {
         // throws error only on production server
         throw new NotSupportedException('Function ini_set() is not enabled.');
     }
     if ($logErrors) {
         if (is_string($logErrors)) {
             self::$logFile = strpos($logErrors, '%') === FALSE ? $logErrors : Environment::expand($logErrors);
         } else {
             try {
                 self::$logFile = Environment::expand('%logDir%/php_error.log');
             } catch (InvalidStateException $e) {
                 self::$logFile = 'php_error.log';
             }
         }
         ini_set('error_log', self::$logFile);
     }
     self::$sendEmails = $logErrors && $sendEmails;
     if (self::$sendEmails) {
         if (is_string($sendEmails)) {
             self::$emailHeaders['To'] = $sendEmails;
         } elseif (is_array($sendEmails)) {
             self::$emailHeaders = $sendEmails + self::$emailHeaders;
         }
         if (mt_rand() / mt_getrandmax() < self::$emailProbability) {
             self::observeErrorLog();
         }
     }
     if (!defined('E_RECOVERABLE_ERROR')) {
         define('E_RECOVERABLE_ERROR', 4096);
     }
     if (!defined('E_DEPRECATED')) {
         define('E_DEPRECATED', 8192);
     }
     set_exception_handler(array(__CLASS__, 'exceptionHandler'));
     set_error_handler(array(__CLASS__, 'errorHandler'));
     self::$enabled = TRUE;
 }
 public function onTitlePageFormSubmit(Form $form)
 {
     if (!$form->isValid()) {
         return;
     }
     $content = "<?php\nreturn ";
     $content .= var_export($form['content']->getValue(), TRUE);
     $content .= ";";
     if (!@file_put_contents('safe://' . Environment::expand('%titlePageFile%'), $content)) {
         $form->addError(__('Cannot write to file.'));
         return;
     }
     adminlog::log(__('Updated title page'), $form['content']->getValue());
     $this->redirect('this');
     $this->terminate();
 }
 public function onChangeLoginFormSubmit(Form $form)
 {
     if (!$form->isValid()) {
         return;
     }
     if ($form['old_password']->getValue() !== Environment::expand('%adminPassword%')) {
         $form->addError(__('Bad old password.'));
         return;
     }
     $content = "<?php\nreturn " . var_export(array('username' => $form['username']->getValue(), 'password' => $form['new_password']->getValue()), TRUE) . ";\n";
     if (!@file_put_contents(Environment::expand('%adminLoginFile%'), $content)) {
         $form->addError(__('Cannot write new login settings.'));
         return;
     }
     Environment::getUser()->signOut(TRUE);
     adminlog::log(__('Changed login credentials, logging out'));
     $this->redirect('this');
     $this->terminate();
 }
Example #19
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;
 }
Example #20
0
 /**
  * Expand all variables.
  * @return void
  */
 public function expand()
 {
     $this->updating();
     $data = $this->getArrayCopy();
     foreach ($data as $key => $val) {
         if (is_string($val)) {
             $data[$key] = Environment::expand($val);
         } elseif ($val instanceof self) {
             $val->expand();
         }
     }
     $this->setArray($data);
 }
Example #21
0
 public function listLatestActualities($count)
 {
     $template = clone $this->template;
     $template->setFile(Environment::expand('%templatesDir%/FrontModule/@actualities.phtml'));
     $template->presenter = $this;
     $template->control = $this;
     $template->actualities = mapper::actualities()->findLatest($count);
     return "/---html\n" . $template->__toString() . "\n\\---\n";
 }
Example #22
0
//dump(Debug::$productionMode);
//Environment::setMode(Environment::PRODUCTION, true);
//Environment::setMode(Environment::PRODUCTION, true);
//Environment::setMode(Environment::DEVELOPMENT, false);
// 2b) load configuration from config.ini file
//require LIBS_DIR . '/Custom/MultipleConfigurator.php';
//Environment::setConfigurator(new MultipleConfigurator());
//$config = Environment::loadConfig();
// 2c) check if cache, sessions and log directories are writable
if (@file_put_contents(Environment::expand('%tempDir%/_check'), '') === FALSE) {
    throw new Exception("Make directory '" . Environment::getVariable('tempDir') . "' writable!");
}
if (@file_put_contents(Environment::expand('%sessionDir%/_check'), '') === FALSE) {
    throw new Exception("Make directory '" . Environment::getVariable('sessionDir') . "' writable!");
}
if (@file_put_contents(Environment::expand('%logDir%/_check'), '') === FALSE) {
    throw new Exception("Make directory '" . Environment::getVariable('logDir') . "' writable!");
}
$session = Environment::getSession();
$session->setSavePath(Environment::getVariable('sessionDir'));
//Environment::getHttpResponse()->cookiePath = '/'; // toto tu treba, aby fungovali cookie..v novsej verzii je to uz fixnute
$session->setExpiration($config['session']['lifetime']);
if (!$session->isStarted()) {
    $session->start();
}
/**
 * create new httpRequest for CLI
 * @see http://wiki.nette.org/cs/cookbook/http-routovani-v-cli
 */
if (Environment::isConsole()) {
    function createHttpRequestService()
Example #23
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);
     }
 }
Example #24
0
 /**
  * Save given order
  * @param order
  * @param array
  * @return bool
  */
 public function save(order $order, array $products, array $visited)
 {
     // order data
     $data = $order->__toArray();
     $data['at'] = date('Y-m-d H:i:s', time());
     $data['delivery_type_id'] = $data['delivery_type']->getId();
     unset($data['delivery_type']);
     $data['payment_type_id'] = $data['payment_type']->getId();
     unset($data['payment_type']);
     $data['status_id'] = $data['status']->getId();
     unset($data['status']);
     // start transaction
     dibi::begin();
     try {
         $this->insert($data);
         $order_id = dibi::query('SELECT LAST_INSERT_ID()')->fetchSingle();
         $order->setId($order_id);
         $order->dirty(order::UNDIRT);
         foreach (mapper::products()->findByIds(array_keys($products)) as $product) {
             dibi::query('INSERT INTO [:prefix:orders_products]', array('order_id' => $order_id, 'product_id' => $product->getId(), 'price' => $product->getPrice(), 'amount' => $products[$product->getId()]));
         }
         foreach ($visited as $_) {
             $values = array('order_id' => $order_id);
             $values['product_id'] = $_[0]->getId();
             $values['visited_at'] = date('Y-m-d H:i:s', $_[1]);
             dibi::query('INSERT INTO [:prefix:order_visited_products]', $values);
         }
         $mail = new Mail();
         $mail->setFrom(Environment::expand('%shopEmail%'))->addTo(Environment::expand('%shopEmail%'))->setSubject(__('New order'))->setBody(__('Hello, new order arrived'))->send();
         $mail = new Mail();
         $mail->setFrom(Environment::expand('%shopEmail%'))->addTo($data['email'])->setSubject(__('Your order at %s has been accepted', Environment::expand('%shopName%')))->setBody(str_replace('\\n', "\n", __('Hello, your order has been accepted.')))->send();
     } catch (Exception $e) {
         dibi::rollback();
         return FALSE;
     }
     dibi::commit();
     return TRUE;
 }