<commit_before><?php
namespace Bolt\Controller\Backend;

use Bolt\AccessControl\Permissions;
use Bolt\Translation\Translator as Trans;
use Silex\ControllerCollection;
use Symfony\Component\Form\Form;
use Symfony\Component\Form\FormBuilder;
use Symfony\Component\Form\FormError;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * Backend controller for user maintenance routes.
 *
 * Prior to v2.3 this functionality primarily existed in the monolithic
 * Bolt\Controllers\Backend class.
 *
 * @author <NAME> <<EMAIL>>
 */
class Users extends BackendBase
{
    protected function addRoutes(ControllerCollection $c)
    {
        $c->get('/users', 'admin')
            ->bind('users');

        $c->match('/users/edit/{id}', 'edit')
            ->assert('id', '\d*')
            ->bind('useredit');

        $c->match('/userfirst', 'first')
            ->bind('userfirst');

        $c->post('/user/{action}/{id}', 'modify')
            ->bind('useraction');

        $c->match('/profile', 'profile')
            ->bind('profile');

        $c->get('/roles', 'viewRoles')
            ->bind('roles');
    }

    /**
     * All users admin page.
     *
     * @return \Bolt\Response\BoltResponse
     */
    public function admin()
    {
        $currentuser = $this->getUser();
        $users = $this->users()->getUsers();
        $sessions = $this->authentication()->getActiveSessions();

        foreach ($users as $name => $user) {
            if (($key = array_search(Permissions::ROLE_EVERYONE, $user['roles'], true)) !== false) {
                unset($users[$name]['roles'][$key]);
            }
        }

        $context = [
            'currentuser' => $currentuser,
            'users'       => $users,
            'sessions'    => $sessions
        ];

        return $this->render('users/users.twig', $context);
    }

    /**
     * User edit route.
     *
     * @param Request $request The Symfony Request
     * @param integer $id      The user ID
     *
     * @return \Bolt\Response\BoltResponse|\Symfony\Component\HttpFoundation\RedirectResponse
     */
    public function edit(Request $request, $id)
    {
        $currentuser = $this->getUser();

        // Get the user we want to edit (if any)
        if (!empty($id)) {
            $user = $this->getUser($id);

            // Verify the current user has access to edit this user
            if (!$this->app['permissions']->isAllowedToManipulate($user, $currentuser)) {
                $this->flashes()->error(Trans::__('You do not have the right privileges to edit that user.'));

                return $this->redirectToRoute('users');
            }
        } else {
            $user = $this->users()->getEmptyUser();
        }

        $enabledoptions = [
            1 => Trans::__('page.edit-users.activated.yes'),
            0 => Trans::__('page.edit-users.activated.no')
        ];

        $roles = array_map(
            function ($role) {
                return $role['label'];
            },
            $this->app['permissions']->getDefinedRoles()
        );

        $form = $this->getUserForm($user, true);

        // New users and the current users don't need to disable themselves
        if ($currentuser['id'] != $id) {
            $form->add(
                'enabled',
                'choice',
                [
                    'choices'     => $enabledoptions,
                    'expanded'    => false,
                    'constraints' => new Assert\Choice(array_keys($enabledoptions)),
                    'label'       => Trans::__('page.edit-users.label.user-enabled'),
                ]
            );
        }

        $form
            ->add(
                'roles',
                'choice',
                [
                    'choices'  => $roles,
                    'expanded' => true,
                    'multiple' => true,
                    'label'    => Trans::__('page.edit-users.label.assigned-roles')
                ]
            )
            ->add(
                'lastseen',
                'text',
                [
                    'disabled' => true,
                    'label'    => Trans::__('page.edit-users.label.last-seen')
                ]
            )
            ->add(
                'lastip',
                'text',
                [
                    'disabled' => true,
                    'label'    => Trans::__('page.edit-users.label.last-ip')
                ]
            );

        // Set the validation
        $form = $this->setUserFormValidation($form, true);

        $form = $form->getForm();

        // Check if the form was POST-ed, and valid. If so, store the user.
        if ($request->isMethod('POST')) {
            $user = $this->validateUserForm($request, $form, false);

            $currentuser = $this->getUser();

            if ($user !== false && $user['id'] === $currentuser['id'] && $user['username'] !== $currentuser['username']) {
                // If the current user changed their own login name, the session is effectively
                // invalidated. If so, we must redirect to the login page with a flash message.
                $this->flashes()->error(Trans::__('page.edit-users.message.change-self'));

                return $this->redirectToRoute('login');
            } elseif ($user !== false) {
                // Return to the 'Edit users' screen.
                return $this->redirectToRoute('users');
            }
        }

        /** @var \Symfony\Component\Form\FormView|\Symfony\Component\Form\FormView[] $formView */
        $formView = $form->createView();

        $manipulatableRoles = $this->app['permissions']->getManipulatableRoles($currentuser);
        foreach ($formView['roles'] as $role) {
            if (!in_array($role->vars['value'], $manipulatableRoles)) {
                $role->vars['attr']['disabled'] = 'disabled';
            }
        }

        $context = [
            'kind'        => empty($id) ? 'create' : 'edit',
            'form'        => $formView,
            'note'        => '',
            'displayname' => $user['displayname'],
        ];

        return $this->render('edituser/edituser.twig', $context);
    }

