Esempio n. 1
0
 /**
  * Get connection to database
  *
  * @param string $name Connection name
  * @param array $config Connection config (not required)
  *
  * @return \Kalibri\Db\Driver\Base
  */
 public function getConnection($name = null, $config = null)
 {
     // Use default connection name if name is not passed
     $name = $name ?: $this->_defaultConnectName;
     // Check is driver already connected
     if ($this->isConnected($name)) {
         return $this->_connections[$name];
     }
     // Is config not passed and we have stored config
     if (!$config && isset($this->_config['connection'][$name])) {
         $config = $this->_config['connection'][$name];
     } else {
         // Config not passed and not available in config file
         \Kalibri::error()->show("Invalid DB connection name '{$name}'.");
     }
     // Calculate driver name
     $driverName = '\\Kalibri\\Db\\Driver\\' . \ucfirst($config['driver']);
     try {
         $this->_connections[$name] = new $driverName($config);
         \Kalibri::logger()->add(Logger::L_INFO, "Connected to database: driverName={$driverName}, connection={$name}");
     } catch (Exception $e) {
         \Kalibri::error()->showException($e);
     }
     // Return connected driver
     return $this->_connections[$name];
 }
Esempio n. 2
0
 /**
  * Get controller page instance
  * 
  * @return \Kalibri\View\Page
  */
 public function &page()
 {
     if (!$this->_page) {
         $this->_page = \Kalibri::page(new \Kalibri\View\Page());
     }
     return $this->_page;
 }
Esempio n. 3
0
 public function getRouteName()
 {
     if (!$this->_routeName) {
         $this->_routeName = \Kalibri::router()->getController() . '_' . \Kalibri::router()->getAction();
     }
     return $this->_routeName;
 }
Esempio n. 4
0
 /**
  * Get DB connection instance
  * 
  * @return \Kalibri\Db\Driver\Mysql
  */
 protected function db()
 {
     if (!$this->_db) {
         $this->_db = \Kalibri::db()->getConnection($this->connectName);
     }
     return $this->_db;
 }
Esempio n. 5
0
 public function remove($key)
 {
     if (\Kalibri::config()->get('debug.log.is-enabled', false)) {
         \Kalibri::logger()->add(\Kalibri\Logger\Base::L_DEBUG, 'REMOVE: ' . $key, $this);
     }
     unset($this->_local[$key]);
     return $this->_memcache->delete($key);
 }
Esempio n. 6
0
 public function load($configName = null, $configLocation = null)
 {
     $configName = $configName ?: self::MAIN_CONFIG_NAME;
     $configLocation = $configLocation ?: \Kalibri::app()->getLocation() . 'App/Config/';
     $configPath = $configLocation . $configName . '.php';
     if (file_exists($configPath)) {
         $this->_data = array_merge($this->_data, include $configPath);
         (K_COMPILE_BASE || K_COMPILE_ROUTES) && \Kalibri::compiler()->skip($configPath);
         return $this;
     }
     throw new \Kalibri\Exception("Config '{$configName}' not found");
 }
Esempio n. 7
0
 protected function init()
 {
     \Kalibri::config()->load();
     if ($this->_mode) {
         \Kalibri::config()->load($this->_mode);
     }
     // Set list of classes that will be auto inited on use
     \Kalibri::setAutoInitClasses(\Kalibri::config()->get('init.classes'));
     if (\Kalibri::config()->get('debug.log.is-enabled', false)) {
         \Kalibri::logger()->add(\Kalibri\Logger\Base::L_DEBUG, 'init', $this);
     }
 }
Esempio n. 8
0
 public function init(array $options = null)
 {
     if ($options) {
         $this->_options = $options;
     }
     // Load options from config if not initialized yet
     if (!$this->_options) {
         $this->_options = \Kalibri::config()->get('debug.log');
     }
     // Set default date format if skipped in config
     if (!isset($this->_options['date-format'])) {
         $this->_options['date-format'] = self::DEFAULT_DATE_FORMAT;
     }
     $this->_uniq = uniqid();
 }
