public function display()
 {
     $front = \Nf\Front::getInstance();
     $response = $front->getResponse();
     $response->addBodyPart(json_encode($this->_errors));
     $response->sendResponse();
 }
Exemple #2
0
 protected function __construct()
 {
     parent::__construct();
     $front = Front::getInstance();
     $this->setBasePath($front->getModuleName());
     // send the label Manager to the view
     $this->_vars['labels'] = \Nf\LabelManager::getInstance();
 }
 public function __construct($config)
 {
     require_once realpath(Registry::get('libraryPath') . '/php/classes/FirePHPCore/FirePHP.class.php');
     $this->firephp = \FirePHP::getInstance(true);
     $this->label = static::LABEL_TEMPLATE;
     $front = \Nf\Front::getInstance();
     $this->dbName = $config['name'];
     $front->registerMiddleware($this);
     $this->payload = array(array('Duration', 'Query', 'Time'));
 }
Exemple #4
0
 public function display()
 {
     $front = \Nf\Front::getInstance();
     $response = $front->getResponse();
     if ($response->getContentType() == 'json') {
         $response->addBodyPart(json_encode(['message' => $this->getMessage()]));
     } else {
         $response->addBodyPart($this->getMessage());
     }
     $response->sendResponse();
 }
Exemple #5
0
 public function redirect($url, $code = 302, $exit = true)
 {
     $this->canSendHeaders();
     $this->setHeader('Location', $url, true)->setHttpResponseCode($code);
     if ($exit) {
         $front = \Nf\Front::getInstance();
         $front->postLaunchAction();
         $this->clearBuffer();
         $this->clearBody();
         $this->sendHeaders();
         exit;
     }
     return $this;
 }
 public static function displayAndLogError($exception = null)
 {
     $err = self::getLastError();
     if (\Nf\Registry::isRegistered('config')) {
         $config = \Nf\Registry::get('config');
         $front = \Nf\Front::getInstance();
         $response = $front->getResponse();
         // optional error logging
         if (isset($exception->doLog) && $exception->doLog || !isset($exception->doLog)) {
             if (isset($config->error->logger->class) && strtolower($config->error->logger->class) != 'syslog') {
                 $className = $config->error->logger->class;
                 $logger = new $className();
                 if (!$logger->log($err)) {
                 }
             } else {
                 $logger = new \Nf\Error\Logger\Syslog();
                 if (!$logger->log($err)) {
                 }
             }
         }
         if ($response->isBinary()) {
             $response->setContentType('html');
         }
         if (isset($config->error->clearResponse) && $config->error->clearResponse || !isset($config->error->clearResponse)) {
             $response->clearBody();
             $response->clearBuffer();
         }
         try {
             $response->setHttpResponseCode($err['httpCode']);
             $response->sendHeaders();
         } catch (Exception $e) {
         }
         if (isset($config->error->displayMethod)) {
             if ($config->error->displayMethod == 'forward') {
                 // forward
                 if (!$front->forward($config->error->forward->module, $config->error->forward->controller, $config->error->forward->action)) {
                     echo '** Nf: Cannot instantiate error module, printing error message **' . PHP_EOL . PHP_EOL;
                     $response->displayError($err);
                     echo PHP_EOL;
                 } else {
                     $response->sendResponse();
                 }
                 return true;
             } else {
                 if (method_exists($exception, 'display')) {
                     $response->setHttpResponseCode($err['httpCode']);
                     $exception->display();
                 } else {
                     // default : display (if xhr, use alternative display)
                     $response->displayError($err, $front->getRequest()->isXhr());
                 }
             }
         }
         return true;
     } else {
         @header('HTTP/1.1 500 Internal Server Error');
         print_r($err);
         error_log(print_r($err, true));
         return true;
     }
 }
