<?php

namespace Axioma;

class Utils
{
    public static function isWindows()
    {
        return strtoupper(substr(PHP_OS, 0, 3)) === 'WIN';
    }

    public static function isAbsolutePath($file)
    {
        return '' !== $file
            && (strspn($file, '/\\', 0, 1)
                || (\strlen($file) > 3 && ctype_alpha($file[0]) && ':' === $file[1] && strspn($file, '/\\', 2, 1))
                || null !== parse_url($file, \PHP_URL_SCHEME)
            );
    }

    public static function makeAbsolutePath($path, $basePath = '')
    {
        if (self::isAbsolutePath($path)) {
            return $path;
        }

        if (empty($basePath)) {
            $basePath = dirname($_SERVER['SCRIPT_FILENAME']);
        }
        $path = $basePath . DIRECTORY_SEPARATOR . $path;

        $components = array();
        foreach (explode(DIRECTORY_SEPARATOR, rtrim($path, DIRECTORY_SEPARATOR)) as $name) {
            if ($name === '..') {
                array_pop($components);
            } elseif ($name !== '.' && !(count($components) && $name === '')) {
                $components[] = $name;
            }
        }
        return implode(DIRECTORY_SEPARATOR, $components);
    }

    public static function fixTailSeparator($dir_path)
    {
        if (substr($dir_path, -1) != DIRECTORY_SEPARATOR) {
            $dir_path .= DIRECTORY_SEPARATOR;
        }
        return $dir_path;
    }

    public static function callCheck($obj, $func, &$errors, &$warnings)
    {
        $error = '';
        $f = array($obj, $func);
        if ($f($error)) {
            if (empty($error)) {
                echo '<span class="ok">&#x2713;</span>';
            } else {
                echo '<span class="warning" data-error="' . $error . '">&#x26A0;</span>';
                $warnings[] = $error;
            }
            return true;
        } else {
            echo '<span class="error" data-error="' . $error . '">&#x2717;</span>';
            $errors[] = $error;
            return false;
        }
    }

    public static function showMessageBlocks($errors, $warnings, $info, $div_type = 'formDiv')
    {
        echo '<div id="errorDiv" class="' . $div_type . ' errorDiv"' . (count($errors) === 0 ? ' hidden' : '') . '>';
        if (count($errors) > 0) {
            foreach ($errors as $error_str) {
                echo "<p>$error_str</p>";
            }
        }
        echo '</div>';
        $warn_count = count($warnings) + count($info);
        echo '<div id="infoDiv" class="' . $div_type . ' infoDiv"' . ($warn_count === 0 ? ' hidden' : '') . '>';
        if ($warn_count > 0) {
            foreach ($info as $info_str) {
                echo '<p class="ok">' . $info_str . '</p>';
            }
            foreach ($warnings as $warn) {
                echo '<p class="warning">' . $warn . '</p>';
            }
        }
        echo '</div>';
    }

    public static function makeActivationText($app, $config)
    {
        $text = array();
        $text[] = _('Название программы: ') . \Axioma\Server\App::completeName();
        $text[] = _('Название компании:') . $app->company();
        $text[] = _('Серийный номер: ') . $app->serialNumber();
        $text[] = _('Идентификатор оборудования:');
        $text[] = '== == == == == == == == == == == == == == == == == == == == == == == == == == ==';
        $text[] = $config->hwid;
        $text[] = '== == == == == == == == == == == == == == == == == == == == == == == == == == ==';
        return $text;
    }

    public static function getClientIPInfo()
    {
        $ip_remote = inet_pton($_SERVER['REMOTE_ADDR']);
        $ip_forward = null;
        if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $ip_forward = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR'])[0];
            $ip_forward = filter_var($ip_forward, FILTER_VALIDATE_IP) ? inet_pton($ip_forward) : null;
        }
        $ip_client = isset($_SERVER['HTTP_CLIENT_IP']) &&
            filter_var($_SERVER['HTTP_CLIENT_IP'], FILTER_VALIDATE_IP) ?  inet_pton($_SERVER['HTTP_CLIENT_IP']) : null;

        $ip_block_type = 1 + (is_null($ip_forward) ? 0 : 2) + (is_null($ip_client) ? 0 : 4);
        $all_data[] = chr($ip_block_type);
        $all_data[] = chr(strlen($ip_remote));
        $all_data[] = $ip_remote;
        if (!is_null($ip_forward)) {
            $all_data[] = chr(strlen($ip_forward));
            $all_data[] = $ip_forward;
        }
        if (!is_null($ip_client)) {
            $all_data[] = chr(strlen($ip_client));
            $all_data[] = $ip_client;
        }
        return $all_data;
    }

    public static function getRunningUser()
    {
        if (function_exists('posix_geteuid') && function_exists('posix_getpwuid')) {
            $pwu_data = posix_getpwuid(posix_geteuid());
            return $pwu_data['name'];
        } else {
            return exec('whoami');
        }
    }

    public static function checkPhpRequirements(&$errors = null)
    {
        $errors = [];
        if (version_compare(PHP_VERSION, '5.4.0', '<')) {
            $errors[] = _('Требуется PHP версии 5.4 или выше');
        }
        if (!extension_loaded('pdo_sqlite')) {
            $errors[] = _("Необходимо включить модуль 'pdo_sqlite' в настройках php веб-сервера");
        }
        if (@exec('echo EXEC') != 'EXEC') {
            $errors[] = _("Необходимо разрешить вызов 'exec' в настройках веб-сервера");
        }
        return empty($errors);
    }
}
