<?php

/**
 * CodeIgniter
 *
 * An open source application development framework for PHP
 *
 * This content is released under the MIT License (MIT)
 *
 * Copyright (c) 2014-2019 British Columbia Institute of Technology
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 *
 * @package    CodeIgniter
 * @author     CodeIgniter Dev Team
 * @copyright  2014-2019 British Columbia Institute of Technology (https://bcit.ca/)
 * @license    https://opensource.org/licenses/MIT	MIT License
 * @link       https://codeigniter.com
 * @since      Version 3.0.0
 * @filesource
 */

namespace CodeIgniter\Debug;

/**
 * Class Timer
 *
 * Provides a simple way to measure the amount of time
 * that elapses between two points.
 *
 * NOTE: All methods are static since the class is intended
 * to measure throughout an entire application's life cycle.
 *
 * @package CodeIgniter\Benchmark
 */
class Timer
{

	/**
	 * List of all timers.
	 *
	 * @var array
	 */
	protected $timers = [];

	//--------------------------------------------------------------------

	/**
	 * Starts a timer running.
	 *
	 * Multiple calls can be made to this method so that several
	 * execution points can be measured.
	 *
	 * @param string $name The name of this timer.
	 * @param float  $time Allows user to provide time.
	 *
	 * @return Timer
	 */
	public function start(string $name, float $time = null)
	{
		$this->timers[strtolower($name)] = [
			'start' => ! empty($time) ? $time : microtime(true),
			'end'   => null,
		];

		return $this;
	}

	//--------------------------------------------------------------------

	/**
	 * Stops a running timer.
	 *
	 * If the timer is not stopped before the timers() method is called,
	 * it will be automatically stopped at that point.
	 *
	 * @param string $name The name of this timer.
	 *
	 * @return Timer
	 */
	public function stop(string $name)
	{
		$name = strtolower($name);

		if (empty($this->timers[$name]))
		{
			throw new \RuntimeException('Cannot stop timer: invalid name given.');
		}

		$this->timers[$name]['end'] = microtime(true);

		return $this;
	}

	//--------------------------------------------------------------------

	/**
	 * Returns the duration of a recorded timer.
	 *
	 * @param string  $name     The name of the timer.
	 * @param integer $decimals Number of decimal places.
	 *
	 * @return null|float       Returns null if timer exists by that name.
	 *                          Returns a float representing the number of
	 *                          seconds elapsed while that timer was running.
	 */
	public function getElapsedTime(string $name, int $decimals = 4)
	{
		$name = strtolower($name);

		if (empty($this->timers[$name]))
		{
			return null;
		}

		$timer = $this->timers[$name];

		if (empty($timer['end']))
		{
			$timer['end'] = microtime(true);
		}

		return (float) number_format($timer['end'] - $timer['start'], $decimals);
	}

	//--------------------------------------------------------------------

	/**
	 * Returns the array of timers, with the duration pre-calculated for you.
	 *
	 * @param integer $decimals Number of decimal places
	 *
	 * @return array
	 */
	public function getTimers(int $decimals = 4): array
	{
		$timers = $this->timers;

		foreach ($timers as &$timer)
		{
			if (empty($timer['end']))
			{
				$timer['end'] = microtime(true);
			}

			$timer['duration'] = (float) number_format($timer['end'] - $timer['start'], $decimals);
		}

		return $timers;
	}

	//--------------------------------------------------------------------

	/**
	 * Checks whether or not a timer with the specified name exists.
	 *
	 * @param string $name
	 *
	 * @return boolean
	 */
	public function has(string $name): bool
	{
		return array_key_exists(strtolower($name), $this->timers);
	}

	//--------------------------------------------------------------------
}


<?php

/**
 * CodeIgniter
 *
 * An open source application development framework for PHP
 *
 * This content is released under the MIT License (MIT)
 *
 * Copyright (c) 2014-2019 British Columbia Institute of Technology
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 *
 * @package    CodeIgniter
 * @author     CodeIgniter Dev Team
 * @copyright  2014-2019 British Columbia Institute of Technology (https://bcit.ca/)
 * @license    https://opensource.org/licenses/MIT	MIT License
 * @link       https://codeigniter.com
 * @since      Version 3.0.0
 * @filesource
 */

namespace CodeIgniter\Database;

use CodeIgniter\Events\Events;
use CodeIgniter\Database\Exceptions\DatabaseException;

/**
 * Class BaseConnection
 */
abstract class BaseConnection implements ConnectionInterface
{

	/**
	 * Data Source Name / Connect string
	 *
	 * @var string
	 */
	protected $DSN;

	/**
	 * Database port
	 *
	 * @var integer
	 */
	protected $port = '';

	/**
	 * Hostname
	 *
	 * @var string
	 */
	protected $hostname;

	/**
	 * Username
	 *
	 * @var string
	 */
	protected $username;

	/**
	 * Password
	 *
	 * @var string
	 */
	protected $password;

	/**
	 * Database name
	 *
	 * @var string
	 */
	protected $database;

	/**
	 * Database driver
	 *
	 * @var string
	 */
	protected $DBDriver = 'MySQLi';

	/**
	 * Sub-driver
	 *
	 * @used-by CI_DB_pdo_driver
	 * @var     string
	 */
	protected $subdriver;

	/**
	 * Table prefix
	 *
	 * @var string
	 */
	protected $DBPrefix = '';

	/**
	 * Persistent connection flag
	 *
	 * @var boolean
	 */
	protected $pConnect = false;

	/**
	 * Debug flag
	 *
	 * Whether to display error messages.
	 *
	 * @var boolean
	 */
	protected $DBDebug = false;

	/**
	 * Should we cache results?
	 *
	 * @var boolean
	 */
	protected $cacheOn = false;

	/**
	 * Path to store cache files.
	 *
	 * @var string
	 */
	protected $cacheDir;

	/**
	 * Character set
	 *
	 * @var string
	 */
	protected $charset = 'utf8';

	/**
	 * Collation
	 *
	 * @var string
	 */
	protected $DBCollat = 'utf8_general_ci';

	/**
	 * Swap Prefix
	 *
	 * @var string
	 */
	protected $swapPre = '';

	/**
	 * Encryption flag/data
	 *
	 * @var mixed
	 */
	protected $encrypt = false;

	/**
	 * Compression flag
	 *
	 * @var boolean
	 */
	protected $compress = false;

	/**
	 * Strict ON flag
	 *
	 * Whether we're running in strict SQL mode.
	 *
	 * @var boolean
	 */
	protected $strictOn;

	/**
	 * Settings for a failover connection.
	 *
	 * @var array
	 */
	protected $failover = [];

	//--------------------------------------------------------------------

	/**
	 * The last query object that was executed
	 * on this connection.
	 *
	 * @var array
	 */
	protected $lastQuery;

	/**
	 * Connection ID
	 *
	 * @var object|resource
	 */
	public $connID = false;

	/**
	 * Result ID
	 *
	 * @var object|resource
	 */
	public $resultID = false;

	/**
	 * Protect identifiers flag
	 *
	 * @var boolean
	 */
	public $protectIdentifiers = true;

	/**
	 * List of reserved identifiers
	 *
	 * Identifiers that must NOT be escaped.
	 *
	 * @var array
	 */
	protected $reservedIdentifiers = ['*'];

	/**
	 * Identifier escape character
	 *
	 * @var string
	 */
	public $escapeChar = '"';

	/**
	 * ESCAPE statement string
	 *
	 * @var string
	 */
	public $likeEscapeStr = " ESCAPE '%s' ";

	/**
	 * ESCAPE character
	 *
	 * @var string
	 */
	public $likeEscapeChar = '!';

	/**
	 * Holds previously looked up data
	 * for performance reasons.
	 *
	 * @var array
	 */
	public $dataCache = [];

	/**
	 * Microtime when connection was made
	 *
	 * @var float
	 */
	protected $connectTime;

	/**
	 * How long it took to establish connection.
	 *
	 * @var float
	 */
	protected $connectDuration;

	/**
	 * If true, no queries will actually be
	 * ran against the database.
	 *
	 * @var boolean
	 */
	protected $pretend = false;

	/**
	 * Transaction enabled flag
	 *
	 * @var boolean
	 */
	public $transEnabled = true;

	/**
	 * Strict transaction mode flag
	 *
	 * @var boolean
	 */
	public $transStrict = true;

	/**
	 * Transaction depth level
	 *
	 * @var integer
	 */
	protected $transDepth = 0;

	/**
	 * Transaction status flag
	 *
	 * Used with transactions to determine if a rollback should occur.
	 *
	 * @var boolean
	 */
	protected $transStatus = true;

	/**
	 * Transaction failure flag
	 *
	 * Used with transactions to determine if a transaction has failed.
	 *
	 * @var boolean
	 */
	protected $transFailure = false;

	/**
	 * Array of table aliases.
	 *
	 * @var array
	 */
	protected $aliasedTables = [];

	//--------------------------------------------------------------------

	/**
	 * Saves our connection settings.
	 *
	 * @param array $params
	 */
	public function __construct(array $params)
	{
		foreach ($params as $key => $value)
		{
			if (property_exists($this, $key))
			{
				$this->$key = $value;
			}
		}
	}

	//--------------------------------------------------------------------

	/**
	 * Initializes the database connection/settings.
	 *
	 * @return mixed|void
	 * @throws \CodeIgniter\Database\Exceptions\DatabaseException
	 */
	public function initialize()
	{
		/* If an established connection is available, then there's
		 * no need to connect and select the database.
		 *
		 * Depending on the database driver, conn_id can be either
		 * boolean TRUE, a resource or an object.
		 */
		if ($this->connID)
		{
			return;
		}

		//--------------------------------------------------------------------

		$this->connectTime = microtime(true);

		// Connect to the database and set the connection ID
		$this->connID = $this->connect($this->pConnect);

		// No connection resource? Check if there is a failover else throw an error
		if (! $this->connID)
		{
			// Check if there is a failover set
			if (! empty($this->failover) && is_array($this->failover))
			{
				// Go over all the failovers
				foreach ($this->failover as $failover)
				{
					// Replace the current settings with those of the failover
					foreach ($failover as $key => $val)
					{
						if (property_exists($this, $key))
						{
							$this->$key = $val;
						}
					}

					// Try to connect
					$this->connID = $this->connect($this->pConnect);

					// If a connection is made break the foreach loop
					if ($this->connID)
					{
						break;
					}
				}
			}

			// We still don't have a connection?
			if (! $this->connID)
			{
				throw new DatabaseException('Unable to connect to the database.');
			}
		}

		$this->connectDuration = microtime(true) - $this->connectTime;
	}

	//--------------------------------------------------------------------

	/**
	 * Connect to the database.
	 *
	 * @param  boolean $persistent
	 * @return mixed
	 */
	abstract public function connect(bool $persistent = false);

	//--------------------------------------------------------------------

	/**
	 * Close the database connection.
	 *
	 * @return void
	 */
	public function close()
	{
		if ($this->connID)
		{
			$this->_close();
			$this->connID = false;
		}
	}

	//--------------------------------------------------------------------

	/**
	 * Platform dependent way method for closing the connection.
	 *
	 * @return mixed
	 */
	abstract protected function _close();