Exemple #7
0
 private function findRouteFromFiles($uri, $version, $locale)
 {
     $foundController = null;
     $front = Front::getInstance();
     if (isset($this->allRoutesByVersionAndLocale[$version][$locale])) {
         $routes = $this->allRoutesByVersionAndLocale[$version][$locale];
         if (!$foundController) {
             $routes = array_reverse($routes);
             foreach ($routes as $route) {
                 if (!$foundController) {
                     // default type is "default"
                     $requestType = 'default';
                     // if a specific type is requested
                     if (isset($route['type'])) {
                         $requestType = $route['type'];
                     }
                     $routeRegexpWithoutNamedParams = preg_replace('/\\([\\w_]+:/', '(', $route['regexp']);
                     $arrRouteModuleControllerAction = explode('/', $route['controller']);
                     // check if this is a match, or else continue until we have a match
                     if (preg_match('#^' . $routeRegexpWithoutNamedParams . '#', $uri, $refs)) {
                         // if using a rest request, the user can override the method
                         if ($requestType == 'rest') {
                             // default action
                             if (isset($_SERVER['REQUEST_METHOD'])) {
                                 $action = strtolower($_SERVER['REQUEST_METHOD']);
                             }
                             if ($_SERVER['REQUEST_METHOD'] == 'POST') {
                                 // overloading the method with the "method" parameter if the request is POST
                                 if (isset($_POST['method'])) {
                                     $action = strtolower($_POST['method']);
                                 }
                                 // overloading the method with http headers
                                 // X-HTTP-Method (Microsoft) or X-HTTP-Method-Override (Google/GData) or X-METHOD-OVERRIDE (IBM)
                                 $acceptableOverridingHeaders = array('HTTP_X_HTTP_METHOD', 'HTTP_X_HTTP_METHOD_OVERRIDE', 'HTTP_X_METHOD_OVERRIDE');
                                 foreach ($acceptableOverridingHeaders as $overridingHeader) {
                                     if (isset($_SERVER[$overridingHeader])) {
                                         $action = strtolower($_SERVER[$overridingHeader]);
                                     }
                                 }
                             }
                             // if overriding the action in the route
                             if (isset($arrRouteModuleControllerAction[2])) {
                                 $action = $arrRouteModuleControllerAction[2];
                             }
                         } else {
                             $action = $arrRouteModuleControllerAction[2];
                         }
                         // on teste la présence du module controller action indiqué dans la route
                         if ($foundController = $front->checkModuleControllerAction($arrRouteModuleControllerAction[0], $arrRouteModuleControllerAction[1], $action)) {
                             $this->activeRoute = $route;
                             $front->setRequestType($requestType);
                             $front->associateParams($route['regexp'], $refs);
                             break;
                         }
                     }
                 }
             }
             unset($route);
         }
     }
     return $foundController;
 }
Exemple #8
0
 function go()
 {
     if (php_sapi_name() == 'cli') {
         $inAction = $this->initCliEnvironment();
         $uri = $inAction['uri'];
         Error\Handler::setErrorDisplaying();
         $front = Front::getInstance();
         $request = new Front\Request\Cli($uri);
         $front->setRequest($request);
         $request->setAdditionalCliParams();
         $response = new Front\Response\Cli();
         $front->setResponse($response);
         $front->setApplicationNamespace($this->_applicationNamespace);
         $this->setTimezone();
         // routing
         $router = Router::getInstance();
         $front->setRouter($router);
         $router->addAllRoutes();
         // order in finding routes
         $router->setStructuredRoutes();
         $front->addModuleDirectory($this->_applicationNamespace, Registry::get('applicationPath') . '/application/cli/');
         $front->addModuleDirectory('library', Registry::get('libraryPath') . '/php/application/cli/');
         $labelManager = LabelManager::getInstance();
         $labelManager->loadLabels(Registry::get('locale'));
         $localization = Localization::getInstance();
         $localization->setLocale(Registry::get('locale'));
         if ($inAction['type'] == 'default') {
             $testDispatch = $front->dispatch();
             if ($testDispatch) {
                 if ($front->init() !== false) {
                     $front->launchAction();
                     $front->postLaunchAction();
                 }
                 $response->sendResponse();
             } else {
                 throw new \Exception('Action not found : ' . $uri);
             }
         } else {
             $front->parseParameters($inAction['uri']);
             $className = array();
             // $inAction['uri'] might be a class name with a static method like \Nf\Make::compress
             if (strpos($inAction['uri'], '\\') !== false) {
                 if (strpos($inAction['uri'], '::') === false) {
                     throw new \Exception('You have to specify the model and method to call, or just choose a method from the "Nf\\Make" class.');
                 } else {
                     $uriSplit = explode('::', $inAction['uri']);
                     $className = $uriSplit[0];
                     $methodName = $uriSplit[1];
                     $obj = new $className();
                     $className::$methodName();
                 }
             } else {
                 // or an already integrated method in Nf\Make
                 $methodName = $inAction['uri'];
                 \Nf\Make::$methodName();
             }
         }
     } else {
         $this->initHttpEnvironment();
         Error\Handler::setErrorDisplaying();
         $front = Front::getInstance();
         $request = new Front\Request\Http();
         $front->setRequest($request);
         $response = new Front\Response\Http();
         $front->setResponse($response);
         $front->setApplicationNamespace($this->_applicationNamespace);
         $this->setTimezone();
         // routing
         $router = Router::getInstance();
         $front->setRouter($router);
         $router->addAllRoutes();
         // order in finding routes
         $router->setRoutesFromFiles();
         $router->setRootRoutes();
         $router->setStructuredRoutes();
         // modules directory for this version
         $front->addModuleDirectory($this->_applicationNamespace, Registry::get('applicationPath') . '/application/' . Registry::get('version') . '/');
         $front->addModuleDirectory('library', Registry::get('libraryPath') . '/php/application/' . Registry::get('version') . '/');
         $config = Registry::get('config');
         if (isset($config->session->handler)) {
             $front->setSession(Session::start());
         }
         $labelManager = LabelManager::getInstance();
         $labelManager->loadLabels(Registry::get('locale'));
         $localization = Localization::getInstance();
         Localization::setLocale(Registry::get('locale'));
         $testDispatch = $front->dispatch();
         $requestIsClean = $request->sanitizeUri();
         if ($requestIsClean) {
             if ($testDispatch === true) {
                 $request->setPutFromRequest();
                 if (!$request->redirectForTrailingSlash()) {
                     if ($front->init() !== false) {
                         if (!$front->response->isRedirect()) {
                             $front->launchAction();
                         }
                         if (!$front->response->isRedirect()) {
                             $front->postLaunchAction();
                         }
                     }
                 }
             } else {
                 Error\Handler::handleNotFound(404);
             }
         } else {
             Error\Handler::handleForbidden(403);
         }
         $response->sendResponse();
     }
 }
