/** * Servicio que devuelve las cabeceras de autenticación * @return string HTML */ public function setAdminHeaders() { $platform = trim(Config::getInstance()->get("platform_name")); header('HTTP/1.1 401 Unauthorized'); header('WWW-Authenticate: Basic Realm="' . $platform . '"'); echo _("Zona restringida"); exit; }
/** * Initialize api */ public function init() { parent::init(); $this->domain = $this->getApi(); $this->debug = Config::getInstance()->getDebugMode() || Config::getInstance()->get('debugQueries'); $this->hydrateRequestData(); $this->hydrateOrders(); $this->createConnection(); }
/** * @internal param string $path */ public function __construct() { $config = Config::getInstance(); $args = func_get_args(); list($logger, $debug, $path) = $this->setup($config, $args); $this->stream = fopen($path . DIRECTORY_SEPARATOR . date("Ymd") . ".log", "a+"); $this->addPushLogger($logger, $debug, $config); $this->log_level = Config::getInstance()->get('log.level') ?: 'info'; }
private function simulateRequiredConfig() { $config = Config::getInstance(); $data = []; foreach (Config::$required as $key) { $data[$key] = uniqid('test'); } Config::save($data, []); $config->loadConfigData(); }
/** * Basic test for Config functionality */ public function testConfig() { $config = Config::getInstance(); // Is config instance? $this->assertTrue($config instanceof Config); // Is the platform configured? $this->assertTrue(is_bool($config->isConfigured())); // Is the platform in debug mode? $this->assertTrue(is_bool($config->getDebugMode())); // Check the variable extraction $this->assertEmpty($config->get(uniqid())); }
/** * Test non default logger configurations set */ public function testLogSetup() { // Add memory logger to test this functionality $config = Config::getInstance(); $defaultConfig = $config->dumpConfig(); Config::save(array_merge($defaultConfig, ['logger.memory' => true]), []); // Create a new logger instance $logger = new Logger(['test', true]); $logger->debugLog('Test'); $logger = null; unset($defaultConfig['logger.memory']); Config::save($defaultConfig, []); }
/** * Método estático de login de administrador * @param string $route * @return string HTML * @throws \PSFS\base\exception\FormException */ public static function staticAdminLogon($route = null) { if ('login' !== Config::getInstance()->get('admin_login')) { return AdminServices::getInstance()->setAdminHeaders(); } else { $form = new LoginForm(); $form->setData(array("route" => $route)); $form->build(); $tpl = Template::getInstance(); $tpl->setPublicZone(true); return $tpl->render("login.html.twig", array('form' => $form)); } }
/** * Method that checks the access to the restricted zone * * @param string $route * * @throws AccessDeniedException */ public static function checkRestrictedAccess($route) { Logger::log('Checking admin zone'); //Chequeamos si entramos en el admin if (!Config::getInstance()->checkTryToSaveConfig() && (preg_match('/^\\/(admin|setup\\-admin)/i', $route) || NULL !== Config::getInstance()->get('restricted'))) { if (!file_exists(CONFIG_DIR . DIRECTORY_SEPARATOR . 'admins.json')) { //Si no hay fichero de usuarios redirigimos directamente al gestor return UserController::getInstance()->adminers(); } if (!Security::getInstance()->checkAdmin()) { throw new AccessDeniedException(); } Logger::log('Admin access granted'); } }
/** * Check service authentication * @return bool */ private function checkAuth() { $namespace = explode('\\', $this->getModelTableMap()); $module = strtolower($namespace[0]); $secret = Config::getInstance()->get($module . '.api.secret'); if (NULL === $secret) { $secret = Config::getInstance()->get("api.secret"); } if (NULL === $secret) { $auth = TRUE; } else { $token = Request::getInstance()->getHeader('X-API-SEC-TOKEN'); if (array_key_exists('API_TOKEN', $this->query)) { $token = $this->query['API_TOKEN']; } $auth = Security::checkToken($token ?: '', $secret, $module); } return $auth || $this->isAdmin(); }
/** * Check CROS requests */ public static function checkCORS() { Logger::log('Checking CORS'); $corsEnabled = Config::getInstance()->get('cors.enabled'); $request = Request::getInstance(); if (NULL !== $corsEnabled) { if ($corsEnabled === '*' || preg_match($corsEnabled, $request->getServer('HTTP_REFERER'))) { if (!headers_sent()) { // TODO include this headers in Template class output method header("Access-Control-Allow-Credentials: true"); header("Access-Control-Allow-Origin: *"); header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS"); header("Access-Control-Allow-Headers: Access-Control-Allow-Methods, Access-Control-Allow-Headers, Access-Control-Allow-Origin, Origin, X-Requested-With, Content-Type, Accept, Authorization, X-API-SEC-TOKEN, X-API-USER-TOKEN"); } if (Request::getInstance()->getMethod() == 'OPTIONS') { Logger::log('Returning OPTIONS header confirmation for CORS pre flight requests'); header("HTTP/1.1 200 OK"); exit; } } } }
/** * Servicio que guarda la configuración de la plataforma * @POST * @route /admin/config * @visible false * @return string * @throws \HttpException */ public function saveConfig() { Logger::getInstance()->infoLog(_("Guardando configuración")); /* @var $form \PSFS\base\config\ConfigForm */ $form = new ConfigForm(Router::getInstance()->getRoute('admin-config'), Config::$required, Config::$optional, Config::getInstance()->dumpConfig()); $form->build(); $form->hydrate(); if ($form->isValid()) { $debug = Config::getInstance()->getDebugMode(); $newDebug = $form->getFieldValue("debug"); if (Config::save($form->getData(), $form->getExtraData())) { Logger::log(_('Configuración guardada correctamente')); //Verificamos si tenemos que limpiar la cache del DocumentRoot if (boolval($debug) !== boolval($newDebug)) { Config::clearDocumentRoot(); } Security::getInstance()->setFlash("callback_message", _("Configuración actualizada correctamente")); Security::getInstance()->setFlash("callback_route", $this->getRoute("admin-config", true)); } else { throw new \HttpException(_('Error al guardar la configuración, prueba a cambiar los permisos'), 403); } } return $this->render('welcome.html.twig', array('text' => _("Bienvenido a PSFS"), 'config' => $form, 'typeahead_data' => array_merge(Config::$required, Config::$optional))); }
/** * Método que actualiza el idioma de los modelos con i18n */ protected function setModelLocale() { if (method_exists($this->model, "setLocale")) { $this->model->setLocale(Config::getInstance()->get('default_language')); } }
public function init() { parent::init(); $this->setDomain($this->domain)->setTemplatePath(Config::getInstance()->getTemplatePath()); }
/** * Método que calcula el path de un recurso web * @param string $string * @param string $name * @param boolean $return * @param string $filename_path * * @return string[] */ public static function calculateAssetPath($string, $name, $return, $filename_path) { $ppath = explode("/", $string); $original_filename = $ppath[count($ppath) - 1]; $base = WEB_DIR . DIRECTORY_SEPARATOR; $file = ""; $html_base = ""; $debug = Config::getInstance()->getDebugMode(); if (preg_match('/\\.css$/i', $string)) { $file = "/" . substr(md5($string), 0, 8) . ".css"; $html_base = "css"; if ($debug) { $file = str_replace(".css", "_" . $original_filename, $file); } } elseif (preg_match('/\\.js$/i', $string)) { $file = "/" . substr(md5($string), 0, 8) . ".js"; $html_base = "js"; if ($debug) { $file = str_replace(".js", "_" . $original_filename, $file); } } elseif (preg_match("/image/i", mime_content_type($filename_path))) { $ext = explode(".", $string); $file = "/" . substr(md5($string), 0, 8) . "." . $ext[count($ext) - 1]; $html_base = "img"; if ($debug) { $file = str_replace("." . $ext[count($ext) - 1], "_" . $original_filename, $file); } } elseif (preg_match("/(doc|pdf)/i", mime_content_type($filename_path))) { $ext = explode(".", $string); $file = "/" . substr(md5($string), 0, 8) . "." . $ext[count($ext) - 1]; $html_base = "docs"; if ($debug) { $file = str_replace("." . $ext[count($ext) - 1], "_" . $original_filename, $file); } } elseif (preg_match("/(video|audio|ogg)/i", mime_content_type($filename_path))) { $ext = explode(".", $string); $file = "/" . substr(md5($string), 0, 8) . "." . $ext[count($ext) - 1]; $html_base = "media"; if ($debug) { $file = str_replace("." . $ext[count($ext) - 1], "_" . $original_filename, $file); } } elseif (!$return && !is_null($name)) { $html_base = ''; $file = $name; } $file_path = $html_base . $file; return array($base, $html_base, $file_path); }
/** * @GET * @route /admin/translations * @return string */ public function defaultTranslations() { return $this->getTranslations(Config::getInstance()->get('default_language')); }
/** * Método que ejecuta una acción del framework y revisa si lo tenemos cacheado ya o no * * @param string $route * @param array|null $action * @param types\Controller $class * @param array $params */ protected function executeCachedRoute($route, $action, $class, $params = NULL) { Logger::log('Executing route ' . $route, LOG_INFO); Security::getInstance()->setSessionKey("__CACHE__", $action); $cache = Cache::needCache(); $execute = TRUE; if (FALSE !== $cache && Config::getInstance()->getDebugMode() === FALSE) { $cacheDataName = $this->cache->getRequestCacheHash(); $cachedData = $this->cache->readFromCache("templates" . DIRECTORY_SEPARATOR . $cacheDataName, $cache, function () { }); if (NULL !== $cachedData) { $headers = $this->cache->readFromCache("templates" . DIRECTORY_SEPARATOR . $cacheDataName . ".headers", $cache, function () { }, Cache::JSON); Template::getInstance()->renderCache($cachedData, $headers); $execute = FALSE; } } if ($execute) { call_user_func_array(array($class, $action['method']), $params); } }
/** * Método que inyecta automáticamente las dependencias en la clase */ public function init() { if (!$this->isLoaded()) { $cacheFilename = "reflections" . DIRECTORY_SEPARATOR . sha1(get_class($this)) . ".json"; /** @var \PSFS\base\Cache $cacheService */ $cacheService = Cache::getInstance(); /** @var \PSFS\base\config\Config $configService */ $configService = Config::getInstance(); $properties = $cacheService->getDataFromFile($cacheFilename, Cache::JSON); if (true === $configService->getDebugMode() || null === $properties) { $properties = InjectorHelper::getClassProperties(get_class($this)); $cacheService->storeData($cacheFilename, $properties, Cache::JSON); } /** @var \ReflectionProperty $property */ if (!empty($properties) && is_array($properties)) { foreach ($properties as $property => $class) { $this->load($property, true, $class); } } $this->setLoaded(); } else { Logger::log(get_class($this) . ' already loaded', LOG_INFO); } }
/** * @param string $route * @return null|string */ public static function checkDefaultRoute($route) { $default = null; if (FALSE !== preg_match('/\\/$/', $route)) { $default = Config::getInstance()->get('home_action'); } elseif (false !== preg_match('/admin/', $route)) { $default = Config::getInstance()->get('admin_action') ?: 'admin-login'; } if (null !== $default) { return Router::getInstance()->execute(Router::getInstance()->getRoute($default)); } return null; }
/** * Método que inicializa el motor de plantillas */ private function setup() { $this->debug = Config::getInstance()->getDebugMode() ?: FALSE; $this->cache = Cache::getInstance(); $loader = new \Twig_Loader_Filesystem(Config::getInstance()->getTemplatePath()); $this->tpl = new \Twig_Environment($loader, array('cache' => Config::getInstance()->getCachePath() . DIRECTORY_SEPARATOR . 'twig', 'debug' => (bool) $this->debug, 'auto_reload' => TRUE)); }
/** * Función que copia un recurso directamente en el DocumentRoot * @param string $path * @param string $dest * @param bool|FALSE $force * * @return string * @throws ConfigException */ public static function resource($path, $dest, $force = false) { $debug = Config::getInstance()->getDebugMode(); $domains = Template::getDomains(true); $filename_path = self::extractPathname($path, $domains); GeneratorService::copyResources($dest, $force, $filename_path, $debug); return ''; }
/** * Method that saves all the configuration in the system * * @param array $data * @param array|null $extra * @return boolean */ public static function save(array $data, array $extra = null) { $data = self::saveConfigParams($data, $extra); $final_data = self::saveExtraParams($data); $saved = false; try { Cache::getInstance()->storeData(CONFIG_DIR . DIRECTORY_SEPARATOR . "config.json", $final_data, Cache::JSON, true); Config::getInstance()->loadConfigData(); $saved = true; } catch (ConfigException $e) { Logger::log($e->getMessage(), LOG_ERR); } return $saved; }
/** * Static wrapper for extracting params * @param string $key * @param mixed|null $defaultValue * @return mixed|null */ public static function getParam($key, $defaultValue = null) { $param = Config::getInstance()->get($key); return null !== $param ? $param : $defaultValue; }