	//--------------------------------------------------------------------

	/**
	 * Create a persistent database connection.
	 *
	 * @return mixed
	 */
	public function persistentConnect()
	{
		return $this->connect(true);
	}

	//--------------------------------------------------------------------

	/**
	 * Keep or establish the connection if no queries have been sent for
	 * a length of time exceeding the server's idle timeout.
	 *
	 * @return mixed
	 */
	abstract public function reconnect();

	//--------------------------------------------------------------------

	/**
	 * Returns the actual connection object. If both a 'read' and 'write'
	 * connection has been specified, you can pass either term in to
	 * get that connection. If you pass either alias in and only a single
	 * connection is present, it must return the sole connection.
	 *
	 * @param string|null $alias
	 *
	 * @return mixed
	 */
	public function getConnection(string $alias = null)
	{
		//@todo work with read/write connections
		return $this->connID;
	}

	//--------------------------------------------------------------------

	/**
	 * Select a specific database table to use.
	 *
	 * @param string $databaseName
	 *
	 * @return mixed
	 */
	abstract public function setDatabase(string $databaseName);

	//--------------------------------------------------------------------

	/**
	 * Returns the name of the current database being used.
	 *
	 * @return string
	 */
	public function getDatabase(): string
	{
		return empty($this->database) ? '' : $this->database;
	}

	//--------------------------------------------------------------------

	/**
	 * Returns the last error encountered by this connection.
	 *
	 * @return mixed
	 */
	public function getError()
	{
	}

	//--------------------------------------------------------------------

	/**
	 * The name of the platform in use (MySQLi, mssql, etc)
	 *
	 * @return string
	 */
	public function getPlatform(): string
	{
		return $this->DBDriver;
	}

	//--------------------------------------------------------------------

	/**
	 * Returns a string containing the version of the database being used.
	 *
	 * @return string
	 */
	abstract public function getVersion(): string;

	//--------------------------------------------------------------------

	/**
	 * Sets the Table Aliases to use. These are typically
	 * collected during use of the Builder, and set here
	 * so queries are built correctly.
	 *
	 * @param array $aliases
	 *
	 * @return $this
	 */
	public function setAliasedTables(array $aliases)
	{
		$this->aliasedTables = $aliases;

		return $this;
	}

	//--------------------------------------------------------------------

	/**
	 * Add a table alias to our list.
	 *
	 * @param string $table
	 *
	 * @return $this
	 */
	public function addTableAlias(string $table)
	{
		if (! in_array($table, $this->aliasedTables))
		{
			$this->aliasedTables[] = $table;
		}

		return $this;
	}

	/**
	 * Executes the query against the database.
	 *
	 * @param $sql
	 *
	 * @return mixed
	 */
	abstract protected function execute(string $sql);

	//--------------------------------------------------------------------

	/**
	 * Orchestrates a query against the database. Queries must use
	 * Database\Statement objects to store the query and build it.
	 * This method works with the cache.
	 *
	 * Should automatically handle different connections for read/write
	 * queries if needed.
	 *
	 * @param string  $sql
	 * @param mixed   ...$binds
	 * @param boolean $setEscapeFlags
	 * @param string  $queryClass
	 *
	 * @return BaseResult|Query|false
	 */
	public function query(string $sql, $binds = null, bool $setEscapeFlags = true, string $queryClass = 'CodeIgniter\\Database\\Query')
	{
		if (empty($this->connID))
		{
			$this->initialize();
		}

		$resultClass = str_replace('Connection', 'Result', get_class($this));
		/**
		 * @var Query $query
		 */
		$query = new $queryClass($this);

		$query->setQuery($sql, $binds, $setEscapeFlags);

		if (! empty($this->swapPre) && ! empty($this->DBPrefix))
		{
			$query->swapPrefix($this->DBPrefix, $this->swapPre);
		}

		$startTime = microtime(true);

		// Always save the last query so we can use
		// the getLastQuery() method.
		$this->lastQuery = $query;

		// Run the query for real
		if (! $this->pretend && false === ($this->resultID = $this->simpleQuery($query->getQuery())))
		{
			$query->setDuration($startTime, $startTime);

			// This will trigger a rollback if transactions are being used
			if ($this->transDepth !== 0)
			{
				$this->transStatus = false;
			}

			if ($this->DBDebug)
			{
				// We call this function in order to roll-back queries
				// if transactions are enabled. If we don't call this here
				// the error message will trigger an exit, causing the
				// transactions to remain in limbo.
				while ($this->transDepth !== 0)
				{
					$transDepth = $this->transDepth;
					$this->transComplete();

					if ($transDepth === $this->transDepth)
					{
						log_message('error', 'Database: Failure during an automated transaction commit/rollback!');
						break;
					}
				}

				return false;
			}

			if (! $this->pretend)
			{
				// Let others do something with this query.
				Events::trigger('DBQuery', $query);
			}

			return new $resultClass($this->connID, $this->resultID);
		}

		$query->setDuration($startTime);

		if (! $this->pretend)
		{
			// Let others do something with this query
			Events::trigger('DBQuery', $query);
		}

		// If $pretend is true, then we just want to return
		// the actual query object here. There won't be
		// any results to return.
		return $this->pretend ? $query : new $resultClass($this->connID, $this->resultID);
	}

	//--------------------------------------------------------------------

	/**
	 * Performs a basic query against the database. No binding or caching
	 * is performed, nor are transactions handled. Simply takes a raw
	 * query string and returns the database-specific result id.
	 *
	 * @param string $sql
	 *
	 * @return mixed
	 */
	public function simpleQuery(string $sql)
	{
		if (empty($this->connID))
		{
			$this->initialize();
		}

		return $this->execute($sql);
	}

	//--------------------------------------------------------------------

	/**
	 * Disable Transactions
	 *
	 * This permits transactions to be disabled at run-time.
	 *
	 * @return void
	 */
	public function transOff()
	{
		$this->transEnabled = false;
	}

	//--------------------------------------------------------------------

	/**
	 * Enable/disable Transaction Strict Mode
	 *
	 * When strict mode is enabled, if you are running multiple groups of
	 * transactions, if one group fails all subsequent groups will be
	 * rolled back.
	 *
	 * If strict mode is disabled, each group is treated autonomously,
	 * meaning a failure of one group will not affect any others
	 *
	 * @param boolean $mode = true
	 *
	 * @return $this
	 */
	public function transStrict(bool $mode = true)
	{
		$this->transStrict = $mode;

		return $this;
	}

	//--------------------------------------------------------------------

	/**
	 * Start Transaction
	 *
	 * @param  boolean $test_mode = FALSE
	 * @return boolean
	 */
	public function transStart(bool $test_mode = false): bool
	{
		if (! $this->transEnabled)
		{
			return false;
		}

		return $this->transBegin($test_mode);
	}

	//--------------------------------------------------------------------

	/**
	 * Complete Transaction
	 *
	 * @return boolean
	 */
	public function transComplete(): bool
	{
		if (! $this->transEnabled)
		{
			return false;
		}

		// The query() function will set this flag to FALSE in the event that a query failed
		if ($this->transStatus === false || $this->transFailure === true)
		{
			$this->transRollback();

			// If we are NOT running in strict mode, we will reset
			// the _trans_status flag so that subsequent groups of
			// transactions will be permitted.
			if ($this->transStrict === false)
			{
				$this->transStatus = true;
			}

			//            log_message('debug', 'DB Transaction Failure');
			return false;
		}

		return $this->transCommit();
	}

	//--------------------------------------------------------------------

	/**
	 * Lets you retrieve the transaction flag to determine if it has failed
	 *
	 * @return boolean
	 */
	public function transStatus(): bool
	{
		return $this->transStatus;
	}

	//--------------------------------------------------------------------

	/**
	 * Begin Transaction
	 *
	 * @param  boolean $test_mode
	 * @return boolean
	 */
	public function transBegin(bool $test_mode = false): bool
	{
		if (! $this->transEnabled)
		{
			return false;
		}
		// When transactions are nested we only begin/commit/rollback the outermost ones
		elseif ($this->transDepth > 0)
		{
			$this->transDepth ++;
			return true;
		}

		if (empty($this->connID))
		{
			$this->initialize();
		}

		// Reset the transaction failure flag.
		// If the $test_mode flag is set to TRUE transactions will be rolled back
		// even if the queries produce a successful result.
		$this->transFailure = ($test_mode === true);

		if ($this->_transBegin())
		{
			$this->transDepth ++;
			return true;
		}

		return false;
	}

	//--------------------------------------------------------------------

	/**
	 * Commit Transaction
	 *
	 * @return boolean
	 */
	public function transCommit(): bool
	{
		if (! $this->transEnabled || $this->transDepth === 0)
		{
			return false;
		}
		// When transactions are nested we only begin/commit/rollback the outermost ones
		elseif ($this->transDepth > 1 || $this->_transCommit())
		{
			$this->transDepth --;
			return true;
		}

		return false;
	}

	//--------------------------------------------------------------------

	/**
	 * Rollback Transaction
	 *
	 * @return boolean
	 */
	public function transRollback(): bool
	{
		if (! $this->transEnabled || $this->transDepth === 0)
		{
			return false;
		}
		// When transactions are nested we only begin/commit/rollback the outermost ones
		elseif ($this->transDepth > 1 || $this->_transRollback())
		{
			$this->transDepth --;
			return true;
		}

		return false;
	}

	//--------------------------------------------------------------------

	/**
	 * Begin Transaction
	 *
	 * @return boolean
	 */
	abstract protected function _transBegin(): bool;

	//--------------------------------------------------------------------

	/**
	 * Commit Transaction
	 *
	 * @return boolean
	 */
	abstract protected function _transCommit(): bool;

	//--------------------------------------------------------------------

	/**
	 * Rollback Transaction
	 *
	 * @return boolean
	 */
	abstract protected function _transRollback(): bool;

	//--------------------------------------------------------------------

	/**
	 * Returns an instance of the query builder for this connection.
	 *
	 * @param string|array $tableName
	 *
	 * @return BaseBuilder
	 * @throws DatabaseException
	 */
	public function table($tableName)
	{
		if (empty($tableName))
		{
			throw new DatabaseException('You must set the database table to be used with your query.');
		}

		$className = str_replace('Connection', 'Builder', get_class($this));

		return new $className($tableName, $this);
	}

	//--------------------------------------------------------------------

	/**
	 * Creates a prepared statement with the database that can then
	 * be used to execute multiple statements against. Within the
	 * closure, you would build the query in any normal way, though
	 * the Query Builder is the expected manner.
	 *
	 * Example:
	 *    $stmt = $db->prepare(function($db)
	 *           {
	 *             return $db->table('users')
	 *                   ->where('id', 1)
	 *                     ->get();
	 *           })
	 *
	 * @param \Closure $func
	 * @param array    $options Passed to the prepare() method
	 *
	 * @return BasePreparedQuery|null
	 */
	public function prepare(\Closure $func, array $options = [])
	{
		if (empty($this->connID))
		{
			$this->initialize();
		}

		$this->pretend(true);

		$sql = $func($this);

		$this->pretend(false);

		if ($sql instanceof QueryInterface)
		{
			$sql = $sql->getOriginalQuery();
		}

		$class = str_ireplace('Connection', 'PreparedQuery', get_class($this));
		/**
		 * @var BasePreparedQuery $class
		 */
		$class = new $class($this);

		return $class->prepare($sql, $options);
	}

