/**
  * @param string $template
  * @param array  $data
  * @param string $path Path to templates if you do not want to use PIMF framework restriction.
  */
 public function __construct($template = 'default.phtml', array $data = array(), $path = null)
 {
     $conf = Registry::get('conf');
     $this->data = new \ArrayObject($data, \ArrayObject::ARRAY_AS_PROPS);
     $this->path = !$path ? BASE_PATH . 'app/' . $conf['app']['name'] . '/_templates' : $path;
     $this->template = (string) $template;
 }
 /**
  * Method to show the content.
  *
  * @return mixed
  * @throws \Exception If not supported request method or bad controller
  */
 public function render()
 {
     $conf = Registry::get('conf');
     if (Sapi::isCli() && $conf['environment'] == 'production') {
         $suffix = 'CliAction';
         $action = $this->request->fromCli()->get('action', 'index');
     } else {
         $suffix = 'Action';
         $bag = 'from' . ucfirst(strtolower($this->response->getMethod()));
         $action = $this->request->{$bag}()->get('action', 'index');
         if ($conf['app']['routeable'] === true) {
             $target = Registry::get('router')->find();
             if ($target instanceof \Pimf\Route\Target) {
                 $action = $target->getAction();
                 Request::$getData = new Param((array) Request::stripSlashesIfMagicQuotes(array_merge($target->getParams(), Request::$getData->getAll())));
             }
         }
     }
     $action = strtolower($action) . $suffix;
     if (method_exists($this, 'init')) {
         call_user_func(array($this, 'init'));
     }
     if (!method_exists($this, $action)) {
         throw new Bomb("no action '{$action}' defined at controller " . get_class($this));
     }
     return call_user_func(array($this, $action));
 }
 /**
  * @return \Pimf\Controller\Base
  * @throws \Exception If no controller specified or no controller found at the repository.
  */
 public function process()
 {
     $path = str_replace($this->repositoryPath, '', $this->controllerPath);
     $name = str_replace('/', $this->controllerClass, $path);
     $controller = str_replace('.php', '', $name);
     if (!class_exists($controller)) {
         throw new Bomb('can not load class "' . $controller . '" from the repository');
     }
     return new $controller($this->request, new Response(Registry::get('env')->REQUEST_METHOD));
 }
 /**
  * @param string $template
  * @param array  $data
  */
 public function __construct($template, array $data = array())
 {
     parent::__construct($template, $data);
     $conf = Registry::get('conf');
     $options = array('debug' => Value::ensureBoolean($conf['view']['haanga']['debug']), 'template_dir' => $this->path, 'autoload' => Value::ensureBoolean($conf['view']['haanga']['auto_reload']));
     if ($conf['view']['haanga']['cache'] === true) {
         $options['cache_dir'] = $this->path . '/haanga_cache';
     }
     require_once BASE_PATH . "Haanga/lib/Haanga.php";
     \Haanga::configure($options);
 }
 /**
  * Get the URI for the current request.
  *
  * @return string
  */
 public static function current()
 {
     if (!is_null(static::$uri)) {
         return static::$uri;
     }
     //Format a given URI.
     $uri = trim(Registry::get('env')->PATH_INFO, '/') ?: '/';
     //Set the URI segments for the request.
     $segments = explode('/', trim($uri, '/'));
     static::$segments = array_diff($segments, array(''));
     return static::$uri = $uri;
 }
 /**
  * @param string $template
  * @param array  $data
  */
 public function __construct($template, array $data = array())
 {
     parent::__construct($template, $data);
     $conf = Registry::get('conf');
     require_once BASE_PATH . "Twig/lib/Twig/Autoloader.php";
     \Twig_Autoloader::register();
     $options = array('debug' => Value::ensureBoolean($conf['view']['twig']['debug']), 'auto_reload' => Value::ensureBoolean($conf['view']['twig']['auto_reload']));
     if ($conf['view']['twig']['cache'] === true) {
         $options['cache'] = $this->path . '/twig_cache';
     }
     // define the Twig environment.
     $this->twig = new \Twig_Environment(new \Twig_Loader_Filesystem(array($this->path)), $options);
 }
 /**
  * Test 5: Database updates
  */
 public function updatesAction()
 {
     $queries = max(1, min($this->request->fromGet()->get('queries', 1), 500));
     $worlds = array();
     /* @var $em \Pimf\EntityManager */
     $em = Registry::get('em');
     $em->beginTransaction();
     for ($i = 0; $i < $queries; ++$i) {
         $worlds[] = $em->world->find(mt_rand(1, 10000));
     }
     foreach ($worlds as $row) {
         $row['randomNumber'] = rand(1, 10000);
         $em->world->update($row);
     }
     $em->commitTransaction();
     $this->response->asJSON()->send($worlds);
 }
 /**
  * Returns a 32-bit integer that identifies this host.
  *
  * The node identifier needs to be unique among nodes
  * in a cluster for a given application in order to
  * avoid collisions between generated identifiers.
  *
  * @return integer
  */
 private static function getNodeId()
 {
     $host = Registry::get('env')->getIp();
     $hostname = Registry::get('env')->getHost();
     if ($host === null && true === function_exists('gethostname')) {
         $hostname = gethostname();
         $host = gethostbyname($hostname);
     }
     if ($host === null && true === function_exists('php_uname')) {
         $hostname = php_uname('n');
         $host = gethostbyname($hostname);
     }
     if ($host === null && $hostname !== null) {
         $host = crc32($hostname);
     }
     if ($host === null) {
         $host = '127.0.0.1';
     }
     return ip2long($host);
 }
 /**
  * @param string $appClr
  * @param string $coreClr
  * @param string $root
  *
  * @return array
  */
 public static function collect($appClr = null, $coreClr = null, $root = null)
 {
     $classes = array();
     $conf = Registry::get('conf');
     $dis = DIRECTORY_SEPARATOR;
     if (!$root && !$coreClr && !$appClr) {
         // compute the PIMF framework path restriction.
         $root = dirname(dirname(dirname(dirname(__FILE__))));
         $coreClr = str_replace('/', $dis, $root . '/pimf-framework/core/Pimf/Controller/');
         $appClr = str_replace('/', $dis, $root . '/app/' . $conf['app']['name'] . '/Controller/');
     }
     foreach (array($appClr, $coreClr) as $dir) {
         $iterator = new \RegexIterator(new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($dir)), '/^.+\\.php$/i', \RecursiveRegexIterator::GET_MATCH);
         foreach (iterator_to_array($iterator, false) as $file) {
             $file = str_replace("\\", '/', current($file));
             $file = str_replace('/', $dis, $file);
             $name = str_replace(array($root . $dis . 'pimf-framework' . $dis . 'core' . $dis, $root . $dis . 'app' . $dis), '', $file);
             $name = str_replace($dis, '\\', $name);
             $name = str_replace('.php', '', $name);
             $classes[] = '\\' . $name;
         }
     }
     return $classes;
 }
 /**
  * Create a new session storage instance.
  *
  * @param string $storage
  *
  * @return Storage\Storage
  * @throws \RuntimeException
  */
 public static function factory($storage)
 {
     $conf = Registry::get('conf');
     switch ($storage) {
         case 'apc':
             return new Storage\Apc(Cache::storage('apc'));
         case 'cookie':
             return new Storage\Cookie();
         case 'file':
             return new Storage\File($conf['session']['storage_path']);
         case 'pdo':
             return new Storage\Pdo(Pdo\Factory::get($conf['session']['database']));
         case 'memcached':
             return new Storage\Memcached(Cache::storage('memcached'));
         case 'memory':
             return new Storage\Memory();
         case 'redis':
             return new Storage\Redis(Cache::storage('redis'));
         case 'dba':
             return new Storage\Dba(Cache::storage('dba'));
         default:
             throw new \RuntimeException("Session storage [{$storage}] is not supported.");
     }
 }
 /**
  * Create a new cache storage instance.
  *
  * @param string $storage
  *
  * @return CS\Apc|CS\Dba|CS\File|CS\Memcached|CS\Memory|CS\Pdo|CS\Redis|CS\WinCache
  * @throws \RuntimeException
  */
 protected static function factory($storage)
 {
     $conf = Registry::get('conf');
     switch ($storage) {
         case 'apc':
             return new CS\Apc($conf['cache']['key']);
         case 'file':
             return new CS\File($conf['cache']['storage_path']);
         case 'pdo':
             return new CS\Pdo(Pdo\Factory::get($conf['cache']['database']), $conf['cache']['key']);
         case 'memcached':
             return new CS\Memcached(Memcached::connection(), $conf['cache']['key']);
         case 'memory':
             return new CS\Memory();
         case 'redis':
             return new CS\Redis(Redis::database());
         case 'wincache':
             return new CS\WinCache($conf['cache']['key']);
         case 'dba':
             return new CS\Dba(String::ensureTrailing('/', $conf['cache']['storage_path']) . $conf['cache']['key']);
         default:
             throw new \RuntimeException("Cache storage {$storage} is not supported.");
     }
 }
 /**
  * @param int    $code    HTTP response code
  * @param string $status  The header string which will be used to figure out the HTTP status code to send.
  * @param bool   $replace Whether the header should replace a previous similar header.
  */
 public static function send($code, $status, $replace = true)
 {
     header('' . Registry::get('env')->SERVER_PROTOCOL . ' ' . $code . ' ' . $status, $replace, $code);
 }
 /**
  * @param string $type
  * @param string $for
  *
  * @return bool
  * @throws \DomainException
  */
 protected function createTable($type, $for)
 {
     $type = trim($type);
     try {
         $pdo = $file = null;
         $conf = Registry::get('conf');
         switch ($for) {
             case 'cache':
                 $pdo = Factory::get($conf['cache']['database']);
                 $file = 'create-cache-table-' . $type . '.sql';
                 break;
             case 'session':
                 $pdo = Factory::get($conf['session']['database']);
                 $file = 'create-session-table-' . $type . '.sql';
                 break;
         }
         $file = str_replace('/', DS, BASE_PATH . 'pimf-framework/core/Pimf/_database/' . $file);
         return $pdo->exec(file_get_contents(new File($file))) or print_r($pdo->errorInfo(), true);
     } catch (\PDOException $pdoe) {
         throw new Bomb($pdoe->getMessage());
     }
 }
 /**
  * Log an exception.
  *
  * @param \Exception $exception
  */
 public static function log(\Exception $exception)
 {
     $conf = Registry::get('conf');
     if (isset($conf['error']['log']) && $conf['error']['log'] === true) {
         Registry::get('logger')->error($exception->getMessage() . ' ' . $exception->getTraceAsString());
     }
 }
 /**
  * Clean up expired sessions.
  *
  * @return void
  */
 public function clean()
 {
     if ($this->storage instanceof \Pimf\Contracts\Cleanable) {
         $conf = Registry::get('conf');
         $this->storage->clean(time() - $conf['session']['lifetime'] * 60);
     }
 }
 /**
  * @param boolean $routeable
  * @param string  $routes Path to routes definition file.
  */
 private static function loadRoutes($routeable, $routes)
 {
     if ($routeable === true && file_exists($routes)) {
         Registry::set('router', new Router());
         foreach ((array) (include $routes) as $route) {
             Registry::get('router')->map($route);
         }
     }
 }
 /**
  * Sends file as download-header through any firewall to the browsers like >=IE6 >=FF3.6, Safari, Chrome, Opera.
  *
  * @link http://reeg.junetz.de/DSP/node16.html
  * @link http://www.php.net/manual/de/function.header.php#88038
  *
  * @param string $fileOrString
  * @param string $fileName
  * @param boolean $exit Optional for testing
  */
 public static function sendDownloadDialog($fileOrString, $fileName, $exit = true)
 {
     $disposition = false !== strpos(Registry::get('env')->getUserAgent(), 'MSIE 5.5') ? '' : 'attachment; ';
     header("Pragma: public");
     header("Expires: 0");
     header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
     header("Cache-Control: private", false);
     header("Content-Disposition: " . $disposition . "filename=" . $fileName . ";");
     if (is_file($fileOrString)) {
         readfile($fileOrString);
     } else {
         echo $fileOrString;
     }
     if ($exit) {
         exit(0);
     }
 }
 /**
  * Get cleaner URLs or old-fashioned » RFC 3986 URL-query string.
  *
  * @param string $route controller/action
  * @param array  $params
  * @param null   $https
  * @param bool   $asset
  *
  * @return string
  */
 public static function compute($route = '', array $params = array(), $https = null, $asset = false)
 {
     // if your application should work with RFC 3986 URL-query strings
     $conf = Registry::get('conf');
     if ($conf['app']['routeable'] === false) {
         list($controller, $action) = explode('/', $route);
         $params = array_merge(compact('controller', 'action'), $params);
         return Str::ensureTrailing('/', self::format($https, $asset)) . '?' . http_build_query($params, null, '&');
     }
     // otherwise PIMF will serve you cleaner URLs
     $slug = implode('/', $params);
     if ($slug != '') {
         $slug = '/' . $slug;
     }
     return self::to($route, $https, $asset) . $slug;
 }