/** * Método que genera un nuevo módulo * @GET * @route /admin/module * * @return string HTML * @throws \HttpException */ public function generateModule() { Logger::log("Arranque generador de módulos al solicitar " . $this->getRequest()->getRequestUri()); /* @var $form \PSFS\base\config\ConfigForm */ $form = new ModuleForm(); $form->build(); return $this->render("modules.html.twig", array('properties' => $this->config->getPropelParams(), 'form' => $form)); }
/** * 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'); } }
/** * Test all the functionality for the logger class */ public function testLogFunctions() { // Basic log Logger::log('Test normal log'); // Warning log Logger::log('Test warning log', LOG_WARNING); // Info log Logger::log('Test info log', LOG_INFO); // Error log Logger::log('Test error log', LOG_ERR); // Critical log Logger::log('Test critical log', LOG_CRIT); // Debug log Logger::log('Test debug logs', LOG_DEBUG); // Other logs Logger::log('Test other logs', LOG_CRON); }
/** * 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))); }
/** * @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'"))); }
/** * 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; }
/** * @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); } }
/** * Create new {__API__} * * @POST * @PAYLOAD {__API__} * @ROUTE /api/{__API__} * * @return \PSFS\base\dto\JsonResponse(data={__API__}) */ public function post() { $saved = FALSE; $status = 400; $model = NULL; try { $this->con->beginTransaction(); $this->hydrateFromRequest(); if ($this->model->save($this->con)) { $status = 200; $saved = TRUE; $model = $this->model->toArray(); } } catch (\Exception $e) { Logger::log($e->getMessage(), LOG_ERR); } return $this->json(new JsonResponse($model, $saved), $status); }
/** * 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); } }
/** * 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(); }
/** * 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()); } } } }