setStub($stub); $this->state = null; $this->setContainer((null===$container) ? \frdl\i::c() : $container); if(true===$initialize){ $Event = new \webfan\hps\Event('initialize:before'); $Event->setArgument('Shield', $this); $Event->setArgumentReference('container', $this->container); $this->getEmitter()->emit($Event->getName(), $Event); call_user_func_array([$this, 'initialize'], []); } } public function __destruct(){ // if($this->session_started()){ // $_SESSION[TerminalEmulator::SESSIONKEY]['cwd'] = getcwd(); // } } public static function getInstance($stub = null, \Psr\Container\ContainerInterface $container = null, $enableLoginPost = false){ if(null === self::$instance){ self::$instance = new self((null===$container) ? \frdl\i::c() : $container, $stub, false, $enableLoginPost); } return self::$instance; } public function getVersion($full = true){ $this->getV(); if(true===$full){ return $this->version; }else{ return $this->version['version']; } } public function getCacheBustKey(){ return sha1( date('Y').date('W').'.'.max(filemtime($this->getStub()->location), 1).$this->getVersion(false).$this->getStub()->location); } public function terminate(){ if( 'cli'!==strtolower(\PHP_SAPI) && 'web-cli'!==strtolower(\PHP_SAPI) ){ ignore_user_abort(true); if(session_status() === \PHP_SESSION_ACTIVE)session_write_close(); while(($ob_status = ob_get_status(false)) && $ob_status && is_array($ob_status) && 0 < count($ob_status) && isset($ob_status[0]) && isset($ob_status[0]['status']) && $ob_status[0]['status'] !== \PHP_OUTPUT_HANDLER_END && ob_get_level()){ ob_end_flush(); } // if (version_compare(PHP_VERSION, '7.1.15') >= 0) { // die('hi'); // } /* try{ if(function_exists('fastcgi_finish_request'))fastcgi_finish_request(); }catch(\Exception $e){ error_log($e->getMessage()); } */ } } public function __get($name){ if('config' === $name){ $this->config = (true ===$this->__configLoaded && is_object($this->config) && $this->config instanceof \webfan\hps\patch\ngScope) ? $this->config : $this->loadConfig()->config; return $this->config; }elseif('updateAvailable' === $name){ return !version_compare($this->getVersion(false), $this->v->latest, '>='); }elseif('emitter' === $name){ return $this->getEmitter(); } if(null!==$this->container && $this->getContainer()->has($name)){ return $this->container->get($name); } if(property_exists($this, $name)){ return $this->{$name}; } throw new \Exception('Undefined property `'.$name.'` of '.__CLASS__); } public function getEmitter(){ if(null === $this->_emitter){ $this->_emitter = $this->getContainer()->get('emitter'); $emitter = $this->_emitter; $container = $this->container; $this->_emitter->required(['loaded:version', 'Shield.initialized', 'initialize:before', 'loaded:config', 'loaded:config:caches'], function($states) use(&$emitter, &$container){ $Event = new \webfan\hps\Event('ready:for:checkForAutoSelfUpdate'); $Event->setArgument('event-states', $states); $Event->setArgumentReference('container', $container); $emitter->emit($Event->getName(), $Event); }, false); $this->registerEvents(); } return $this->_emitter; } public function getFinalStateMachine(){ return $this->getContainer()->get('webfan.app.fsm'); } public function getFsm(){ return $this->getFinalStateMachine(); } public function getContainer(){ if(!$this->container->has('emitter')){ $this->container->register(new ShieldServiceProvider($this)); } return $this->container; } protected function setContainer(\Psr\Container\ContainerInterface $container){ $this->container=$container; return $this; } public function getConfig(){ $this->config = (true ===$this->__configLoaded && is_object($this->config) && $this->config instanceof \webfan\hps\patch\ngScope) ? $this->config : $this->loadConfig()->config; $this->config['baseUrlInstaller'] = (isset($this->config['baseUrlInstaller'])) ? $this->config['baseUrlInstaller'] // : rtrim(\webfan\hps\patch\Fs::getPathUrl($this->getStub()->location), \DIRECTORY_SEPARATOR.'/ ').\DIRECTORY_SEPARATOR.basename($_SERVER['PHP_SELF']); : rtrim(\webfan\hps\patch\Fs::getPathUrl($_SERVER['PHP_SELF']), \DIRECTORY_SEPARATOR.'/ ').\DIRECTORY_SEPARATOR.basename($this->stub->location); return $this->config; } protected function setStub($stub){ $this->stub=$stub; return $this; } public function getStub(){ if(null === $this->stub){ $StubRunner = require __FILE__; $this->stub = $StubRunner->getStub(); } return $this->stub; } public function serialize() { $reflect = new \ReflectionObject($this); $props = $reflect->getProperties(\ReflectionProperty::IS_PUBLIC | \ReflectionProperty::IS_PROTECTED); $state = []; foreach ($props as $prop) { // print $prop->getName() . "\n"; if(!is_scalar($this->{$prop->getName()}) && !is_array($this->{$prop->getName()}) && (!is_object($this->{$prop->getName()}) || true !== $this->{$prop->getName()} instanceof \webfan\hps\patch\ngScope) ){ continue; } // $state[$prop->getName()] = serialize($this->{$prop->getName()}); $state[$prop->getName()] =(!is_object($this->{$prop->getName()}) || true !== $this->{$prop->getName()} instanceof \webfan\hps\patch\ngScope) ? $this->{$prop->getName()} : $this->{$prop->getName()}->export(); } return serialize($state); } public function unserialize($data) { $scopes = ['config']; foreach(unserialize($data) as $k => $v){ if(in_array($k, $scopes)){ $this->{$k} = new \webfan\hps\patch\ngScope($v); }else{ $this->{$k} = $v; } } // $this->stub = self::getInstance()->getStub(); } public function clearSession(){ unset($_SESSION[self::SESSIONKEY]['webfan.app.shield']); // unset($_SESSION[self::SESSIONKEY]['time']); } public function persist(){ // $_SESSION[self::SESSIONKEY]['state'] = serialize($this-> getContainer()->get('webfan.app.fsm')); // $_SESSION[self::SESSIONKEY]['state.user'] = serialize($this-> getContainer()->get('webfan.app.fsm.user')); // $_SESSION[self::SESSIONKEY]['webfan.app.shield'] = serialize( $this->getContainer()->get('webfan.app.shield') ); $_SESSION[self::SESSIONKEY]['webfan.app.shield'] = serialize( $this ); $_SESSION[self::SESSIONKEY]['time'] = time(); // print_r($_SESSION[self::SESSIONKEY]['state']); // print_r($_SESSION[self::SESSIONKEY]['state.user']); //webfan.app.shield } public function clearPeristant(){ unset($_SESSION[self::SESSIONKEY]['webfan.app.shield']); unset($_SESSION[self::SESSIONKEY]['time']); } public function getLockFile(Shield $AppShield = null){ if(null===$AppShield){ $AppShield = $this; } $lockfile = str_replace('.php', '.lock', $AppShield->stub->location); if(!file_exists($lockfile)){ @chmod(dirname($lockfile), 0755); file_put_contents($lockfile, ''); } return $lockfile; } public function updateSelf(){ ob_start(); $maxExecutionTime = intval(ini_get('max_execution_time')); set_time_limit(max($maxExecutionTime, 180)); $config = $this->getConfig(); if(empty($config['workspace']))$config['workspace']='frdl.webfan.de'; $client = new \PhpJsonRpc\Client('https://'.$config['workspace'].'/software-center/modules-api/rpc/0.0.2/', \PhpJsonRpc\Client::ERRMODE_EXCEPTION); $params = [ 'workspace' => $config['workspace'], ]; if(isset($config['stub']))$params['stub']=$config['stub']; $result = $client->call('frdl.apc.download', $params); if(!isset($result[1]) || !isset($result[1]['contents']) ){ return false; } ignore_user_abort(true); //'webfan.app.mutex.lock.stub' // $mutex = new \malkusch\lock\mutex\FlockMutex(fopen($this->getLockFile($this), "r")); $mutex = self::getInstance()->getContainer()->get('webfan.app.mutex.lock.stub'); $AppShield = $this; $method = __METHOD__; $success = $mutex->synchronized(function () use ( $AppShield, $result, $method) : bool { $maxExecutionTime = intval(ini_get('max_execution_time')); set_time_limit(max($maxExecutionTime, 180)); $tmpfname = tempnam($AppShield->getCacheDir(), 'frdl_stub'); $tmpfname_backup = tempnam($AppShield->getCacheDir(), 'frdl_stub_backup'); $AppShield->getStub()->lint(false); $oldLocation = $AppShield->getStub()->location; // $oldConfig = self::getInstance()->getStubConfig(); file_put_contents($tmpfname, base64_decode($result[1]['contents'])); if(!\frdl\Lint\Php::lintFileStatic($tmpfname, false)){ unlink($tmpfname); trigger_error('Php parsing error in installer stub found, update failed in '.$method, \E_USER_ERROR); throw new \Exception('Php parsing error in installer stub found, update failed in '.$method); return false; } $config = (is_object($AppShield->config) && $AppShield->config instanceof \webfan\hps\patch\ngScope) ? $AppShield->config : new \webfan\hps\patch\ngScope($AppShield->config); $oldStubConfig = $AppShield->getStubConfig(); try{ if(isset($config->wsdir) && is_dir($config->wsdir) && file_exists($config->wsdir.self::CONFIG_FILENAME) ){ $configFileConfig = require $config->wsdir.self::CONFIG_FILENAME; }else{ $configFileConfig = []; } }catch(\Exception $e){ $configFileConfig = []; } //unset($configFileConfig['hashed_password']); // unset($oldStubConfig['hashed_password']); $newConfig =array_merge($oldStubConfig, $configFileConfig); // if(isset($newConfig['hashed_password']))unset($newConfig['hashed_password']); if(!defined('\___BLOCK_WEBFAN_MIME_VM_RUNNING_STUB___')){ define('\___BLOCK_WEBFAN_MIME_VM_RUNNING_STUB___', true); } $maxExecutionTime = intval(ini_get('max_execution_time')); set_time_limit(max($maxExecutionTime, 180)); // $vm = \webfan\hps\Compile\MimeStub2::vm($tmpfname, strpos(file_get_contents($tmpfname), '__halt_compiler' )); require $tmpfname; $vm = $run($tmpfname, false); $vm->lint(false); // // $newStubConfig = $vm->_run_php_1($vm->get_file($vm->document, '$HOME/apc_config.php', 'stub apc_config.php')); $vm->get_file($vm->document, '$HOME/apc_config.php', 'stub apc_config.php') -> setBody(' return '.var_export(array_merge( $newConfig, [ 'hashed_password' => (isset($oldStubConfig['hashed_password'])) ? $oldStubConfig['hashed_password'] : $newConfig['hashed_password'], ]), true).'; ') ; /**/ // $AppShield->clearPeristant(); // \webfan\hps\patch\Fs::pruneDir($AppShield->getCacheDir('PSR4'), time() - max(filemtime($vm->location), $time), true, true); // usleep(100); $time = time(); // $vm->location = $AppShield->getStub()->location; //file_put_contents($oldLocation, file_get_contents($tmpfname)); file_put_contents($tmpfname_backup, file_get_contents($oldLocation) ); try{ // file_put_contents($oldLocation, file_get_contents($tmpfname)); $vm->location = $AppShield->getStub()->location; // $AppShield->setConfig($newConfig, true, true); }catch(\Exception $e){ file_put_contents($oldLocation, file_get_contents($tmpfname_backup)); print_r($e->getMessage()); return false; } call_user_func(\frdlweb\Thread\ShutdownTasks::mutex(), function($CacheDir, $tmpfname, $tmpfname_backup){ if(file_exists($tmpfname)){ unlink($tmpfname); } if(file_exists($tmpfname_backup)){ unlink($tmpfname_backup); } $maxExecutionTime = intval(ini_get('max_execution_time')); set_time_limit(max($maxExecutionTime, 180)); \webfan\hps\patch\Fs::pruneDir($CacheDir, 900, true, true); }, $AppShield->getCacheDir(), $tmpfname, $tmpfname_backup); return true; }); return $success; } public function setConfig($config, $save = false, $saveFile = false){ $this->config = (is_object($config) && $config instanceof \webfan\hps\patch\ngScope) ? $config : new \webfan\hps\patch\ngScope($config); // $this->config = $config; if(true===$save && null!==$this->getStub()){ $export = $this->config->export(); unset($export['imports']); // unset($export['wsdir']); $this->getStub()->get_file($this->stub->document, '$HOME/apc_config.php', 'stub apc_config.php') -> setBody(' return '.var_export($export, true).'; ') ; } if(true===$save && true===$saveFile && null!==$this->stub){ $AppShield = $this; // $mutex = new \malkusch\lock\mutex\FlockMutex(fopen($this->getLockFile($this), "r")); $mutex = self::getInstance()->getContainer()->get('webfan.app.mutex.lock.stub'); $mutex->synchronized(function () use ( $AppShield , $export ) { $AppShield->getStub()->location = $AppShield->getStub()->location; $configFile = rtrim($AppShield->config->wsdir, \DIRECTORY_SEPARATOR.' ').\DIRECTORY_SEPARATOR.self::CONFIG_FILENAME; if(file_exists( $configFile) ){ $e = var_export($export, true); $t = time(); $banner = <<config[$key] = $value; } public function loadConfig(){ /* isset($this->config['imports']['frdl.config.stub.php']) && isset($this->config['imports']['frdl.config.app.php']) && isset($this->config['imports']['frdl.config.install.php']) && isset($this->config['imports']['frdl.config.update.php']) && isset($this->config['imports']['frdl.index.php']) && isset($this->config['imports']['frdl.version.php']) && isset($this->config['imports']['frdl.feature-implementations.php']) && */ $this->__configLoaded =true; if(!is_array($this->config) || !count($this->config) ){ $this->setConfig($this->getStubConfig(), false, false); } $this->config = (is_object($this->config) && $this->config instanceof \webfan\hps\patch\ngScope) ? $this->config : new \webfan\hps\patch\ngScope($this->config); $this->getV(isset($_REQUEST['force']) && 'update-check' === $_REQUEST['force']); $_ENV['FRDL_HPS_CACHE_DIR'] = $this->getCacheDir(); $_ENV['FRDL_HPS_PSR4_CACHE_DIR'] = $this->getCacheDir('PSR4'); //$this->config = new \webfan\hps\patch\ngScope([]); //$_ENV['FRDL_HPS_PSR4_CACHE_LIMIT'] = (isset($_ENV['FRDL_HPS_PSR4_CACHE_LIMIT'])) ? intval($_ENV['FRDL_HPS_PSR4_CACHE_LIMIT']) : time() - intval($this->latest->time); /* $_ENV['FRDL_HPS_PSR4_CACHE_LIMIT'] = max(0, time() - max((((!isset($this->config['autoupdate']) || true === $this->config['autoupdate'] || 'true' === $this->config['autoupdate'])) ? intval($this->latest->time) : 0), filemtime($this->stub->location)) ); */ $_ENV['FRDL_HPS_PSR4_CACHE_LIMIT'] = time() - filemtime($this->stub->location); $this->config->baseUrl = (isset($this->config->baseUrl)) ? $this->config->baseUrl : \webfan\hps\patch\Fs::getPathUrl(); $this->config->baseUrlInstaller = (isset($this->config->baseUrlInstaller)) ? $this->config->baseUrlInstaller //: rtrim(\webfan\hps\patch\Fs::getPathUrl($_SERVER['PHP_SELF'], true), \DIRECTORY_SEPARATOR.'/ ').'/'.basename($this->stub->location); // : explode('?', \webfan\hps\patch\Fs::getPathUrl($_SERVER['PHP_SELF'], true).$_SERVER['REQUEST_URI'], 2)[0] : $this->config->baseUrl.basename($this->stub->location) ; if(isset($this->config->wsdir) && \DIRECTORY_SEPARATOR === substr($this->config->wsdir,0,1)){ $this->config->wsdir = \webfan\hps\patch\Fs::getRelativePath(getcwd(), $this->config->wsdir); } if(isset($this->config->wsdir) && is_dir($this->config->wsdir) && file_exists($this->config->wsdir.self::CONFIG_FILENAME) ){ $i = require $this->config->wsdir.self::CONFIG_FILENAME; $this->config->import($i); }else{ set_time_limit(120); $time = time(); //$finder = $this->container->get('finder'); $finder = new \Symfony\Component\Finder\Finder(); $finder->name('*'.self::CONFIG_FILENAME) ->ignoreUnreadableDirs() ->ignoreVCS(false) ; // if(!isset($this->config->wsdir) || !is_dir($this->config->wsdir)){ $sDir = \webfan\hps\patch\Fs::getRelativePath(getcwd(),dirname($this->stub->location)); // } $sDir_2 = \webfan\hps\patch\Fs::getRelativePath(getcwd(), dirname($_SERVER['DOCUMENT_ROOT'])); if(!($HOME = getenv('FRDL_HOME'))){ $HOME = \webfan\hps\patch\Fs::getRelativePath(getcwd(), \webfan\hps\patch\Fs::getRootDir($_SERVER['DOCUMENT_ROOT'])); } $finder->depth('< 5'); //foreach ($finder->in([$sDir, $sDir_2] )//->files() as $file) { foreach ($finder->in($HOME) as $file) { // $absoluteFilePath = $file->getRealPath(); // $fileNameWithExtension = $file->getRelativePathname(); //$file->getContents() $i = require $file->getRealPath(); $this->config->import($i); break; } } if(!isset($this->config->CACHE_ASSETS_HTTP)){ $this->config->CACHE_ASSETS_HTTP = true; } $Event = new \webfan\hps\Event('loaded:config'); $Event->setArgument('Shield', $this); $Event->setArgument('container', $this->getContainer()); $Event->setArgument('config', $this->config); $this->getEmitter()->emit($Event->getName(), $Event); return $this; } //getContainer() public function getStubConfig(){ if(null!==$this->stub){ $config = $this->stub->_run_php_1($this->stub->get_file($this->stub->document, '$HOME/apc_config.php', 'stub apc_config.php')); unset($config['imports']); return $config; }elseif(null!==self::getInstance($this->getStub())->getStub()){ $config = self::getInstance($this->getStub())-> getStub()->_run_php_1(self::getInstance($this->getStub()) ->getStub()->get_file(self::getInstance($this->getStub()) ->getStub()->document, '$HOME/apc_config.php', 'stub apc_config.php')); unset($config['imports']); return $config; }else{ throw new \Exception('No stub set in '.__METHOD__); } } public function getV($reload = false){ $Event = new \webfan\hps\Event('loaded:version'); $Event->setArgument('Shield', $this); $Event->setArgument('container', $this->getContainer()); if(true!==$reload && null!==$this->v && null!==$this->version){ $Event->setArgument('version', $this->version); $this->getEmitter()->emit($Event->getName(), $Event); return $this->version; } if(!is_dir($this->getCacheDir())){ mkdir($this->getCacheDir(), 0755, true); } $vFile =$this->getCacheDir() . 'v.json'; if(true===$reload || !file_exists($vFile) || filemtime($vFile) < time() - 60 * 10 || 0===filesize($vFile)){ $_url = 'https://'. ((isset($this->config['workspace'])) ? $this->config['workspace'] : 'frdl.webfan.de' ) .'/install/version.php'; $vc = file_get_contents($_url); if(!is_string($vc)){ throw new \Exception(sprintf('Cannot load version informations from %s', $_url)); } file_put_contents($vFile, $vc); } $this->v = json_decode(file_get_contents($vFile)); $this->v->versions=(array)$this->v->versions; // ksort($this->v->versions); $this->v->versions = new \webfan\hps\patch\ngScope($this->v->versions); $this->latest = $this->v->versions->{$this->v->latest}; //$this->config->latest=$this->latest; // if(isset($this->config['imports']) // && isset($this->config['imports']['frdl.version.php']) // ){ // $this->v_current = new \webfan\hps\patch\ngScope($this->config['imports']['frdl.version.php']); //} $this->version = $this->stub->_run_php_1($this->stub->get_file($this->stub->document, '$HOME/version_config.php', 'stub version_config.php')); $Event->setArgument('version', $this->version); $this->getEmitter()->emit($Event->getName(), $Event); return $this->v; } public function isAutoupdate(){ return !isset($this->config['autoupdate']) || (0 !== $this->config['autoupdate'] && false !== $this->config['autoupdate'] && 'false' !== $this->config['autoupdate']) ? true : false; } public function checkForAutoSelfUpdate(){ if($this->isAutoupdate() && (!file_exists('admin.lock') || filemtime('admin.lock')latest->time); $sk = 'already_refreshed_'.sha1(__FILE__. ' '.$latest_time); $stub_time = filemtime($this->stub->location); $AppShield = $this; if($this->session_started() && isset($_SESSION[$sk]) && intval($_SESSION[$sk])>=20){ $_SESSION[$sk]++; if($_SESSION[$sk]>25){ unset($_SESSION[$sk]); } } \frdl\webfan\App::God(false)->refreshPageIf(2, function() use($sk, $AppShield){ return $AppShield->session_started() && isset($_SESSION[$sk]) && 20 === intval($_SESSION[$sk]) && 'GET' === $_SERVER['REQUEST_METHOD'] ? false : true; }, function() use($sk, $AppShield){ $_SESSION[$sk]=21; // $AppShield->terminate(); die(); }, '

An cache/version update may take a little moment.

', [ ] ); \frdl\webfan\App::God(false)->refreshPageIf(10, function() use($sk, $AppShield){ return $AppShield->session_started() && isset($_SESSION[$sk]) && 0 === intval($_SESSION[$sk]) && 'GET' === $_SERVER['REQUEST_METHOD'] && true===$AppShield->updateAvailable ? false : true; }, function() use($sk, $AppShield){ $_SESSION[$sk]=20; $AppShield->terminate(); // call_user_func_array(\frdlweb\Thread\ShutdownTasks::mutex(), [function($AppShield){ $AppShield->updateSelf(); // }, $AppShield]); //$AppShield->terminate(); die(); }, '

An cache/version update may take a little moment.

', [ ] ); \frdl\webfan\App::God(false)->refreshPageIf(2, function() use($sk, $latest_time, $stub_time, $AppShield) { return ( // $stub_time < time() - $_ENV['FRDL_HPS_PSR4_CACHE_LIMIT'] // && ($stub_time<$latest_time) // && true===$AppShield->updateAvailable ) && ($AppShield->session_started() && (!isset($_SESSION[$sk]) || intval($_SESSION[$sk]) > 25) ) && 'GET' === $_SERVER['REQUEST_METHOD'] && !isset($_GET['web']) ? false : true ; }, function() use($sk, $AppShield) { $_SESSION[$sk]=0; // $AppShield->terminate(); die(); }, '

An cache/version update may take a little moment.

', [ ] ); }//if(!isset($this->config['autoupdate']) || true === $this->config['autoupdate']){ else{ unset($_ENV['FRDL_HPS_PSR4_CACHE_LIMIT']); } } public static function mxGetARandomString($laenge = 32, $string_ = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789') { $randstr = ''; mt_rand((double)microtime()*1000000,(double)microtime()*1000000+9999999); for ($i=1; $i <= $laenge; $i++) { $randstr.= substr($string_, mt_rand(0,strlen($string_)-1), 1); } return $randstr; } public function getCacheDir($name = ''){ $name = strtoupper($name); if(!isset($_ENV['FRDL_HPS_CACHE_DIR']))$_ENV['FRDL_HPS_CACHE_DIR']=getenv('FRDL_HPS_CACHE_DIR'); if(!isset($_ENV['FRDL_HPS_PSR4_CACHE_DIR']))$_ENV['FRDL_HPS_PSR4_CACHE_DIR']=getenv('FRDL_HPS_PSR4_CACHE_DIR'); $_ENV['FRDL_HPS_CACHE_DIR'] = ((!empty($_ENV['FRDL_HPS_CACHE_DIR'])) ? $_ENV['FRDL_HPS_CACHE_DIR'] : sys_get_temp_dir() . \DIRECTORY_SEPARATOR . get_current_user(). \DIRECTORY_SEPARATOR . 'cache' . \DIRECTORY_SEPARATOR ); $_ENV['FRDL_HPS_PSR4_CACHE_DIR'] = ((!empty($_ENV['FRDL_HPS_PSR4_CACHE_DIR'])) ? $_ENV['FRDL_HPS_PSR4_CACHE_DIR'] : $_ENV['FRDL_HPS_CACHE_DIR']. 'psr4'. \DIRECTORY_SEPARATOR ); $Event = new \webfan\hps\Event('loaded:config:caches'); $Event->setArgument('Shield', $this); $Event->setArgument('container', $this->getContainer()); $this->getEmitter()->emit($Event->getName(), $Event); return (empty($name)) ? $_ENV['FRDL_HPS_CACHE_DIR'] : $_ENV['FRDL_HPS_'.$name.'_CACHE_DIR']; } public function registerEvents(){ //Shield.initialized $this->getEmitter()->once('Shield.initialized',static function(string $eventName, \frdl\Flow\EventEmitter $emitter, \webfan\hps\Event $Event){ // if(!$Event->getArgument('Shield')->isInstalled()){ // return; // } if($Event->getArgument('Shield')->session_started() && !isset($_SESSION[TerminalEmulator::SESSIONKEY])){ $_SESSION[TerminalEmulator::SESSIONKEY]=[]; } $path = (isset($_REQUEST['path']) && $Event->getArgument('Shield')->isAdmin(null, false)) ? $_REQUEST['path'] : ( ( $Event->getArgument('Shield')->session_started() && isset($_SESSION[TerminalEmulator::SESSIONKEY]) && isset($_SESSION[TerminalEmulator::SESSIONKEY]['cwd']) && is_string($_SESSION[TerminalEmulator::SESSIONKEY]['cwd']) && !empty($_SESSION[TerminalEmulator::SESSIONKEY]['cwd']) ) ? $_SESSION[TerminalEmulator::SESSIONKEY]['cwd'] : ((isset($Event->getArgument('Shield')->getConfig()->wsdir) && is_dir($Event->getArgument('Shield')->getConfig()->wsdir)) ? rtrim($Event->getArgument('Shield')->getConfig()->wsdir, \DIRECTORY_SEPARATOR) // : \webfan\hps\patch\Fs::getRootDir(dirname($_SERVER['DOCUMENT_ROOT'])) // : \webfan\hps\patch\Fs::getRootDir($_SERVER['DOCUMENT_ROOT']) : getenv('HOME') ) ); // die($path); if(@is_dir($path) && (@is_writable($path) || @is_readable($path)) && ($path !== getcwd() || (!isset($_SESSION[TerminalEmulator::SESSIONKEY]['cwd']) || $_SESSION[TerminalEmulator::SESSIONKEY]['cwd'] !== $path )) ){ chdir($path); if($Event->getArgument('Shield')->session_started()){ $_SESSION[TerminalEmulator::SESSIONKEY]['cwd'] = getcwd(); } }else{ if($Event->getArgument('Shield')->session_started() && $_SESSION[TerminalEmulator::SESSIONKEY]['cwd'] === $path){ unset($_SESSION[TerminalEmulator::SESSIONKEY]['cwd']); } } }); $this->getEmitter()->once('project.autoload.force', static function(string $eventName, \frdl\Flow\EventEmitter $emitter, $projectDir){ $projectDir = rtrim($projectDir, \DIRECTORY_SEPARATOR); $file = $projectDir.\DIRECTORY_SEPARATOR.'vendor'.\DIRECTORY_SEPARATOR.'autoload.php'; if(file_exists($file)){ require $file; } }); $this->getEmitter()->once('project.autoload.force', static function(string $eventName, \frdl\Flow\EventEmitter $emitter, $projectDir){ $projectDir = rtrim($projectDir, \DIRECTORY_SEPARATOR); $f1 = $projectDir.\DIRECTORY_SEPARATOR.'compiled'. \DIRECTORY_SEPARATOR.'RawCompiledContainer.php'; $f2 = $projectDir.\DIRECTORY_SEPARATOR.'compiled'.\DIRECTORY_SEPARATOR.'RawCompiledContainer.backup.php'; \frdl\webfan\Autoloading\SourceLoader::top() ->class_mapping_add(\RawCompiledContainer::class,(file_exists($f1)) ? $f1 : $f2, $success) // -> autoload_register() // -> unregister([\frdl\webfan\Autoloading\SourceLoader::top(),'autoloadClassFromServer']) ; }); $this->getEmitter()->once('project.autoload.force', static function(string $eventName, \frdl\Flow\EventEmitter $emitter, $projectDir){ $projectDir = rtrim($projectDir, \DIRECTORY_SEPARATOR); $d = $projectDir.\DIRECTORY_SEPARATOR.'compiled'.\DIRECTORY_SEPARATOR.'~events'.\DIRECTORY_SEPARATOR; if(!is_dir($d)){ mkdir($d, 0755, true); } \Webfan\App\EventModule::setBaseDir($d); }); $this->getEmitter()->once('ready:for:checkForAutoSelfUpdate',static function(string $eventName, \frdl\Flow\EventEmitter $emitter, \webfan\hps\Event $Event){ $Event->getArgument('container')->get('webfan.app.shield')->checkForAutoSelfUpdate(); }); $this->getEmitter()->once('before.compile',static function(string $eventName, \frdl\Flow\EventEmitter $emitter, $eventData){ $eventData['container']->register(new \Webfan\App\AppBuilderServiceProvider($eventData['AppShield'])); }); $this->getEmitter()->once('before.rpc',static function(string $eventName, \frdl\Flow\EventEmitter $emitter, $eventData){ $eventData['container']->register(new \Webfan\App\Rpc\RpcServiceProvider()); }); $this->getEmitter()->once('login.isAdmin::POST',static function(){ \frdl\webfan\App::God(false)->refreshPageIf(1, function() { return false; }, function() { die(); }, '

Welcome!

You will be redirected...

', ['title' => 'Login...' ] ); }); /* $this->emitter->once('isAdmin::POST',static function(string $eventName, \frdl\Flow\EventEmitter $emitter, $eventData){ \frdl\webfan\App::God(false)->refreshPageIf(60, function() use($eventData){ $FloodProtection = $eventData[1]->getContainer()->get('floodprotection.login.admin'); return !$FloodProtection->check($_SERVER['REMOTE_ADDR']); }, function() { header("HTTP/1.1 429 Too Many Requests"); ob_end_flush(); die(); }, '

Too Many Login Requests!
Please try again later!

', [ ] ); }); */ $this->getEmitter()->once('isAdmin::POST::try',static function(string $eventName, \frdl\Flow\EventEmitter $emitter, \webfan\hps\Event $Event){ \frdl\webfan\App::God(false)->refreshPageIf(60, function() use($Event){ $FloodProtection = $Event->getArgument('Shield')->getContainer()->get('floodprotection.login.admin'); return !$FloodProtection->check($_SERVER['REMOTE_ADDR']); }, function() { header("HTTP/1.1 429 Too Many Requests"); ob_end_flush(); die(); }, '

Too Many Login Requests!
Please try again later!

', ['title'=>'Too Many Login Requests', ] ); }); $this->getEmitter()->once('login.failed',static function(string $eventName, \frdl\Flow\EventEmitter $emitter, $eventData/* ['as'=>$_POST['username'], 'REMOTE_ADDR'=>$_SEVER['REMOTE_ADDR'], 'FORWARDED_FOR'=> (isset($_SEVER['HTTP_X_FORWARDED_FOR'])) ? $_SEVER['HTTP_X_FORWARDED_FOR'] : false ]*/){ sleep(1); }); $this->getEmitter()->once('kernel.Shield.send_response',static function(string $eventName, \frdl\Flow\EventEmitter $emitter, \webfan\hps\Event $Event){ if($Event->getArgument('container')->get('webfan.app.shield')->session_started()){ call_user_func(function($sessionKey){ if(!isset($_SESSION[$sessionKey])){ $_SESSION[$sessionKey]=[]; } // if(isset($_SESSION[$sessionKey]) && isset($_SESSION[$sessionKey]['isAdmin']) && true === $_SESSION[$sessionKey]['isAdmin']){ // $_SESSION[$sessionKey]['lasthit.admin'] = time(); // } $_SESSION[$sessionKey]['lasthit'] = time(); }, self::SESSIONKEY); } }); $this->getEmitter()->on('kernel.Shield.send_response',static function(string $eventName, \frdl\Flow\EventEmitter $emitter, \webfan\hps\Event $Event){ $Event->getArgument('container')->get('webfan.app.shield')->clear_duplicate_cookies(); }); $this->getEmitter()->once('kernel.Shield.send_response',static function(string $eventName, \frdl\Flow\EventEmitter $emitter, \webfan\hps\Event $Event){ // if($Event->getArgument('container')->get('webfan.app.shield')->session_started()){ // session_write_close(); // } if($Event->getArgument('container')->get('webfan.app.shield')->session_started()){ if(!isset($_SESSION[TerminalEmulator::SESSIONKEY])){ $_SESSION[TerminalEmulator::SESSIONKEY]=[]; } $_SESSION[TerminalEmulator::SESSIONKEY]['cwd'] = getcwd(); } }); /* $this->getEmitter()->on('kernel.Shield.send_response',static function(string $eventName, \frdl\Flow\EventEmitter $emitter, \webfan\hps\Event $Event){ // !ob_get_length() && ob_start(); if( !headers_sent() ){ $size=ob_get_length(); header("Content-Length: $size"); header('Connection: close'); } }); $Event = new \webfan\hps\Event('session:started'); $Event->setArgument('SESSION_NAME', session_name()); $this->getEmitter()->emit($Event->getName(), $Event); */ $this->getEmitter()->once('session:started',static function(string $eventName, \frdl\Flow\EventEmitter $emitter, \webfan\hps\Event $Event){ $SESSIONKEY = $Event->getArgument('SESSIONKEY'); if(!isset($_SESSION[$SESSIONKEY])){ $_SESSION[$SESSIONKEY] = []; } if(!isset($_SESSION[$SESSIONKEY]['breaker'])){ $_SESSION[$SESSIONKEY]['breaker'] = []; } }); $this->getEmitter()->once('initialize:before',static function(string $eventName, \frdl\Flow\EventEmitter $emitter, \webfan\hps\Event $Event){ if(!in_array('ob_gzhandler', ob_list_handlers()))ob_start('ob_gzhandler'); $Event->getArgument('Shield')->ob_start([$Event->getArgument('Shield'), 'onBeforeResponse']); $Event->getArgument('Shield')->session_start(); $Event->getArgument('Shield')->loadConfig(); }); } public function onBeforeResponse(string $content = null){ if(!is_string($content)){ $content = ob_get_contents(); $size=ob_get_length(); }else{ $size= strlen($content); } if( !headers_sent() ){ header("Content-Length: $size"); header('Connection: close'); } return $content; } public function ob_start($fn = null){ // if(!headers_sent() // && !ob_get_level() // ){ return null !== $fn ? ob_start($fn) : !ob_get_length() && ob_start(); // } // return ob_get_level(); } protected function _session_started(){ if ( strtolower(substr(\php_sapi_name(), 0, strlen('cli'))) !== 'cli' ) { if ( version_compare(phpversion(), '5.4.0', '>=') ) { return session_status() === \PHP_SESSION_ACTIVE ? true : false; } else { return session_id() === '' ? false : true; } } return false; } public function session_started(){ if(true === $this->_session_started()){ $Event = new \webfan\hps\Event('session:started'); $Event->setArgument('SESSION_NAME', session_name()); $Event->setArgument('SESSIONKEY', self::SESSIONKEY); $this->getEmitter()->emit($Event->getName(), $Event); return true; }else{ return false; } } public function session_switch($name = "PHPSESSID") { $Event = new \webfan\hps\Event('session:start'); $Event->setArgument('SESSION_NAME', $name); $Event->setArgument('SESSIONKEY', self::SESSIONKEY); $this->getEmitter()->emit($Event->getName(), $Event); $this->session_set_cookie_params(); if ($this->session_started()) { // if a session is currently opened, close it session_write_close(); } session_name($name); $iS = false; if (isset($_COOKIE[$name])) { // if a specific session already exists, merge with $created_sessions self::$created_sessions[$name] = $_COOKIE[$name]; } if (isset(self::$created_sessions[$name])) { // if existing session, impersonate it try{ session_id(self::$created_sessions[$name]); $iS = @session_start() ? true : false; }catch(\Exception $e){ $iS = false; } } if(false === $iS) { // create new session session_start(); // $_SESSION = []; // empty content before duplicating session file // duplicate last session file with new id and current $_SESSION content // If this is the first created session, there is nothing to duplicate from and passing true as argument will take care of "creating" only one session file session_regenerate_id(empty(self::$created_sessions)); self::$created_sessions[$name] = session_id(); } if (ini_get('session.use_cookies')){ $p = session_get_cookie_params(); setcookie(session_name(),session_id(),time()+24 * 60 * 60, $p['path'], $p['domain'], $p['secure'], $p['httponly']); } } public function session_destroy(){ $_SESSION = []; // $this->session_set_cookie_params(); $_SESSION = []; if (ini_get('session.use_cookies')){ $p = session_get_cookie_params(); setcookie(session_name(), '', time() - 31536000, $p['path'], $p['domain'], $p['secure'], $p['httponly']); } $Event = new \webfan\hps\Event('session:destroy'); $Event->setArgument('SESSION_NAME', session_name()); $Event->setArgument('SESSIONKEY', self::SESSIONKEY); $this->getEmitter()->emit($Event->getName(), $Event); session_unset(); session_destroy(); } public function session_set_cookie_params(){ $p = parse_url($_SERVER['REQUEST_URI']); session_set_cookie_params(time() + 24 * 60 * 60, $p['path'], '.' . $_SERVER['HTTP_HOST'], 0, 1); } public function session_start(){ if(!$this->session_started()){ ini_set("session.auto_start" , '0'); // Auto-start session ini_set("session.gc_probability" , 10); // Garbage collection in % MUST be > 0 ini_set("session.serialize_handler", 'php_serialize'); // How to store data ini_set("session.use_cookies" , '1'); // Use cookie to store the session ID ini_set("session.gc_maxlifetime" , 24 * 60 * 60); // Sekunden Inactivity timeout for user sessions ini_set("url_rewriter.tags" , ''); // verhindern, dass SID an URL gehaengt wird ini_set("session.use_only_cookies", "1"); ini_set("session.cookie_samesite" , 'Strict'); session_cache_limiter('private, must-revalidate'); $Event = new \webfan\hps\Event('session:config'); $Event->setArgument('SESSION_NAME', self::SESSION_NAME); $Event->setArgument('SESSIONKEY', self::SESSIONKEY); $this->getEmitter()->emit($Event->getName(), $Event); $this->session_switch(self::SESSION_NAME); } return $this->session_started(); } public function clear_duplicate_cookies() { // If headers have already been sent, there's nothing we can do if (headers_sent()) { return; } $cookies = array(); foreach (\headers_list() as $header) { // Identify cookie headers if (strpos($header, 'Set-Cookie:') === 0) { $cookies[] = $header; } } // Removes all cookie headers, including duplicates \header_remove('Set-Cookie'); // Restore one copy of each cookie foreach(array_unique($cookies) as $cookie) { header($cookie, false); } } public function initialize(){ if(isset($this->initilaized) && true===$this->initilaized){ return $this; } $this->initilaized = true; if(null === self::$instance){ self::$instance = &$this; } if(\spl_object_id(self::$instance) !== \spl_object_id($this) ){ throw new \ErrorException('Only singletone instances can be initialized by '.__METHOD__); } //for composer... $userEnv = defined('\PHP_WINDOWS_VERSION_MAJOR') ? 'APPDATA' : 'HOME'; $userDir = getenv($userEnv); if(!$userDir){ putenv($userEnv.'='.\webfan\hps\patch\Fs::getRootDir($_SERVER['DOCUMENT_ROOT'])); } $Event = new \webfan\hps\Event('initialize:before'); $Event->setArgument('Shield', $this); $Event->setArgumentReference('container', $this->container); $this->getEmitter()->emit($Event->getName(), $Event); $installLoader = new \Finite\Loader\ArrayLoader([ 'class' => '\Webfan\App\Shield', 'graph' => 'install', 'property_path' => 'installStatus', 'states' => [ 'uninstalled' => ['type' => \Finite\State\StateInterface::TYPE_INITIAL], 'loading' => ['type' => \Finite\State\StateInterface::TYPE_NORMAL, 'properties' => [ 'wsdir' => (isset($this->config->wsdir)) ? $this->config->wsdir : false, ]], 'prepared' => ['type' => \Finite\State\StateInterface::TYPE_NORMAL, 'properties' => [ 'wsdir' => (isset($this->config->wsdir)) ? $this->config->wsdir : false, ]], 'installed' => ['type' => \Finite\State\StateInterface::TYPE_FINAL, 'properties' => [ 'wsdir' => (isset($this->config->wsdir)) ? $this->config->wsdir : false, ]], 'running' => ['type' => \Finite\State\StateInterface::TYPE_FINAL, 'properties' => [ 'wsdir' => (isset($this->config->wsdir)) ? $this->config->wsdir : false, ]], 'rpc' => ['type' => \Finite\State\StateInterface::TYPE_FINAL, 'properties' => [ 'wsdir' => (isset($this->config->wsdir)) ? $this->config->wsdir : false, ]], /* 'failed' => ['type' => \Finite\State\StateInterface::TYPE_FINAL], 'installing' => ['type' => \Finite\State\StateInterface::TYPE_NORMAL, 'properties' => [ 'wsdir' => (isset($this->config->wsdir)) ? $this->config->wsdir : false, ]], 'updating' => ['type' => \Finite\State\StateInterface::TYPE_NORMAL, 'properties' => [ 'wsdir' => (isset($this->config->wsdir)) ? $this->config->wsdir : false, ]], 'installing.admin' => ['type' => \Finite\State\StateInterface::TYPE_NORMAL], 'installing.paths' => ['type' => \Finite\State\StateInterface::TYPE_NORMAL], 'installing.finish' => ['type' => \Finite\State\StateInterface::TYPE_NORMAL], */ ], 'transitions' => [ 'load' => ['from' => ['uninstalled'//, 'installing.finish' ], 'to' => 'loading', // 'guard' => [$this->container->get('webfan.app.shield'), 'isLoading'], 'guard' => [$this, 'isLoading'], 'properties' => [ 'wsdir' => (isset($this->config->wsdir)) ? $this->config->wsdir : false, ], 'configure_properties' => static function(\Symfony\Component\OptionsResolver\OptionsResolver $optionsResolver) { $optionsResolver->setRequired('wsdir'); }], 'run' => ['from' => ['uninstalled', 'loading', 'prepared'], // 'to' => 'installed', 'guard' => [$this->container->get('webfan.app.shield'), 'isInstalled'], 'to' => 'installed', 'guard' => [$this, 'isInstalled'], 'properties' => [ 'wsdir' => (isset($this->config->wsdir)) ? $this->config->wsdir : false, ], 'configure_properties' => static function(\Symfony\Component\OptionsResolver\OptionsResolver $optionsResolver) { $optionsResolver->setRequired('wsdir'); }], 'prepare' => ['from' => ['uninstalled', 'loading'], // 'to' => 'prepared', 'guard' => [$this->container->get('webfan.app.shield'), 'isPrepared'], 'to' => 'prepared', 'guard' => [$this, 'isPrepared'], 'properties' => [ 'wsdir' => (isset($this->config->wsdir)) ? $this->config->wsdir : false, ], 'configure_properties' => static function(\Symfony\Component\OptionsResolver\OptionsResolver $optionsResolver) { $optionsResolver->setRequired('wsdir'); }], ], 'callbacks' => [ 'after' => [ [ 'to' => ['run'], 'do' => static function(\Finite\StatefulInterface $AppShield, \Finite\Event\TransitionEvent $e) { // $sm = $AppShield->getContainer()->get('webfan.app.fsm'); chdir($AppShield->config->wsdir); }, ], ] ], ]); $stateMachine = $this->container->get('webfan.app.fsm'); $installLoader->load($stateMachine); //$stateMachine->setObject( new self($this->container, $this->stub, false)); //$stateMachine->setObject( $this->container->get('webfan.app.shield')); $stateMachine->setObject( $this); $stateMachine->initialize(); //return $this; $userLoader = new \Finite\Loader\ArrayLoader([ 'class' => '\Webfan\App\Shield', 'graph' => 'user', 'property_path' => 'userStatus', 'states' => [ 'guest' => ['type' => \Finite\State\StateInterface::TYPE_INITIAL], 'admin' => ['type' => \Finite\State\StateInterface::TYPE_FINAL], ], 'transitions' => [ // 'login' => ['from' => ['guest'], 'to' => 'admin', 'guard' => [$this->container->get('webfan.app.shield'), '_isAdmin']], 'login' => ['from' => ['guest'], 'to' => 'admin', 'guard' => [$this, '_isAdmin']], 'logout' => ['from' => ['guest'], 'to' => 'guest'], ], 'callbacks' => [ 'after' => [ [ 'to' => ['logout'], 'do' => static function(\Finite\StatefulInterface $AppShield, \Finite\Event\TransitionEvent $e) { // echo 'Applying transition '.$e->getTransition()->getName(), "\n"; // if(isset($_SESSION[self::SESSIONKEY]['isAdmin'])){ $_SESSION[self::SESSIONKEY]['isAdmin'] = false; // } $_SESSION[self::SESSIONKEY]['user'] = [ 'sec_fingerprint' => $AppShield->fingerprint(), ]; // $AppShield->persist(); }, ] ] ], ]); $stateMachineUser = $this->container->get('webfan.app.fsm.user'); $userLoader->load($stateMachineUser); //$stateMachineUser->setObject( new self($this->container, $this->stub, false)); $stateMachineUser->setObject($this->container->get('webfan.app.shield.user') ); $stateMachineUser->initialize(); if($this->isAdmin($stateMachineUser, 'POST'===$_SERVER['REQUEST_METHOD'] && isset($_POST['op_login']) && self::$loginAttempts<=0 && true === self::$enableLoginPost)){ $stateMachineUser->apply('login'); }else{ $stateMachineUser->apply('logout'); } if(true===$this->isInstalled($stateMachine)){ $stateMachine ->apply('run', [ 'wsdir' => (isset($this->config->wsdir)) ? $this->config->wsdir : false, ]); }elseif(true===$this->isPrepared($stateMachine)){ $stateMachine ->apply('prepare', [ 'wsdir' => (isset($this->config->wsdir)) ? $this->config->wsdir : false, ]); }elseif($this->isLoading($stateMachine)){ $stateMachine->apply('load', [ 'wsdir' => (isset($this->config->wsdir)) ? $this->config->wsdir : getenv('HOME').\DIRECTORY_SEPARATOR.'.frdl'.\DIRECTORY_SEPARATOR, ]); }else{ // $stateMachine->apply('uninstalled'); } $Event = new \webfan\hps\Event('Shield.initialized'); $Event->setArgument('Shield', $this); $this->getEmitter()->emit($Event->getName(), $Event); return $this; } public function _isAdmin(\Finite\StateMachine\StateMachine $stateMachine = null){ if(null === $stateMachine){ $stateMachine = $this->container->get('webfan.app.fsm'); } return call_user_func_array([$this, 'isAdmin'], [$stateMachine, 'POST'===$_SERVER['REQUEST_METHOD'] && isset($_POST['op_login']) && self::$loginAttempts<=0, (isset($_POST['username'])) ? $_POST['username'] : null, (isset($_POST['password'])) ? $_POST['password'] : null ]); } public function isAdmin(\Finite\StateMachine\StateMachine $stateMachine = null, $login = null, $username = null, $password = null, $lockUri = null){ $this->initialize(); if(null === $username){ $username = (isset($_POST['username']) && !empty($_POST['username'])) ? $_POST['username'] : false; } if(false === $username || empty($username)){ unset($username); } if(null === $password){ $password = (isset($_POST['password']) && !empty($_POST['password'])) ? $_POST['password'] : false; } if(false === $password || empty($password)){ unset($password); } if(null === $stateMachine){ $stateMachine = $this->container->get('webfan.app.fsm'); } if(!is_bool($login)){ $login = (self::$loginAttempts <=1 && 'POST'===$_SERVER['REQUEST_METHOD']) ? true : false; } // if(!$this->session_started()){ // session_start(); // } $StubConfig = $this->getStubConfig(); // if(true === $login && 'POST'===$_SERVER['REQUEST_METHOD'] && isset($_POST['op_login']) ){ if( true === self::$enableLoginPost && true === $login && isset($username) && is_string($username) && isset($password) && is_string($password) ){ //todo bruteforce protection self::$loginAttempts++; /* $this->emitter->emit('isAdmin::POST', [$_POST, $this]); */ $Event = new \webfan\hps\Event('isAdmin::POST::try'); $Event->setArgument('Shield', $this); $this->getEmitter()->emit($Event->getName(), $Event); $admins = []; if(isset($this->config->ADMIN_EMAIL) && !empty($this->config->ADMIN_EMAIL) && isset($this->config->ADMIN_EMAIL_CONFIRMED) && true === $this->config->ADMIN_EMAIL_CONFIRMED ){ $admins[]=$this->config->ADMIN_EMAIL; }elseif(isset($this->config->ADMIN_EMAIL) && !empty($this->config->ADMIN_EMAIL) && isset($this->config->ADMIN_EMAIL_CONFIRMED) && true !== $this->config->ADMIN_EMAIL_CONFIRMED ){ $admins[]=$this->config->ADMIN_EMAIL; // $admins[]='admin'; // $admins[]='root'; $admins[]= get_current_user(); }else{ $admins[]= get_current_user(); // $admins[]='admin'; // $admins[]='root'; } if( isset($username) && in_array($username, $admins) && isset($password) && true === $this->container->get('csrf-token-service')->validateRequest($lockUri) && ( (isset($this->config['hashed_password']) && true===password_verify($password, $this->config['hashed_password']) ) || (isset($StubConfig['hashed_password']) && true===password_verify($password, $StubConfig['hashed_password']) ) // || true===password_verify($_POST['password'], $this->config['imports']['frdl.config.stub.php']['hashed_password']) ) ){ $_SESSION[self::SESSIONKEY]['isAdmin'] = true; $_SESSION[self::SESSIONKEY]['user'] = [ 'username' => $username, 'email' => $this->config->ADMIN_EMAIL, 'email_confirmed_status' => $this->config->ADMIN_EMAIL_CONFIRMED, 'sec_fingerprint' => $this->fingerprint(), ]; $this->getEmitter()->emit('login.isAdmin::POST', []); }else{ $this->getEmitter()->emit('login.failed', ['as'=>$username, 'REMOTE_ADDR'=>$_SERVER['REMOTE_ADDR'], 'FORWARDED_FOR'=> (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : false ]); } } return $this->_logedInSession(); } protected function _logedInSession(){ $check1 = (isset($_SESSION[self::SESSIONKEY]['isAdmin']) && true===$_SESSION[self::SESSIONKEY]['isAdmin']) ?true:false; $check2 = (isset($_SESSION[self::SESSIONKEY]['user']) && isset($_SESSION[self::SESSIONKEY]['user']['sec_fingerprint']) && $_SESSION[self::SESSIONKEY]['user']['sec_fingerprint'] === $this->fingerprint() ) ?true:false; $valid = true===$check1 && true === $check2 ? true : false; if(true !== $valid){ // unset( $_SESSION[self::SESSIONKEY]['isAdmin']); // // unset($_SESSION[self::SESSIONKEY]['user']); // if(isset($_SESSION[self::SESSIONKEY]['user'])){ // unset($_SESSION[self::SESSIONKEY]['user']); // } // if(isset($_SESSION[self::SESSIONKEY]['isAdmin'])){ // unset($_SESSION[self::SESSIONKEY]['isAdmin']); //// } // unset($_SESSION[self::SESSIONKEY]); if(isset($_SESSION[self::SESSIONKEY]['isAdmin'])){ $_SESSION[self::SESSIONKEY]['isAdmin'] = false; } if(isset($_SESSION[self::SESSIONKEY]['user'])){ $_SESSION[self::SESSIONKEY]['user'] = [ 'sec_fingerprint' => $this->fingerprint(), ]; } } /* if(isset($this->config->ADMIN_EMAIL) && !empty($this->config->ADMIN_EMAIL) && isset($this->config->ADMIN_EMAIL_CONFIRMED) && true === $this->config->ADMIN_EMAIL_CONFIRMED && ( !isset($this->config->ADMIN_BROWSER_IP) || ( $this->config->ADMIN_BROWSER_IP !== $_SERVER['REMOTE_ADDR'] && $this->config->ADMIN_BROWSER_IP !== $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) ){ if(!isset($this->config->ADMIN_BROWSER_IP_SIGNSECRET) || (!isset($_SESSION[self::SESSIONKEY]['last_mail_sended:admin-remote-client-ip']) || intval($_SESSION[self::SESSIONKEY]['last_mail_sended:admin-remote-client-ip']) < time() - 12 * 60 * 60) ){ $this->pc('install.config.set', ['ADMIN_BROWSER_IP_SIGNSECRET'=>$this->getContainer()->get('.rand.str')]); // $this->loadConfig(); \frdl\webfan\App::God(false)->refreshPageIf(2, function() { return true; }, function() { die(); }, '

Configuration...

', [ ] ); exit; } $k = $this->config->ADMIN_BROWSER_IP_SIGNSECRET; $k.=(isset($_SERVER['HTTP_X_FORWARDED_FOR']))?$_SERVER['HTTP_X_FORWARDED_FOR']:$_SERVER['REMOTE_ADDR']; $urlSigner = new MD5UrlSigner($k); if(isset($_GET['admin-remote-client-ip'])){ $url = Url::createFromServer($_SERVER); $url = ''.$url; $url = (string)$url; $v = $urlSigner->validate($url); if(true===$v){ $this->pc('install.config.set', ['ADMIN_BROWSER_IP'=>(isset($_SERVER['HTTP_X_FORWARDED_FOR']))?$_SERVER['HTTP_X_FORWARDED_FOR']:$_SERVER['REMOTE_ADDR']]); \frdl\webfan\App::God(false)->refreshPageIf(2, function() { return true; }, function() { die(); }, '

You where authorized and will be redirected...

', [ ] ); } }elseif(!isset($_SESSION[self::SESSIONKEY]['last_mail_sended:admin-remote-client-ip']) || intval($_SESSION[self::SESSIONKEY]['last_mail_sended:admin-remote-client-ip']) < time() - 12 * 60 * 60){ $url = lHttp::createFromString($this->config->baseUrlInstaller); // $query = Query::extract($url->getQuery()); // $query['login-helper'] = 'admin-remote-client-ip'; // $url = $url->withQuery($this->buildQueryStringFromArray($query)); $url = ''.$url.'?login-helper=admin-remote-client-ip'; $url = (string)$url; $expirationDate = (new \DateTime)->modify('1 days'); $link = $urlSigner->sign($url, $expirationDate); $footer = 'Frdlweb Webfan PHP-Installer@'.((isset($_SERVER['SERVER_NAME']))?$_SERVER['SERVER_NAME']:$_SERVER['HTTP_HOST']); $message = " Please visit the following link to authorize an admin-session: $link $footer "; $_SESSION[self::SESSIONKEY]['last_mail_sended:admin-remote-client-ip']=time(); mail($this->config->ADMIN_EMAIL, "Confirm Admin-Access Confirmation", $message); \frdl\webfan\App::God(false)->refreshPageIf(2, function() { return false; }, function() { die(); }, '

Please check you mailbox and visit the authorize-link in the confirmation-email to authorize an admin-session!

', [ ] ); } } */ return $valid; } protected function fingerprint(){ $xIp = (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : '*ZERO*'; $Ip = (isset($_SERVER['REMOTE_ADDR'])) ? $_SERVER['REMOTE_ADDR'] : '*ZERO*'; $userAgent = (isset($_SERVER['HTTP_USER_AGENT'])) ? $_SERVER['HTTP_USER_AGENT'] : '*ZERO*'; return sha1($userAgent.$xIp.$Ip); } public function isInstalled(\Finite\StateMachine\StateMachine $stateMachine = null){ if(null === $stateMachine){ $stateMachine = $this->container->get('webfan.app.fsm'); } if(!isset($this->config->COMPOSER_PATH))return false; if(!isset($this->config->NODE_PATH))return false; if(!isset($this->config->NPM_PATH))return false; if(!isset($this->config->FRDLJS_PATH))return false; //if(!isset($this->config->wsdir) || !is_dir($this->config->wsdir) )return false; if(!isset($this->config->wsdir) )return false; if(!file_exists( rtrim($this->config->wsdir, \DIRECTORY_SEPARATOR.' ').\DIRECTORY_SEPARATOR.self::WORKSPACES_FILENAME) )return false; if(!file_exists( rtrim($this->config->wsdir, \DIRECTORY_SEPARATOR.' ').\DIRECTORY_SEPARATOR.self::CONFIG_FILENAME) )return false; if(!file_exists( rtrim($this->config->wsdir, \DIRECTORY_SEPARATOR.' ').\DIRECTORY_SEPARATOR.self::VERSION_FILENAME) )return false; if($this->session_started()){ $isBashfile = false; if(!isset($_SESSION[$SESSIONKEY]['breaker']['BASH_FILENAME'])){ $_SESSION[$SESSIONKEY]['breaker']['BASH_FILENAME'] = [ 'time' => 0, 'succes' => file_exists( rtrim($this->config->wsdir, \DIRECTORY_SEPARATOR.' ').\DIRECTORY_SEPARATOR.self::BASH_FILENAME) ]; } elseif(isset($_SESSION[$SESSIONKEY]['breaker']['BASH_FILENAME']['succes']) && true===$_SESSION[$SESSIONKEY]['breaker']['BASH_FILENAME']['succes'] ) { $isBashfile = file_exists( rtrim($this->config->wsdir, \DIRECTORY_SEPARATOR.' ').\DIRECTORY_SEPARATOR.self::BASH_FILENAME); } if(true!== $isBashfile && true !== $_SESSION[$SESSIONKEY]['breaker']['BASH_FILENAME']['succes'] && (0===$_SESSION[$SESSIONKEY]['breaker']['BASH_FILENAME']['time'] || $_SESSION[$SESSIONKEY]['breaker']['BASH_FILENAME']['time'] < time() - 60 ) && true===$this->_isAdmin($this->container->get('webfan.app.fsm')) ){ $_SESSION[$SESSIONKEY]['breaker']['BASH_FILENAME']['time'] = time(); $isBashfile = $this->installBashFile( rtrim($this->config->wsdir, \DIRECTORY_SEPARATOR.' ').\DIRECTORY_SEPARATOR.self::BASH_FILENAME ); $_SESSION[$SESSIONKEY]['breaker']['BASH_FILENAME']['succes'] = $isBashfile; } if(true!== $isBashfile)return false; } if(!file_exists( rtrim($this->config->wsdir, \DIRECTORY_SEPARATOR.' ').\DIRECTORY_SEPARATOR.self::BASH_FILENAME) )return false; return true; } protected function installBashFile(string $bashfile = null):bool{ if(null===$bashfile){ $bashfile= rtrim($this->config->wsdir, \DIRECTORY_SEPARATOR.' ').\DIRECTORY_SEPARATOR.self::BASH_FILENAME; }elseif($bashfile !== rtrim($this->config->wsdir, \DIRECTORY_SEPARATOR.' ').\DIRECTORY_SEPARATOR.self::BASH_FILENAME){ throw new \Exception('BASH file SHOULD be installed into this installers workspace directory in '.__METHOD__); return false; } if (file_exists($bashfile)) { return true; } if(dirname($bashfile) === $_SERVER['DOCUMENT_ROOT']){ throw new \Exception('BASH file MUST NOT be public in '.__METHOD__); return false; } if(!is_dir(dirname($bashfile))){ mkdir(dirname($bashfile), 0755, true); } chmod(dirname($bashfile), 0755); if (!file_exists($bashfile)) { $p = dirname($bashfile); $bashrc = <<container->get('webfan.app.fsm'); } if(!isset($this->config->COMPOSER_PATH))return false; if(!isset($this->config->NODE_PATH))return false; if(!isset($this->config->NPM_PATH))return false; if(!isset($this->config->FRDLJS_PATH))return false; // if(!isset($this->config->wsdir) || !is_dir($this->config->wsdir) )return false; if(!isset($this->config->wsdir) )return false; return true; } public function isLoading(\Finite\StateMachine\StateMachine $stateMachine = null){ if(null === $stateMachine){ $stateMachine = $this->container->get('webfan.app.fsm'); } return isset($this->config->wsdir) && is_dir($this->config->wsdir); } public function index($uri = null){ $this->uri = (is_string($uri)) ? $uri : $_SERVER['REQUEST_URI']; // if (!headers_sent()) { // header('Connection: close'); // } $this->initialize(); $Event = new \webfan\hps\Event('kernel.Shield.send_response'); $Event->setArgument('Shield', $this); $Event->setArgument('container', $this->getContainer()); $this->getEmitter()->emit($Event->getName(), $Event); switch($this->uri){ case '/proxy/' : $this->proxy(); break; case '/dashboard/' : $this->dashboard(); break; case '/rpc/' : $this->rpc(); break; case '/' : case '/login/' : case '/index.php' : default : if('/login/'===$this->uri){ self::$enableLoginPost = true; // $success = $this->initialize()->isAdmin($this->container->get('webfan.app.fsm'), true, $_POST['username'], $_POST['password'], '/login/'); $success = $this->isAdmin($this->getContainer()->get('webfan.app.fsm'), true, $_POST['username'], $_POST['password'], '/login/'); if(true===$success){ die(); }else{ die('Login failed'); } }else{ self::$enableLoginPost = false; } $Template = new IndexShield($this); $Template($this->config); break; } } protected function proxy(){ if(!$this->initialize()->isAdmin($this->getContainer()->get('webfan.app.fsm'), false)){ die('You are not logged in as root!'); exit; } // $TestProxy = new \Webfan\App\TestProxy('blue', '/testprojekt/'); // $TestProxy->handle(); } public function rpc(){ $this->getEmitter()->emit('before.rpc', ['container'=>$this->getContainer()]); // header_remove(); header('Content-Type: application/json'); $this->stop( $this->getContainer()->get('webfan.app.rpc.server')->run(file_get_contents('php://input')) ); } public function pc($method, $params){ $this->getEmitter()->emit('before.rpc', ['container'=>$this->getContainer()]); $client = $this->getContainer()->get('json-rpc.encoder'); $client->query($this->_pci++, $method, $params); $message = $client->encode(); $result = json_decode($this->getContainer()->get('webfan.app.rpc.server')->run($message)); return $result->result; // $client->query(1, 'add', array(1, 2)); // $message = $client->encode(); // message: {"jsonrpc":"2.0","method":"add","params":[1,2],"id":1} } public function stop($r = null){ if('cli' === strtolower(substr(\PHP_SAPI, 0, strlen('cli')))){ return (!is_int($r)) ? exit : exit($r); }else{ /* $Event = new \webfan\hps\Event('kernel.Shield.send_response'); $Event->setArgument('Shield', $this); $Event->setArgument('container', $this->container); $Event->setArgument('content', $r); $this->getEmitter()->emit($Event->getName(), $Event); */ return (null === $r) ? die() : die($r); } } public function getFiniteState() { return $this->state; } public function setFiniteState($state) { $this->state = $state; } public function setInstallStatus($installStatus) { $this->installStatus = $installStatus; } public function getInstallStatus() { return $this->installStatus; } public function setUpdateStatus($updateStatus) { $this->updateStatus = $updateStatus; } public function getUpdateStatus() { return $this->updateStatus; } public function setAppStatus($appStatus) { $this->appStatus = $appStatus; } public function getAppStatus() { return $this->appStatus; } public function setUserStatus($userStatus) { $this->userStatus = $userStatus; } public function getUserStatus() { return $this->userStatus; } public function setSetupStatus($setupStatus) { $this->setupStatus = $setupStatus; } public function getSetupStatus() { return $this->setupStatus; } public function setJobStatus($jobStatus) { $this->jobStatus = $jobStatus; } public function getJobStatus() { return $this->jobStatus; } } __halt_compiler();----SIGNATURE:----TLP8y3jjXs5+SV8h/kqei7EDo//sT3X5Skm2SBrLyNp2FKrEOxIRD+6zi69HD2gbf0jdq6qrcGjM0C8IHOxSgV/wN0Iobv5R1KgowdDYfCqvnl8fIrIenHt+ZldizZPQvodiuwIXs5PTtveT26qi/5F77T6HTyM7x8W5P5QpNFtJeKa8AF1wbPJrs434DlNxigrsJi1Q3AOG0KvFJXOYlDwqhmpWzWUmZPv/rm4Rfs6Zwdm7Z8hJS6bYFN6RlvbaEkBlA1/mdPiSGboc5iaMHdm35atNpA/ytHScn0PNpeyETcmT9ojgxqlqScG6MYgyL99xwOtCYpck7qlOC28VHxZb4lPue6mjtSabnI9g1tYTVcdRQ+E4Zh5k9J14U3hoqbSfumuzJHq11E+f/stvDRjPHVmHpYpRtm/p1Nf+QGrU/QboWnSvEbYe/v9pNiPaPaWfsMjd1XkK7FTHjvcgEI3GqT+lK4c74zBeMYoslGzKxOlFhW68K3yk7lJKBygy2+hdKXRnuDCiepL+F44RZQOR8f+S17sXfszxP/pK1b5cFftIvqRAsUwYC6vhO/aYWiVNfoRLEoS8FXgEmHcHRD2P/U3FKkNZ9QXUr9E0FOBJViWIvJMjtng1ALFLHnrl5b9lsW5R0hD5OwBdpLWzNfeEhOdMYW6OcgcN2UpSj4A=----ATTACHMENT:----NzQ3NzAzMjI0MTQ3MjA3MSAyNTEzNDk5OTE3NTYzMTg1IDI1NTMyOTAyMTg3MTAxMDA=