/** * 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; }
/** * Método que guarda un text en un fichero * @param string $data * @param string $path * @param boolean $absolute * @throws ConfigException */ private function saveTextToFile($data, $path, $absolute = false) { $absolutePath = $absolute ? $path : CACHE_DIR . DIRECTORY_SEPARATOR . $path; $filename = basename($absolutePath); Config::createDir(str_replace($filename, "", $absolutePath)); if (false === file_put_contents($absolutePath, $data)) { throw new ConfigException(_('No se tienen los permisos suficientes para escribir en el fichero ') . $absolutePath); } }
/** * 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(); }
/** * Debug function to catch warnings as exceptions */ protected function bindWarningAsExceptions() { if ($this->config->getDebugMode()) { Logger::log('Added handlers for errors'); //Warning & Notice handler set_error_handler(function ($errno, $errstr, $errfile, $errline) { Logger::log($errstr, LOG_CRIT, ['file' => $errfile, 'line' => $errline]); throw new \Exception($errstr, 500); }); } }
/** * 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())); }
/** * Método que mete en las variables de las plantillas las cabeceras de debug * @param array $vars * * @return array */ public static function setDebugHeaders(array $vars) { if (Config::getParam('debug', true)) { Logger::log('Adding debug headers to render response'); $vars["__DEBUG__"]["includes"] = get_included_files(); $vars["__DEBUG__"]["trace"] = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS); header('X-PSFS-DEBUG-TS: ' . Dispatcher::getInstance()->getTs() . ' s'); header('X-PSFS-DEBUG-MEM: ' . Dispatcher::getInstance()->getMem('MBytes') . ' MBytes'); header('X-PSFS-DEBUG-FILES: ' . count(get_included_files()) . ' files opened'); } return $vars; }
/** * 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 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); } }
public function init() { parent::init(); $this->setDomain($this->domain)->setTemplatePath(Config::getInstance()->getTemplatePath()); }
/** * Método que crea el path del logger * @param Config $config * * @return string */ private function createLoggerPath(Config $config) { $logger = $this->setLoggerName($config); $path = LOG_DIR . DIRECTORY_SEPARATOR . $logger . DIRECTORY_SEPARATOR . date('Y') . DIRECTORY_SEPARATOR . date('m'); Config::createDir($path); return $path; }
public function testConfigFileFunctions() { $config = $this->getInstance(); // Original config data $original_data = $this->getBasicConfigUse(); Config::save($original_data, []); $this->assertEquals($original_data, $config->dumpConfig(), 'Missmatch configurations'); Config::save($original_data, ['label' => [uniqid()], 'value' => [microtime(true)]]); $this->assertNotEquals($original_data, $config->dumpConfig(), 'The same configuration file'); Config::save($original_data, []); }
/** * Método que extrae el recurso css de una línea de estilos css * @param $handle * @param string $filename_path * @throws ConfigException */ public static function extractCssLineResource($handle, $filename_path) { $line = fgets($handle); $urls = array(); if (preg_match_all('#url\\((.*?)\\)#', $line, $urls, PREG_SET_ORDER)) { foreach ($urls as $source) { $orig = self::calculateResourcePathname($filename_path, $source); $orig_part = explode("Public", $orig); $dest = WEB_DIR . $orig_part[1]; Config::createDir(dirname($dest)); if (@copy($orig, $dest) === false) { throw new ConfigException("Can't copy " . $orig . " to " . $dest); } } } }
/** * 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); } }
/** * @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)); }
/** * Método que procesa un recurso para su copia en el DocumentRoot * @param string $string * @param string $name * @param boolean $return * @param string $filename_path * * @return string */ private static function processAsset($string, $name, $return, $filename_path) { $file_path = $filename_path; if (file_exists($filename_path)) { list($base, $html_base, $file_path) = AssetsParser::calculateAssetPath($string, $name, $return, $filename_path); //Creamos el directorio si no existe Config::createDir($base . $html_base); //Si se ha modificado if (!file_exists($base . $file_path) || filemtime($base . $file_path) < filemtime($filename_path)) { if ($html_base == 'css') { self::processCssLines($filename_path); } self::putResourceContent($name, $filename_path, $base, $file_path); } } return $file_path; }
/** * @GET * @route /admin/translations * @return string */ public function defaultTranslations() { return $this->getTranslations(Config::getInstance()->get('default_language')); }
/** * 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; }
/** * Method that copy a resource * @param string $src * @param string $dst * @throws ConfigException */ public static function copyr($src, $dst) { $dir = opendir($src); Config::createDir($dst); while (false !== ($file = readdir($dir))) { if ($file != '.' && $file != '..') { if (is_dir($src . '/' . $file)) { self::copyr($src . '/' . $file, $dst . '/' . $file); } elseif (@copy($src . '/' . $file, $dst . '/' . $file) === false) { throw new ConfigException("Can't copy " . $src . " to " . $dst); } } } closedir($dir); }
/** * 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; }
/** * 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')); } }
if (!isset($console)) { $console = new Application(); } $console->register('psfs:create:root')->setDefinition(array(new InputArgument('path', InputArgument::OPTIONAL, 'Path en el que crear el Document Root')))->setDescription('Comando de creación del Document Root del projecto')->setCode(function (InputInterface $input, OutputInterface $output) { // Creates the html path $path = $input->getArgument('path'); if (empty($path)) { $path = WEB_DIR; } \PSFS\base\config\Config::createDir($path); $paths = array("js", "css", "img", "media", "font"); foreach ($paths as $htmlPath) { \PSFS\base\config\Config::createDir($path . DIRECTORY_SEPARATOR . $htmlPath); } // Generates the root needed files $files = ['_' => '_.php', 'browserconfig' => 'browserconfig.xml', 'crossdomain' => 'crossdomain.xml', 'humans' => 'humans.txt', 'robots' => 'robots.txt']; foreach ($files as $templates => $filename) { $text = \PSFS\base\Template::getInstance()->dump("generator/html/" . $templates . '.html.twig'); if (false === file_put_contents($path . DIRECTORY_SEPARATOR . $filename, $text)) { $output->writeln('Can\\t create the file ' . $filename); } else { $output->writeln($filename . ' created successfully'); } } //Export base locale translations if (!file_exists(BASE_DIR . DIRECTORY_SEPARATOR . 'locale')) { \PSFS\base\config\Config::createDir(BASE_DIR . DIRECTORY_SEPARATOR . 'locale'); \PSFS\Services\GeneratorService::copyr(SOURCE_DIR . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'locale', BASE_DIR . DIRECTORY_SEPARATOR . 'locale'); } $output->writeln("Document root generado en " . $path); });