Esempio n. 9
0
 public function write()
 {
     // Skip empty log saving
     if (!count($this->_messages)) {
         return false;
     }
     if ((!\file_exists($this->_options['path']) || !\is_dir($this->_options['path']) || !is_writable($this->_options['path'])) && !@mkdir($this->_options['path'], 0777, true)) {
         \Kalibri::error()->show("Can't create log file in '" . $this->_options['path'] . "'");
     }
     if (($fResource = @\fopen($this->_options['path'] . 'k' . \date('Y-m-d') . '.log', 'a')) !== null) {
         \fwrite($fResource, $this->getAsString());
         \fclose($fResource);
     }
     return true;
 }
Esempio n. 10
0
 public function register()
 {
     if (\Kalibri::auth()->getProfile()) {
         \Url::redirect(\Kalibri::config()->get('page.after-login'));
     }
     $this->page()->setTitle(tr('Sign up'));
     if (isset($_POST['login'], $_POST['password'], $_POST['re-password'])) {
         $errors = array();
         if (empty($_POST['password'])) {
             $errors[] = tr('Password should not be empty.');
         }
         if ($_POST['password'] !== $_POST['re-password']) {
             $errors[] = tr('Password and Re-password should match.');
         }
         if (strlen($_POST['password']) < \Kalibri::config()->get('auth.min-password-length')) {
             $errors[] = tr('Password should be minimum :min-length letters.', array('min-length' => \Kalibri::config()->get('auth.min-password-length')));
         }
         if (empty($_POST['login'])) {
             $errors[] = tr('Login should not be empty.');
         }
         if (!\Kalibri::auth()->isValidLogin($_POST['login'])) {
             $errors[] = tr('Login should contain latin letters or digits and be from 4 to 15 chars long.');
         }
         if (\Kalibri::auth()->getProfileByLogin($_POST['login'])) {
             $errors[] = tr('Profile with this name already registered.');
         }
         $this->page()->errorMsg = $errors;
         if (!count($errors)) {
             $model = \Kalibri::auth()->getModel();
             //$model->register(
             $model->getEmpty()->setLogin($_POST['login'])->setPassword(\Kalibri::auth()->encryptPassword($_POST['password']))->save();
             //);
             if (\Kalibri::auth()->tryLogin($_POST['login'], $_POST['password'])) {
                 \Url::redirect(\Kalibri::config()->get('page.after-login'));
             } else {
                 \Kalibri::error()->show(tr('Ooops. Something go wrong.'));
             }
         }
     }
 }
Esempio n. 11
0
 public function execStatment($query, array $params = null)
 {
     if (\Kalibri::config()->get('debug.log.is-enabled', false) && \Kalibri::config()->get('debug.log.collect-db-queries', false)) {
         \Kalibri::logger()->add(\Kalibri\Logger\Base::L_DEBUG, 'SQL query:' . $query, $this);
         \Kalibri::logger()->add(\Kalibri\Logger\Base::L_DEBUG, 'SQL params:' . var_export($params, true), $this);
     }
     try {
         $stmt = $this->connect()->prepare($query);
         $stmt->execute($params);
     } catch (\Exception $e) {
         $exception = new \Kalibri\Db\Exception($e->getMessage());
         $exception->setQueryinfo($query, $params);
         throw $exception;
     }
     return new \Kalibri\Db\Result\Mysql($stmt);
 }