Exemple #9
0
 protected function __construct()
 {
     $this->_smarty = new \Smarty();
     $front = \Nf\Front::getInstance();
     $this->setBasePath($front->getModuleName());
 }
Exemple #10
0
require $libraryPath . '/Nf/Autoloader.php';
$autoloader = new \Nf\Autoloader();
$autoloader->addNamespaceRoot($applicationNamespace, $applicationPath . '/models');
$autoloader->addNamespaceRoot('Nf', $libraryPath . '/Nf');
$autoloader->addNamespaceRoot('Library', $libraryPath . '/php/models');
$autoloader->addNamespaceRoot('', $applicationPath . '/models');
$autoloader->register();
\Nf\Registry::set('libraryPath', $libraryPath);
\Nf\Registry::set('applicationPath', $applicationPath);
$urlIni = \Nf\Ini::parse(\Nf\Registry::get('applicationPath') . '/configs/url.ini', true);
\Nf\Registry::set('urlIni', $urlIni);
\Nf\Registry::set('environment', 'test');
\Nf\Registry::set('locale', $urlIni->i18n->defaultLocale);
\Nf\Registry::set('version', 'cli');
$config = \Nf\Ini::parse(\Nf\Registry::get('applicationPath') . '/configs/config.ini', true, \Nf\Registry::get('locale') . '_' . \Nf\Registry::get('environment') . '_' . \Nf\Registry::get('version'));
\Nf\Registry::set('config', $config);
\Nf\Error\Handler::setErrorDisplaying();
$front = \Nf\Front::getInstance();
$request = new \Nf\Front\Request\Cli('/');
$front->setRequest($request);
$response = new \Nf\Front\Response\Cli();
$front->setResponse($response);
$front->setApplicationNamespace($applicationNamespace);
// routing
$router = \Nf\Router::getInstance();
$front->setRouter($router);
$router->addAllRoutes();
$labelManager = \Nf\LabelManager::getInstance();
$labelManager->loadLabels(\Nf\Registry::get('locale'));
$localization = \Nf\Localization::getInstance();
$localization->setLocale(\Nf\Registry::get('locale'));
 protected function _setCachedResult($cacheKey, $result)
 {
     if ($this->_cache !== false) {
         $cache = \Nf\Front::getInstance()->getCache('global');
         $cacheKey = isset($this->_cache['key']) ? $this->_cache['key'] : $cacheKey;
         return $cache->save('sql', $cacheKey, $result, $this->_cache['lifetime']);
     }
     return false;
 }
