<commit_before><?php

class PicoAdmin extends AbstractPicoPlugin
{
    protected $dependsOn = array('PicoSession');

    protected $session;

    protected $modules = array();

    protected $requestModule;
    protected $requestAction;
    protected $requestPayload;

    protected $authenticated = false;
    protected $authenticationRequired = false;

    protected $adminThemeUrl;

    /**
     * Loads built-in admin modules as Pico plugins
     *
     * @see DummyPlugin::onPluginsLoaded()
     */
    public function onPluginsLoaded(array &$plugins)
    {
        // require >= Pico 2.0; Pico::VERSION wasn't defined before Pico 2.0
        if (!defined('Pico::VERSION')) {
            $this->setEnabled(false);
            return;
        }

        // load built-in admin module PicoContentAdmin
        require_once(__DIR__ . '/PicoContentAdmin.php');
        $this->loadPlugin(new PicoContentAdmin($this->getPico()));
    }

    /**
     * Bootstrap the plugin's default configuration
     *
     * @see DummyPlugin::onConfigLoaded()
     */
    public function onConfigLoaded(array &$config)
    {
        $defaultPluginConfig = array(
            'url' => 'admin',
            'auth_token' => ''
        );

        if (!isset($config['PicoAdmin']) || !is_array($config['PicoAdmin'])) {
            $config['PicoAdmin'] = $defaultPluginConfig;
            return;
        }

        $config['PicoAdmin'] += $defaultPluginConfig;
        if (!$config['PicoAdmin']['url']) {
            $config['PicoAdmin']['url'] = $defaultPluginConfig['url'];
        } else {
            $config['PicoAdmin']['url'] = trim($config['PicoAdmin']['url'], '/');
        }
    }

    public function onSessionInit(PicoSession $session, &$pluginsReadOnly, &$plugins)
    {
        $this->session = $session;
        $plugins['PicoAdmin'] = $this;
    }

    public function onRequestUrl(&$url)
    {
        $adminUrlPrefix = $this->getPluginConfig('url');
        $adminUrlRegex = '#^' . preg_quote($adminUrlPrefix, '#') . '(?:/(\w+)(?:/(\w+)(?:/(.+))?)?)?$#';
        if (preg_match($adminUrlRegex, $url, $adminUrlMatches)) {
            $this->requestModule = isset($adminUrlMatches[1]) ? $adminUrlMatches[1] : '';
            $this->requestAction = isset($adminUrlMatches[2]) ? $adminUrlMatches[2] : '';
            $this->requestPayload = isset($adminUrlMatches[3]) ? $adminUrlMatches[3] : '';

            $this->triggerEvent('onAdminInitializing', array($this, &$this->modules));

            $this->handleAdminRequest();
            $this->handleAuthentication();

            $this->triggerEvent('onAdminInitialized');
            return;
        }

        // the user wasn't requesting a page of this plugin
        $this->setEnabled(false);
    }

    protected function handleAdminRequest()
    {
        $authToken = $this->getPluginConfig('auth_token');
        if (!$authToken) {
            // force info screen when no auth token is configured
            $this->requestModule = 'info';
            $this->requestAction = $this->requestPayload = '';
        } elseif (!$this->requestModule) {
            // when only a single module is registered, redirect to the main page of this module
            if (count($this->modules) === 1) {
                foreach ($this->modules as $moduleName => $module) {
                    header('307 Temporary Redirect');
                    header('Location: ' . $this->getAdminPageUrl($moduleName));
                    die();
                }
            }

            // show built-in landing page when no specific module was requested
            // landing page requires authentication, therefore non-authenticated users will end up on the login page
            $this->requestModule = 'landing';
            $this->authenticationRequired = true;
        }

        $this->triggerEvent('onAdminRequest', array(
            &$this->requestModule,
            &$this->requestAction,
            &$this->requestPayload
        ));
    }