Esempio n. 12
0
 /**
  *  Called on each method request. Will try to find appropriete action for field.
  *
  *  @param string $name Method name
  *  @param string $arguments Arguments passed to method
  *
  *  @return mixed
  */
 public function __call($name, $arguments)
 {
     if (\method_exists($this, $name) && \is_callable([$this, $name])) {
         return \call_user_func([&$this, $name], $arguments);
     }
     if (!$this->_withMagic) {
         \Kalibri::error()->show('Method not available: ' . get_class($this) . '::' . $name);
     }
     $type = null;
     $fieldName = null;
     if (strpos($name, 'get') === 0 || strpos($name, 'set') === 0) {
         $type = substr($name, 0, 3);
         $fieldName = substr($name, 3);
         $fieldName = strtolower($fieldName[0]) . substr($fieldName, 1);
     }
     if (property_exists($this, $fieldName)) {
         switch ($type) {
             case 'get':
                 return $this->{$fieldName};
             case 'set':
                 $this->{$fieldName} = current($arguments);
                 $this->registerChanged(Text::camelToUnderscore($fieldName));
                 return $this;
         }
     } else {
         \Kalibri::error()->show('Method not available: ' . get_class($this) . '::' . $name);
     }
     return null;
 }
Esempio n. 13
0
 public function save()
 {
     \Kalibri::model('user')->save($this->getSaveData());
 }
Esempio n. 14
0
 /**
  * Render view
  *
  * @param bool $asString
  *
  * @return mixed(string,bool)
  */
 public function render($asString = false, $path = null)
 {
     $output = null;
     if (!empty($this->_name)) {
         if ($this->isExists($this->_name, $path)) {
             \ob_start();
             \extract(\Kalibri::data()->getData());
             include $location = $this->getLocation(null, $path);
             $output = ob_get_contents();
             K_COMPILE_ROUTES && \Kalibri::compiler()->skip($location);
             @\ob_end_clean();
         } else {
             \Kalibri::error()->show("View with name '{$this->_name}' not found");
         }
     }
     if (!$asString) {
         echo $output;
     }
     \Kalibri::data()->set(self::VAR_CONTENT, $output);
     return $output;
 }
Esempio n. 15
0
 public function __construct($content = null)
 {
     $this->_name = md5((string) $content);
     $this->_path = \Kalibri::tmp('dynamic-views/');
     $this->storeContent($this->_path, (string) $content);
 }
Esempio n. 16
0
 /**
  * Called on each method request. Will try to find appropriete action for field.
  *
  * @param string $name Method name
  * @param string $arguments Arguments passed to method
  *
  * @return mixed
  */
 public function __call($name, $arguments)
 {
     if (\method_exists($this, $name) && \is_callable(array($this, $name))) {
         return \call_user_func(array(&$this, $name), $arguments);
     }
     $type = '';
     $fieldName = '';
     if (\strpos($name, 'get') === 0 || \strpos($name, 'set') === 0) {
         $type = \substr($name, 0, 3);
         $fieldName = \substr($name, 3);
         $fieldName = \strtolower($fieldName[0]) . substr($fieldName, 1);
     } elseif (\strpos($name, 'is') === 0) {
         $type = 'is';
         $fieldName = \substr($name, 2);
         $fieldName = \strtolower($fieldName[0]) . substr($fieldName, 1);
     }
     if (property_exists($this, $fieldName)) {
         switch ($type) {
             case 'is':
                 return $this->__is($fieldName, current($arguments));
             case 'get':
                 return $this->__get($fieldName);
             case 'set':
                 return $this->__set($fieldName, current($arguments));
         }
     } else {
         \Kalibri::error()->show('Method not available: ' . get_class($this) . '::' . $name);
     }
     return null;
 }
Esempio n. 17
0
function tr($key, array $params = null, $language = null)
{
    return \Kalibri::l10n()->tr($key, $params, $language);
}
Esempio n. 18
0
 public function __construct()
 {
     $this->_appName = \Kalibri::app()->getNamespace();
 }
Esempio n. 19
0
 protected function _setTableName($tableName, $alias = null)
 {
     if ($this->usePrefix()) {
         $tableName = \Kalibri::config()->get("db.connections.{$this->_connectName}.table-prefix", '') . $tableName;
     }
     if ($alias) {
         $this->_data['table_name'] = array($alias => $tableName);
         return;
     }
     $this->_data['table_name'] = $tableName;
 }
