<commit_before><?php

namespace Carbon;
use Carbon\Helpers\Serialized;

/**
 * Class Carbon
 * @package Carbon
 *
 * This is CarbonPHP, a simple framework designed to make building robust web
 * applications extremely quick. The following class is the setup for the rest
 * of library. For reference and support visit
 *
 * @link http://www.carbonphp.com/
 */
class Carbon
{
    /**
     * @var bool $safelyExit determines if start application should be executed
     * when running the invoke magic method.
     */
    private $safelyExit = false;


    /** If safely exit is false run startApplication(), otherwise return $safelyExit
     * @link http://php.net/manual/en/language.oop5.magic.php#object.invoke
     * @return bool
     */
    public function __invoke()
    {
        return $this->safelyExit ?: startApplication();
    }

    /**
     * @type $PHP = [
     *       'SITE' => [
     *           'URL' => string '',                                  // Server Url name you do not need to chane in remote development
     *           'ROOT' => string '__FILE__',                         // This was defined in our ../index.php
     *           'ALLOWED_EXTENSIONS' => string 'jpg|png',            // File ending in these extentions will be served
     *           'CONFIG' => string __FILE__,                         // Send to sockets
     *           'TIMEZONE' => string 'America/Chicago',              //  Current timezone TODO - look up php
     *           'TITLE' => string 'Carbon 6',                        // Website title
     *           'VERSION' => string /phpversion(),                   // Add link to symantic versioning
     *           'SEND_EMAIL' => string '',                           // I send emails to validate accounts
     *           'REPLY_EMAIL' => string '',
     *           'BOOTSTRAP' => string '',                            // This file is executed when the startApplication() function is called
     *           'HTTP' => bool true
     *       ],
     *       'DATABASE' => [
     *           'DB_DSN'  => string '',                        // Host and Database get put here
     *           'DB_USER' => string '',
     *           'DB_PASS' => string '',
     *           'DB_BUILD'=> string '',                        // Absolute file path to your database set up file
     *           'REBUILD' => bool false
     *       ],
     *       'SESSION' => [
     *           'REMOTE' => bool true,             // Store the session in the SQL database
     *           'SERIALIZE' => [],                 // These global variables will be stored between session
     *           'CALLBACK' => callable,
     *       'SOCKET' => [
     *           'WEBSOCKETD' => bool false,        // Todo - remove websockets
     *           'PORT' => int 8888,
     *           'DEV' => bool false,
     *           'SSL' => [
     *               'KEY' => string '',
     *               'CERT' => string ''
     *           ]
     *       ],
     *       'ERROR' => [
     *           'LEVEL' => (int) E_ALL | E_STRICT,
     *           'STORE' => (bool) true,                // Database if specified and / or File 'LOCATION' in your system
     *           'SHOW' => (bool) true,                 // Show errors on browser
     *           'FULL' => (bool) true                  // Generate custom stacktrace will high detail - DO NOT set to TRUE in PRODUCTION
     *       ],
     *       'VIEW' => [
     *           'VIEW' => string '/',          // This is where the MVC() function will map the HTML.PHP and HTML.HBS . See Carbonphp.com/mvc
     *          'WRAPPER' => string '',         // View::content() will produce this
     *      ],
     * ]
     */
    public function __construct(array $PHP = [])
    {
        ####################  GENERAL CONF  ######################
        error_reporting($PHP['ERROR']['LEVEL'] ?? E_ALL | E_STRICT);

        ini_set('display_errors', $PHP['ERROR']['SHOW'] ?? true);

        date_default_timezone_set($PHP['SITE']['TIMEZONE'] ?? 'America/Chicago');

        if (!defined('DS')) define('DS', DIRECTORY_SEPARATOR, false);

        define('CARBON_ROOT', dirname(dirname(__FILE__)) . DS);

        if (!defined('SERVER_ROOT')) define('SERVER_ROOT', CARBON_ROOT);

        define('REPORTS', $PHP['ERROR']['LOCATION'] ?? SERVER_ROOT);

        #####################   AUTOLOAD    #######################
        if (!array_key_exists('AUTOLOAD', $PHP) || $PHP['AUTOLOAD']) {

            $PSR4 = include_once CARBON_ROOT . 'Structure/AutoLoad.php';

            if (is_array($PHP['AUTOLOAD'] ?? false))
                foreach ($PHP['AUTOLOAD'] as $name => $path)
                    $PSR4->addNamespace($name, $path);
        }

        #####################   ERRORS    #######################
        // TODO - debating on removing the start and attempting to catch our own errors. look into later
        Error\ErrorCatcher::$defaultLocation = REPORTS . 'Log_' . ($_SESSION['id'] ?? '') . '_' . time() . '.log';
        Error\ErrorCatcher::$fullReports = $PHP['ERROR']['STORE'] ?? false;
        Error\ErrorCatcher::$printToScreen = $PHP['ERROR']['SHOW'] ?? true;
        Error\ErrorCatcher::$storeReport = $PHP['ERROR']['FULL'] ?? true;
        Error\ErrorCatcher::$level = $PHP['ERROR']['LEVEL'] ?? ' E_ALL | E_STRICT';
        Error\ErrorCatcher::start();            // Catch application errors and alerts

        // More cache control is given in the .htaccess File
        Request::setHeader('Cache-Control:  must-revalidate');

        #################   SOCKET AND SYNC    #######################
        if (!\defined('SOCKET')) {

            \define('SOCKET', false);

            if (($PHP['SOCKET'] ?? false) && getservbyport($PHP['SOCKET']['PORT'] ?? 8888, 'tcp')) {
                $path = CARBON_ROOT . ($PHP['SOCKET']['WEBSOCKETD'] ?? false ?
                            'Extras' . DS . 'Websocketd.php' :
                            'Structure' . DS . 'Server.php');

                $config = $PHP['SITE']['CONFIG'] ?? SERVER_ROOT;

                $CMD = '/usr/local/bin/websocketd --port=' . ($PHP['SOCKET']['PORT'] ?? 8888) . ' ' .
                    (($PHP['SOCKET']['DEV'] ?? false) ? '--devconsole ' : '') .
                    (($PHP['SOCKET']['SSL'] ?? false) ? "--ssl --sslkey={$PHP['SOCKET']['SSL']['KEY']} --sslcert={$PHP['SOCKET']['SSL']['CERT']} " : ' ') .
                    "php $path " . SERVER_ROOT . ' ' . $config . ' 2>&1';

                Helpers\Fork::become_daemon(function () use ($CMD) {
                    `$CMD`;
                });
            }
        }

        #################  DATABASE  ########################
        if ($PHP['DATABASE'] ?? false) {
            Database::$dsn = $PHP['DATABASE']['DB_DSN'] ?? '';
            Database::$username = $PHP['DATABASE']['DB_USER'] ?? '';
            Database::$password = $PHP['DATABASE']['DB_PASS'] ?? '';
            Database::$setup = $PHP['DATABASE']['DB_BUILD'] ?? '';
        }

        ##################  VALIDATE URL / URI ##################
        // Even if a request is bad, we need to store the log
        define('LOCAL_SERVER', self::isClientServer());

        if (!LOCAL_SERVER) self::IP_FILTER();

        $this->URI_FILTER($PHP['SITE']['URL'] ?? '', $PHP['SITE']['ALLOWED_EXTENSIONS'] ?? '');

        if ($PHP['DATABASE']['REBUILD'] ?? false)
            Database::setUp(false);   // redirect = false

        #################  SITE  ########################
        if ($PHP['SITE'] ?? false) {
            \define('BOOTSTRAP', SERVER_ROOT . $PHP['SITE']['BOOTSTRAP'] ?? '');          // Routing file

            \define('SITE_TITLE', $PHP['SITE']['TITLE'] ?? 'CarbonPHP');                     // Carbon doesnt use

            \define('SITE_VERSION', $PHP['SITE']['VERSION'] ?? PHP_VERSION);                // printed in the footer

            \define('SYSTEM_EMAIL', $PHP['SEND_EMAIL'] ?? '');                               // server email system

            \define('REPLY_EMAIL', $PHP['REPLY_EMAIL'] ?? '');                               // I give you options :P
        }

        #######################   Pjax Ajax Refresh  ######################
        // Must return a non empty value
        \define('PJAX', isset($_GET['_pjax']) || (isset($_SERVER['HTTP_X_PJAX']) && $_SERVER['HTTP_X_PJAX']));

        // (PJAX == true) return required, else (!PJAX && AJAX) return optional (socket valid)
        \define('AJAX', PJAX || (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest'));<commit_msg>optimizations... I probably broke everything<commit_after><?php

namespace Carbon;
use Carbon\Helpers\Serialized;

/**
 * Class Carbon
 * @package Carbon
 *
 * This is CarbonPHP, a simple framework designed to make building robust web
 * applications extremely quick. The following class is the setup for the rest
 * of library. For reference and support visit
 *
 * @link http://www.carbonphp.com/
 */
class Carbon
{
    /**
     * @var bool $safelyExit determines if start application should be executed
     * when running the invoke magic method.
     */
    private $safelyExit = false;


    /** If safely exit is false run startApplication(), otherwise return $safelyExit
     * @link http://php.net/manual/en/language.oop5.magic.php#object.invoke
     * @return bool
     */
    public function __invoke()
    {
        return $this->safelyExit ?: startApplication();
    }

    /**
     * @type $PHP = [
     *       'AUTOLOAD' => []                       // Provide PSR-4 namespace roots
     *       'SITE' => [
     *           'URL' => string '',                                  // Server Url name you do not need to chane in remote development
     *           'ROOT' => string '__FILE__',                         // This was defined in our ../index.php
     *           'ALLOWED_EXTENSIONS' => string 'jpg|png',            // File ending in these extentions will be served
     *           'CONFIG' => string __FILE__,                         // Send to sockets
     *           'TIMEZONE' => string 'America/Chicago',              //  Current timezone TODO - look up php
     *           'TITLE' => string 'Carbon 6',                        // Website title
     *           'VERSION' => string /phpversion(),                   // Add link to symantic versioning
     *           'SEND_EMAIL' => string '',                           // I send emails to validate accounts
     *           'REPLY_EMAIL' => string '',
     *           'BOOTSTRAP' => string '',                            // This file is executed when the startApplication() function is called
     *           'HTTP' => bool true
     *       ],
     *       'DATABASE' => [
     *           'DB_DSN'  => string '',                        // Host and Database get put here
     *           'DB_USER' => string '',
     *           'DB_PASS' => string '',
     *           'DB_BUILD'=> string '',                        // Absolute file path to your database set up file
     *           'REBUILD' => bool false
     *       ],
     *       'SESSION' => [
     *           'REMOTE' => bool true,             // Store the session in the SQL database
     *           'SERIALIZE' => [],                 // These global variables will be stored between session
     *           'CALLBACK' => callable,
     *       'SOCKET' => [
     *           'WEBSOCKETD' => bool false,        // Todo - remove websockets
     *           'PORT' => int 8888,
     *           'DEV' => bool false,
     *           'SSL' => [
     *               'KEY' => string '',
     *               'CERT' => string ''
     *           ]
     *       ],
     *       'ERROR' => [
     *           'LEVEL' => (int) E_ALL | E_STRICT,
     *           'STORE' => (bool) true,                // Database if specified and / or File 'LOCATION' in your system
     *           'SHOW' => (bool) true,                 // Show errors on browser
     *           'FULL' => (bool) true                  // Generate custom stacktrace will high detail - DO NOT set to TRUE in PRODUCTION
     *       ],
     *       'VIEW' => [
     *           'VIEW' => string '/',          // This is where the MVC() function will map the HTML.PHP and HTML.HBS . See Carbonphp.com/mvc
     *          'WRAPPER' => string '',         // View::content() will produce this
     *      ],
     * ]
     */
    public function __construct(array $PHP = [])
    {
        ####################  GENERAL CONF  ######################
        error_reporting($PHP['ERROR']['LEVEL'] ?? E_ALL | E_STRICT);

        ini_set('display_errors', $PHP['ERROR']['SHOW'] ?? true);

        date_default_timezone_set($PHP['SITE']['TIMEZONE'] ?? 'America/Chicago');

        if (!\defined('DS')) {
            \define('DS', DIRECTORY_SEPARATOR);
        }

        \define('CARBON_ROOT', \dirname(__FILE__, 2) . DS);

        if (!\defined('SERVER_ROOT')) define('SERVER_ROOT', CARBON_ROOT);

        \define('REPORTS', $PHP['ERROR']['LOCATION'] ?? SERVER_ROOT);

        #####################   AUTOLOAD    #######################
        if (!array_key_exists('AUTOLOAD', $PHP) || $PHP['AUTOLOAD']) {

            $PSR4 = include CARBON_ROOT . 'Structure/AutoLoad.php';

            if (\is_array($PHP['AUTOLOAD'] ?? false)) {
                foreach ($PHP['AUTOLOAD'] as $name => $path) {
                    $PSR4->addNamespace($name, $path);
                }
            }
        }

        #####################   ERRORS    #######################
        // TODO - debating on removing the start and attempting to catch our own errors. look into later
        Error\ErrorCatcher::$defaultLocation = REPORTS . 'Log_' . ($_SESSION['id'] ?? '') . '_' . time() . '.log';
        Error\ErrorCatcher::$fullReports = $PHP['ERROR']['STORE'] ?? false;
        Error\ErrorCatcher::$printToScreen = $PHP['ERROR']['SHOW'] ?? true;
        Error\ErrorCatcher::$storeReport = $PHP['ERROR']['FULL'] ?? true;
        Error\ErrorCatcher::$level = $PHP['ERROR']['LEVEL'] ?? ' E_ALL | E_STRICT';
        Error\ErrorCatcher::start();            // Catch application errors and alerts

        // More cache control is given in the .htaccess File
        Request::setHeader('Cache-Control:  must-revalidate');

        #################   SOCKET AND SYNC    #######################
        if (!\defined('SOCKET')) {

            \define('SOCKET', false);

            if (($PHP['SOCKET'] ?? false) && getservbyport($PHP['SOCKET']['PORT'] ?? 8888, 'tcp')) {
                $path = CARBON_ROOT . ($PHP['SOCKET']['WEBSOCKETD'] ?? false ?
                            'Extras' . DS . 'Websocketd.php' :
                            'Structure' . DS . 'Server.php');

                $config = $PHP['SITE']['CONFIG'] ?? SERVER_ROOT;

                $CMD = '/usr/local/bin/websocketd --port=' . ($PHP['SOCKET']['PORT'] ?? 8888) . ' ' .
                    (($PHP['SOCKET']['DEV'] ?? false) ? '--devconsole ' : '') .
                    (($PHP['SOCKET']['SSL'] ?? false) ? "--ssl --sslkey={$PHP['SOCKET']['SSL']['KEY']} --sslcert={$PHP['SOCKET']['SSL']['CERT']} " : ' ') .
                    "php $path " . SERVER_ROOT . ' ' . $config . ' 2>&1';

                Helpers\Fork::become_daemon(function () use ($CMD) {`$CMD`;});
            }
        }

        #################  DATABASE  ########################
        if ($PHP['DATABASE'] ?? false) {
            Database::$dsn = $PHP['DATABASE']['DB_DSN'] ?? '';
            Database::$username = $PHP['DATABASE']['DB_USER'] ?? '';
            Database::$password = $PHP['DATABASE']['DB_PASS'] ?? '';
            Database::$setup = $PHP['DATABASE']['DB_BUILD'] ?? '';
        }

        ##################  VALIDATE URL / URI ##################
        // Even if a request is bad, we need to store the log
        \define('LOCAL_SERVER', $this->isClientServer());

        if (!LOCAL_SERVER) $this->IP_FILTER();

        $this->URI_FILTER($PHP['SITE']['URL'] ?? '', $PHP['SITE']['ALLOWED_EXTENSIONS'] ?? '');

        if ($PHP['DATABASE']['REBUILD'] ?? false)
            Database::setUp(false);   // redirect = false

        #################  SITE  ########################
        if ($PHP['SITE'] ?? false) {
            \define('BOOTSTRAP', SERVER_ROOT . $PHP['SITE']['BOOTSTRAP'] ?? '');          // Routing file

            \define('SITE_TITLE', $PHP['SITE']['TITLE'] ?? 'CarbonPHP');                     // Carbon doesnt use

            \define('SITE_VERSION', $PHP['SITE']['VERSION'] ?? PHP_VERSION);                // printed in the footer

            \define('SYSTEM_EMAIL', $PHP['SEND_EMAIL'] ?? '');                               // server email system

            \define('REPLY_EMAIL', $PHP['REPLY_EMAIL'] ?? '');                               // I give you options :P
        }

        #######################   Pjax Ajax Refresh  ######################
        // Must return a non empty value
        \define('PJAX', isset($_GET['_pjax']) || (isset($_SERVER['HTTP_X_PJAX']) && $_SERVER['HTTP_X_PJAX']));

        // (PJAX == true) return required, else (!PJAX && AJAX) return optional (socket valid)
        \define('AJAX', PJAX || (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest'));
{'fraction_non_alphanumeric': 0.1936957779063042, 'fraction_numerical': 0.002197802197802198, 'mean_word_length': 1.8147484942210645, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 90, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 2}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 14, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3668123', 'n_tokens_mistral': 4949, 'n_tokens_neox': 4745, 'n_words': 1122}