	//--------------------------------------------------------------------

	/**
	 * Returns the last query's statement object.
	 *
	 * @return mixed
	 */
	public function getLastQuery()
	{
		return $this->lastQuery;
	}

	//--------------------------------------------------------------------

	/**
	 * Returns a string representation of the last query's statement object.
	 *
	 * @return string
	 */
	public function showLastQuery(): string
	{
		return (string) $this->lastQuery;
	}

	//--------------------------------------------------------------------

	/**
	 * Returns the time we started to connect to this database in
	 * seconds with microseconds.
	 *
	 * Used by the Debug Toolbar's timeline.
	 *
	 * @return float
	 */
	public function getConnectStart(): float
	{
		return $this->connectTime;
	}

	//--------------------------------------------------------------------

	/**
	 * Returns the number of seconds with microseconds that it took
	 * to connect to the database.
	 *
	 * Used by the Debug Toolbar's timeline.
	 *
	 * @param integer $decimals
	 *
	 * @return string
	 */
	public function getConnectDuration(int $decimals = 6): string
	{
		return number_format($this->connectDuration, $decimals);
	}

	//--------------------------------------------------------------------

	/**
	 * Protect Identifiers
	 *
	 * This function is used extensively by the Query Builder class, and by
	 * a couple functions in this class.
	 * It takes a column or table name (optionally with an alias) and inserts
	 * the table prefix onto it. Some logic is necessary in order to deal with
	 * column names that include the path. Consider a query like this:
	 *
	 * SELECT hostname.database.table.column AS c FROM hostname.database.table
	 *
	 * Or a query with aliasing:
	 *
	 * SELECT m.member_id, m.member_name FROM members AS m
	 *
	 * Since the column name can include up to four segments (host, DB, table, column)
	 * or also have an alias prefix, we need to do a bit of work to figure this out and
	 * insert the table prefix (if it exists) in the proper position, and escape only
	 * the correct identifiers.
	 *
	 * @param string|array  $item
	 * @param boolean       $prefixSingle
	 * @param boolean       $protectIdentifiers
	 * @param boolean       $fieldExists
	 *
	 * @return string|array
	 */
	public function protectIdentifiers($item, bool $prefixSingle = false, bool $protectIdentifiers = null, bool $fieldExists = true)
	{
		if (! is_bool($protectIdentifiers))
		{
			$protectIdentifiers = $this->protectIdentifiers;
		}

		if (is_array($item))
		{
			$escaped_array = [];
			foreach ($item as $k => $v)
			{
				$escaped_array[$this->protectIdentifiers($k)] = $this->protectIdentifiers($v, $prefixSingle, $protectIdentifiers, $fieldExists);
			}

			return $escaped_array;
		}

		// This is basically a bug fix for queries that use MAX, MIN, etc.
		// If a parenthesis is found we know that we do not need to
		// escape the data or add a prefix. There's probably a more graceful
		// way to deal with this, but I'm not thinking of it
		//
		// Added exception for single quotes as well, we don't want to alter
		// literal strings.
		if (strcspn($item, "()'") !== strlen($item))
		{
			return $item;
		}

		// Convert tabs or multiple spaces into single spaces
		$item = preg_replace('/\s+/', ' ', trim($item));

		// If the item has an alias declaration we remove it and set it aside.
		// Note: strripos() is used in order to support spaces in table names
		if ($offset = strripos($item, ' AS '))
		{
			$alias = ($protectIdentifiers) ? substr($item, $offset, 4) . $this->escapeIdentifiers(substr($item, $offset + 4)) : substr($item, $offset);
			$item  = substr($item, 0, $offset);
		}
		elseif ($offset = strrpos($item, ' '))
		{
			$alias = ($protectIdentifiers) ? ' ' . $this->escapeIdentifiers(substr($item, $offset + 1)) : substr($item, $offset);
			$item  = substr($item, 0, $offset);
		}
		else
		{
			$alias = '';
		}

		// Break the string apart if it contains periods, then insert the table prefix
		// in the correct location, assuming the period doesn't indicate that we're dealing
		// with an alias. While we're at it, we will escape the components
		if (strpos($item, '.') !== false)
		{
			$parts = explode('.', $item);

			// Does the first segment of the exploded item match
			// one of the aliases previously identified? If so,
			// we have nothing more to do other than escape the item
			//
			// NOTE: The ! empty() condition prevents this method
			//       from breaking when QB isn't enabled.
			if (! empty($this->aliasedTables) && in_array($parts[0], $this->aliasedTables))
			{
				if ($protectIdentifiers === true)
				{
					foreach ($parts as $key => $val)
					{
						if (! in_array($val, $this->reservedIdentifiers))
						{
							$parts[$key] = $this->escapeIdentifiers($val);
						}
					}

					$item = implode('.', $parts);
				}

				return $item . $alias;
			}

			// Is there a table prefix defined in the config file? If not, no need to do anything
			if ($this->DBPrefix !== '')
			{
				// We now add the table prefix based on some logic.
				// Do we have 4 segments (hostname.database.table.column)?
				// If so, we add the table prefix to the column name in the 3rd segment.
				if (isset($parts[3]))
				{
					$i = 2;
				}
				// Do we have 3 segments (database.table.column)?
				// If so, we add the table prefix to the column name in 2nd position
				elseif (isset($parts[2]))
				{
					$i = 1;
				}
				// Do we have 2 segments (table.column)?
				// If so, we add the table prefix to the column name in 1st segment
				else
				{
					$i = 0;
				}

				// This flag is set when the supplied $item does not contain a field name.
				// This can happen when this function is being called from a JOIN.
				if ($fieldExists === false)
				{
					$i ++;
				}

				// Verify table prefix and replace if necessary
				if ($this->swapPre !== '' && strpos($parts[$i], $this->swapPre) === 0)
				{
					$parts[$i] = preg_replace('/^' . $this->swapPre . '(\S+?)/', $this->DBPrefix . '\\1', $parts[$i]);
				}
				// We only add the table prefix if it does not already exist
				elseif (strpos($parts[$i], $this->DBPrefix) !== 0)
				{
					$parts[$i] = $this->DBPrefix . $parts[$i];
				}

				// Put the parts back together
				$item = implode('.', $parts);
			}

			if ($protectIdentifiers === true)
			{
				$item = $this->escapeIdentifiers($item);
			}

			return $item . $alias;
		}

		// In some cases, especially 'from', we end up running through
		// protect_identifiers twice. This algorithm won't work when
		// it contains the escapeChar so strip it out.
		$item = trim($item, $this->escapeChar);

		// Is there a table prefix? If not, no need to insert it
		if ($this->DBPrefix !== '')
		{
			// Verify table prefix and replace if necessary
			if ($this->swapPre !== '' && strpos($item, $this->swapPre) === 0)
			{
				$item = preg_replace('/^' . $this->swapPre . '(\S+?)/', $this->DBPrefix . '\\1', $item);
			}
			// Do we prefix an item with no segments?
			elseif ($prefixSingle === true && strpos($item, $this->DBPrefix) !== 0)
			{
				$item = $this->DBPrefix . $item;
			}
		}

		if ($protectIdentifiers === true && ! in_array($item, $this->reservedIdentifiers))
		{
			$item = $this->escapeIdentifiers($item);
		}

		return $item . $alias;
	}

	//--------------------------------------------------------------------

	/**
	 * Escape the SQL Identifiers
	 *
	 * This function escapes column and table names
	 *
	 * @param mixed $item
	 *
	 * @return mixed
	 */
	public function escapeIdentifiers($item)
	{
		if ($this->escapeChar === '' || empty($item) || in_array($item, $this->reservedIdentifiers))
		{
			return $item;
		}
		elseif (is_array($item))
		{
			foreach ($item as $key => $value)
			{
				$item[$key] = $this->escapeIdentifiers($value);
			}

			return $item;
		}
		// Avoid breaking functions and literal values inside queries
		elseif (ctype_digit($item) || $item[0] === "'" || ( $this->escapeChar !== '"' && $item[0] === '"') ||
				strpos($item, '(') !== false
		)
		{
			return $item;
		}

		static $preg_ec = [];

		if (empty($preg_ec))
		{
			if (is_array($this->escapeChar))
			{
				$preg_ec = [
					preg_quote($this->escapeChar[0], '/'),
					preg_quote($this->escapeChar[1], '/'),
					$this->escapeChar[0],
					$this->escapeChar[1],
				];
			}
			else
			{
				$preg_ec[0] = $preg_ec[1] = preg_quote($this->escapeChar, '/');
				$preg_ec[2] = $preg_ec[3] = $this->escapeChar;
			}
		}

		foreach ($this->reservedIdentifiers as $id)
		{
			if (strpos($item, '.' . $id) !== false)
			{
				return preg_replace('/' . $preg_ec[0] . '?([^' . $preg_ec[1] . '\.]+)' . $preg_ec[1] . '?\./i', $preg_ec[2] . '$1' . $preg_ec[3] . '.', $item);
			}
		}

		return preg_replace('/' . $preg_ec[0] . '?([^' . $preg_ec[1] . '\.]+)' . $preg_ec[1] . '?(\.)?/i', $preg_ec[2] . '$1' . $preg_ec[3] . '$2', $item);
	}

	//--------------------------------------------------------------------

	/**
	 * DB Prefix
	 *
	 * Prepends a database prefix if one exists in configuration
	 *
	 * @param string $table the table
	 *
	 * @return string
	 * @throws \CodeIgniter\Database\Exceptions\DatabaseException
	 */
	public function prefixTable(string $table = ''): string
	{
		if ($table === '')
		{
			throw new DatabaseException('A table name is required for that operation.');
		}

		return $this->DBPrefix . $table;
	}

	//--------------------------------------------------------------------

	/**
	 * Set DB Prefix
	 *
	 * Set's the DB Prefix to something new without needing to reconnect
	 *
	 * @param string $prefix The prefix
	 *
	 * @return string
	 */
	public function setPrefix(string $prefix = ''): string
	{
		return $this->DBPrefix = $prefix;
	}

	//--------------------------------------------------------------------

	/**
	 * Returns the total number of rows affected by this query.
	 *
	 * @return mixed
	 */
	abstract public function affectedRows(): int;

	//--------------------------------------------------------------------

	/**
	 * "Smart" Escape String
	 *
	 * Escapes data based on type.
	 * Sets boolean and null types
	 *
	 * @param mixed $str
	 *
	 * @return mixed
	 */
	public function escape($str)
	{
		if (is_array($str))
		{
			$str = array_map([&$this, 'escape'], $str);

			return $str;
		}
		else if (is_string($str) || ( is_object($str) && method_exists($str, '__toString')))
		{
			return "'" . $this->escapeString($str) . "'";
		}
		else if (is_bool($str))
		{
			return ($str === false) ? 0 : 1;
		}
		else if (is_numeric($str) && $str < 0)
		{
			return "'{$str}'";
		}
		else if ($str === null)
		{
			return 'NULL';
		}

		return $str;
	}

	//--------------------------------------------------------------------