    protected function handleAuthentication()
    {
        // check auth token
        $authToken = $this->getPluginConfig('auth_token');
        if ($authToken) {
            if (isset($_REQUEST['logout'])) {
                // perform logout
                $this->authenticated = false;

                if ($this->session->get('PicoAdmin', 'authenticated')) {
                    $this->session->migrateSession();
                    $this->session->set('PicoAdmin', 'authenticated', false);
                }
            } elseif (isset($_POST['password'])) {
                // verify password
                $this->authenticated = password_verify((string) $_POST['password'], $authToken);

                if ($this->authenticated !== $this->session->get('PicoAdmin', 'authenticated')) {
                    $this->session->migrateSession();
                    $this->session->set('PicoAdmin', 'authenticated', $this->authenticated);
                }
            } else {
                // already authenticated session
                $this->authenticated = (bool) $this->session->get('PicoAdmin', 'authenticated');
            }

            $this->session->close('PicoAdmin');
        }

        $this->triggerEvent('onAdminAuthentication', array(
            &$this->authenticationRequired,
            &$this->authenticated
        ));

        if ($this->authenticationRequired && !$this->authenticated) {
            // force login screen when authentication was requested, but user isn't authenticated
            // admin modules which require authentication MUST disable themselves in this case!<commit_msg>Improve session authentication handling<commit_after><?php

class PicoAdmin extends AbstractPicoPlugin
{
    protected $dependsOn = array('PicoSession');

    protected $session;

    protected $modules = array();

    protected $requestModule;
    protected $requestAction;
    protected $requestPayload;

    protected $authenticated = false;
    protected $authenticationRequired = false;

    protected $adminThemeUrl;

    /**
     * Loads built-in admin modules as Pico plugins
     *
     * @see DummyPlugin::onPluginsLoaded()
     */
    public function onPluginsLoaded(array &$plugins)
    {
        // require >= Pico 2.0; Pico::VERSION wasn't defined before Pico 2.0
        if (!defined('Pico::VERSION')) {
            $this->setEnabled(false);
            return;
        }

        // load built-in admin module PicoContentAdmin
        require_once(__DIR__ . '/PicoContentAdmin.php');
        $this->loadPlugin(new PicoContentAdmin($this->getPico()));
    }

    /**
     * Bootstrap the plugin's default configuration
     *
     * @see DummyPlugin::onConfigLoaded()
     */
    public function onConfigLoaded(array &$config)
    {
        $defaultPluginConfig = array(
            'url' => 'admin',
            'auth_token' => ''
        );

        if (!isset($config['PicoAdmin']) || !is_array($config['PicoAdmin'])) {
            $config['PicoAdmin'] = $defaultPluginConfig;
            return;
        }

        $config['PicoAdmin'] += $defaultPluginConfig;
        if (!$config['PicoAdmin']['url']) {
            $config['PicoAdmin']['url'] = $defaultPluginConfig['url'];
        } else {
            $config['PicoAdmin']['url'] = trim($config['PicoAdmin']['url'], '/');
        }
    }

    public function onSessionInit(PicoSession $session, &$pluginsReadOnly, &$plugins)
    {
        $this->session = $session;
        $plugins['PicoAdmin'] = $this;
    }

    public function onRequestUrl(&$url)
    {
        $adminUrlPrefix = $this->getPluginConfig('url');
        $adminUrlRegex = '#^' . preg_quote($adminUrlPrefix, '#') . '(?:/(\w+)(?:/(\w+)(?:/(.+))?)?)?$#';
        if (preg_match($adminUrlRegex, $url, $adminUrlMatches)) {
            $this->requestModule = isset($adminUrlMatches[1]) ? $adminUrlMatches[1] : '';
            $this->requestAction = isset($adminUrlMatches[2]) ? $adminUrlMatches[2] : '';
            $this->requestPayload = isset($adminUrlMatches[3]) ? $adminUrlMatches[3] : '';

            $this->triggerEvent('onAdminInitializing', array($this, &$this->modules));

            $this->handleAdminRequest();
            $this->handleAuthentication();

            $this->triggerEvent('onAdminInitialized');
            return;
        }

        // the user wasn't requesting a page of this plugin
        $this->setEnabled(false);
    }

    protected function handleAdminRequest()
    {
        $authToken = $this->getPluginConfig('auth_token');
        if (!$authToken) {
            // force info screen when no auth token is configured
            $this->requestModule = 'info';
            $this->requestAction = $this->requestPayload = '';
        } elseif (!$this->requestModule) {
            // when only a single module is registered, redirect to the main page of this module
            if (count($this->modules) === 1) {
                foreach ($this->modules as $moduleName => $module) {
                    header('307 Temporary Redirect');
                    header('Location: ' . $this->getAdminPageUrl($moduleName));
                    die();
                }
            }

            // show built-in landing page when no specific module was requested
            // landing page requires authentication, therefore non-authenticated users will end up on the login page
            $this->requestModule = 'landing';
            $this->authenticationRequired = true;
        }

        $this->triggerEvent('onAdminRequest', array(
            &$this->requestModule,
            &$this->requestAction,
            &$this->requestPayload
        ));
    }

    protected function handleAuthentication()
    {
        // check auth token
        $authToken = $this->getPluginConfig('auth_token');
        if ($authToken) {
            if (isset($_REQUEST['logout'])) {
                // perform logout
                $this->authenticated = false;

                $this->session->set('PicoAdmin', 'authenticated', false);
                $this->session->migrateSession();
            } elseif (isset($_POST['password'])) {
                // verify password
                $this->authenticated = password_verify((string) $_POST['password'], $authToken);

                $this->session->migrateSession();
                $this->session->set('PicoAdmin', 'authenticated', $this->authenticated);
            } else {
                // already authenticated session
                $this->authenticated = (bool) $this->session->get('PicoAdmin', 'authenticated');
            }

            $this->session->close('PicoAdmin');
        }

        $this->triggerEvent('onAdminAuthentication', array(
            &$this->authenticationRequired,
            &$this->authenticated
        ));

        if ($this->authenticationRequired && !$this->authenticated) {
            // force login screen when authentication was requested, but the user isn't authenticated
            // admin modules which require authentication MUST disable themselves in this case!
{'fraction_non_alphanumeric': 0.14230107721553362, 'fraction_numerical': 0.002534624785009505, 'mean_word_length': 2.198610306890562, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 116, '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': '2813555', 'n_tokens_mistral': 2954, 'n_tokens_neox': 2817, 'n_words': 600}