<?php

namespace Eater\Glim\Handler\Install;

use Eater\Glim\Handler\Main;
use Eater\Glim\Model\UserQuery;

class Show extends Main
{
    public function beforeHandle() {
        if (UserQuery::create()->findOne()) {
            return $this->redirect('/login');
        }
    }

    public function handle()
    {
        $return = 1;
        $execEnabled = $this->isExecEnabled();
        $hasOpenSsl = false;
        if ($execEnabled) {
            exec('command -v openssl', $output, $return);
            $hasOpenSsl = $return === 0;
        }

        /* @var \Aura\Session\Session $session */
        $session = $this->get('session');
        $segment = $session->getSegment('main');

        $data = [
            'hasExecEnabled' => $execEnabled,
            'hasOpenSsl' => $hasOpenSsl,
            'hasOpenSslExtension' => extension_loaded('openssl'),
            'hasZipExtension' => extension_loaded('zip'),
            'hostname' => parse_url($_SERVER['HTTP_HOST'], PHP_URL_HOST),
            'hostnameWithPort' => $_SERVER['HTTP_HOST'],
            'error' => $segment->getFlash('error')
        ];

        return $this->render('install.html.twig', $data);
    }

    private function isExecEnabled() {
        if (ini_get('safe_mode')) {
            return false;
        } else {
            $d = ini_get('disable_functions');
            $s = ini_get('suhosin.executor.func.blacklist');
            if ("$d$s") {
                $array = preg_split('/,\s*/', "$d,$s");
                if (in_array('exec', $array)) {
                    return false;
                }
            }
        }

        return true;
    }
}