	/**
	 * Escape String
	 *
	 * @param  string|string[] $str  Input string
	 * @param  boolean         $like Whether or not the string will be used in a LIKE condition
	 * @return string|string[]
	 */
	public function escapeString($str, bool $like = false)
	{
		if (is_array($str))
		{
			foreach ($str as $key => $val)
			{
				$str[$key] = $this->escapeString($val, $like);
			}

			return $str;
		}

		$str = $this->_escapeString($str);

		// escape LIKE condition wildcards
		if ($like === true)
		{
			return str_replace([
				$this->likeEscapeChar,
				'%',
				'_',
			], [
				$this->likeEscapeChar . $this->likeEscapeChar,
				$this->likeEscapeChar . '%',
				$this->likeEscapeChar . '_',
			], $str
			);
		}

		return $str;
	}

	//--------------------------------------------------------------------

	/**
	 * Escape LIKE String
	 *
	 * Calls the individual driver for platform
	 * specific escaping for LIKE conditions
	 *
	 * @param  string|string[]
	 * @return string|string[]
	 */
	public function escapeLikeString($str)
	{
		return $this->escapeString($str, true);
	}

	//--------------------------------------------------------------------

	/**
	 * Platform independent string escape.
	 *
	 * Will likely be overridden in child classes.
	 *
	 * @param string $str
	 *
	 * @return string
	 */
	protected function _escapeString(string $str): string
	{
		return str_replace("'", "''", remove_invisible_characters($str, false));
	}

	//--------------------------------------------------------------------

	/**
	 * This function enables you to call PHP database functions that are not natively included
	 * in CodeIgniter, in a platform independent manner.
	 *
	 * @param string $functionName
	 * @param array  ...$params
	 *
	 * @return boolean
	 * @throws DatabaseException
	 */
	public function callFunction(string $functionName, ...$params): bool
	{
		$driver = ($this->DBDriver === 'postgre' ? 'pg' : strtolower($this->DBDriver)) . '_';

		if (false === strpos($driver, $functionName))
		{
			$functionName = $driver . $functionName;
		}

		if (! function_exists($functionName))
		{
			if ($this->DBDebug)
			{
				throw new DatabaseException('This feature is not available for the database you are using.');
			}

			return false;
		}

		return $functionName(...$params);
	}

	//--------------------------------------------------------------------
	//--------------------------------------------------------------------
	// META Methods
	//--------------------------------------------------------------------

	/**
	 * Returns an array of table names
	 *
	 * @param  boolean $constrainByPrefix = FALSE
	 * @return boolean|array
	 * @throws \CodeIgniter\Database\Exceptions\DatabaseException
	 */
	public function listTables(bool $constrainByPrefix = false)
	{
		// Is there a cached result?
		if (isset($this->dataCache['table_names']) && $this->dataCache['table_names'])
		{
			return $this->dataCache['table_names'];
		}

		if (false === ($sql = $this->_listTables($constrainByPrefix)))
		{
			if ($this->DBDebug)
			{
				throw new DatabaseException('This feature is not available for the database you are using.');
			}
			return false;
		}

		$this->dataCache['table_names'] = [];
		$query                          = $this->query($sql);

		foreach ($query->getResultArray() as $row)
		{
			// Do we know from which column to get the table name?
			if (! isset($key))
			{
				if (isset($row['table_name']))
				{
					$key = 'table_name';
				}
				elseif (isset($row['TABLE_NAME']))
				{
					$key = 'TABLE_NAME';
				}
				else
				{
					/* We have no other choice but to just get the first element's key.
					 * Due to array_shift() accepting its argument by reference, if
					 * E_STRICT is on, this would trigger a warning. So we'll have to
					 * assign it first.
					 */
					$key = array_keys($row);
					$key = array_shift($key);
				}
			}

			$this->dataCache['table_names'][] = $row[$key];
		}

		return $this->dataCache['table_names'];
	}

	//--------------------------------------------------------------------

	/**
	 * Determine if a particular table exists
	 *
	 * @param  string $tableName
	 * @return boolean
	 */
	public function tableExists(string $tableName): bool
	{
		return in_array($this->protectIdentifiers($tableName, true, false, false), $this->listTables());
	}

	//--------------------------------------------------------------------

	/**
	 * Fetch Field Names
	 *
	 * @param string $table Table name
	 *
	 * @return array|false
	 * @throws DatabaseException
	 */
	public function getFieldNames(string $table)
	{
		// Is there a cached result?
		if (isset($this->dataCache['field_names'][$table]))
		{
			return $this->dataCache['field_names'][$table];
		}

		if (empty($this->connID))
		{
			$this->initialize();
		}

		if (false === ($sql = $this->_listColumns($table)))
		{
			if ($this->DBDebug)
			{
				throw new DatabaseException('This feature is not available for the database you are using.');
			}
			return false;
		}

		$query                                  = $this->query($sql);
		$this->dataCache['field_names'][$table] = [];

		foreach ($query->getResultArray() as $row)
		{
			// Do we know from where to get the column's name?
			if (! isset($key))
			{
				if (isset($row['column_name']))
				{
					$key = 'column_name';
				}
				elseif (isset($row['COLUMN_NAME']))
				{
					$key = 'COLUMN_NAME';
				}
				else
				{
					// We have no other choice but to just get the first element's key.
					$key = key($row);
				}
			}

			$this->dataCache['field_names'][$table][] = $row[$key];
		}

		return $this->dataCache['field_names'][$table];
	}

	//--------------------------------------------------------------------

	/**
	 * Determine if a particular field exists
	 *
	 * @param  string   $fieldName
	 * @param  string   $tableName
	 * @return boolean
	 */
	public function fieldExists(string $fieldName, string $tableName): bool
	{
		return in_array($fieldName, $this->getFieldNames($tableName));
	}

	//--------------------------------------------------------------------

	/**
	 * Returns an object with field data
	 *
	 * @param  string $table the table name
	 * @return array|false
	 */
	public function getFieldData(string $table)
	{
		$fields = $this->_fieldData($this->protectIdentifiers($table, true, false, false));

		return $fields ?? false;
	}

	//--------------------------------------------------------------------

	/**
	 * Returns an object with key data
	 *
	 * @param  string $table the table name
	 * @return array|false
	 */
	public function getIndexData(string $table)
	{
		$fields = $this->_indexData($this->protectIdentifiers($table, true, false, false));

		return $fields ?? false;
	}

	//--------------------------------------------------------------------

	/**
	 * Returns an object with foreign key data
	 *
	 * @param  string $table the table name
	 * @return array|false
	 */
	public function getForeignKeyData(string $table)
	{
		$fields = $this->_foreignKeyData($this->protectIdentifiers($table, true, false, false));

		return $fields ?? false;
	}

	//--------------------------------------------------------------------

	/**
	 * Allows the engine to be set into a mode where queries are not
	 * actually executed, but they are still generated, timed, etc.
	 *
	 * This is primarily used by the prepared query functionality.
	 *
	 * @param boolean $pretend
	 *
	 * @return $this
	 */
	public function pretend(bool $pretend = true)
	{
		$this->pretend = $pretend;

		return $this;
	}

	//--------------------------------------------------------------------

	/**
	 * Empties our data cache. Especially helpful during testing.
	 *
	 * @return $this
	 */
	public function resetDataCache()
	{
		$this->dataCache = [];

		return $this;
	}

	//--------------------------------------------------------------------

	/**
	 * Returns the last error code and message.
	 *
	 * Must return an array with keys 'code' and 'message':
	 *
	 *  return ['code' => null, 'message' => null);
	 *
	 * @return array
	 */
	abstract public function error(): array;

	//--------------------------------------------------------------------

	/**
	 * Insert ID
	 *
	 * @return integer
	 */
	abstract public function insertID(): int;

	//--------------------------------------------------------------------

	/**
	 * Generates the SQL for listing tables in a platform-dependent manner.
	 *
	 * @param boolean $constrainByPrefix
	 *
	 * @return string
	 */
	abstract protected function _listTables(bool $constrainByPrefix = false): string;

	//--------------------------------------------------------------------

	/**
	 * Generates a platform-specific query string so that the column names can be fetched.
	 *
	 * @param string $table
	 *
	 * @return string
	 */
	abstract protected function _listColumns(string $table = ''): string;

	//--------------------------------------------------------------------

	/**
	 * Platform-specific field data information.
	 *
	 * @param  string $table
	 * @see    getFieldData()
	 * @return array
	 */
	abstract protected function _fieldData(string $table): array;

	//--------------------------------------------------------------------

	/**
	 * Platform-specific index data.
	 *
	 * @param  string $table
	 * @see    getIndexData()
	 * @return array
	 */
	abstract protected function _indexData(string $table): array;

	//--------------------------------------------------------------------

	/**
	 * Platform-specific foreign keys data.
	 *
	 * @param  string $table
	 * @see    getForeignKeyData()
	 * @return array
	 */
	abstract protected function _foreignKeyData(string $table): array;

	//--------------------------------------------------------------------

	/**
	 * @param string $key
	 *
	 * @return mixed
	 */
	public function __get(string $key)
	{
		if (property_exists($this, $key))
		{
			return $this->$key;
		}

		return null;
	}

	//--------------------------------------------------------------------

}


<?php

/**
 * CodeIgniter
 *
 * An open source application development framework for PHP
 *
 * This content is released under the MIT License (MIT)
 *
 * Copyright (c) 2014-2019 British Columbia Institute of Technology
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 *
 * @package    CodeIgniter
 * @author     CodeIgniter Dev Team
 * @copyright  2014-2019 British Columbia Institute of Technology (https://bcit.ca/)
 * @license    https://opensource.org/licenses/MIT	MIT License
 * @link       https://codeigniter.com
 * @since      Version 3.0.0
 * @filesource
 */

namespace CodeIgniter\Config;

/**
 * Class BaseConfig
 *
 * Not intended to be used on its own, this class will attempt to
 * automatically populate the child class' properties with values
 * from the environment.
 *
 * These can be set within the .env file.
 */
class BaseConfig
{

	/**
	 * An optional array of classes that will act as Registrars
	 * for rapidly setting config class properties.
	 *
	 * @var array
	 */
	public static $registrars      = [];
	protected static $didDiscovery = false;
	protected static $moduleConfig;

	/**
	 * Will attempt to get environment variables with names
	 * that match the properties of the child class.
	 *
	 * The "shortPrefix" is the lowercase-only config class name.
	 */
	public function __construct()
	{
		static::$moduleConfig = config('Modules');

		$properties  = array_keys(get_object_vars($this));
		$prefix      = get_class($this);
		$slashAt     = strrpos($prefix, '\\');
		$shortPrefix = strtolower(substr($prefix, $slashAt === false ? 0 : $slashAt + 1));

		foreach ($properties as $property)
		{
			if (is_array($this->$property))
			{
				foreach ($this->$property as $key => $val)
				{
					if ($value = $this->getEnvValue("{$property}.{$key}", $prefix, $shortPrefix))
					{
						if (! is_null($value))
						{
							if ($value === 'false')
							{
								$value = false;
							}
							elseif ($value === 'true')
							{
								$value = true;
							}

							$this->$property[$key] = $value;
						}
					}
				}
			}
			else
			{
				if (($value = $this->getEnvValue($property, $prefix, $shortPrefix)) !== false)
				{
					if (! is_null($value))
					{
						if ($value === 'false')
						{
							$value = false;
						}
						elseif ($value === 'true')
						{
							$value = true;
						}

						$this->$property = is_bool($value) ? $value : trim($value, '\'"');
					}
				}
			}
		}

		if (defined('ENVIRONMENT') && ENVIRONMENT !== 'testing')
		{
			// well, this won't happen during unit testing
			// @codeCoverageIgnoreStart
			$this->registerProperties();
			// @codeCoverageIgnoreEnd
		}
	}

