<commit_before><?php
namespace Install;

use Zend\Module\Consumer\AutoloaderProvider,
    Zend\Module\Manager as ModuleManager,
    Zend\EventManager\StaticEventManager,
    Stuki\Version,
    Doctrine\ORM\Tools\SchemaTool
    ;

class Module
{
    public function init(ModuleManager $manager) {
        $events = StaticEventManager::getInstance();
        $events->attach('bootstrap', 'bootstrap', array($this, 'checkInstall'));
    }

    public function checkInstall($e) {

        $events = StaticEventManager::getInstance();
        $application = $e->getParam('application');
        $em = $application->getLocator()->get('doctrine_em');

        // Default events for install check
        $events->attach('Zend\Mvc\Application', 'route', array($this, 'checkPaths'));
        $events->attach('Zend\Mvc\Application', 'route', array($this, 'checkIni'));

        $conn = $em->getConnection();
        $sql = "SELECT * FROM users";
        try {

            $stmt = $conn->query($sql);

            // Installed; check for db updates
            $events->attach('Zend\Mvc\Application', 'route', array($this, 'syncronizeDatabase'));

            return; // Stuki is installed

        } catch (\PDOException $error) {
            switch ($error->getCode()) {
                case 1049: // Database does not exist
                    $events->attach('Zend\Mvc\Application', 'route', array($this, 'notifyNoDatabase'));
                    break;
                case '42S02':  // Table or view not found; this is what we expect
                    if ($application->getRequest()->query()->get('install')) {
                        // The last event in this list must stop propogation
                        $events->attach('Zend\Mvc\Application', 'route', array($this, 'buildDatabase'));
                        $events->attach('Zend\Mvc\Application', 'route', array($this, 'setDefaults'));
                    } else {
                        // Begin installation
                        $events->attach('Zend\Mvc\Application', 'route', array($this, 'showInstall'));
                    }
                    break;
                default:
                    echo '<h1>An unexpected database error has occurred while checking installation</h1>';
                    die($error->getMessage());
            }
        } catch (\Exception $e) {
            die('exception');
        }
    }

    /**
     * FIXME: This is intended as a development tool and will be replaced later on
     */
    public function syncronizeDatabase($e) {
        if (isset($_REQUEST['overrideSync'])) return;

        $em = $e->getTarget()->getLocator()->get('doctrine_em');
        $tool = new \Doctrine\ORM\Tools\SchemaTool($em);

        // update the database
        if (isset($_REQUEST['sync'])) $res = $tool->UpdateSchema($em->getMetadataFactory()->getAllMetadata());

        if ($res = $tool->getUpdateSchemaSql($em->getMetadataFactory()->getAllMetadata())) {
            echo "Database Sync Needed.  Use ?overrideSync=true to bypass.<br><pre>";
            // Show the pending sql statements
            print_r($res);
            echo  "</pre><BR><BR><a href=\"/?sync=true\">Sync</a>";

            $e->stopPropagation();
            return $e->getTarget()->getResponse();
        }
    }

    public function notifyNoDatabase($e) {
        $response = $e->getTarget()->getResponse();
        echo '<h1>Stuki ' . Version::getVersion() . '</h1>
              The stuki database does not exist.
              Please create the database and try again.
        ';
        $e->stopPropagation();
        return $response;
    }

    /**
     * Begin the installation
     */
    public function showInstall($e) {
        $response = $e->getTarget()->getResponse();
        echo '<h1>Stuki ' . Version::getVersion() . '</h1>
              Welcome to Stuki.  Stuki thinks it is not installed because it cannot connect to your
              database.
              <br>
              <a href="/?install=1">Begin installation</a>
        ';

        $e->stopPropagation();
        return $response;
    }

    /**
     * Check ini setttings
     */
    public function checkIni($e) {
        $response = $e->getTarget()->getResponse();
        $return = '';
        $errors = array();

        //
        try {
            $date = new \Datetime();
        } catch (\Exception $exception) {

            $errors = true;
        }

        $return .= '
            Your default timezone is not set in your php ini settings.<br>
            You must fix this error to continue.
        ';

        if ($errors) {
            echo $return;
            $e->stopPropagation();
            return $response;
        }

        return true;
    }