    /**
     * Create the first user.
     *
     * @param Request $request The Symfony Request
     *
     * @return \Bolt\Response\BoltResponse|\Symfony\Component\HttpFoundation\RedirectResponse
     */
    public function first(Request $request)
    {
        // We should only be here for creating the first user
        if ($this->app['integritychecker']->checkUserTableIntegrity() && $this->users()->hasUsers()) {
            return $this->redirectToRoute('dashboard');
        }

        // Get and empty user array
        $user = $this->users()->getEmptyUser();

        // Add a note, if we're setting up the first user using SQLite.
        $dbdriver = $this->getOption('general/database/driver');
        if ($dbdriver === 'sqlite' || $dbdriver === 'pdo_sqlite') {
            $note = Trans::__('page.edit-users.note-sqlite');
        } else {
            $note = '';
        }

        // If we get here, chances are we don't have the tables set up, yet.
        $this->app['integritychecker']->repairTables();

        // Grant 'root' to first user by default
        $user['roles'] = [Permissions::ROLE_ROOT];

        // Get the form
        $form = $this->getUserForm($user, true);

        // Set the validation
        $form = $this->setUserFormValidation($form, true);

        /** @var \Symfony\Component\Form\Form */
        $form = $form->getForm();

        // Check if the form was POST-ed, and valid. If so, store the user.
        if ($request->isMethod('POST')) {
            if ($this->validateUserForm($request, $form, true)) {
                // To the dashboard, where 'login' will be triggered
                return $this->redirectToRoute('dashboard');
            }
        }

        $context = [
            'kind'        => 'create',
            'form'        => $form->createView(),
            'note'        => $note,
            'displayname' => $user['displayname'],
            'sitename'    => $this->getOption('general/sitename'),
        ];

        return $this->render('firstuser/firstuser.twig', $context);
    }

