Beispiel #1
3
 public function __construct($string)
 {
     \Twig_Autoloader::register();
     $this->loader = new \Twig_Loader_String();
     $this->twig = new \Twig_Environment($this->loader);
     $this->string = $string;
     /**
      * let twig know the BACBOX_URLBASE
      * templates need this information to correctly locate css, js and any other
      * static content from the webserver
      */
     $this->_urlbase = BACBOX_URLBASE;
     /**
      * in case that multilanguage is enabled, we need to append the
      * language token to the urlbase for in-template links
      */
     if (Registry::get('language_token')) {
         $this->_linkbase = BACBOX_URLBASE . Registry::get('language_token') . '/';
     } else {
         $this->_linkbase = BACBOX_URLBASE;
     }
     // register the hostname for absolute linking
     $this->_hostname = Config::get('system.hostname');
     $this->setHeader('Content-Type', 'text/html; charset="UTF-8"');
 }
Beispiel #2
1
 public function __construct($debug = false)
 {
     define('DEBUG', $debug);
     /**
      * Initialize whoops to handle exceptions
      */
     Registry::set('whoops', new Run());
     if (DEBUG) {
         Registry::get('whoops')->pushHandler(new PrettyPageHandler());
     }
     Registry::get('whoops')->pushHandler(new ExceptionHandler());
     Registry::get('whoops')->register();
     if (!defined('BACBOX_APP')) {
         throw new Exception("Please define the path to the app directory in your bootstrap by setting BACBOX_APP");
     }
     /**
      * set some basic php configuration parameters
      * these are mainly used for new installations and
      * will be overriden later based on configuration tokens
      */
     ini_set('display_errors', (bool) $debug);
     ini_set('error_reporting', E_ALL ^ E_STRICT);
     ini_set('max_execution_time', 30);
     // define paths
     define('DS', preg_match("/\\//", __DIR__) ? "/" : "\\");
     define('BACBOX_LIB', __DIR__);
     define('BACBOX_SRC', BACBOX_APP . '../src' . DS);
     // set the bacbox urlbase, e.g. /bacbox/
     $urlbase = dirname($_SERVER['SCRIPT_NAME']);
     $urlbase = preg_replace('#\\\\+#', '/', $urlbase);
     if (!preg_match('#/$#', $urlbase)) {
         $urlbase .= "/";
     }
     define('BACBOX_URLBASE', $urlbase);
     // setup cache
     phpFastCache::setup('storage', 'files');
     phpFastCache::setup('path', BACBOX_APP . 'cache');
     phpFastCache::setup('securityKey', 'phpFastCache');
     // initialize Uberloader
     $loader = new Uberloader();
     $loader->set_cache_backend(new UberloaderCacheBackendFilesystem(BACBOX_APP . "cache" . DS));
     $loader->add_path(BACBOX_LIB . DS . 'models');
     $loader->add_path(BACBOX_LIB . DS . 'migrations');
     $loader->add_path(BACBOX_SRC);
     $loader->register();
     Registry::set('loader', $loader);
     // init basic configuration tokens to gain database-access
     Config::init();
     // establish database link
     ORM::configure('mysql:host=' . Config::get('mysql.host') . ';dbname=' . Config::get('mysql.database'));
     ORM::configure('username', Config::get('mysql.user'));
     ORM::configure('password', Config::get('mysql.pass'));
     ORM::configure('driver_options', array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'));
     ORM::configure('logging', true);
     // load remaining configuration tokens from database or cache
     Config::load();
     // execute database migrations if .autoMigrate = true
     Config::get('migrations.autoMigrate') ? Migrator::run() : null;
     // initialize and register request helper
     Registry::set('Request', $request = new Request());
     // run core controller to pre-process the user's request
     Controller::run();
     // run site migrations
     if (Registry::get('site')->site_auto_migrate) {
         SiteMigrator::run();
     }
     // initialize hooks subsystem
     Hooks::init();
     Hooks::run('core.hooks.initialized');
     // run config overrides in case the site specifies any
     Config::run_config_overrides();
     // initialize and register session handler
     Registry::set('Session', new Session());
     // initialize localization subsystem
     Registry::set('Localization', new Localization());
     // run the user's request
     Hooks::run('core.response.before');
     Registry::set('Response', $response = Dispatcher::run($request));
     Hooks::run('core.response.after');
     // send the response
     $response->send();
     // that's it, folks
     exit;
 }
Beispiel #3
0
 public function __construct($location, $permanent = false)
 {
     $this->clearHeaders();
     // set header
     if ($permanent) {
         $this->setHttpHeader(301);
     } else {
         $this->setHttpHeader(302);
     }
     // internal or external?
     if (preg_match("/^[A-Z-a-z]{3,5}\\:\\/{2}/", $location)) {
         // external
         $location = $location;
     } else {
         $location = $location . '/';
         // prepend language token if available
         if (Registry::get('language_token')) {
             $location = Registry::get('language_token') . '/' . $location;
         }
         // build location
         $location = BACBOX_URLBASE . '/' . $location . '/';
         // make sure there's no multiple slashes (/)
         $location = preg_replace("#/{2,}#", '/', $location);
     }
     $this->setHeader('Location', $location);
 }
Beispiel #4
0
 /**
  * Run the Exception handler
  *
  * @return int|null
  */
 public function handle()
 {
     // check if the the loaded site provides its own ExceptionHandler
     if (!is_null(Registry::get('namespace'))) {
         // only continue if run-origin in bacbox\ExceptionHandler
         if (!defined('CUSTOM_EXCEPTION_HANDLER')) {
             $exceptionAsset = Registry::get('namespace') . "\\" . "Assets\\ExceptionHandler";
             // overload Uberloader scope and try to load the site's specific ExceptionHandler
             Registry::get('loader')->disable_bruteforce(Registry::get('site_src_path') . 'Assets');
             if (class_exists($exceptionAsset) && is_subclass_of($exceptionAsset, 'bacbox\\ExceptionHandler')) {
                 /*
                  * This flag makes sure that the site's exception handler is called only once
                  * If it fails to return a proper Whoops exit-code, the internal bacbox\ExceptionHandler takes over again,
                  * which in turn delegates to Whoops or displays an error response suitable for public
                  */
                 define('CUSTOM_EXCEPTION_HANDLER', true);
                 // check if the custom ExceptionHandler wants to take care of this kind of exception
                 $exceptionHandler = new $exceptionAsset();
                 $exceptionType = get_class($this->getException());
                 if (is_array($exceptionHandler->handleErrors) && array_key_exists($exceptionType, $exceptionHandler->handleErrors)) {
                     Registry::get('whoops')->unregister();
                     Registry::get('whoops')->pushHandler(new $exceptionAsset());
                     Registry::get('whoops')->register();
                     // handle Exception
                     ob_start();
                     Registry::get('whoops')->handleException($this->getException());
                 }
             }
         } else {
             ob_clean();
         }
     }
     /**
      * if we reach this point, no custom ExceptionHandler is available to take over
      */
     if (DEBUG) {
         // @todo: set a few debugging hints
         // just let Whoops handle the error
         return Handler::DONE;
     } else {
         // for now, just print ugly message
         $exceptionType = get_class($this->getException());
         $resp = new ResponseTwigString('<h1>Error {{ status }}<h1><h2>{{ message }}</h2>');
         $resp->status = 500;
         $resp->message = 'Internal Server Error';
         $errors = array('bacbox\\Error401Unauthorized' => array(401, 'Unauthorized'), 'bacbox\\Error404NotFound' => array(404, 'Not Found'), 'bacbox\\Error500Internal' => array(500, 'Internal Server Error'), 'bacbox\\ErrorSiteInactive' => array(503, 'Service Unavailable'));
         if (array_key_exists($exceptionType, $errors)) {
             $resp->status = $errors[$exceptionType][0];
             $resp->message = $errors[$exceptionType][1];
         }
         $resp->setHttpHeader($resp->status);
         $resp->send();
         Handler::DONE;
     }
     exit;
 }
Beispiel #5
0
 /**
  * sample how to send mails
  * @param $rq
  * @param $params
  * @return ResponseTwigString
  */
 public function sendmail_action($rq, $params)
 {
     $message = \Swift_Message::newInstance('Test E-Mail')->setFrom(array('*****@*****.**' => 'John Doe'))->setTo(array('*****@*****.**' => 'Name of the recipient'))->setBody('Just a test-message');
     // Send the message
     if ($result = Registry::get('mailer')->send($message)) {
         return new ResponseTwigString('Mail sent!');
     } else {
         // if you want, you can fetch the exception
         $exception = Registry::get('mailer')->getException();
         return new ResponseTwigString('Mail could not be sent, check your serverconfig!');
     }
 }
Beispiel #6
0
 /**
  * Returns a module object for the given path
  */
 private static function call_controller($rq)
 {
     // normalize path for trailing/leading slashes
     $path = preg_replace('#^/*(.*?)/*$#', '$1', Controller::$request_url);
     $request_params = explode('/', $path);
     $first_param = array_shift($request_params);
     if (strlen($first_param) == 0) {
         // we're at root level -> just load the default controller
         $first_param = self::$default_controller;
     } else {
         // the request must be checked for potential xss-attacks
         if (!preg_match('#^[^\\d]\\w[\\d\\w]*$#', $first_param)) {
             // possible attack - issue 404 error
             throw new Error404NotFound("Invalid module name");
         }
     }
     // prepare controller name
     $controllerClass = Registry::get('namespace') . "\\" . "Controller\\" . ucfirst(strtolower($first_param));
     /**
      * look for requested controller in sites namespace directory
      * (and only in this directory!)
      * we need to overload Uberloader at this point to avoid performance issues
      * with non-existant controller (-> error 404)
      */
     Registry::get('loader')->disable_bruteforce(Registry::get('site_src_path') . 'Controller');
     try {
         // try locating the requested module class
         class_exists($controllerClass);
         // if we got this far, the module class exists
         try {
             // try calling the controller
             $controller = new $controllerClass($rq, $request_params);
         } catch (Error401Unauthorized $e) {
             // the controller might issue a non-authorized error here, re-throw
             throw $e;
         } catch (Exception $e) {
             // there was an error while calling the module
             throw $e;
         }
     } catch (UberloaderException $e) {
         // Uberloader was unable to locate the requested module class declaration
         // we can still check if the request points to an action within the default controller
         $controllerClass = Registry::get('namespace') . "\\" . "Controller\\" . ucfirst(strtolower(self::$default_controller));
         // overload Uberloader scope
         Registry::get('loader')->disable_bruteforce(Registry::get('site_src_path') . 'Controller');
         try {
             // try calling the default controller
             $controller = new $controllerClass($rq, $request_params);
         } catch (Error401Unauthorized $e) {
             // the default module might issue a non-authorized error here, re-throw
             throw $e;
         } catch (UberloaderException $e) {
             // Uberloader was unable to locate the default module
             throw new Error500Internal("Failed to load default controller '" . $controllerClass . "'");
         }
         /**
          * apparently everything is fine with the default controller
          * is there an action that fits the request?
          */
         if (method_exists($controller, $first_param . '_action')) {
             /* the method exists, pass it back to the action-loader
              * we need to re-add the first_param to the list of parameters again, so that
              * the action loader knows what action is requested
              */
             array_unshift($request_params, $first_param);
             return array($request_params, $controller);
         } else {
             /**
              * still no luck, there's neither a module nor an action in the default controller
              * that would fit the request
              */
             throw new Error404NotFound("Unable to find requested controller or a matching action in the default controller");
         }
     }
     return array($request_params, $controller);
 }
Beispiel #7
0
 /**
  * method overrides allowed general config tokens with site-specific ones
  */
 public static function run_config_overrides()
 {
     // try to load site-specific config tokens for config-override
     if ($site_tokens = Registry::get('site')->config_overrides()->find_many()) {
         /**
          * site-specific config overrides found
          *
          * override if
          * - token already exists (has been set globally)
          * - token override is allowed
          * - new value differs from old
          */
         $override_count = 0;
         foreach ($site_tokens as $token_override) {
             if (in_array($token_override->key, self::$overrideable_tokens)) {
                 if (unserialize($token_override->value) != self::get($token_override->key)) {
                     self::set($token_override->key, unserialize($token_override->value));
                     $override_count++;
                 }
             }
         }
         // if one or more tokens were overriden, re-set system_settings
         if ($override_count > 0) {
             self::set_system_settings();
         }
     }
 }
Beispiel #8
0
 public function __construct()
 {
     parent::__construct();
     // set some directories
     $this->setTemplateDir(Registry::get('site_src_path') . 'templates');
     $this->setCompileDir(BACBOX_APP . "cache" . DS . "smarty" . DS . "templates_c");
     $this->setCacheDir(BACBOX_APP . "cache" . DS . "smarty" . DS . "cache");
     $this->setConfigDir(BACBOX_APP . "cache" . DS . "smarty" . DS . "config");
     // set the plugins directory
     $this->setPluginsDir(BACBOX_LIB . "utils" . DS . "smarty_plugins" . DS);
     // add site-specific plugin directory
     $this->addPluginsDir(Registry::get('site_src_path') . "Assets" . DS . "smarty_plugins" . DS);
 }
Beispiel #9
0
 /**
  * Get hooks
  *
  * @param $hookName
  * @return bool
  */
 private function getHook($hookName)
 {
     $hooks = Registry::get('hooks')->hooks;
     if (isset($hooks[$hookName])) {
         return $hooks[$hookName];
     }
     return false;
 }