<commit_before><?php

namespace Ojs\CoreBundle\Command;

use Composer\Script\CommandEvent;
use Ojs\AdminBundle\Entity\AdminPage;
use Ojs\CoreBundle\Acl\JournalRoleSecurityIdentity;
use Ojs\JournalBundle\Entity\Journal;
use Ojs\JournalBundle\Entity\JournalUser;
use Ojs\JournalBundle\Entity\Theme;
use Ojs\UserBundle\Entity\Role;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Bundle\FrameworkBundle\Console\Application;
use Symfony\Component\Console\Helper\DialogHelper;
use Symfony\Component\Console\Helper\HelperSet;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\StringInput;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Process\PhpExecutableFinder;
use Symfony\Component\Process\Process;
use Symfony\Component\Security\Acl\Permission\MaskBuilder;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Ojs\CoreBundle\Events\CoreEvents;
use Ojs\CoreBundle\Events\CoreEvent;

class InstallCommand extends ContainerAwareCommand
{
    public static function composer(CommandEvent $event)
    {
        $options = self::getOptions($event);
        $appDir = $options['symfony-app-dir'];
        $webDir = $options['symfony-web-dir'];

        if (!is_dir($webDir)) {
            echo 'The symfony-web-dir ('.$webDir.') specified in composer.json was not found in '.getcwd(
                ).', can not install assets.'.PHP_EOL;

            return;
        }

        static::executeCommand($event, $appDir, 'ojs:install');
    }

    protected static function getOptions(CommandEvent $event)
    {
        $options = array_merge(
            array(
                'symfony-app-dir' => 'app',
                'symfony-web-dir' => 'web',
                'symfony-assets-install' => 'hard',
            ),
            $event->getComposer()->getPackage()->getExtra()
        );

        $options['symfony-assets-install'] = getenv('SYMFONY_ASSETS_INSTALL') ?: $options['symfony-assets-install'];

        $options['process-timeout'] = $event->getComposer()->getConfig()->get('process-timeout');

        return $options;
    }

    protected static function executeCommand(CommandEvent $event, $appDir, $cmd, $timeout = 300)
    {
        $php = escapeshellarg(self::getPhp());
        $console = escapeshellarg($appDir.'/console');
        if ($event->getIO()->isDecorated()) {
            $console .= ' --ansi';
        }

        $process = new Process($php.' '.$console.' '.$cmd, null, null, null, $timeout);
        $process->run(
            function ($type, $buffer) {
                echo $buffer;
            }
        );
        if (!$process->isSuccessful()) {
            throw new \RuntimeException(
                sprintf('An error occurred when executing the "%s" command.', escapeshellarg($cmd))
            );
        }
    }

    protected static function getPhp()
    {
        $phpFinder = new PhpExecutableFinder();
        if (!$phpPath = $phpFinder->find()) {
            throw new \RuntimeException(
                'The php executable could not be found, add it to your PATH environment variable and try again'
            );
        }

        return $phpPath;
    }