	//--------------------------------------------------------------------

	/**
	 * Retrieve an environment-specific configuration setting
	 *
	 * @param string $property
	 * @param string $prefix
	 * @param string $shortPrefix
	 *
	 * @return mixed
	 */
	protected function getEnvValue(string $property, string $prefix, string $shortPrefix)
	{
		$shortPrefix = ltrim($shortPrefix, '\\');
		switch (true)
		{
			case array_key_exists("{$shortPrefix}.{$property}", $_ENV):
				return $_ENV["{$shortPrefix}.{$property}"];
				break;
			case array_key_exists("{$shortPrefix}.{$property}", $_SERVER):
				return $_SERVER["{$shortPrefix}.{$property}"];
				break;
			case array_key_exists("{$prefix}.{$property}", $_ENV):
				return $_ENV["{$prefix}.{$property}"];
				break;
			case array_key_exists("{$prefix}.{$property}", $_SERVER):
				return $_SERVER["{$prefix}.{$property}"];
				break;
			default:
				$value = getenv($property);
				return $value === false ? null : $value;
		}
	}

	//--------------------------------------------------------------------

	/**
	 * Provides external libraries a simple way to register one or more
	 * options into a config file.
	 *
	 * @throws \ReflectionException
	 */
	protected function registerProperties()
	{
		if (! static::$moduleConfig->shouldDiscover('registrars'))
		{
			return;
		}

		if (! static::$didDiscovery)
		{
			$locator         = \Config\Services::locator();
			$registrarsFiles = $locator->search('Config/Registrar.php');

			foreach ($registrarsFiles as $file)
			{
				$className = $locator->getClassname($file);
				static::$registrars[] = new $className();
			}

			static::$didDiscovery = true;
		}

		$shortName = (new \ReflectionClass($this))->getShortName();

		// Check the registrar class for a method named after this class' shortName
		foreach (static::$registrars as $callable)
		{
			// ignore non-applicable registrars
			if (! method_exists($callable, $shortName))
			{
				continue;
			}

			$properties = $callable::$shortName();

			if (! is_array($properties))
			{
				throw new \RuntimeException('Registrars must return an array of properties and their values.');
			}

			foreach ($properties as $property => $value)
			{
				if (isset($this->$property) && is_array($this->$property) && is_array($value))
				{
					$this->$property = array_merge($this->$property, $value);
				}
				else
				{
					$this->$property = $value;
				}
			}
		}
	}

	//--------------------------------------------------------------------
}


<?php

/**
 * CodeIgniter
 *
 * An open source application development framework for PHP
 *
 * This content is released under the MIT License (MIT)
 *
 * Copyright (c) 2014-2019 British Columbia Institute of Technology
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 *
 * @package    CodeIgniter
 * @author     CodeIgniter Dev Team
 * @copyright  2014-2019 British Columbia Institute of Technology (https://bcit.ca/)
 * @license    https://opensource.org/licenses/MIT	MIT License
 * @link       https://codeigniter.com
 * @since      Version 3.0.0
 * @filesource
 */

namespace CodeIgniter\Cache\Handlers;

use CodeIgniter\Cache\CacheInterface;
use CodeIgniter\Cache\Exceptions\CacheException;

/**
 * File system cache handler
 */
class FileHandler implements CacheInterface
{

	/**
	 * Prefixed to all cache names.
	 *
	 * @var string
	 */
	protected $prefix;

	/**
	 * Where to store cached files on the disk.
	 *
	 * @var string
	 */
	protected $path;

	//--------------------------------------------------------------------

	public function __construct($config)
	{
		$path = ! empty($config->storePath) ? $config->storePath : WRITEPATH . 'cache';
		if (! is_really_writable($path))
		{
			throw CacheException::forUnableToWrite($path);
		}

		$this->prefix = $config->prefix ?: '';
		$this->path   = rtrim($path, '/') . '/';
	}

	//--------------------------------------------------------------------

	/**
	 * Takes care of any handler-specific setup that must be done.
	 */
	public function initialize()
	{
		// Not to see here...
	}

	//--------------------------------------------------------------------

	/**
	 * Attempts to fetch an item from the cache store.
	 *
	 * @param string $key Cache item name
	 *
	 * @return mixed
	 */
	public function get(string $key)
	{
		$key = $this->prefix . $key;

		$data = $this->getItem($key);

		return is_array($data) ? $data['data'] : null;
	}

	//--------------------------------------------------------------------

	/**
	 * Saves an item to the cache store.
	 *
	 * @param string  $key   Cache item name
	 * @param mixed   $value The data to save
	 * @param integer $ttl   Time To Live, in seconds (default 60)
	 *
	 * @return mixed
	 */
	public function save(string $key, $value, int $ttl = 60)
	{
		$key = $this->prefix . $key;

		$contents = [
			'time' => time(),
			'ttl'  => $ttl,
			'data' => $value,
		];

		if ($this->writeFile($this->path . $key, serialize($contents)))
		{
			chmod($this->path . $key, 0640);

			return true;
		}

		return false;
	}

	//--------------------------------------------------------------------

	/**
	 * Deletes a specific item from the cache store.
	 *
	 * @param string $key Cache item name
	 *
	 * @return mixed
	 */
	public function delete(string $key)
	{
		$key = $this->prefix . $key;

		return is_file($this->path . $key) ? unlink($this->path . $key) : false;
	}

	//--------------------------------------------------------------------

	/**
	 * Performs atomic incrementation of a raw stored value.
	 *
	 * @param string  $key    Cache ID
	 * @param integer $offset Step/value to increase by
	 *
	 * @return mixed
	 */
	public function increment(string $key, int $offset = 1)
	{
		$key = $this->prefix . $key;

		$data = $this->getItem($key);

		if ($data === false)
		{
			$data = [
				'data' => 0,
				'ttl'  => 60,
			];
		}
		elseif (! is_int($data['data']))
		{
			return false;
		}

		$new_value = $data['data'] + $offset;

		return $this->save($key, $new_value, $data['ttl']) ? $new_value : false;
	}

	//--------------------------------------------------------------------

	/**
	 * Performs atomic decrementation of a raw stored value.
	 *
	 * @param string  $key    Cache ID
	 * @param integer $offset Step/value to increase by
	 *
	 * @return mixed
	 */
	public function decrement(string $key, int $offset = 1)
	{
		$key = $this->prefix . $key;

		$data = $this->getItem($key);

		if ($data === false)
		{
			$data = [
				'data' => 0,
				'ttl'  => 60,
			];
		}
		elseif (! is_int($data['data']))
		{
			return false;
		}

		$new_value = $data['data'] - $offset;

		return $this->save($key, $new_value, $data['ttl']) ? $new_value : false;
	}

	//--------------------------------------------------------------------

	/**
	 * Will delete all items in the entire cache.
	 *
	 * @return mixed
	 */
	public function clean()
	{
		return $this->deleteFiles($this->path, false, true);
	}

	//--------------------------------------------------------------------

	/**
	 * Returns information on the entire cache.
	 *
	 * The information returned and the structure of the data
	 * varies depending on the handler.
	 *
	 * @return mixed
	 */
	public function getCacheInfo()
	{
		return $this->getDirFileInfo($this->path);
	}

	//--------------------------------------------------------------------

	/**
	 * Returns detailed information about the specific item in the cache.
	 *
	 * @param string $key Cache item name.
	 *
	 * @return mixed
	 */
	public function getMetaData(string $key)
	{
		$key = $this->prefix . $key;

		if (! is_file($this->path . $key))
		{
			return false;
		}

		$data = @unserialize(file_get_contents($this->path . $key));

		if (is_array($data))
		{
			$mtime = filemtime($this->path . $key);

			if (! isset($data['ttl']))
			{
				return false;
			}

			return [
				'expire' => $mtime + $data['ttl'],
				'mtime'  => $mtime,
				'data'   => $data['data'],
			];
		}

		return false;
	}

	//--------------------------------------------------------------------

	/**
	 * Determines if the driver is supported on this system.
	 *
	 * @return boolean
	 */
	public function isSupported(): bool
	{
		return is_writable($this->path);
	}

	//--------------------------------------------------------------------

	/**
	 * Does the heavy lifting of actually retrieving the file and
	 * verifying it's age.
	 *
	 * @param string $key
	 *
	 * @return boolean|mixed
	 */
	protected function getItem(string $key)
	{
		if (! is_file($this->path . $key))
		{
			return false;
		}

		$data = unserialize(file_get_contents($this->path . $key));

		if ($data['ttl'] > 0 && time() > $data['time'] + $data['ttl'])
		{
			unlink($this->path . $key);

			return false;
		}

		return $data;
	}

	//--------------------------------------------------------------------
	//--------------------------------------------------------------------
	// SUPPORT METHODS FOR FILES
	//--------------------------------------------------------------------

	/**
	 * Writes a file to disk, or returns false if not successful.
	 *
	 * @param $path
	 * @param $data
	 * @param string $mode
	 *
	 * @return boolean
	 */
	protected function writeFile($path, $data, $mode = 'wb')
	{
		if (($fp = @fopen($path, $mode)) === false)
		{
			return false;
		}

		flock($fp, LOCK_EX);

		for ($result = $written = 0, $length = strlen($data); $written < $length; $written += $result)
		{
			if (($result = fwrite($fp, substr($data, $written))) === false)
			{
				break;
			}
		}

		flock($fp, LOCK_UN);
		fclose($fp);

		return is_int($result);
	}

	//--------------------------------------------------------------------

	/**
	 * Delete Files
	 *
	 * Deletes all files contained in the supplied directory path.
	 * Files must be writable or owned by the system in order to be deleted.
	 * If the second parameter is set to TRUE, any directories contained
	 * within the supplied base directory will be nuked as well.
	 *
	 * @param string  $path    File path
	 * @param boolean $del_dir Whether to delete any directories found in the path
	 * @param boolean $htdocs  Whether to skip deleting .htaccess and index page files
	 * @param integer $_level  Current directory depth level (default: 0; internal use only)
	 *
	 * @return boolean
	 */
	protected function deleteFiles(string $path, bool $del_dir = false, bool $htdocs = false, int $_level = 0): bool
	{
		// Trim the trailing slash
		$path = rtrim($path, '/\\');

		if (! $current_dir = @opendir($path))
		{
			return false;
		}

		while (false !== ($filename = @readdir($current_dir)))
		{
			if ($filename !== '.' && $filename !== '..')
			{
				if (is_dir($path . DIRECTORY_SEPARATOR . $filename) && $filename[0] !== '.')
				{
					$this->deleteFiles($path . DIRECTORY_SEPARATOR . $filename, $del_dir, $htdocs, $_level + 1);
				}
				elseif ($htdocs !== true || ! preg_match('/^(\.htaccess|index\.(html|htm|php)|web\.config)$/i', $filename))
				{
					@unlink($path . DIRECTORY_SEPARATOR . $filename);
				}
			}
		}

		closedir($current_dir);

		return ($del_dir === true && $_level > 0) ? @rmdir($path) : true;
	}