    public function checkPaths($e) {
        $response = $e->getTarget()->getResponse();
        $return = '';
        $errors = array();

        // Check directories
        $checkDirs = array(
            'Session Save Path' => session_save_path(),
            'Upload Temp' => ini_get('upload_tmp_dir'),
            'Search' => APPLICATION_PATH . '/data/Search/',
            'Cache' => APPLICATION_PATH . '/data/Cache/',
            'Doctrine Proxies' => APPLICATION_PATH . '/data/DoctrineORMModule/Proxy'
        );
        $return .= '<style>span.fail {color: red;}</style>';
        $return .= "<h1>Stuki Installation Step 1 - Paths</h1><pre>";

        foreach ($checkDirs as $key => $checkDir) {
            $return .= "Testing $key Directory\n";

            // Directory testing from Smarty->testInstall();
            if (!is_dir($checkDir)) {
                $status = false;
                $message = "<span class=\"fail\">FAILED</span>: {$checkDir} is not a directory";
                $return .= $message . ".\n\n";
                $errors['compile_dir'] = $message;
            } elseif (!is_readable($checkDir)) {
                $status = false;
                $message = "<span class=\"fail\">FAILED</span>: {$checkDir} is not readable";
                $return .= $message . ".\n\n";
                $errors['compile_dir'] = $message;
            } elseif (!is_writable($checkDir)) {<commit_msg>Removed ini dir checks<commit_after><?php
namespace Install;

use Zend\Module\Consumer\AutoloaderProvider,
    Zend\Module\Manager as ModuleManager,
    Zend\EventManager\StaticEventManager,
    Stuki\Version,
    Doctrine\ORM\Tools\SchemaTool
    ;

class Module
{
    public function init(ModuleManager $manager) {
        $events = StaticEventManager::getInstance();
        $events->attach('bootstrap', 'bootstrap', array($this, 'checkInstall'));
    }

    public function checkInstall($e) {

        $events = StaticEventManager::getInstance();
        $application = $e->getParam('application');
        $em = $application->getLocator()->get('doctrine_em');

        // Default events for install check
        $events->attach('Zend\Mvc\Application', 'route', array($this, 'checkPaths'));
        $events->attach('Zend\Mvc\Application', 'route', array($this, 'checkIni'));

        $conn = $em->getConnection();
        $sql = "SELECT * FROM users";
        try {

            $stmt = $conn->query($sql);

            // Installed; check for db updates
            $events->attach('Zend\Mvc\Application', 'route', array($this, 'syncronizeDatabase'));

            return; // Stuki is installed

        } catch (\PDOException $error) {
            switch ($error->getCode()) {
                case 1049: // Database does not exist
                    $events->attach('Zend\Mvc\Application', 'route', array($this, 'notifyNoDatabase'));
                    break;
                case '42S02':  // Table or view not found; this is what we expect
                    if ($application->getRequest()->query()->get('install')) {
                        // The last event in this list must stop propogation
                        $events->attach('Zend\Mvc\Application', 'route', array($this, 'buildDatabase'));
                        $events->attach('Zend\Mvc\Application', 'route', array($this, 'setDefaults'));
                    } else {
                        // Begin installation
                        $events->attach('Zend\Mvc\Application', 'route', array($this, 'showInstall'));
                    }
                    break;
                default:
                    echo '<h1>An unexpected database error has occurred while checking installation</h1>';
                    die($error->getMessage());
            }
        } catch (\Exception $e) {
            die('exception');
        }
    }

    /**
     * FIXME: This is intended as a development tool and will be replaced later on
     */
    public function syncronizeDatabase($e) {
        if (isset($_REQUEST['overrideSync'])) return;

        $em = $e->getTarget()->getLocator()->get('doctrine_em');
        $tool = new \Doctrine\ORM\Tools\SchemaTool($em);

        // update the database
        if (isset($_REQUEST['sync'])) $res = $tool->UpdateSchema($em->getMetadataFactory()->getAllMetadata());

        if ($res = $tool->getUpdateSchemaSql($em->getMetadataFactory()->getAllMetadata())) {
            echo "Database Sync Needed.  Use ?overrideSync=true to bypass.<br><pre>";
            // Show the pending sql statements
            print_r($res);
            echo  "</pre><BR><BR><a href=\"/?sync=true\">Sync</a>";

            $e->stopPropagation();
            return $e->getTarget()->getResponse();
        }
    }

    public function notifyNoDatabase($e) {
        $response = $e->getTarget()->getResponse();
        echo '<h1>Stuki ' . Version::getVersion() . '</h1>
              The stuki database does not exist.
              Please create the database and try again.
        ';
        $e->stopPropagation();
        return $response;
    }

    /**
     * Begin the installation
     */
    public function showInstall($e) {
        $response = $e->getTarget()->getResponse();
        echo '<h1>Stuki ' . Version::getVersion() . '</h1>
              Welcome to Stuki.  Stuki thinks it is not installed because it cannot connect to your
              database.
              <br>
              <a href="/?install=1">Begin installation</a>
        ';

        $e->stopPropagation();
        return $response;
    }

    /**
     * Check ini setttings
     */
    public function checkIni($e) {
        $response = $e->getTarget()->getResponse();
        $return = '';
        $errors = array();

        //
        try {
            $date = new \Datetime();
        } catch (\Exception $exception) {

            $errors = true;
        }

        $return .= '
            Your default timezone is not set in your php ini settings.<br>
            You must fix this error to continue.
        ';

        if ($errors) {
            echo $return;
            $e->stopPropagation();
            return $response;
        }

        return true;
    }

    public function checkPaths($e) {
        $response = $e->getTarget()->getResponse();
        $return = '';
        $errors = array();

        // Check directories
        $checkDirs = array(
            'Search' => APPLICATION_PATH . '/data/Search/',
            'Cache' => APPLICATION_PATH . '/data/Cache/',
            'Doctrine Proxies' => APPLICATION_PATH . '/data/DoctrineORMModule/Proxy'
        );
        $return .= '<style>span.fail {color: red;}</style>';
        $return .= "<h1>Stuki Installation Step 1 - Paths</h1><pre>";

        foreach ($checkDirs as $key => $checkDir) {
            $return .= "Testing $key Directory\n";

            // Directory testing from Smarty->testInstall();
            if (!is_dir($checkDir)) {
                $status = false;
                $message = "<span class=\"fail\">FAILED</span>: {$checkDir} is not a directory";
                $return .= $message . ".\n\n";
                $errors['compile_dir'] = $message;
            } elseif (!is_readable($checkDir)) {
                $status = false;
                $message = "<span class=\"fail\">FAILED</span>: {$checkDir} is not readable";
                $return .= $message . ".\n\n";
                $errors['compile_dir'] = $message;
            } elseif (!is_writable($checkDir)) {
{'fraction_non_alphanumeric': 0.1491753507836219, 'fraction_numerical': 0.0029539673422499385, 'mean_word_length': 1.8738505069559066, 'pattern_counts': {'":': 0, '<': 57, '<?xml version=': 0, '>': 149, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6428500', 'n_tokens_mistral': 3290, 'n_tokens_neox': 3177, 'n_words': 774}