    protected function configure()
    {
        $this
            ->setName('ojs:install')
            ->setDescription('Ojs first installation')
            ->addOption('no-role', null, InputOption::VALUE_NONE, 'Without role data')
            ->addOption('no-admin', null, InputOption::VALUE_NONE, 'Without admin records')
            ->addOption('no-location', null, InputOption::VALUE_NONE, 'Without location data')
            ->addOption('no-theme', null, InputOption::VALUE_NONE, 'Without themes')
            ->addOption('no-acl', null, InputOption::VALUE_NONE, 'Without ACL Data')
            ->addOption('fix-acl', null, InputOption::VALUE_NONE, 'Fix ACL structure')
            ->addOption('no-page', null, InputOption::VALUE_NONE, 'Without default pages');
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $sb = '<fg=black;bg=green>';
        $se = '</fg=black;bg=green>';
        $translator = $this->getContainer()->get('translator');
        /** @var $dispatcher EventDispatcherInterface */
        $dispatcher = $this->getContainer()->get('event_dispatcher');

        /** @var HelperSet $helperSet */
        $helperSet = $this->getHelperSet();
        /** @var DialogHelper $dialog */
        $dialog = $helperSet->get('dialog');
        $kernel = $this->getContainer()->get('kernel');
        $application = new Application($kernel);
        $application->setAutoExit(false);
        //$translator->setLocale('tr_TR');
        $output->writeln($this->printWelcome());
        $output->writeln(
            '<info>'.
            $translator->trans('ojs.install.title').
            '</info>'
        );

        if (!$dialog->askConfirmation(
            $output,
            '<question>'.
            $translator->trans('ojs.install.confirm').
            ' (y/n) : </question>',
            true
        )
        ) {
            return;
        }

        $command2 = 'doctrine:schema:update --force';
        $output->writeln('<info>Updating db schema!</info>');
        $application->run(new StringInput($command2));

        if (!$input->getOption('no-location')) {
            $location = $this->getContainer()->get('kernel')->getRootDir(
                ).'/../vendor/okulbilisim/location-bundle/Resources/data/location.sql';
            $locationSql = file_get_contents($location);

            $driver = $this->getContainer()->getParameter('database_driver');
            if ($driver == 'pdo_mysql') {

                $locationSql = 'SET foreign_key_checks = 0;' . $locationSql . 'SET foreign_key_checks = 1;';
            }
            $command3 = 'doctrine:query:sql "'.$locationSql.'"';
            $application->run(new StringInput($command3));
            $output->writeln('Locations inserted.');
        }

        if (!$input->getOption('no-role')) {
            $output->writeln($sb.'Inserting roles to db'.$se);
            $this->insertRoles($output);

            if (!$input->getOption('no-admin')) {
                $admin_username = $dialog->ask(
                    $output,
                    '<info>Set system admin username (admin) : </info>',
                    'admin'
                );
                $admin_email = $dialog->ask(
                    $output,
                    '<info>Set system admin email'.
                    ' (<EMAIL>) : </info>',
                    '<EMAIL>'
                );
                $admin_password = $dialog->ask(
                    $output,
                    '<info>Set system admin password (admin) </info>',
                    '<PASSWORD>'
                );

                $output->writeln($sb.'Inserting system admin user to db'.$se);
                $this->insertAdmin($admin_username, $admin_email, $admin_password);
            }
        }

        if (!$input->getOption('no-theme')) {
            $output->writeln($sb.'Inserting default theme record'.$se);<commit_msg>Use DBAL for inserting location SQL<commit_after><?php

namespace Ojs\CoreBundle\Command;

use Composer\Script\CommandEvent;
use Exception;
use Ojs\AdminBundle\Entity\AdminPage;
use Ojs\CoreBundle\Acl\JournalRoleSecurityIdentity;
use Ojs\JournalBundle\Entity\Journal;
use Ojs\JournalBundle\Entity\JournalUser;
use Ojs\JournalBundle\Entity\Theme;
use Ojs\UserBundle\Entity\Role;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Bundle\FrameworkBundle\Console\Application;
use Symfony\Component\Console\Helper\DialogHelper;
use Symfony\Component\Console\Helper\HelperSet;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\StringInput;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Process\PhpExecutableFinder;
use Symfony\Component\Process\Process;
use Symfony\Component\Security\Acl\Permission\MaskBuilder;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Ojs\CoreBundle\Events\CoreEvents;
use Ojs\CoreBundle\Events\CoreEvent;

class InstallCommand extends ContainerAwareCommand
{
    public static function composer(CommandEvent $event)
    {
        $options = self::getOptions($event);
        $appDir = $options['symfony-app-dir'];
        $webDir = $options['symfony-web-dir'];

        if (!is_dir($webDir)) {
            echo 'The symfony-web-dir ('.$webDir.') specified in composer.json was not found in '.getcwd(
                ).', can not install assets.'.PHP_EOL;

            return;
        }

        static::executeCommand($event, $appDir, 'ojs:install');
    }

    protected static function getOptions(CommandEvent $event)
    {
        $options = array_merge(
            array(
                'symfony-app-dir' => 'app',
                'symfony-web-dir' => 'web',
                'symfony-assets-install' => 'hard',
            ),
            $event->getComposer()->getPackage()->getExtra()
        );

        $options['symfony-assets-install'] = getenv('SYMFONY_ASSETS_INSTALL') ?: $options['symfony-assets-install'];

        $options['process-timeout'] = $event->getComposer()->getConfig()->get('process-timeout');

        return $options;
    }

    protected static function executeCommand(CommandEvent $event, $appDir, $cmd, $timeout = 300)
    {
        $php = escapeshellarg(self::getPhp());
        $console = escapeshellarg($appDir.'/console');
        if ($event->getIO()->isDecorated()) {
            $console .= ' --ansi';
        }

        $process = new Process($php.' '.$console.' '.$cmd, null, null, null, $timeout);
        $process->run(
            function ($type, $buffer) {
                echo $buffer;
            }
        );
        if (!$process->isSuccessful()) {
            throw new \RuntimeException(
                sprintf('An error occurred when executing the "%s" command.', escapeshellarg($cmd))
            );
        }
    }

    protected static function getPhp()
    {
        $phpFinder = new PhpExecutableFinder();
        if (!$phpPath = $phpFinder->find()) {
            throw new \RuntimeException(
                'The php executable could not be found, add it to your PATH environment variable and try again'
            );
        }

        return $phpPath;
    }

    protected function configure()
    {
        $this
            ->setName('ojs:install')
            ->setDescription('Ojs first installation')
            ->addOption('no-role', null, InputOption::VALUE_NONE, 'Without role data')
            ->addOption('no-admin', null, InputOption::VALUE_NONE, 'Without admin records')
            ->addOption('no-location', null, InputOption::VALUE_NONE, 'Without location data')
            ->addOption('no-theme', null, InputOption::VALUE_NONE, 'Without themes')
            ->addOption('no-acl', null, InputOption::VALUE_NONE, 'Without ACL Data')
            ->addOption('fix-acl', null, InputOption::VALUE_NONE, 'Fix ACL structure')
            ->addOption('no-page', null, InputOption::VALUE_NONE, 'Without default pages');
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $sb = '<fg=black;bg=green>';
        $se = '</fg=black;bg=green>';
        $translator = $this->getContainer()->get('translator');
        /** @var $dispatcher EventDispatcherInterface */
        $dispatcher = $this->getContainer()->get('event_dispatcher');

        /** @var HelperSet $helperSet */
        $helperSet = $this->getHelperSet();
        /** @var DialogHelper $dialog */
        $dialog = $helperSet->get('dialog');
        $kernel = $this->getContainer()->get('kernel');
        $application = new Application($kernel);
        $application->setAutoExit(false);
        //$translator->setLocale('tr_TR');
        $output->writeln($this->printWelcome());
        $output->writeln(
            '<info>'.
            $translator->trans('ojs.install.title').
            '</info>'
        );

        if (!$dialog->askConfirmation(
            $output,
            '<question>'.
            $translator->trans('ojs.install.confirm').
            ' (y/n) : </question>',
            true
        )
        ) {
            return;
        }

        $command2 = 'doctrine:schema:update --force';
        $output->writeln('<info>Updating db schema!</info>');
        $application->run(new StringInput($command2));

        if (!$input->getOption('no-location')) {
            try {
                $location = $this
                        ->getContainer()->get('kernel')
                        ->getRootDir() . '/../vendor/okulbilisim/location-bundle/Resources/data/location.sql';
                $locationSql = file_get_contents($location);

                $driver = $this->getContainer()->getParameter('database_driver');

                if ($driver == 'pdo_mysql') {
                    $locationSql = 'SET foreign_key_checks = 0;' . $locationSql . 'SET foreign_key_checks = 1;';
                }

                $parameters = [
                    'host' => $this->getContainer()->getParameter('database_host'),
                    'user' => $this->getContainer()->getParameter('database_user'),
                    'password' => $this->getContainer()->getParameter('database_password'),
                    'dbname' => $this->getContainer()->getParameter('database_name'),
                    'driver' => $this->getContainer()->getParameter('database_driver'),
                    'charset' => 'utf8',
                ];


                $connection = $this
                    ->getContainer()
                    ->get('doctrine.dbal.connection_factory')
                    ->createConnection($parameters);

                $connection->executeQuery($locationSql);
                $output->writeln('Locations inserted.');
            } catch (Exception $e) {
                $output->writeln('Location insertion failed.');
            }
        }

        if (!$input->getOption('no-role')) {
            $output->writeln($sb.'Inserting roles to db'.$se);
            $this->insertRoles($output);

            if (!$input->getOption('no-admin')) {
                $admin_username = $dialog->ask(
                    $output,
                    '<info>Set system admin username (admin) : </info>',
                    'admin'
                );
                $admin_email = $dialog->ask(
                    $output,
                    '<info>Set system admin email'.
                    ' (<EMAIL>) : </info>',
                    '<EMAIL>'
                );
                $admin_password = $dialog->ask(
                    $output,
                    '<info>Set system admin password (admin) </info>',
                    '<PASSWORD>'
                );

                $output->writeln($sb.'Inserting system admin user to db'.$se);
                $this->insertAdmin($admin_username, $admin_email, $admin_password);
            }
        }

        if (!$input->getOption('no-theme')) {
            $output->writeln($sb.'Inserting default theme record'.$se);
{'fraction_non_alphanumeric': 0.14724006817883833, 'fraction_numerical': 0.0011144617805165858, 'mean_word_length': 2.1834307178631054, 'pattern_counts': {'":': 0, '<': 39, '<?xml version=': 0, '>': 177, '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': '1681997', 'n_tokens_mistral': 4189, 'n_tokens_neox': 4075, 'n_words': 765}