Exemple #12
0
 public function execute()
 {
     $settings = Settings::getInstance();
     // reference: https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
     // if CORS is enabled in the config+env settings
     if (isset($settings->security->cors->enable)) {
         if ($settings->security->cors->enable) {
             $front = Front::getInstance();
             if ($front->getRequest() instanceof Http) {
                 // is it a CORS preflight request ?
                 if (isset($_SERVER['HTTP_ORIGIN']) && isset($_SERVER['HTTP_HOST'])) {
                     $parsedOrigin = parse_url($_SERVER['HTTP_ORIGIN']);
                     $parsedCurrent = [];
                     $parsedCurrent['host'] = $_SERVER['HTTP_HOST'];
                     $parsedCurrent['scheme'] = $_SERVER['REQUEST_SCHEME'];
                     $parsedCurrent['port'] = $_SERVER['SERVER_PORT'];
                     if (!($parsedCurrent['host'] === $parsedOrigin['host']) || !($parsedCurrent['port'] === $parsedOrigin['port']) || !($parsedCurrent['scheme'] === $parsedOrigin['scheme'])) {
                         $corsAllowed = false;
                         // it's a CORS request
                         // origins
                         if (isset($settings->security->cors->allowed_origins)) {
                             $allowedOriginsFromSettings = $settings->security->cors->allowed_origins;
                         } else {
                             $allowedOriginsFromSettings = self::DEFAULT_ALLOWED_ORIGINS;
                         }
                         if ($allowedOriginsFromSettings != '*') {
                             $allowedOrigins = array_map('trim', explode(',', $settings->security->cors->allowed_origins));
                             if (in_array($parsedCurrent['host'], $allowedOrigins)) {
                                 $corsAllowed = true;
                             }
                         } else {
                             $corsAllowed = true;
                         }
                         // methods
                         if (isset($settings->security->cors->allowed_methods)) {
                             $allowedMethodsFromSettings = $settings->security->cors->allowed_methods;
                         } else {
                             $allowedMethodsFromSettings = self::DEFAULT_ALLOWED_METHODS;
                         }
                         $allowedMethods = array_map('strtoupper', array_map('trim', explode(',', $allowedMethodsFromSettings)));
                         if (!in_array(strtoupper($front->getRequest()->getMethod()), $allowedMethods)) {
                             $corsAllowed = false;
                         }
                         // headers
                         if (isset($settings->security->cors->allowed_headers)) {
                             $allowedHeadersFromSettings = $settings->security->cors->allowed_headers;
                         } else {
                             $allowedHeadersFromSettings = self::DEFAULT_ALLOWED_HEADERS;
                         }
                         $allowedHeaders = array_map('trim', explode(',', $allowedHeadersFromSettings));
                         // sending the response
                         if ($corsAllowed) {
                             header('Access-Control-Allow-Origin: ' . $_SERVER['HTTP_ORIGIN']);
                             if ($allowedOriginsFromSettings == '*') {
                                 if (isset($_SERVER['HTTP_VARY'])) {
                                     $varyHeaders = array_map('trim', explode(',', $_SERVER['HTTP_VARY']));
                                 }
                                 // adding the Vary: Origin for proxied requests
                                 $varyHeaders[] = 'Origin';
                             }
                             header('Vary: ' . implode(', ', $varyHeaders));
                             if ($front->getRequest()->isOptions()) {
                                 header('Access-Control-Allow-Methods: ' . implode(', ', $allowedMethods));
                             }
                             if (isset($settings->security->cors->allowed_credentials)) {
                                 $allowedCredentialsFromSettings = $settings->security->cors->allowed_credentials;
                             } else {
                                 $allowedCredentialsFromSettings = self::DEFAULT_ALLOWED_CREDENTIALS;
                             }
                             if ($allowedCredentialsFromSettings) {
                                 header('Access-Control-Allow-Credentials: true');
                             }
                             if ($front->getRequest()->isOptions()) {
                                 header('Access-Control-Allow-Headers: ' . implode(', ', $allowedHeaders));
                             }
                             // max-age
                             if (isset($settings->security->cors->max_age)) {
                                 $allowedMaxAgeFromSettings = $settings->security->cors->max_age;
                             } else {
                                 $allowedMaxAgeFromSettings = self::DEFAULT_MAX_AGE;
                             }
                             header('Access-Control-Max-Age: ' . $allowedMaxAgeFromSettings);
                             // every OPTIONS request should return a 200 ok and bypass every other middleware
                             if ($front->getRequest()->isOptions()) {
                                 return false;
                             }
                             return true;
                         } else {
                             return false;
                         }
                     }
                 }
             }
         }
     }
     return true;
 }
Exemple #13
0
 public function display()
 {
     $front = \Nf\Front::getInstance();
     $response = $front->getResponse();
     $response->sendResponse();
 }