	//--------------------------------------------------------------------

	/**
	 * Get Directory File Information
	 *
	 * Reads the specified directory and builds an array containing the filenames,
	 * filesize, dates, and permissions
	 *
	 * Any sub-folders contained within the specified path are read as well.
	 *
	 * @param string  $source_dir     Path to source
	 * @param boolean $top_level_only Look only at the top level directory specified?
	 * @param boolean $_recursion     Internal variable to determine recursion status - do not use in calls
	 *
	 * @return array|false
	 */
	protected function getDirFileInfo(string $source_dir, bool $top_level_only = true, bool $_recursion = false)
	{
		static $_filedata = [];
		$relative_path    = $source_dir;

		if ($fp = @opendir($source_dir))
		{
			// reset the array and make sure $source_dir has a trailing slash on the initial call
			if ($_recursion === false)
			{
				$_filedata  = [];
				$source_dir = rtrim(realpath($source_dir), DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;
			}

			// Used to be foreach (scandir($source_dir, 1) as $file), but scandir() is simply not as fast
			while (false !== ($file = readdir($fp)))
			{
				if (is_dir($source_dir . $file) && $file[0] !== '.' && $top_level_only === false)
				{
					$this->getDirFileInfo($source_dir . $file . DIRECTORY_SEPARATOR, $top_level_only, true);
				}
				elseif ($file[0] !== '.')
				{
					$_filedata[$file]                  = $this->getFileInfo($source_dir . $file);
					$_filedata[$file]['relative_path'] = $relative_path;
				}
			}

			closedir($fp);

			return $_filedata;
		}

		return false;
	}

	//--------------------------------------------------------------------

	/**
	 * Get File Info
	 *
	 * Given a file and path, returns the name, path, size, date modified
	 * Second parameter allows you to explicitly declare what information you want returned
	 * Options are: name, server_path, size, date, readable, writable, executable, fileperms
	 * Returns FALSE if the file cannot be found.
	 *
	 * @param string $file            Path to file
	 * @param mixed  $returned_values Array or comma separated string of information returned
	 *
	 * @return array|false
	 */
	protected function getFileInfo(string $file, $returned_values = ['name', 'server_path', 'size', 'date'])
	{
		if (! is_file($file))
		{
			return false;
		}

		if (is_string($returned_values))
		{
			$returned_values = explode(',', $returned_values);
		}

		foreach ($returned_values as $key)
		{
			switch ($key)
			{
				case 'name':
					$fileInfo['name'] = basename($file);
					break;
				case 'server_path':
					$fileInfo['server_path'] = $file;
					break;
				case 'size':
					$fileInfo['size'] = filesize($file);
					break;
				case 'date':
					$fileInfo['date'] = filemtime($file);
					break;
				case 'readable':
					$fileInfo['readable'] = is_readable($file);
					break;
				case 'writable':
					$fileInfo['writable'] = is_writable($file);
					break;
				case 'executable':
					$fileInfo['executable'] = is_executable($file);
					break;
				case 'fileperms':
					$fileInfo['fileperms'] = fileperms($file);
					break;
			}
		}

		return $fileInfo;
	}

	//--------------------------------------------------------------------
}


<?php

/**
 * CodeIgniter
 *
 * An open source application development framework for PHP
 *
 * This content is released under the MIT License (MIT)
 *
 * Copyright (c) 2014-2019 British Columbia Institute of Technology
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 *
 * @package    CodeIgniter
 * @author     CodeIgniter Dev Team
 * @copyright  2014-2019 British Columbia Institute of Technology (https://bcit.ca/)
 * @license    https://opensource.org/licenses/MIT	MIT License
 * @link       https://codeigniter.com
 * @since      Version 4.0.0
 * @filesource
 */

namespace CodeIgniter\Debug\Toolbar\Collectors;

/**
 * Files collector
 */
class Files extends BaseCollector
{

	/**
	 * Whether this collector has data that can
	 * be displayed in the Timeline.
	 *
	 * @var boolean
	 */
	protected $hasTimeline = false;

	/**
	 * Whether this collector needs to display
	 * content in a tab or not.
	 *
	 * @var boolean
	 */
	protected $hasTabContent = true;

	/**
	 * The 'title' of this Collector.
	 * Used to name things in the toolbar HTML.
	 *
	 * @var string
	 */
	protected $title = 'Files';

	//--------------------------------------------------------------------

	/**
	 * Returns any information that should be shown next to the title.
	 *
	 * @return string
	 */
	public function getTitleDetails(): string
	{
		return '( ' . (int) count(get_included_files()) . ' )';
	}

	//--------------------------------------------------------------------

	/**
	 * Returns the data of this collector to be formatted in the toolbar
	 *
	 * @return array
	 */
	public function display(): array
	{
		$rawFiles  = get_included_files();
		$coreFiles = [];
		$userFiles = [];

		foreach ($rawFiles as $file)
		{
			$path = $this->cleanPath($file);

			if (strpos($path, 'SYSTEMPATH') !== false)
			{
				$coreFiles[] = [
					'name' => basename($file),
					'path' => $path,
				];
			}
			else
			{
				$userFiles[] = [
					'name' => basename($file),
					'path' => $path,
				];
			}
		}

		sort($userFiles);
		sort($coreFiles);

		return [
			'coreFiles' => $coreFiles,
			'userFiles' => $userFiles,
		];
	}

	//--------------------------------------------------------------------

	/**
	 * Displays the number of included files as a badge in the tab button.
	 *
	 * @return integer
	 */
	public function getBadgeValue(): int
	{
		return count(get_included_files());
	}

	//--------------------------------------------------------------------

	/**
	 * Display the icon.
	 *
	 * Icon from https://icons8.com - 1em package
	 *
	 * @return string
	 */
	public function icon(): string
	{
		return 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAGBSURBVEhL7ZQ9S8NQGIVTBQUncfMfCO4uLgoKbuKQOWg+OkXERRE1IAXrIHbVDrqIDuLiJgj+gro7S3dnpfq88b1FMTE3VZx64HBzzvvZWxKnj15QCcPwCD5HUfSWR+JtzgmtsUcQBEva5IIm9SwSu+95CAWbUuy67qBa32ByZEDpIaZYZSZMjjQuPcQUq8yEyYEb8FSerYeQVGbAFzJkX1PyQWLhgCz0BxTCekC1Wp0hsa6yokzhed4oje6Iz6rlJEkyIKfUEFtITVtQdAibn5rMyaYsMS+a5wTv8qeXMhcU16QZbKgl3hbs+L4/pnpdc87MElZgq10p5DxGdq8I7xrvUWUKvG3NbSK7ubngYzdJwSsF7TiOh9VOgfcEz1UayNe3JUPM1RWC5GXYgTfc75B4NBmXJnAtTfpABX0iPvEd9ezALwkplCFXcr9styiNOKc1RRZpaPM9tcqBwlWzGY1qPL9wjqRBgF5BH6j8HWh2S7MHlX8PrmbK+k/8PzjOOzx1D3i1pKTTAAAAAElFTkSuQmCC';
	}
}


<?php
/**
 * CodeIgniter
 *
 * An open source application development framework for PHP
 *
 * This content is released under the MIT License (MIT)
 *
 * Copyright (c) 2014-2019 British Columbia Institute of Technology
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 *
 * @package    CodeIgniter
 * @author     CodeIgniter Dev Team
 * @copyright  2014-2019 British Columbia Institute of Technology (https://bcit.ca/)
 * @license    https://opensource.org/licenses/MIT	MIT License
 * @link       https://codeigniter.com
 * @since      Version 3.0.0
 * @filesource
 */

namespace CodeIgniter;

use Closure;
use CodeIgniter\Filters\Exceptions\FilterException;
use CodeIgniter\HTTP\DownloadResponse;
use CodeIgniter\HTTP\RedirectResponse;
use CodeIgniter\HTTP\Request;
use CodeIgniter\HTTP\ResponseInterface;
use Config\Services;
use Config\Cache;
use CodeIgniter\HTTP\URI;
use CodeIgniter\Debug\Timer;
use CodeIgniter\Events\Events;
use CodeIgniter\HTTP\Response;
use CodeIgniter\HTTP\CLIRequest;
use CodeIgniter\Router\RouteCollectionInterface;
use CodeIgniter\Exceptions\PageNotFoundException;
use Exception;

/**
 * This class is the core of the framework, and will analyse the
 * request, route it to a controller, and send back the response.
 * Of course, there are variations to that flow, but this is the brains.
 */
class CodeIgniter
{

	/**
	 * The current version of CodeIgniter Framework
	 */
	const CI_VERSION = '4.0.0-beta.2';

	/**
	 * App startup time.
	 *
	 * @var mixed
	 */
	protected $startTime;

	/**
	 * Total app execution time
	 *
	 * @var float
	 */
	protected $totalTime;

	/**
	 * Main application configuration
	 *
	 * @var \Config\App
	 */
	protected $config;

	/**
	 * Timer instance.
	 *
	 * @var Timer
	 */
	protected $benchmark;

	/**
	 * Current request.
	 *
	 * @var HTTP\Request|HTTP\IncomingRequest|CLIRequest
	 */
	protected $request;

	/**
	 * Current response.
	 *
	 * @var HTTP\ResponseInterface
	 */
	protected $response;

	/**
	 * Router to use.
	 *
	 * @var Router\Router
	 */
	protected $router;

	/**
	 * Controller to use.
	 *
	 * @var string|\Closure
	 */
	protected $controller;

	/**
	 * Controller method to invoke.
	 *
	 * @var string
	 */
	protected $method;

	/**
	 * Output handler to use.
	 *
	 * @var string
	 */
	protected $output;

	/**
	 * Cache expiration time
	 *
	 * @var integer
	 */
	protected static $cacheTTL = 0;

	/**
	 * Request path to use.
	 *
	 * @var string
	 */
	protected $path;

	/**
	 * Should the Response instance "pretend"
	 * to keep from setting headers/cookies/etc
	 *
	 * @var boolean
	 */
	protected $useSafeOutput = false;

	//--------------------------------------------------------------------

	public function __construct($config)
	{
		$this->startTime = microtime(true);
		$this->config    = $config;
	}

	//--------------------------------------------------------------------

	/**
	 * Handles some basic app and environment setup.
	 */
	public function initialize()
	{
		// Set default timezone on the server
		date_default_timezone_set($this->config->appTimezone ?? 'UTC');

		// Setup Exception Handling
		Services::exceptions()
				->initialize();

		$this->detectEnvironment();
		$this->bootstrapEnvironment();

		if (CI_DEBUG)
		{
			require_once SYSTEMPATH . 'ThirdParty/Kint/kint.php';
		}
	}

	//--------------------------------------------------------------------