Esempio n. 20
0
 protected function init()
 {
     K_COMPILE_ROUTES && \Kalibri::compiler()->compile(Compiler::NAME_BASE);
     \Kalibri::config()->load();
     if ($this->_mode) {
         try {
             \Kalibri::config()->load($this->_mode);
         } catch (\Exception $e) {
         }
     }
     // Set list of classes that will be auto inited on use
     \Kalibri::setAutoInitClasses(\Kalibri::config()->get('init.classes'));
     //\Kalibri::logger()->init( \Kalibri::config()->get('debug.log') );
     \Kalibri::router()->setSegments(\Kalibri::uri()->getSegments());
     if (session_status() == PHP_SESSION_NONE) {
         session_start();
     }
     if (\Kalibri::config()->get('debug.log.is-enabled', false)) {
         \Kalibri::logger()->add(\Kalibri\Logger\Base::L_DEBUG, 'init', $this);
     }
     ob_start();
 }
Esempio n. 21
0
 /**
  * Execute controller and action
  */
 public function run()
 {
     try {
         $controllerName = "\\{$this->_baseNamespace}\\App\\Controller\\" . str_replace('/', '\\', $this->_dir . $this->_controller);
         if (\class_exists($controllerName)) {
             $actionName = $this->_action . $this->_options['action-prefix'];
             /** @var $controller \Kalibri\Controller\Page*/
             $controller = new $controllerName();
             // Set global controller instance
             \Kalibri::controller($controller);
             //If exists method '_remap' call it and pass method name and params
             if (\method_exists($controller, '_remap')) {
                 \call_user_func_array([$controller, '_remap'], [$actionName, $this->_params]);
             } elseif (\is_callable("{$controllerName}::{$actionName}")) {
                 \call_user_func_array([$controller, $actionName], $this->_params);
             } else {
                 throw new NotFound();
             }
             // Check is controller already rendered by hand, if not render it
             if (!$controller->isRendered()) {
                 \call_user_func_array([$controller, '_render'], []);
             }
             return $this;
         }
     } catch (NotFound $e) {
         \Kalibri::error()->showPageNotFound();
     } catch (\Exception $e) {
         \Kalibri::error()->showException($e);
     }
     \Kalibri::error()->showPageNotFound();
     return $this;
 }
Esempio n. 22
0
 public function load($shortName = null)
 {
     $shortName = $shortName ?: $this->_currentLang;
     if (isset($this->_isLoaded[$shortName])) {
         return true;
     }
     $appLocation = \Kalibri::app()->getLocation();
     $locations = array(K_ROOT . 'Kalibri/Data/Locale/' . $shortName . '/', $appLocation . 'Locale/' . $shortName . '/');
     if (!isset($this->_messages[$shortName])) {
         $this->_messages[$shortName] = array();
     }
     foreach ($locations as $location) {
         if (is_dir($location)) {
             foreach (scandir($location) as $fileName) {
                 if (!is_dir($location . $fileName)) {
                     $this->_messages[$shortName] = array_merge($this->_messages[$shortName], include $location . $fileName);
                 }
             }
         }
     }
     $this->_isLoaded[$shortName] = true;
 }
Esempio n. 23
0
 public function encryptPassword($rawPassword)
 {
     return md5($rawPassword . \Kalibri::config()->get('auth.salt'));
 }
Esempio n. 24
0
<?php

session_start();
define('PAGE_START', microtime(true));
define('K_APP_FOLDER', str_replace('\\', '/', realpath('..')) . '/');
require_once '../../Kalibri/_init.php';
$appMode = strpos($_SERVER['HTTP_HOST'], '.dev') === false ? null : 'dev';
Kalibri::app(new \Kalibri\Application(K_APP_FOLDER, $appMode))->run();
Esempio n. 25
0
 public static function current($fullPath = false)
 {
     /**
      * @todo Add protocol detection
      */
     $uri = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
     $root = \Kalibri::config()->get('base') . \Kalibri::config()->get('entry');
     return $fullPath ? $uri : str_replace($root, '', $uri);
 }
