diff --git a/system/Cache/Handlers/MemcachedHandler.php b/system/Cache/Handlers/MemcachedHandler.php index 6d0c8aec4d97..3633dc8e40da 100644 --- a/system/Cache/Handlers/MemcachedHandler.php +++ b/system/Cache/Handlers/MemcachedHandler.php @@ -180,9 +180,11 @@ public function decrement(string $key, int $offset = 1): false|int $key = static::validateKey($key, $this->prefix); - // FIXME: third parameter isn't other handler actions. - - return $this->memcached->decrement($key, $offset, $offset, 60); + // Memcached counters are unsigned and saturate at 0, so a missing + // key can only ever be initialized to 0, never a negative value. + // Use Memcached::decrement()'s own default of 0 as the initial + // value instead of $offset, so a new key no longer starts positive. + return $this->memcached->decrement($key, $offset, 0, 60); } public function clean(): bool diff --git a/system/CodeIgniter.php b/system/CodeIgniter.php index 1654e82399e7..bf8700660f2a 100644 --- a/system/CodeIgniter.php +++ b/system/CodeIgniter.php @@ -505,29 +505,29 @@ protected function handleRequest(?RouteCollectionInterface $routes, Cache $cache // If startController returned a Response (from an attribute or Closure), use it if ($returned instanceof ResponseInterface) { $this->gatherOutput($cacheConfig, $returned); - } - // Closure controller has run in startController(). - elseif (! is_callable($this->controller)) { - $controller = $this->createController(); + } else { + // Closure controller has run in startController(). + if (! is_callable($this->controller)) { + $controller = $this->createController(); - if (! method_exists($controller, '_remap') && ! is_callable([$controller, $this->method], false)) { - throw PageNotFoundException::forMethodNotFound($this->method); - } + if (! method_exists($controller, '_remap') && ! is_callable([$controller, $this->method], false)) { + throw PageNotFoundException::forMethodNotFound($this->method); + } - // Is there a "post_controller_constructor" event? - Events::trigger('post_controller_constructor'); + // 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); + $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); + } if ($this->enableFilters) { /** @var Filters $filters */ $filters = service('filters'); diff --git a/system/Database/Database.php b/system/Database/Database.php index 4cb5dfaf1627..a6f0e9cb73ef 100644 --- a/system/Database/Database.php +++ b/system/Database/Database.php @@ -58,7 +58,7 @@ public function load(array $params = [], string $alias = '') throw new InvalidArgumentException('You have not selected a database type to connect to.'); } - assert($this->checkDbExtension($params['DBDriver'])); + $this->checkDbExtension($params['DBDriver']); $this->connections[$alias] = $this->initDriver($params['DBDriver'], 'Connection', $params); @@ -154,15 +154,17 @@ protected function initDriver(string $driver, string $class, $argument): object } /** - * Check the PHP database extension is loaded. + * Check if the PHP database extension is loaded. * * @param string $driver DB driver or FQCN for custom driver + * + * @throws ConfigException if the driver is invalid + * @throws CriticalError if the required PHP extension is not loaded */ - private function checkDbExtension(string $driver): bool + private function checkDbExtension(string $driver): void { if (str_contains($driver, '\\')) { - // Cannot check a fully qualified classname for a custom driver. - return true; + return; // Cannot check a fully qualified classname for a custom driver. } $extensionMap = [ @@ -174,21 +176,17 @@ private function checkDbExtension(string $driver): bool 'OCI8' => 'oci8', ]; - $extension = $extensionMap[$driver] ?? ''; - - if ($extension === '') { - $message = 'Invalid DBDriver name: "' . $driver . '"'; - - throw new ConfigException($message); - } + $extension = $extensionMap[$driver] + ?? throw new ConfigException(sprintf('Invalid DBDriver name: "%s".', $driver)); if (extension_loaded($extension)) { - return true; + return; } - $message = 'The required PHP extension "' . $extension . '" is not loaded.' - . ' Install and enable it to use "' . $driver . '" driver.'; - - throw new CriticalError($message); + throw new CriticalError(sprintf( + 'The required PHP extension "%s" is not loaded. Install and enable it to use "%s" driver.', + $extension, + $driver, + )); } } diff --git a/system/Database/SQLite3/Table.php b/system/Database/SQLite3/Table.php index 1884d8c3ed44..3737822eaeeb 100644 --- a/system/Database/SQLite3/Table.php +++ b/system/Database/SQLite3/Table.php @@ -333,9 +333,16 @@ protected function createTable() } foreach ($this->foreignKeys as $foreignKey) { + $foreignTableName = $foreignKey->foreign_table_name; + $prefix = $this->db->DBPrefix; + + if ($prefix !== '' && str_starts_with($foreignTableName, $prefix)) { + $foreignTableName = substr($foreignTableName, strlen($prefix)); + } + $this->forge->addForeignKey( $foreignKey->column_name, - trim($foreignKey->foreign_table_name, $this->db->DBPrefix), + $foreignTableName, $foreignKey->foreign_column_name, ); } diff --git a/system/Files/File.php b/system/Files/File.php index feda0cd5780d..2cf394355185 100644 --- a/system/Files/File.php +++ b/system/Files/File.php @@ -170,7 +170,7 @@ public function move(string $targetPath, ?string $name = null, bool $overwrite = throw FileException::forUnableToMove($this->getBasename(), $targetPath, strip_tags($error['message'])); } - @chmod($destination, 0777 & ~umask()); + @chmod($destination, 0666 & ~umask()); return new self($destination); } diff --git a/system/HTTP/Files/FileCollection.php b/system/HTTP/Files/FileCollection.php index 058e86c3a4aa..c1c0582f6ff5 100644 --- a/system/HTTP/Files/FileCollection.php +++ b/system/HTTP/Files/FileCollection.php @@ -189,7 +189,7 @@ protected function createFileObject(array $array) return new UploadedFile( $array['tmp_name'] ?? null, - $array['name'] ?? null, + $array['name'], $array['type'] ?? null, ($array['size'] ?? null) === null ? null : (int) $array['size'], $array['error'] ?? null, diff --git a/system/HTTP/Files/UploadedFile.php b/system/HTTP/Files/UploadedFile.php index bf594acddc38..f469e3e7023a 100644 --- a/system/HTTP/Files/UploadedFile.php +++ b/system/HTTP/Files/UploadedFile.php @@ -159,7 +159,7 @@ public function move(string $targetPath, ?string $name = null, bool $overwrite = throw HTTPException::forMoveFailed(basename($this->path), $targetPath, $message); } - @chmod($targetPath, 0777 & ~umask()); + @chmod($destination, 0666 & ~umask()); // Success, so store our new information $this->path = $targetPath; diff --git a/system/HTTP/SiteURIFactory.php b/system/HTTP/SiteURIFactory.php index 73cc9fe84ee4..11dccce6c540 100644 --- a/system/HTTP/SiteURIFactory.php +++ b/system/HTTP/SiteURIFactory.php @@ -227,7 +227,7 @@ private function createURIFromRoutePath(string $routePath): SiteURI */ private function getHost(): ?string { - $httpHostPort = $this->superglobals->server('HTTP_HOST') ?? null; + $httpHostPort = $this->superglobals->server('HTTP_HOST'); if ($httpHostPort !== null) { [$httpHost] = explode(':', $httpHostPort, 2); diff --git a/system/Helpers/Array/ArrayHelper.php b/system/Helpers/Array/ArrayHelper.php index f70f6905ca5d..d370e1f1112f 100644 --- a/system/Helpers/Array/ArrayHelper.php +++ b/system/Helpers/Array/ArrayHelper.php @@ -324,7 +324,7 @@ public static function recursiveCount(array $array, int $counter = 0): int * @param list|string> $array * @param int|string|null $sortByIndex */ - public static function sortValuesByNatural(array &$array, $sortByIndex = null): bool + public static function sortValuesByNatural(array &$array, $sortByIndex = null): true { return usort($array, static function ($currentValue, $nextValue) use ($sortByIndex): int { if ($sortByIndex !== null) { diff --git a/system/Router/RouteCollection.php b/system/Router/RouteCollection.php index 6ade80e6f9fc..c08c01530b79 100644 --- a/system/Router/RouteCollection.php +++ b/system/Router/RouteCollection.php @@ -1520,7 +1520,7 @@ private function checkSubdomains($subdomains): bool // Routes can be limited to any sub-domain. In that case, though, // it does require a sub-domain to be present. - if (! in_array($this->currentSubdomain, [null, ''], true) && in_array('*', $subdomains, true)) { + if ($this->currentSubdomain !== '' && in_array('*', $subdomains, true)) { return true; } diff --git a/tests/system/Cache/Handlers/MemcachedHandlerTest.php b/tests/system/Cache/Handlers/MemcachedHandlerTest.php index 78412616e5bf..e81c8c9056fe 100644 --- a/tests/system/Cache/Handlers/MemcachedHandlerTest.php +++ b/tests/system/Cache/Handlers/MemcachedHandlerTest.php @@ -151,7 +151,12 @@ public function testDecrement(): void $this->assertSame(9, $memcachedHandler->decrement(self::$key1, 1)); $this->assertFalse($memcachedHandler->decrement(self::$key2, 1)); - $this->assertSame(1, $memcachedHandler->decrement(self::$key3, 1)); + // A key that doesn't exist yet starts at 0, not at the offset + // (Memcached counters are unsigned, so it can't start negative). + $this->assertSame(0, $memcachedHandler->decrement(self::$key3, 5)); + // Memcached stores counter values as decimal strings on the wire, so + // a plain get() on a counter key returns a string, not an int. + $this->assertSame('0', $memcachedHandler->get(self::$key3)); } public function testClean(): void diff --git a/tests/system/CodeIgniterTest.php b/tests/system/CodeIgniterTest.php index c5b3863ee203..da65ffd4a22d 100644 --- a/tests/system/CodeIgniterTest.php +++ b/tests/system/CodeIgniterTest.php @@ -1308,4 +1308,37 @@ public function testResetForWorkerMode(): void $this->assertSame($csp->getStyleNonce(), RichRenderer::$css_nonce); $this->assertTrue(RichRenderer::$needs_pre_render); } + + public function testGatherOutputCalledOnceWhenControllerReturnsResponse(): void + { + $this->resetServices(); + + $superglobals = service('superglobals'); + $superglobals->setServer('argv', ['index.php', 'pages/test']); + $superglobals->setServer('argc', 2); + $superglobals->setServer('REQUEST_URI', '/pages/test'); + $superglobals->setServer('SCRIPT_NAME', '/index.php'); + + $routes = service('routes'); + $routes->add('pages/test', static fn () => service('response')->setBody('Test Body')); + + $config = new App(); + $codeigniter = new class ($config) extends MockCodeIgniter { + public int $gatherOutputCalls = 0; + + protected function gatherOutput(?Cache $cacheConfig = null, $returned = null): void + { + $this->gatherOutputCalls++; + parent::gatherOutput($cacheConfig, $returned); + } + }; + + ob_start(); + $codeigniter->run($routes); + ob_end_clean(); + + // When startController() returns a ResponseInterface (e.g. from a closure route), + // gatherOutput() must be called exactly once — not twice as in the original bug. + $this->assertSame(1, $codeigniter->gatherOutputCalls); + } } diff --git a/tests/system/Database/Live/SQLite3/AlterTableTest.php b/tests/system/Database/Live/SQLite3/AlterTableTest.php index a68d42ca1440..a7ba8ad13f03 100644 --- a/tests/system/Database/Live/SQLite3/AlterTableTest.php +++ b/tests/system/Database/Live/SQLite3/AlterTableTest.php @@ -271,6 +271,68 @@ public function testProcessCopiesOldData(): void $this->seeInDatabase('foo', ['email' => 'funkalicious@example.com']); } + public function testDropColumnKeepsForeignKeyTableNameWhenPrefixIsSet(): void + { + $config = [ + 'DBDriver' => 'SQLite3', + 'database' => ':memory:', + 'DBDebug' => true, + 'DBPrefix' => 'db_', + ]; + + $db = db_connect($config, false); + $this->assertInstanceOf(Connection::class, $db); + + $forge = Database::forge($db); + $this->assertInstanceOf(Forge::class, $forge); + + // The referenced table must begin with a character that also appears in + // the prefix, or the prefix stripping cannot damage its name. + $forge->addField([ + 'id' => [ + 'type' => 'integer', + 'constraint' => 11, + 'unsigned' => true, + 'auto_increment' => true, + ], + ]); + $forge->addPrimaryKey('id'); + $forge->createTable('bandit_fk'); + + $forge->addField([ + 'id' => [ + 'type' => 'integer', + 'constraint' => 11, + 'unsigned' => true, + 'auto_increment' => true, + ], + 'key_id' => [ + 'type' => 'integer', + 'constraint' => 11, + 'unsigned' => true, + ], + 'name' => [ + 'type' => 'varchar', + 'constraint' => 255, + 'null' => true, + ], + ]); + $forge->addPrimaryKey('id'); + $forge->addForeignKey('key_id', 'bandit_fk', 'id'); + $forge->createTable('bandit'); + + // Dropping a column rebuilds the table, recreating its foreign keys. + $this->assertTrue($forge->dropColumn('bandit', 'name')); + + $keys = array_values($db->getForeignKeyData('bandit')); + + $this->assertCount(1, $keys); + $this->assertSame($db->DBPrefix . 'bandit_fk', $keys[0]->foreign_table_name); + + $forge->dropTable('bandit', true); + $forge->dropTable('bandit_fk', true); + } + protected function createTable(string $tableName = 'foo'): void { // Create support table for foreign keys diff --git a/tests/system/Files/FileWithVfsTest.php b/tests/system/Files/FileWithVfsTest.php index a6c26383d187..e0065591963d 100644 --- a/tests/system/Files/FileWithVfsTest.php +++ b/tests/system/Files/FileWithVfsTest.php @@ -150,4 +150,13 @@ public function testMoveReturnsNewInstance(): void $this->assertInstanceOf(File::class, $file); $this->assertSame($destination . '/apple.php', $file->getPathname()); } + + public function testMovePermissions(): void + { + $destination = $this->start . 'baker'; + $this->file->move($destination); + + $expectedPerms = 0666 & ~umask(); + $this->assertSame($expectedPerms, $this->root->getChild('baker/apple.php')->getPermissions()); + } } diff --git a/tests/system/HTTP/Files/FileMovingTest.php b/tests/system/HTTP/Files/FileMovingTest.php index bb4b637fdc47..fb07d10ed74b 100644 --- a/tests/system/HTTP/Files/FileMovingTest.php +++ b/tests/system/HTTP/Files/FileMovingTest.php @@ -98,6 +98,7 @@ public function testMove(): void $this->assertTrue($this->root->hasChild('destination/' . $finalFilename . '.txt')); $this->assertTrue($this->root->hasChild('destination/' . $finalFilename . '_1.txt')); + $this->assertSame(0666 & ~umask(), $this->root->getChild('destination/' . $finalFilename . '.txt')->getPermissions()); } public function testMoveSanitizesClientNameByDefault(): void diff --git a/tests/system/Session/Handlers/FileHandlerTest.php b/tests/system/Session/Handlers/FileHandlerTest.php new file mode 100644 index 000000000000..3c94aacad693 --- /dev/null +++ b/tests/system/Session/Handlers/FileHandlerTest.php @@ -0,0 +1,487 @@ + + * + * For the full copyright and license information, please view + * the LICENSE file that was distributed with this source code. + */ + +namespace CodeIgniter\Session\Handlers; + +use Closure; +use CodeIgniter\Session\Exceptions\SessionException; +use CodeIgniter\Test\CIUnitTestCase; +use CodeIgniter\Test\TestLogger; +use Config\Logger as LoggerConfig; +use Config\Session as SessionConfig; +use PHPUnit\Framework\Attributes\Group; +use PHPUnit\Framework\Attributes\RequiresOperatingSystem; + +/** + * @internal + */ +#[Group('Others')] +final class FileHandlerTest extends CIUnitTestCase +{ + private string $sessionDriver = FileHandler::class; + private string $sessionName = 'ci_session'; + private string $userIpAddress = '127.0.0.1'; + private string $tempPath; + private string $originalSavePath; + private string $originalSidBits; + private string $originalSidLength; + + protected function setUp(): void + { + parent::setUp(); + + $this->originalSavePath = (string) ini_get('session.save_path'); + $this->originalSidBits = (string) ini_get('session.sid_bits_per_character'); + $this->originalSidLength = (string) ini_get('session.sid_length'); + + $this->tempPath = rtrim(sys_get_temp_dir(), '/\\') . DIRECTORY_SEPARATOR . 'FileHandlerTest_' . bin2hex(random_bytes(6)); + mkdir($this->tempPath, 0700, true); + } + + protected function tearDown(): void + { + parent::tearDown(); + + ini_set('session.save_path', $this->originalSavePath); + ini_set('session.sid_bits_per_character', $this->originalSidBits); + ini_set('session.sid_length', $this->originalSidLength); + + $this->removeDirectory($this->tempPath); + } + + /** + * @param array $options Replace values for `Config\Session`. + */ + protected function getInstance(array $options = []): FileHandler + { + $defaults = [ + 'driver' => $this->sessionDriver, + 'cookieName' => $this->sessionName, + 'expiration' => 7200, + 'savePath' => $this->tempPath, + 'matchIP' => false, + 'timeToUpdate' => 300, + 'regenerateDestroy' => false, + ]; + $sessionConfig = new SessionConfig(); + $config = array_merge($defaults, $options); + + foreach ($config as $key => $value) { + $sessionConfig->{$key} = $value; + } + + $handler = new FileHandler($sessionConfig, $this->userIpAddress); + $handler->setLogger(new TestLogger(new LoggerConfig())); + + return $handler; + } + + /** + * Runs a callback while suppressing any PHP warnings it raises. + * + * @param Closure(): mixed $callback + */ + private function withSuppressedErrors(Closure $callback): mixed + { + set_error_handler(static fn (int $severity, string $message): bool => true); + + try { + return $callback(); + } finally { + restore_error_handler(); + } + } + + private function removeDirectory(string $path): void + { + if (! is_dir($path)) { + return; + } + + $items = scandir($path); + + foreach ($items === false ? [] : $items as $item) { + if ($item === '.' || $item === '..') { + continue; + } + + $target = $path . DIRECTORY_SEPARATOR . $item; + + if (is_dir($target)) { + $this->removeDirectory($target); + } else { + @unlink($target); + } + } + + @chmod($path, 0700); + @rmdir($path); + } + + private static function sessionId(string $char): string + { + return str_repeat($char, 32); + } + + // -------------------------------------------------------------------- + // Constructor & Initialization + // -------------------------------------------------------------------- + + public function testConstructorTrimsAndSetsIniSavePath(): void + { + $this->getInstance(['savePath' => $this->tempPath . '//']); + + $this->assertSame($this->tempPath, ini_get('session.save_path')); + } + + public function testConstructorForcesSessionIDRegexSettings(): void + { + ini_set('session.sid_bits_per_character', '5'); + ini_set('session.sid_length', '26'); + + $this->getInstance(); + + $this->assertSame('4', ini_get('session.sid_bits_per_character')); + $this->assertSame('32', ini_get('session.sid_length')); + } + + // -------------------------------------------------------------------- + // open() + // -------------------------------------------------------------------- + + public function testOpenExistingDirectory(): void + { + $handler = $this->getInstance(); + + $this->assertTrue($handler->open($this->tempPath, $this->sessionName)); + } + + public function testOpenWithMatchIPIsolatesSessions(): void + { + $id = self::sessionId('1'); + $data = 'ip_test_data'; + + $handler1 = $this->getInstance(['matchIP' => true]); + $this->assertTrue($handler1->open($this->tempPath, $this->sessionName)); + $this->assertSame('', $handler1->read($id)); + $this->assertTrue($handler1->write($id, $data)); + $this->assertTrue($handler1->close()); + + // File created with hashed IP in filename + $this->assertFileExists($this->tempPath . '/' . $this->sessionName . md5($this->userIpAddress) . $id); + + // Handler with different IP cannot read the session (isolation) + $sessionConfig = new SessionConfig(); + $sessionConfig->driver = $this->sessionDriver; + $sessionConfig->cookieName = $this->sessionName; + $sessionConfig->savePath = $this->tempPath; + $sessionConfig->matchIP = true; + + $handler2 = new FileHandler($sessionConfig, '192.168.1.1'); + $handler2->setLogger(new TestLogger(new LoggerConfig())); + $this->assertTrue($handler2->open($this->tempPath, $this->sessionName)); + $this->assertSame('', $handler2->read($id)); + $this->assertTrue($handler2->close()); + } + + public function testOpenCreatesMissingDirectory(): void + { + $handler = $this->getInstance(); + + $path = $this->tempPath . '/new/nested'; + + $this->assertTrue($handler->open($path, $this->sessionName)); + $this->assertDirectoryExists($path); + } + + public function testOpenThrowsForInvalidSavePath(): void + { + file_put_contents($this->tempPath . '/blocker', 'data'); + + $handler = $this->getInstance(); + + $this->expectException(SessionException::class); + $this->withSuppressedErrors(fn (): bool => $handler->open($this->tempPath . '/blocker/sub', $this->sessionName)); + } + + #[RequiresOperatingSystem('Linux|Darwin')] + public function testOpenThrowsForWriteProtectedSavePath(): void + { + $dir = $this->tempPath . '/readonly'; + mkdir($dir, 0700); + chmod($dir, 0555); + + if (is_writable($dir)) { + $this->markTestSkipped('Directory permissions cannot be restricted for this user (e.g. running as root).'); + } + + try { + $handler = $this->getInstance(); + + $this->expectException(SessionException::class); + $handler->open($dir, $this->sessionName); + } finally { + chmod($dir, 0755); + } + } + + // -------------------------------------------------------------------- + // read() + // -------------------------------------------------------------------- + + public function testReadNewSession(): void + { + $handler = $this->getInstance(); + $handler->open($this->tempPath, $this->sessionName); + + $id = self::sessionId('1'); + + $this->assertSame('', $handler->read($id)); + + $handler->close(); + } + + public function testReadExistingSession(): void + { + $id = self::sessionId('2'); + $data = '__ci_last_regenerate|i:1664607454;key|s:5:"value";'; + file_put_contents($this->tempPath . '/' . $this->sessionName . $id, $data); + + $handler = $this->getInstance(); + $handler->open($this->tempPath, $this->sessionName); + + $this->assertSame($data, $handler->read($id)); + + $handler->close(); + } + + public function testReadTwiceWithoutCloseRewinds(): void + { + $id = self::sessionId('3'); + $data = '__ci_last_regenerate|i:1664607454;key|s:5:"value";'; + + $handler = $this->getInstance(); + $handler->open($this->tempPath, $this->sessionName); + + $this->assertSame('', $handler->read($id)); + $this->assertTrue($handler->write($id, $data)); + + $this->assertSame($data, $handler->read($id)); + + $handler->close(); + } + + public function testReadFailsWhenFileCannotBeOpened(): void + { + $handler = $this->getInstance(); + $handler->open($this->tempPath, $this->sessionName); + + $id = self::sessionId('4'); + mkdir($this->tempPath . '/' . $this->sessionName . $id, 0700, true); + + $result = $this->withSuppressedErrors(static fn (): false|string => $handler->read($id)); + + $this->assertFalse($result); + $this->assertLogContains('error', 'Session: Unable to open file'); + } + + // -------------------------------------------------------------------- + // write() + // -------------------------------------------------------------------- + + public function testWriteFailsWhenNoFileHandle(): void + { + $handler = $this->getInstance(); + + $this->assertFalse($handler->write(self::sessionId('a'), 'data')); + } + + public function testReadWriteRoundtrip(): void + { + $id = self::sessionId('b'); + $data = '__ci_last_regenerate|i:1664607454;key|s:5:"value";'; + + $handler = $this->getInstance(); + $handler->open($this->tempPath, $this->sessionName); + + $this->assertSame('', $handler->read($id)); + $this->assertTrue($handler->write($id, $data)); + // Identical data on a new file returns true without writing again. + $this->assertTrue($handler->write($id, $data)); + + $handler->close(); + + $this->assertSame($data, file_get_contents($this->tempPath . '/' . $this->sessionName . $id)); + + // A second handler reads the file back; an identical write just touches it. + $handler2 = $this->getInstance(); + $handler2->open($this->tempPath, $this->sessionName); + + $this->assertSame($data, $handler2->read($id)); + $this->assertTrue($handler2->write($id, $data)); + + // Different data truncates and rewrites the existing file. + $data2 = 'changed|i:1664607455;key|s:6:"value2";'; + $this->assertTrue($handler2->write($id, $data2)); + + $handler2->close(); + + $this->assertSame($data2, file_get_contents($this->tempPath . '/' . $this->sessionName . $id)); + } + + public function testWriteEmptyDataClearsSession(): void + { + $id = self::sessionId('c'); + $data = 'some_data'; + + $handler1 = $this->getInstance(); + $handler1->open($this->tempPath, $this->sessionName); + $this->assertSame('', $handler1->read($id)); + $this->assertTrue($handler1->write($id, $data)); + $handler1->close(); + + $this->assertSame($data, file_get_contents($this->tempPath . '/' . $this->sessionName . $id)); + + $handler2 = $this->getInstance(); + $handler2->open($this->tempPath, $this->sessionName); + $this->assertSame($data, $handler2->read($id)); + $this->assertTrue($handler2->write($id, '')); + $handler2->close(); + + $this->assertSame('', file_get_contents($this->tempPath . '/' . $this->sessionName . $id)); + } + + public function testWriteWithDifferentSessionID(): void + { + $handler = $this->getInstance(); + $handler->open($this->tempPath, $this->sessionName); + + $id1 = self::sessionId('d'); + $id2 = self::sessionId('e'); + + $this->assertSame('', $handler->read($id1)); + $this->assertTrue($handler->write($id2, 'data')); + $handler->close(); + } + + // -------------------------------------------------------------------- + // close() + // -------------------------------------------------------------------- + + public function testCloseWithOpenFile(): void + { + $handler = $this->getInstance(); + $handler->open($this->tempPath, $this->sessionName); + $handler->read(self::sessionId('1')); + + $this->assertTrue($handler->close()); + // After closing, write fails + $this->assertFalse($handler->write(self::sessionId('1'), 'data')); + } + + public function testCloseWithoutOpenFile(): void + { + $handler = $this->getInstance(); + + $this->assertTrue($handler->close()); + } + + // -------------------------------------------------------------------- + // destroy() + // -------------------------------------------------------------------- + + public function testDestroyExistingSession(): void + { + $handler = $this->getInstance(); + $handler->open($this->tempPath, $this->sessionName); + + $id = self::sessionId('2'); + $handler->read($id); + $handler->close(); + + $this->assertFileExists($this->tempPath . '/' . $this->sessionName . $id); + $this->assertTrue($handler->destroy($id)); + $this->assertFileDoesNotExist($this->tempPath . '/' . $this->sessionName . $id); + } + + public function testDestroyNonexistentSession(): void + { + $handler = $this->getInstance(); + $handler->open($this->tempPath, $this->sessionName); + $handler->close(); + + $this->assertTrue($handler->destroy(self::sessionId('3'))); + } + + // -------------------------------------------------------------------- + // gc() + // -------------------------------------------------------------------- + + public function testGCWhenSavePathMissing(): void + { + $handler = $this->getInstance(['savePath' => $this->tempPath . '/missing']); + + $this->assertFalse($handler->gc(3600)); + $this->assertLogContains('debug', "Session: Garbage collector couldn't list files under directory"); + } + + public function testGCRemovesExpiredSessionsOnly(): void + { + $handler = $this->getInstance(['savePath' => $this->tempPath]); + + $expired = $this->tempPath . '/' . $this->sessionName . self::sessionId('a'); + file_put_contents($expired, 'data'); + touch($expired, time() - 4000); + + $recent = $this->tempPath . '/' . $this->sessionName . self::sessionId('b'); + file_put_contents($recent, 'data'); + touch($recent); + + $directory = $this->tempPath . '/' . $this->sessionName . self::sessionId('c'); + mkdir($directory, 0700); + + $foreign = $this->tempPath . '/not-a-session-file'; + file_put_contents($foreign, 'data'); + touch($foreign, time() - 4000); + + $nonHex = $this->tempPath . '/' . $this->sessionName . str_repeat('z', 32); + file_put_contents($nonHex, 'data'); + touch($nonHex, time() - 4000); + + $this->assertSame(1, $handler->gc(3600)); + + $this->assertFileDoesNotExist($expired); + $this->assertFileExists($recent); + $this->assertDirectoryExists($directory); + $this->assertFileExists($foreign); + $this->assertFileExists($nonHex); + } + + public function testGCWithMatchIP(): void + { + $handler = $this->getInstance(['savePath' => $this->tempPath, 'matchIP' => true]); + + $expired = $this->tempPath . '/' . $this->sessionName . md5($this->userIpAddress) . self::sessionId('a'); + file_put_contents($expired, 'data'); + touch($expired, time() - 4000); + + $withoutIp = $this->tempPath . '/' . $this->sessionName . self::sessionId('b'); + file_put_contents($withoutIp, 'data'); + touch($withoutIp, time() - 4000); + + $this->assertSame(1, $handler->gc(3600)); + + $this->assertFileDoesNotExist($expired); + $this->assertFileExists($withoutIp); + } +} diff --git a/user_guide_src/source/changelogs/v4.7.5.rst b/user_guide_src/source/changelogs/v4.7.5.rst index 9977c5ef7df5..f13a3e4b2b49 100644 --- a/user_guide_src/source/changelogs/v4.7.5.rst +++ b/user_guide_src/source/changelogs/v4.7.5.rst @@ -39,11 +39,15 @@ Bugs Fixed - **CLI:** Fixed a bug where pressing backspace in a ``CLI::prompt()`` erased the prompt text when the ``readline`` extension is enabled. The prompt is now passed to ``readline()`` so line redraws repaint it. ANSI color codes in the prompt (e.g., option defaults) are wrapped in readline's non-printing markers under GNU readline so cursor positioning stays accurate. - **CLIRequest:** Fixed a bug where ``parseCommand()`` could throw a TypeError when ``argv`` is missing. +- **CodeIgniter:** Fixed a bug where ``gatherOutput()`` could be called twice when ``startController()`` returned a ``ResponseInterface`` (e.g., from filter attributes or closure routes). - **Content Security Policy:** Fixed a bug where empty ``Content-Security-Policy``, ``Content-Security-Policy-Report-Only``, and ``Reporting-Endpoints`` response headers were generated when no corresponding values existed. - **Cookie:** Fixed a bug where ``Cookie`` instances created with ``raw: true`` allowed invalid characters in cookie values rejected by ``setrawcookie()``. +- **Database:** Fixed a bug where rebuilding a SQLite3 table (e.g., ``Forge::dropColumn()``, ``Forge::modifyColumn()``, ``Forge::dropForeignKey()`` and ``Forge::dropPrimaryKey()``) corrupted the table names referenced by its foreign keys when ``DBPrefix`` was set. +- **Files:** Fixed a bug where ``File::move()`` and ``UploadedFile::move()`` set executable and overly permissive file permissions (``0777 & ~umask()`` instead of ``0666 & ~umask()``), and ``UploadedFile::move()`` targeted the parent directory instead of the destination file for ``chmod()``. - **Helpers:** Fixed a bug where ``get_dir_file_info()`` returned incomplete entries for subdirectories and missing files instead of omitting them. - **Honeypot:** Fixed a bug where bot detection returned an HTTP 500 response instead of 403 (Forbidden). - **Logger:** Fixed a bug where interpolating a log message with array or non-stringable context values could raise PHP warnings or errors. +- **Cache:** Fixed ``MemcachedHandler::decrement()`` initializing a non-existent counter to the positive offset. Missing counters are now initialized to ``0``, reflecting Memcached's unsigned, saturating counter semantics. See the repo's `CHANGELOG.md `_ diff --git a/user_guide_src/source/libraries/caching.rst b/user_guide_src/source/libraries/caching.rst index b208d63499df..76a696f570ee 100644 --- a/user_guide_src/source/libraries/caching.rst +++ b/user_guide_src/source/libraries/caching.rst @@ -212,6 +212,11 @@ Class Reference .. literalinclude:: caching/008.php + .. important:: Memcached counters are unsigned and saturate at ``0`` instead of + going negative. Decrementing a key that does not yet exist initializes it + to ``0`` (rather than ``-$offset``, as the File, Redis, and Predis handlers + do), and decrementing an existing counter below ``0`` clamps it at ``0``. + .. php:method:: clean() :returns: ``true`` on success, ``false`` on failure