    /**
     * Perform modification actions on users.
     *
     * @param string  $action The action
     * @param integer $id     The user ID
     *
     * @return \Symfony\Component\HttpFoundation\RedirectResponse
     */
    public function modify($action, $id)
    {
        if (!$this->checkAntiCSRFToken()) {
            $this->flashes()->info(Trans::__('An error occurred.'));

            return $this->redirectToRoute('users');
        }
        $user = $this->getUser($id);
<commit_msg>On successful set up of first user, log them in and welcome them<commit_after><?php
namespace Bolt\Controller\Backend;

use Bolt\AccessControl\Permissions;
use Bolt\Translation\Translator as Trans;
use Silex\ControllerCollection;
use Symfony\Component\Form\Form;
use Symfony\Component\Form\FormBuilder;
use Symfony\Component\Form\FormError;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\HttpFoundation\Cookie;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * Backend controller for user maintenance routes.
 *
 * Prior to v2.3 this functionality primarily existed in the monolithic
 * Bolt\Controllers\Backend class.
 *
 * @author <NAME> <<EMAIL>>
 */
class Users extends BackendBase
{
    protected function addRoutes(ControllerCollection $c)
    {
        $c->get('/users', 'admin')
            ->bind('users');

        $c->match('/users/edit/{id}', 'edit')
            ->assert('id', '\d*')
            ->bind('useredit');

        $c->match('/userfirst', 'first')
            ->bind('userfirst');

        $c->post('/user/{action}/{id}', 'modify')
            ->bind('useraction');

        $c->match('/profile', 'profile')
            ->bind('profile');

        $c->get('/roles', 'viewRoles')
            ->bind('roles');
    }

    /**
     * All users admin page.
     *
     * @return \Bolt\Response\BoltResponse
     */
    public function admin()
    {
        $currentuser = $this->getUser();
        $users = $this->users()->getUsers();
        $sessions = $this->authentication()->getActiveSessions();

        foreach ($users as $name => $user) {
            if (($key = array_search(Permissions::ROLE_EVERYONE, $user['roles'], true)) !== false) {
                unset($users[$name]['roles'][$key]);
            }
        }

        $context = [
            'currentuser' => $currentuser,
            'users'       => $users,
            'sessions'    => $sessions
        ];

        return $this->render('users/users.twig', $context);
    }

    /**
     * User edit route.
     *
     * @param Request $request The Symfony Request
     * @param integer $id      The user ID
     *
     * @return \Bolt\Response\BoltResponse|\Symfony\Component\HttpFoundation\RedirectResponse
     */
    public function edit(Request $request, $id)
    {
        $currentuser = $this->getUser();

        // Get the user we want to edit (if any)
        if (!empty($id)) {
            $user = $this->getUser($id);

            // Verify the current user has access to edit this user
            if (!$this->app['permissions']->isAllowedToManipulate($user, $currentuser)) {
                $this->flashes()->error(Trans::__('You do not have the right privileges to edit that user.'));

                return $this->redirectToRoute('users');
            }
        } else {
            $user = $this->users()->getEmptyUser();
        }

        $enabledoptions = [
            1 => Trans::__('page.edit-users.activated.yes'),
            0 => Trans::__('page.edit-users.activated.no')
        ];

        $roles = array_map(
            function ($role) {
                return $role['label'];
            },
            $this->app['permissions']->getDefinedRoles()
        );

        $form = $this->getUserForm($user, true);

        // New users and the current users don't need to disable themselves
        if ($currentuser['id'] != $id) {
            $form->add(
                'enabled',
                'choice',
                [
                    'choices'     => $enabledoptions,
                    'expanded'    => false,
                    'constraints' => new Assert\Choice(array_keys($enabledoptions)),
                    'label'       => Trans::__('page.edit-users.label.user-enabled'),
                ]
            );
        }

        $form
            ->add(
                'roles',
                'choice',
                [
                    'choices'  => $roles,
                    'expanded' => true,
                    'multiple' => true,
                    'label'    => Trans::__('page.edit-users.label.assigned-roles')
                ]
            )
            ->add(
                'lastseen',
                'text',
                [
                    'disabled' => true,
                    'label'    => Trans::__('page.edit-users.label.last-seen')
                ]
            )
            ->add(
                'lastip',
                'text',
                [
                    'disabled' => true,
                    'label'    => Trans::__('page.edit-users.label.last-ip')
                ]
            );

        // Set the validation
        $form = $this->setUserFormValidation($form, true);

        $form = $form->getForm();

        // Check if the form was POST-ed, and valid. If so, store the user.
        if ($request->isMethod('POST')) {
            $user = $this->validateUserForm($request, $form, false);

            $currentuser = $this->getUser();

            if ($user !== false && $user['id'] === $currentuser['id'] && $user['username'] !== $currentuser['username']) {
                // If the current user changed their own login name, the session is effectively
                // invalidated. If so, we must redirect to the login page with a flash message.
                $this->flashes()->error(Trans::__('page.edit-users.message.change-self'));

                return $this->redirectToRoute('login');
            } elseif ($user !== false) {
                // Return to the 'Edit users' screen.
                return $this->redirectToRoute('users');
            }
        }

        /** @var \Symfony\Component\Form\FormView|\Symfony\Component\Form\FormView[] $formView */
        $formView = $form->createView();

        $manipulatableRoles = $this->app['permissions']->getManipulatableRoles($currentuser);
        foreach ($formView['roles'] as $role) {
            if (!in_array($role->vars['value'], $manipulatableRoles)) {
                $role->vars['attr']['disabled'] = 'disabled';
            }
        }

        $context = [
            'kind'        => empty($id) ? 'create' : 'edit',
            'form'        => $formView,
            'note'        => '',
            'displayname' => $user['displayname'],
        ];

        return $this->render('edituser/edituser.twig', $context);
    }

    /**
     * Create the first user.
     *
     * @param Request $request The Symfony Request
     *
     * @return \Bolt\Response\BoltResponse|\Symfony\Component\HttpFoundation\RedirectResponse
     */
    public function first(Request $request)
    {
        // We should only be here for creating the first user
        if ($this->app['integritychecker']->checkUserTableIntegrity() && $this->users()->hasUsers()) {
            return $this->redirectToRoute('dashboard');
        }

        // Get and empty user array
        $user = $this->users()->getEmptyUser();

        // Add a note, if we're setting up the first user using SQLite.
        $dbdriver = $this->getOption('general/database/driver');
        if ($dbdriver === 'sqlite' || $dbdriver === 'pdo_sqlite') {
            $note = Trans::__('page.edit-users.note-sqlite');
        } else {
            $note = '';
        }

        // If we get here, chances are we don't have the tables set up, yet.
        $this->app['integritychecker']->repairTables();

        // Grant 'root' to first user by default
        $user['roles'] = [Permissions::ROLE_ROOT];

        // Get the form
        $form = $this->getUserForm($user, true);

        // Set the validation
        $form = $this->setUserFormValidation($form, true);

        /** @var \Symfony\Component\Form\Form */
        $form = $form->getForm();

        // Check if the form was POST-ed, and valid. If so, store the user.
        if ($request->isMethod('POST')) {
            if ($user = $this->validateUserForm($request, $form, true)) {
                $this->flashes()->clear();
                $this->flashes()->info(Trans::__('Welcome to your new Bolt site, %USER%.', ['%USER%' => $user['displayname']]));

                $token = $this->app['authentication']->login($user['username'], $user['password']);
                $response = $this->setAuthenticationCookie($this->redirectToRoute('dashboard'), $token);

                return $response;
            }
        }

        $context = [
            'kind'        => 'create',
            'form'        => $form->createView(),
            'note'        => $note,
            'displayname' => $user['displayname'],
            'sitename'    => $this->getOption('general/sitename'),
        ];

        return $this->render('firstuser/firstuser.twig', $context);
    }

    /**
     * Perform modification actions on users.
     *
     * @param string  $action The action
     * @param integer $id     The user ID
     *
     * @return \Symfony\Component\HttpFoundation\RedirectResponse
     */
    public function modify($action, $id)
    {
        if (!$this->checkAntiCSRFToken()) {
            $this->flashes()->info(Trans::__('An error occurred.'));

            return $this->redirectToRoute('users');
        }
        $user = $this->getUser($id);

{'fraction_non_alphanumeric': 0.15572232645403378, 'fraction_numerical': 0.0004414523783246882, 'mean_word_length': 1.7744947948560932, 'pattern_counts': {'":': 0, '<': 11, '<?xml version=': 0, '>': 219, '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': '5915615', 'n_tokens_mistral': 5097, 'n_tokens_neox': 4945, 'n_words': 1077}