Esempio n. 26
0
 /**
  * @param string
  * @return bool
  */
 public function isValidUri($uri)
 {
     return (bool) preg_match("/^[" . \Kalibri::config()->get('permitted-uri-chars') . "\\/]+\$/", $uri);
 }
Esempio n. 27
0
 /**
  * Set list of classes that will be auto inited on first use
  *
  * @param array $list
  *
  * @return null
  */
 public static function setAutoInitClasses($list)
 {
     self::$autoClasses = $list;
 }
Esempio n. 28
0
 /**
  * Get all marks. Allmost the same as Kalibri\Benchmark::get(TRUE)
  * but point will not autocomplete
  *
  * @param bool @stopAll
  *
  * @return array
  */
 public function getMarks($stopAll = false)
 {
     if ($stopAll) {
         $total = array('time' => 0, 'memory' => 0, 'marks' => 0, 'peak_memory' => 0, 'includes' => array());
         if (function_exists('memory_get_peak_usage')) {
             $total['peak_memory'] = memory_get_peak_usage(false);
         }
         if (function_exists('get_included_files')) {
             $total['includes'] = get_included_files();
             $basePath = substr(\Kalibri::app()->getLocation(), 0, -strlen(\Kalibri::app()->getNamespace()) - 2);
             $includesCount = count($total['includes']);
             for ($i = 0; $i < $includesCount; $i++) {
                 $total['includes'][$i] = str_replace($basePath, '', $total['includes'][$i]);
             }
         }
         foreach ($this->_marks as $name => $mark) {
             if (!$mark['stop']) {
                 $mark = $this->stop($name);
             }
             $total['time'] += $mark['execution'];
             $total['memory'] += $mark['memory_used'];
         }
         $total['marks'] = count($this->_marks);
         $this->_marks[self::RESULTS_MARK] = $total;
     }
     return $this->_marks;
 }
Esempio n. 29
0
 /**
  * Find view for current controller
  *
  * @param string $directory
  * @param string $controller
  * @param string $action
  *
  * @throws \Kalibri\Exception\View\NotFound
  *
  * @return string
  */
 public function findView($directory = null, $controller = null, $action = null)
 {
     $directory = $directory ?: \Kalibri::router()->getDirectory();
     $controller = $controller ?: \Kalibri::router()->getController();
     $action = $action ?: \Kalibri::router()->getAction();
     //Is directory set to find in
     if (\strcmp($directory, '') != 0) {
         if ($this->getView()->isExists("{$directory}/{$controller}/{$action}", $this->_alternativeViewLocation)) {
             return "{$directory}/{$controller}/{$action}";
         } elseif ($this->getView()->isExists("{$directory}/{$controller}", $this->_alternativeViewLocation)) {
             return "{$directory}/{$controller}";
         } elseif ($this->getView()->isExists("{$directory}/{$controller}_{$action}", $this->_alternativeViewLocation)) {
             return "{$directory}/{$controller}_{$action}";
         }
     }
     //Controller and method
     if ($this->getView()->isExists("{$controller}/{$action}", $this->_alternativeViewLocation)) {
         return "{$controller}/{$action}";
     }
     //Controller and method
     if ($this->getView()->isExists("{$controller}_{$action}", $this->_alternativeViewLocation)) {
         return "{$controller}_{$action}";
     }
     //Controller
     if ($this->getView()->isExists($controller, $this->_alternativeViewLocation)) {
         return $controller;
     }
     throw new \Kalibri\Exception\View\NotFound("Can't automaticaly find view file " . "for controller: '{$controller}' method: '{$action}' directory: '{$directory}'");
 }
Esempio n. 30
0
 private function path($key)
 {
     return \Kalibri::tmp($key);
 }