/** * 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, []); }
/** * Method that extract all the properties of a class * @param string $class * @return array */ public static function getClassProperties($class) { $properties = []; Logger::log('Extracting annotations properties from class ' . $class); $selfReflector = new \ReflectionClass($class); if (false !== $selfReflector->getParentClass()) { $properties = self::getClassProperties($selfReflector->getParentClass()->getName()); } $properties = array_merge($properties, self::extractProperties($selfReflector)); return $properties; }
/** * 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; }
/** * Service to regenerate routes * @GET * @route /admin/routes/gen * @visible false * @return string HTML */ public function regenerateUrls() { $router = Router::getInstance(); try { $router->hydrateRouting(); $router->simpatize(); Security::getInstance()->setFlash("callback_message", _("Rutas generadas correctamente")); Security::getInstance()->setFlash("callback_route", $this->getRoute("admin-routes", true)); } catch (\Exception $e) { Logger::log($e->getMessage(), LOG_ERR); Security::getInstance()->setFlash("callback_message", _("Algo no ha salido bien, revisa los logs")); Security::getInstance()->setFlash("callback_route", $this->getRoute("admin-routes", true)); } return $this->redirect('admin-routes'); }
/** * 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'); } }
/** * Convert dto to array representation * @return array */ public function __toArray() { $dto = array(); try { $reflectionClass = new \ReflectionClass($this); $properties = $reflectionClass->getProperties(\ReflectionProperty::IS_PUBLIC); if (count($properties) > 0) { /** @var \ReflectionProperty $property */ foreach ($properties as $property) { $dto[$property->getName()] = $property->getValue($this); } } } catch (\Exception $e) { Logger::log(get_class($this) . ': ' . $e->getMessage(), LOG_ERR); } return $dto; }
/** * Servicio que guarda los usuarios de administración * @POST * @route /admin/setup * @visible false * @return string|void * @throws \HttpException */ public function setAdminUsers() { $admins = $this->srv->getAdmins(); $form = new AdminForm(); $form->build(); $form->hydrate(); if ($form->isValid()) { if (Security::save($form->getData())) { Logger::log('Configuration saved successful'); Security::getInstance()->setFlash("callback_message", _("Usuario agregado correctamente")); Security::getInstance()->setFlash("callback_route", $this->getRoute("admin"), true); } else { throw new ConfigException(_('Error al guardar los administradores, prueba a cambiar los permisos')); } } return $this->render('admin.html.twig', array('admins' => $admins, 'form' => $form, 'profiles' => Security::getProfiles())); }
/** * Método que extrae de la url los parámetros REST * * @param string $route * * @param string $pattern * * @return array */ public static function extractComponents($route, $pattern) { Logger::log('Extracting parts for the request to execute'); $url = parse_url($route); $_route = explode("/", $url['path']); $_pattern = explode("/", $pattern); $get = array(); if (!empty($_pattern)) { foreach ($_pattern as $index => $component) { $_get = array(); preg_match_all('/^\\{(.*)\\}$/i', $component, $_get); if (!empty($_get[1]) && isset($_route[$index])) { $get[array_pop($_get[1])] = $_route[$index]; } } } return $get; }
function pre($var, $die = FALSE) { $html = '<pre style="padding:10px;margin:0;display:block;background: #EEE; box-shadow: inset 0 0 3px 3px #DDD; color: #666; text-shadow: 1px 1px 1px #CCC;border-radius: 5px;">'; $html .= is_null($var) ? '<b>NULL</b>' : print_r($var, TRUE); $html .= '</pre>'; if (class_exists('\\PSFS\\Dispatcher')) { $html .= '<pre>[' . round(\PSFS\Dispatcher::getInstance()->getMem('MBytes'), 3) . 'Mb - ' . round(\PSFS\Dispatcher::getInstance()->getTs(), 3) . 's]</pre>'; } ob_start(); echo $html; ob_flush(); ob_end_clean(); if ($die) { if (class_exists('\\PSFS\\base\\Logger')) { \PSFS\base\Logger::log('Execution finished via pre', LOG_WARNING); } die; } }
/** * 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))); }
/** * @POST * @route /admin/module * @return string */ public function doGenerateModule() { $form = new ModuleForm(); $form->build(); $form->hydrate(); if ($form->isValid()) { $module = $form->getFieldValue("module"); $force = $form->getFieldValue("force"); $type = $form->getFieldValue("controllerType"); $is_module = $form->getFieldValue("is_module"); try { $module = preg_replace('/(\\\\|\\/)/', '/', $module); $module = preg_replace('/^\\//', '', $module); $this->gen->createStructureModule($module, $force, $type, (bool) $is_module); Security::getInstance()->setFlash("callback_message", str_replace("%s", $module, _("Módulo %s generado correctamente"))); Security::getInstance()->setFlash("callback_route", $this->getRoute("admin-module", true)); } catch (\Exception $e) { pre($e->getMessage(), true); Logger::getInstance()->infoLog($e->getMessage() . " [" . $e->getFile() . ":" . $e->getLine() . "]"); throw new ConfigException('Error al generar el módulo, prueba a cambiar los permisos', 403); } } return $this->render("modules.html.twig", array('properties' => $this->config->getPropelParams(), 'form' => $form)); }
/** * Stats initializer */ private function initiateStats() { Logger::log('Initialicing stats (mem + ts)'); if (null !== $_SERVER && array_key_exists('REQUEST_TIME_FLOAT', $_SERVER)) { $this->ts = (double) $_SERVER['REQUEST_TIME_FLOAT']; } else { $this->ts = $this->parser->getTs(); } $this->mem = memory_get_usage(); }
/** * 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); } }
/** * Static method to trace logs * @param string $msg * @param int $type * @param array $context */ public static function log($msg, $type = LOG_DEBUG, $context = []) { switch ($type) { case LOG_DEBUG: Logger::getInstance()->debugLog($msg, $context); break; case LOG_WARNING: Logger::getInstance()->warningLog($msg, $context); break; case LOG_CRIT: case LOG_ERR: Logger::getInstance()->errorLog($msg, $context); break; case LOG_INFO: Logger::getInstance()->infoLog($msg, $context); break; default: Logger::getInstance()->defaultLog($msg, $context); break; } }
/** * Servicio que actualiza * * @param boolean $closeSession * * @return Security */ public function updateSession($closeSession = FALSE) { Logger::log('Update session'); $_SESSION = $this->session; $_SESSION[self::USER_ID_TOKEN] = serialize($this->user); $_SESSION[self::ADMIN_ID_TOKEN] = serialize($this->admin); if ($closeSession) { Logger::log('Close session'); session_write_close(); } Logger::log('Session updated'); return $this; }
/** * Method that extract all the needed info for each method in each API * * @param string $namespace * @param \ReflectionMethod $method * @param \ReflectionClass $reflection * * @return array */ protected function extractMethodInfo($namespace, \ReflectionMethod $method, \ReflectionClass $reflection) { $methodInfo = NULL; $docComments = $method->getDocComment(); $shortName = $reflection->getShortName(); $modelNamespace = str_replace('Api', 'Models', $namespace); if (FALSE !== $docComments && preg_match('/\\@route\\ /i', $docComments)) { $visibility = $this->extractVisibility($docComments); $route = str_replace('{__API__}', $shortName, $this->extractRoute($docComments)); if ($visibility && preg_match('/^\\/api\\//i', $route)) { try { $methodInfo = ['url' => $route, 'method' => $this->extractMethod($docComments), 'description' => str_replace('{__API__}', $shortName, $this->extractDescription($docComments)), 'return' => $this->extractReturn($modelNamespace, $docComments)]; if (in_array($methodInfo['method'], ['POST', 'PUT'])) { $methodInfo['payload'] = $this->extractPayload($modelNamespace, $docComments); } } catch (\Exception $e) { jpre($e->getMessage()); Logger::getInstance()->errorLog($e->getMessage()); } } } return $methodInfo; }
/** * @return array */ private function getList() { $return = array(); $total = 0; $pages = 0; try { $this->paginate(); if (null !== $this->list) { $return = $this->list->toArray(); $total = $this->list->getNbResults(); $pages = $this->list->getLastPage(); } } catch (\Exception $e) { Logger::getInstance(get_class($this))->errorLog($e->getMessage()); } return array($return, $total, $pages); }
/** * @param string $source * @param string $file */ protected function extractCssResources($source, $file) { $source_file = $this->extractSourceFilename($source); $orig = realpath(dirname($file) . DIRECTORY_SEPARATOR . $source_file); $orig_part = preg_split('/(\\/|\\\\)public(\\/|\\\\)/i', $orig); try { if (count($source) > 1 && array_key_exists(1, $orig_part)) { $dest = $this->path . $orig_part[1]; Config::createDir(dirname($dest)); if (!file_exists($dest) || filemtime($orig) > filemtime($dest)) { if (@copy($orig, $dest) === FALSE) { throw new \RuntimeException('Can\' copy ' . $dest . ''); } Logger::log("{$orig} copiado a {$dest}", LOG_INFO); } } } catch (\Exception $e) { Logger::log($e->getMessage(), LOG_ERR); } }
/** * Method that remove all data in the document root path */ public static function clearDocumentRoot() { $rootDirs = array("css", "js", "media", "font"); foreach ($rootDirs as $dir) { if (file_exists(WEB_DIR . DIRECTORY_SEPARATOR . $dir)) { try { @shell_exec("rm -rf " . WEB_DIR . DIRECTORY_SEPARATOR . $dir); } catch (\Exception $e) { Logger::log($e->getMessage()); } } } }
/** * Método que guarda los datos del formulario en el modelo de datos asociado al formulario * @return bool * @throws FormException */ public function save() { if (null === $this->model) { throw new FormException("No se ha asociado ningún modelo al formulario"); } $this->model->fromArray(array($this->getData())); $save = false; try { $model = $this->getHydratedModel(); $model->save(); $save = true; Logger::getInstance()->infoLog(get_class($this->model) . " guardado con id " . $this->model->getPrimaryKey()); } catch (\Exception $e) { Logger::getInstance()->errorLog($e->getMessage()); throw new FormException($e->getMessage(), $e->getCode(), $e); } return $save; }
/** * @param $tplDir * @param string $domain * * @return mixed */ protected function generateTemplate($tplDir, $domain = '') { $templatesDir = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($tplDir), \RecursiveIteratorIterator::LEAVES_ONLY); foreach ($templatesDir as $file) { // force compilation if ($file->isFile()) { try { $this->tpl->loadTemplate(str_replace($tplDir . '/', '', $file)); } catch (\Exception $e) { Logger::log($e->getMessage(), LOG_ERR); throw $e; } } } return str_replace("%d", $domain, str_replace("%s", $tplDir, _("Generando plantillas en path '%s' para el dominio '%d'"))); }