	/**
	 * Launch the application!
	 *
	 * This is "the loop" if you will. The main entry point into the script
	 * that gets the required class instances, fires off the filters,
	 * tries to route the response, loads the controller and generally
	 * makes all of the pieces work together.
	 *
	 * @param \CodeIgniter\Router\RouteCollectionInterface $routes
	 * @param boolean                                      $returnResponse
	 *
	 * @return boolean|\CodeIgniter\HTTP\RequestInterface|\CodeIgniter\HTTP\Response|\CodeIgniter\HTTP\ResponseInterface|mixed
	 * @throws \CodeIgniter\Filters\Exceptions\FilterException
	 * @throws \Exception
	 */
	public function run(RouteCollectionInterface $routes = null, bool $returnResponse = false)
	{
		$this->startBenchmark();

		$this->getRequestObject();
		$this->getResponseObject();

		$this->forceSecureAccess();

		$this->spoofRequestMethod();

		Events::trigger('pre_system');

		// Check for a cached page. Execution will stop
		// if the page has been cached.
		$cacheConfig = new Cache();
		$response    = $this->displayCache($cacheConfig);
		if ($response instanceof ResponseInterface)
		{
			if ($returnResponse)
			{
				return $response;
			}

			$this->response->pretend($this->useSafeOutput)->send();
			$this->callExit(EXIT_SUCCESS);
		}

		try
		{
			return $this->handleRequest($routes, $cacheConfig, $returnResponse);
		}
		catch (FilterException $e)
		{
			$logger = Services::logger();
			$logger->info('REDIRECTED ROUTE at ' . $e->getMessage());

			// If the route is a 'redirect' route, it throws
			// the exception with the $to as the message
			$this->response->redirect($e->getMessage(), 'auto', $e->getCode());
			$this->callExit(EXIT_SUCCESS);
		}
		catch (PageNotFoundException $e)
		{
			$this->display404errors($e);
		}
	}

	//--------------------------------------------------------------------

	/**
	 * Set our Response instance to "pretend" mode so that things like
	 * cookies and headers are not actually sent, allowing PHP 7.2+ to
	 * not complain when ini_set() function is used.
	 *
	 * @param boolean $safe
	 *
	 * @return $this
	 */
	public function useSafeOutput(bool $safe = true)
	{
		$this->useSafeOutput = $safe;

		return $this;
	}

	//--------------------------------------------------------------------

	/**
	 * Handles the main request logic and fires the controller.
	 *
	 * @param \CodeIgniter\Router\RouteCollectionInterface $routes
	 * @param $cacheConfig
	 * @param boolean                                      $returnResponse
	 *
	 * @return \CodeIgniter\HTTP\RequestInterface|\CodeIgniter\HTTP\Response|\CodeIgniter\HTTP\ResponseInterface|mixed
	 * @throws \CodeIgniter\Router\Exceptions\RedirectException
	 */
	protected function handleRequest(RouteCollectionInterface $routes = null, $cacheConfig, bool $returnResponse = false)
	{
		$routeFilter = $this->tryToRouteIt($routes);

		// Run "before" filters
		$filters = Services::filters();

		// If any filters were specified within the routes file,
		// we need to ensure it's active for the current request
		if (! is_null($routeFilter))
		{
			$filters->enableFilter($routeFilter, 'before');
			$filters->enableFilter($routeFilter, 'after');
		}

		$uri = $this->request instanceof CLIRequest ? $this->request->getPath() : $this->request->uri->getPath();

		// Never run filters when running through Spark cli
		if (! defined('SPARKED'))
		{
			$possibleRedirect = $filters->run($uri, 'before');
			if ($possibleRedirect instanceof RedirectResponse)
			{
				return $possibleRedirect->send();
			}
			// If a Response instance is returned, the Response will be sent back to the client and script execution will stop
			if ($possibleRedirect instanceof ResponseInterface)
			{
				return $possibleRedirect->send();
			}
		}

		$returned = $this->startController();

		// Closure controller has run in startController().
		if (! is_callable($this->controller))
		{
			$controller = $this->createController();

			// Is there a "post_controller_constructor" event?
			Events::trigger('post_controller_constructor');

			$returned = $this->runController($controller);
		}
		else
		{
			$this->benchmark->stop('controller_constructor');
			$this->benchmark->stop('controller');
		}

		// If $returned is a string, then the controller output something,
		// probably a view, instead of echoing it directly. Send it along
		// so it can be used with the output.
		$this->gatherOutput($cacheConfig, $returned);

		// Never run filters when running through Spark cli
		if (! defined('SPARKED'))
		{
			$filters->setResponse($this->response);
			// Run "after" filters
			$response = $filters->run($uri, 'after');
		}
		else
		{
			$response = $this->response;
		}

		if ($response instanceof Response)
		{
			$this->response = $response;
		}

		// Save our current URI as the previous URI in the session
		// for safer, more accurate use with `previous_url()` helper function.
		$this->storePreviousURL($this->request->uri ?? $uri);

		unset($uri);

		if (! $returnResponse)
		{
			$this->sendResponse();
		}

		//--------------------------------------------------------------------
		// Is there a post-system event?
		//--------------------------------------------------------------------
		Events::trigger('post_system');

		return $this->response;
	}

	//--------------------------------------------------------------------

	/**
	 * You can load different configurations depending on your
	 * current environment. Setting the environment also influences
	 * things like logging and error reporting.
	 *
	 * This can be set to anything, but default usage is:
	 *
	 *     development
	 *     testing
	 *     production
	 */
	protected function detectEnvironment()
	{
		// Make sure ENVIRONMENT isn't already set by other means.
		if (! defined('ENVIRONMENT'))
		{
			// running under Continuous Integration server?
			if (getenv('CI') !== false)
			{
				define('ENVIRONMENT', 'testing');
			}
			else
			{
				define('ENVIRONMENT', $_SERVER['CI_ENVIRONMENT'] ?? 'production');
			}
		}
	}

	//--------------------------------------------------------------------

	/**
	 * Load any custom boot files based upon the current environment.
	 *
	 * If no boot file exists, we shouldn't continue because something
	 * is wrong. At the very least, they should have error reporting setup.
	 */
	protected function bootstrapEnvironment()
	{
		if (is_file(APPPATH . 'Config/Boot/' . ENVIRONMENT . '.php'))
		{
			require_once APPPATH . 'Config/Boot/' . ENVIRONMENT . '.php';
		}
		else
		{
			header('HTTP/1.1 503 Service Unavailable.', true, 503);
			echo 'The application environment is not set correctly.';
			exit(1); // EXIT_ERROR
		}
	}

	//--------------------------------------------------------------------

	/**
	 * Start the Benchmark
	 *
	 * The timer is used to display total script execution both in the
	 * debug toolbar, and potentially on the displayed page.
	 */
	protected function startBenchmark()
	{
		$this->startTime = microtime(true);

		$this->benchmark = Services::timer();
		$this->benchmark->start('total_execution', $this->startTime);
		$this->benchmark->start('bootstrap');
	}

	//--------------------------------------------------------------------

	/**
	 * Sets a Request object to be used for this request.
	 * Used when running certain tests.
	 *
	 * @param \CodeIgniter\HTTP\Request $request
	 *
	 * @return \CodeIgniter\CodeIgniter
	 */
	public function setRequest(Request $request)
	{
		$this->request = $request;

		return $this;
	}

	//--------------------------------------------------------------------

	/**
	 * Get our Request object, (either IncomingRequest or CLIRequest)
	 * and set the server protocol based on the information provided
	 * by the server.
	 */
	protected function getRequestObject()
	{
		if ($this->request instanceof Request)
		{
			return;
		}

		if (is_cli() && ! (ENVIRONMENT === 'testing'))
		{
			$this->request = Services::clirequest($this->config);
		}
		else
		{
			$this->request = Services::request($this->config);
			// guess at protocol if needed
			$this->request->setProtocolVersion($_SERVER['SERVER_PROTOCOL'] ?? 'HTTP/1.1');
		}
	}

	//--------------------------------------------------------------------

	/**
	 * Get our Response object, and set some default values, including
	 * the HTTP protocol version and a default successful response.
	 */
	protected function getResponseObject()
	{
		$this->response = Services::response($this->config);

		if (! is_cli() || ENVIRONMENT === 'testing')
		{
			$this->response->setProtocolVersion($this->request->getProtocolVersion());
		}

		// Assume success until proven otherwise.
		$this->response->setStatusCode(200);
	}

	//--------------------------------------------------------------------

	/**
	 * Force Secure Site Access? If the config value 'forceGlobalSecureRequests'
	 * is true, will enforce that all requests to this site are made through
	 * HTTPS. Will redirect the user to the current page with HTTPS, as well
	 * as set the HTTP Strict Transport Security header for those browsers
	 * that support it.
	 *
	 * @param integer $duration How long the Strict Transport Security
	 *                          should be enforced for this URL.
	 */
	protected function forceSecureAccess($duration = 31536000)
	{
		if ($this->config->forceGlobalSecureRequests !== true)
		{
			return;
		}

		force_https($duration, $this->request, $this->response);
	}

	//--------------------------------------------------------------------

	/**
	 * Determines if a response has been cached for the given URI.
	 *
	 * @param \Config\Cache $config
	 *
	 * @throws \Exception
	 *
	 * @return boolean|\CodeIgniter\HTTP\ResponseInterface
	 */
	public function displayCache($config)
	{
		if ($cachedResponse = cache()->get($this->generateCacheName($config)))
		{
			$cachedResponse = unserialize($cachedResponse);
			if (! is_array($cachedResponse) || ! isset($cachedResponse['output']) || ! isset($cachedResponse['headers']))
			{
				throw new Exception('Error unserializing page cache');
			}

			$headers = $cachedResponse['headers'];
			$output  = $cachedResponse['output'];

			// Clear all default headers
			foreach ($this->response->getHeaders() as $key => $val)
			{
				$this->response->removeHeader($key);
			}

			// Set cached headers
			foreach ($headers as $name => $value)
			{
				$this->response->setHeader($name, $value);
			}

			$output = $this->displayPerformanceMetrics($output);
			$this->response->setBody($output);

			return $this->response;
		}

		return false;
	}

	//--------------------------------------------------------------------

	/**
	 * Tells the app that the final output should be cached.
	 *
	 * @param integer $time
	 *
	 * @return void
	 */
	public static function cache(int $time)
	{
		static::$cacheTTL = $time;
	}

	//--------------------------------------------------------------------

	/**
	 * Caches the full response from the current request. Used for
	 * full-page caching for very high performance.
	 *
	 * @param \Config\Cache $config
	 *
	 * @return mixed
	 */
	public function cachePage(Cache $config)
	{
		$headers = [];
		foreach ($this->response->getHeaders() as $header)
		{
			$headers[$header->getName()] = $header->getValueLine();
		}

		return cache()->save(
						$this->generateCacheName($config), serialize(['headers' => $headers, 'output' => $this->output]), static::$cacheTTL
		);
	}

	//--------------------------------------------------------------------

	/**
	 * Returns an array with our basic performance stats collected.
	 *
	 * @return array
	 */
	public function getPerformanceStats(): array
	{
		return [
			'startTime' => $this->startTime,
			'totalTime' => $this->totalTime,
		];
	}

	//--------------------------------------------------------------------

