<?php
// Copyright 1999-2019. Plesk International GmbH. All rights reserved.

namespace Plesk\MigrationLibV8\Plesk;

use Plesk\MigrationLibV8\Utils\ArrayUtils;
use Plesk\MigrationLibV8\Utils\FileUtils;

/**
 * Wrapper around Plesk function called directly by extension, without using official extensions SDK.
 */
class PleskFunctions
{
    public static function encryptPassword($password)
    {
        /** @noinspection PhpUndefinedClassInspection */
        return \Plesk_Base_Utils_String::encryptWithPrefix($password);
    }

    public static function decryptPassword($password)
    {
        /** @noinspection PhpUndefinedClassInspection */
        return \Plesk_Base_Utils_String::decryptWithPrefix($password);
    }

    public static function utilExec($util, $params, $env, &$output)
    {
        /** @noinspection PhpIncludeInspection */
        if (!@include_once('common_func.php')) {
            /** @noinspection PhpIncludeInspection */
            require_once('common_func.php3'); // for Plesk < 17.0
        }

        global $plesk_errormsg, $php_errormsg;

        $execResponse = '';
        /** @var \Db_Table_Broker_ServiceNodes $serviceNodesBroker */
        $serviceNodesBroker = \Db_Table_Broker::get('ServiceNodes');
        $serviceNode = $serviceNodesBroker->getManagementNode();

        $utilPath = $serviceNode->env()->general()->getValue('PRODUCT_ROOT_D') .
            DIRECTORY_SEPARATOR . 'admin' .
            DIRECTORY_SEPARATOR . 'bin64' .
            DIRECTORY_SEPARATOR . $util . '.exe';
        $is64bit = FileUtils::fileExists($utilPath);

        $response = $serviceNode->agent()->exec($util, $params, '', $env, $is64bit)
            ->saveResponse($execResponse)
            ->commit();
        if ($error = $response->getError()) {
            $plesk_errormsg = "util_io_exec() failed: " . $error->getMessage();
            $stdError = $response->getStdErr();
            if ("" != $stdError) {
                $plesk_errormsg .= ' ' . $stdError;
            }

            return false;
        }

        $output = [];
        $out_arr = explode("\n", rtrim($execResponse->stdout));
        foreach ($out_arr as $out_str) {
            $output[] = rtrim($out_str);
        }

        return true;
    }

    public static function sendFileDownloadHeaders($filename)
    {
        /** @noinspection PhpUndefinedFunctionInspection */
        sendHeaders_Download($filename);
    }
    
    public static function getDefaultIPAddress()
    {
        /** @noinspection PhpUndefinedClassInspection */
        $defaultIp = \Db_Table_Broker::get('IpAddresses')->getDefault();
        return $defaultIp ? $defaultIp->ip_address : '';
    }

    public static function getIPAddresses()
    {
        $ipAddresses = [];
        /** @noinspection PhpUndefinedClassInspection */
        foreach (\Db_Table_Broker::get('IpAddresses')->fetchAll() as $ip) {
            $ipAddresses[] = $ip->ip_address;
        }
        return $ipAddresses;
    }

    /**
     * Get URLs to overview pages of each subscription in Plesk.
     *
     * @return string[] list of URLs
     */
    public static function getSubscriptionOverviewUrls()
    {
        /** @noinspection PhpUndefinedClassInspection */
        $data = \Db_Table_Broker::get('domains')->select()->setIntegrityCheck(false)
            ->from(['d' => 'domains'], ['name' => 'd.name', 'id' => 'd.id'])
            ->where('d.webspace_id = 0')
            ->query()->fetchAll();
        foreach ($data as &$item) {
            $item['url'] = '/admin/subscription/overview/id/' . $item['id'];
        }
        return ArrayUtils::groupValueById($data, 'name', 'url');
    }

    /**
     * Get list of existing subscription names in Plesk.
     *
     * @return string[] list of existing subscription names
     */
    public static function getSubscriptionNames()
    {
        $subscriptionNames = [];
        /** @noinspection PhpUndefinedClassInspection */
        $data = \Db_Table_Broker::get('domains')->select()->setIntegrityCheck(false)
            ->from(['d' => 'domains'], ['name' => 'd.name'])
            ->where('d.webspace_id = 0')
            ->query()->fetchAll();
        foreach ($data as $item) {
            $subscriptionNames[] = $item['name'];
        }
        return $subscriptionNames;
    }

    /**
     * Check whether we are working on Plesk Multiserver.
     *
     * @return bool
     */
    public static function isPleskMultiserver()
    {
        /** @noinspection PhpUndefinedClassInspection */
        foreach (\DB_Table_Broker::get('Modules')->fetchAll() as $moduleInfo) {
            if ($moduleInfo->name == 'plesk-multi-server') {
                return true;
            }
        }
        return false;
    }

    /**
     * Check whether target Plesk server has remote SmarterMail as a mail server
     *
     * @return bool
     */
    public static function hasRemoteSmarterMail()
    {
        /** @noinspection PhpUndefinedClassInspection */
        $data = \Db_Table_Broker::get('ServiceNodeEnvironment')->select()
            ->where("section = 'mail' AND name = 'SMTP_Server_package'")
            ->query()->fetchAll();
        return count($data) > 0 && $data[0]['value'] == 'smartermail_remote';
    }

    /**
     * Get IP address of remote SmarterMail server.
     *
     * @return string
     */
    public static function getRemoteSmarterMailIP()
    {
        /** @noinspection PhpUndefinedClassInspection */
        $data = \Db_Table_Broker::get('misc')->select()
            ->where("param = 'smartermail_remote_host'")
            ->query()->fetchAll();
        if (count($data) == 0) {
            return '';
        }
        return gethostbyname($data[0]['val']);
    }

    public static function IDNToASCII($domainName)
    {
        /** @noinspection PhpUndefinedFunctionInspection */
        return @idn_toascii($domainName);
    }
}