	/**
	 * Generates the cache name to use for our full-page caching.
	 *
	 * @param $config
	 *
	 * @return string
	 */
	protected function generateCacheName($config): string
	{
		if (is_cli() && ! (ENVIRONMENT === 'testing'))
		{
			return md5($this->request->getPath());
		}

		$uri = $this->request->uri;

		if ($config->cacheQueryString)
		{
			$name = URI::createURIString(
							$uri->getScheme(), $uri->getAuthority(), $uri->getPath(), $uri->getQuery()
			);
		}
		else
		{
			$name = URI::createURIString(
							$uri->getScheme(), $uri->getAuthority(), $uri->getPath()
			);
		}

		return md5($name);
	}

	//--------------------------------------------------------------------

	/**
	 * Replaces the memory_usage and elapsed_time tags.
	 *
	 * @param string $output
	 *
	 * @return string
	 */
	public function displayPerformanceMetrics(string $output): string
	{
		$this->totalTime = $this->benchmark->getElapsedTime('total_execution');

		$output = str_replace('{elapsed_time}', $this->totalTime, $output);

		return $output;
	}

	//--------------------------------------------------------------------

	/**
	 * Try to Route It - As it sounds like, works with the router to
	 * match a route against the current URI. If the route is a
	 * "redirect route", will also handle the redirect.
	 *
	 * @param RouteCollectionInterface $routes An collection interface to use in place
	 *                                         of the config file.
	 *
	 * @return string
	 * @throws \CodeIgniter\Router\Exceptions\RedirectException
	 */
	protected function tryToRouteIt(RouteCollectionInterface $routes = null)
	{
		if (empty($routes) || ! $routes instanceof RouteCollectionInterface)
		{
			require APPPATH . 'Config/Routes.php';
		}

		// $routes is defined in Config/Routes.php
		$this->router = Services::router($routes);

		$path = $this->determinePath();

		$this->benchmark->stop('bootstrap');
		$this->benchmark->start('routing');

		ob_start();

		$this->controller = $this->router->handle($path);
		$this->method     = $this->router->methodName();

		// If a {locale} segment was matched in the final route,
		// then we need to set the correct locale on our Request.
		if ($this->router->hasLocale())
		{
			$this->request->setLocale($this->router->getLocale());
		}

		$this->benchmark->stop('routing');

		return $this->router->getFilter();
	}

	//--------------------------------------------------------------------

	/**
	 * Determines the path to use for us to try to route to, based
	 * on user input (setPath), or the CLI/IncomingRequest path.
	 */
	protected function determinePath()
	{
		if (! empty($this->path))
		{
			return $this->path;
		}

		return (is_cli() && ! (ENVIRONMENT === 'testing')) ? $this->request->getPath() : $this->request->uri->getPath();
	}

	//--------------------------------------------------------------------

	/**
	 * Allows the request path to be set from outside the class,
	 * instead of relying on CLIRequest or IncomingRequest for the path.
	 *
	 * This is primarily used by the Console.
	 *
	 * @param string $path
	 *
	 * @return $this
	 */
	public function setPath(string $path)
	{
		$this->path = $path;

		return $this;
	}

	//--------------------------------------------------------------------

	/**
	 * Now that everything has been setup, this method attempts to run the
	 * controller method and make the script go. If it's not able to, will
	 * show the appropriate Page Not Found error.
	 */
	protected function startController()
	{
		$this->benchmark->start('controller');
		$this->benchmark->start('controller_constructor');

		// Is it routed to a Closure?
		if (is_object($this->controller) && (get_class($this->controller) === 'Closure'))
		{
			$controller = $this->controller;
			return $controller(...$this->router->params());
		}

		// No controller specified - we don't know what to do now.
		if (empty($this->controller))
		{
			throw PageNotFoundException::forEmptyController();
		}

		// Try to autoload the class
		if (! class_exists($this->controller, true) || $this->method[0] === '_')
		{
			throw PageNotFoundException::forControllerNotFound($this->controller, $this->method);
		}
		else if (! method_exists($this->controller, '_remap') &&
				! is_callable([$this->controller, $this->method], false)
		)
		{
			throw PageNotFoundException::forMethodNotFound($this->method);
		}
	}

	//--------------------------------------------------------------------

	/**
	 * Instantiates the controller class.
	 *
	 * @return mixed
	 */
	protected function createController()
	{
		$class = new $this->controller();
		$class->initController($this->request, $this->response, Services::logger());

		$this->benchmark->stop('controller_constructor');

		return $class;
	}

	//--------------------------------------------------------------------

	/**
	 * Runs the controller, allowing for _remap methods to function.
	 *
	 * @param mixed $class
	 *
	 * @return mixed
	 */
	protected function runController($class)
	{
		if (method_exists($class, '_remap'))
		{
			$output = $class->_remap($this->method, ...$this->router->params());
		}
		else
		{
			$output = $class->{$this->method}(...$this->router->params());
		}

		$this->benchmark->stop('controller');

		return $output;
	}

	//--------------------------------------------------------------------

	/**
	 * Displays a 404 Page Not Found error. If set, will try to
	 * call the 404Override controller/method that was set in routing config.
	 *
	 * @param PageNotFoundException $e
	 */
	protected function display404errors(PageNotFoundException $e)
	{
		// Is there a 404 Override available?
		if ($override = $this->router->get404Override())
		{
			if ($override instanceof Closure)
			{
				echo $override($e->getMessage());
			}
			else if (is_array($override))
			{
				$this->benchmark->start('controller');
				$this->benchmark->start('controller_constructor');

				$this->controller = $override[0];
				$this->method     = $override[1];

				unset($override);

				$controller = $this->createController();
				$this->runController($controller);
			}

			$this->gatherOutput();
			$this->sendResponse();

			return;
		}

		// Display 404 Errors
		$this->response->setStatusCode($e->getCode());

		if (ENVIRONMENT !== 'testing')
		{
			if (ob_get_level() > 0)
			{
				ob_end_flush();
			}
		}
		else
		{
			// When testing, one is for phpunit, another is for test case.
			if (ob_get_level() > 2)
			{
				ob_end_flush();
			}
		}

		throw PageNotFoundException::forPageNotFound($e->getMessage());
	}

	//--------------------------------------------------------------------

	/**
	 * Gathers the script output from the buffer, replaces some execution
	 * time tag in the output and displays the debug toolbar, if required.
	 *
	 * @param null $cacheConfig
	 * @param null $returned
	 */
	protected function gatherOutput($cacheConfig = null, $returned = null)
	{
		$this->output = ob_get_contents();
		// If buffering is not null.
		// Clean (erase) the output buffer and turn off output buffering
		if (ob_get_length())
		{
			ob_end_clean();
		}

		if ($returned instanceof DownloadResponse)
		{
			$this->response = $returned;
			return;
		}
		// If the controller returned a response object,
		// we need to grab the body from it so it can
		// be added to anything else that might have been
		// echoed already.
		// We also need to save the instance locally
		// so that any status code changes, etc, take place.
		if ($returned instanceof Response)
		{
			$this->response = $returned;
			$returned       = $returned->getBody();
		}

		if (is_string($returned))
		{
			$this->output .= $returned;
		}

		// Cache it without the performance metrics replaced
		// so that we can have live speed updates along the way.
		if (static::$cacheTTL > 0)
		{
			$this->cachePage($cacheConfig);
		}

		$this->output = $this->displayPerformanceMetrics($this->output);

		$this->response->setBody($this->output);
	}

	//--------------------------------------------------------------------

	/**
	 * If we have a session object to use, store the current URI
	 * as the previous URI. This is called just prior to sending the
	 * response to the client, and will make it available next request.
	 *
	 * This helps provider safer, more reliable previous_url() detection.
	 *
	 * @param \CodeIgniter\HTTP\URI $uri
	 */
	public function storePreviousURL($uri)
	{
		// This is mainly needed during testing...
		if (is_string($uri))
		{
			$uri = new URI($uri);
		}

		if (isset($_SESSION))
		{
			$_SESSION['_ci_previous_url'] = (string) $uri;
		}
	}

	//--------------------------------------------------------------------

	/**
	 * Modifies the Request Object to use a different method if a POST
	 * variable called _method is found.
	 *
	 * Does not work on CLI commands.
	 */
	public function spoofRequestMethod()
	{
		if (is_cli())
		{
			return;
		}

		// Only works with POSTED forms
		if ($this->request->getMethod() !== 'post')
		{
			return;
		}

		$method = $this->request->getPost('_method');

		if (empty($method))
		{
			return;
		}

		$this->request = $this->request->setMethod($method);
	}

	/**
	 * Sends the output of this request back to the client.
	 * This is what they've been waiting for!
	 */
	protected function sendResponse()
	{
		$this->response->pretend($this->useSafeOutput)->send();
	}

	//--------------------------------------------------------------------

	/**
	 * Exits the application, setting the exit code for CLI-based applications
	 * that might be watching.
	 *
	 * Made into a separate method so that it can be mocked during testing
	 * without actually stopping script execution.
	 *
	 * @param $code
	 */
	protected function callExit($code)
	{
		exit($code);
	}

	//--------------------------------------------------------------------
}


<?php

/**
 * CodeIgniter
 *
 * An open source application development framework for PHP
 *
 * This content is released under the MIT License (MIT)
 *
 * Copyright (c) 2014-2019 British Columbia Institute of Technology
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 *
 * @package    CodeIgniter
 * @author     CodeIgniter Dev Team
 * @copyright  2014-2019 British Columbia Institute of Technology (https://bcit.ca/)
 * @license    https://opensource.org/licenses/MIT	MIT License
 * @link       https://codeigniter.com
 * @since      Version 3.0.0
 * @filesource
 */

namespace CodeIgniter\Cache;

use CodeIgniter\Cache\Exceptions\CacheException;

/**
 * Class Cache
 *
 * A factory for loading the desired
 *
 * @package CodeIgniter\Cache
 */
class CacheFactory
{
	/**
	 * Attempts to create the desired cache handler, based upon the
	 *
	 * @param $config
	 * @param string $handler
	 * @param string $backup
	 *
	 * @return \CodeIgniter\Cache\CacheInterface
	 */
	public static function getHandler($config, string $handler = null, string $backup = null)
	{
		if (! isset($config->validHandlers) || ! is_array($config->validHandlers))
		{
			throw CacheException::forInvalidHandlers();
		}

		if (! isset($config->handler) || ! isset($config->backupHandler))
		{
			throw CacheException::forNoBackup();
		}

		$handler = ! empty($handler) ? $handler : $config->handler;
		$backup  = ! empty($backup) ? $backup : $config->backupHandler;

		if (! array_key_exists($handler, $config->validHandlers) || ! array_key_exists($backup, $config->validHandlers))
		{
			throw CacheException::forHandlerNotFound();
		}

		// Get an instance of our handler.
		$adapter = new $config->validHandlers[$handler]($config);

		if (! $adapter->isSupported())
		{
			$adapter = new $config->validHandlers[$backup]($config);

			if (! $adapter->isSupported())
			{
				// Log stuff here, don't throw exception. No need to raise a fuss.
				// Fall back to the dummy adapter.
				$adapter = new $config->validHandlers['dummy']();
			}
		}

		$adapter->initialize();

		return $adapter;
	}

	//--------------------------------------------------------------------
}