From b7c711d52c14fc050ac82c98eb0483004c62845e Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 17:06:06 +0000 Subject: [PATCH 1/2] HtaccessHelper: read the file once into before/section/after and write it back once (issue #283, C15) The marker state machines of extract() and insert() are one parser, load(), and one writer, store(). Every change reads the file once instead of twice. The output is byte for byte that of the old code for a file with none or one section, with the same results and log messages; a file with several sections now gets one, not the merged section once for each. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01AFJFMNpwNryanqvRcQvqDc --- CHANGELOG | 6 + library/src/Helper/HtaccessHelper.php | 207 ++++++++++------------- tests/Integration/HtaccessHelperTest.php | 12 ++ 3 files changed, 106 insertions(+), 119 deletions(-) diff --git a/CHANGELOG b/CHANGELOG index 78b41d8..e545da5 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -22,6 +22,12 @@ didn't count before either) in a small table of offences per address, #__bfstop_offence, which is kept for a year after an address's latest block, and for at most 10000 addresses + - Code clean-up (issue #283, C15): the .htaccess file is read once for + each change and written back once, as before / block section / after, + instead of being scanned for the markers by two state machines (one to + read the section, one to replace it). A file with several block + sections - not meant to exist - now gets one, with all their addresses, + where a change used to write the merged section once for each of them - phpstan (level 5, with a baseline) runs in CI, against the types of the Joomla! classes (issue #283) - The daily maintenance - purging old failed logins, blocks and unblock diff --git a/library/src/Helper/HtaccessHelper.php b/library/src/Helper/HtaccessHelper.php index 12b8edd..02b12e9 100644 --- a/library/src/Helper/HtaccessHelper.php +++ b/library/src/Helper/HtaccessHelper.php @@ -116,12 +116,13 @@ public function checkRequirements() * which somebody wrote into it by hand. Read from both the current and * the earlier form (see LegacyLines). * + * @param string[] $lines the lines of the section (see load()) * @return array{addresses: string[], errorDocument: string|null, other: string[], legacy: bool} */ - private function parseSection() + private static function parseSection(array $lines) { $section = array('addresses' => array(), 'errorDocument' => null, 'other' => array(), 'legacy' => false); - foreach ($this->extract() as $line) + foreach ($lines as $line) { $trimmed = trim($line); if ($trimmed === '' || $trimmed === self::DenyLine || $trimmed === self::EndIfLine) @@ -288,7 +289,7 @@ public function getDeniedIPs() // the list is shown in the backend, and what it holds is whatever // somebody wrote into the file: only addresses and subnets are // passed on - return array_values(array_filter($this->parseSection()['addresses'], + return array_values(array_filter(self::parseSection($this->load()['section'])['addresses'], array(IpHelper::class, 'isValidIpOrSubnet'))); } @@ -315,7 +316,8 @@ public function denyIP($IP) } return $this->locked(function () use ($IP) { - $section = $this->parseSection(); + $file = $this->load(); + $section = self::parseSection($file['section']); if (!in_array($IP, $section['addresses'], true)) { if (count($section['addresses']) >= self::MaxBlockLines) @@ -329,7 +331,7 @@ public function denyIP($IP) } $section['addresses'][] = $IP; } - return $this->insert(self::renderSection($section)); + return $this->store($file, self::renderSection($section)); }); } @@ -343,7 +345,8 @@ public function undenyIP($IP) { return $this->locked(function () use ($IP) { - $section = $this->parseSection(); + $file = $this->load(); + $section = self::parseSection($file['section']); $key = array_search((string) $IP, $section['addresses'], true); if ($key === false && !$section['legacy']) { @@ -353,7 +356,7 @@ public function undenyIP($IP) { unset($section['addresses'][$key]); } - return $this->insert(self::renderSection($section)); + return $this->store($file, self::renderSection($section)); }); } @@ -363,7 +366,7 @@ public function undenyIP($IP) */ public function hasLegacySection() { - return $this->parseSection()['legacy']; + return self::parseSection($this->load()['section'])['legacy']; } /** @@ -379,9 +382,10 @@ public function upgradeFormat() { return $this->locked(function () { - $section = $this->parseSection(); + $file = $this->load(); + $section = self::parseSection($file['section']); $rendered = self::renderSection($section); - $current = array_values(array_filter($this->extract(), function ($line) + $current = array_values(array_filter($file['section'], function ($line) { return trim($line) !== ''; })); @@ -397,7 +401,7 @@ public function upgradeFormat() : 'Writing the block section of '.$this->path.' in its current form', $section['legacy'] ? Log::WARNING : Log::INFO); } - return $this->insert($rendered); + return $this->store($file, $rendered); }); } @@ -490,7 +494,8 @@ public function removeAddresses(array $addresses, $reason = '', ?callable $activ } return $this->locked(function () use ($addresses, $reason, $active) { - $section = $this->parseSection(); + $file = $this->load(); + $section = self::parseSection($file['section']); $removed = array_values(array_intersect($section['addresses'], $addresses)); $within = array(); foreach (array_diff($section['addresses'], $removed) as $entry) @@ -526,7 +531,7 @@ function ($entry) use ($stillBlocked) return 0; } $section['addresses'] = array_values(array_diff($section['addresses'], $removed)); - if (!$this->insert(self::renderSection($section))) + if (!$this->store($file, self::renderSection($section))) { return false; } @@ -565,9 +570,10 @@ public function edit403Message($message) return $this->locked(function () use ($line) { - $section = $this->parseSection(); + $file = $this->load(); + $section = self::parseSection($file['section']); $section['errorDocument'] = $line; - return $this->insert(self::renderSection($section)); + return $this->store($file, self::renderSection($section)); }); } @@ -580,13 +586,14 @@ public function remove403Message() { return $this->locked(function () { - $section = $this->parseSection(); + $file = $this->load(); + $section = self::parseSection($file['section']); if ($section['errorDocument'] === null && !$section['legacy']) { return true; } $section['errorDocument'] = null; - return $this->insert(self::renderSection($section)); + return $this->store($file, self::renderSection($section)); }); } @@ -694,138 +701,100 @@ private function write($content) private static $marker = 'BFStop Blocks'; /** - * Return array of strings from between BEGIN and END markers from .htaccess. + * The file as the parts the plugin cares about, read once: * - * @return array Array of strings from between BEGIN and END markers from .htaccess. + * - before: the lines up to the block section (all the lines if there is + * none) + * - section: the lines between the BEGIN and END markers, without the + * markers. If the file has several sections (it is not meant to), their + * lines together + * - after: the lines after the first section, those between and after + * the others included + * - found: whether there is a section + * - unterminated: whether a BEGIN marker has no END marker, which makes + * the file's structure unclear: store() doesn't write it then + * + * The lines are those of the file split at "\n", so a file which ends + * with a line break ends with an empty line; store() relies on that to + * write the file back as it was. + * + * @return array{before: string[], section: string[], after: string[], found: bool, unterminated: bool} */ - private function extract() + private function load() { - $result = array(); - + $file = array('before' => array(), 'section' => array(), 'after' => array(), + 'found' => false, 'unterminated' => false); if (!file_exists($this->path)) { - return $result; + return $file; } - - if ($markerdata = explode("\n", implode('', file($this->path)))) + $inside = false; + foreach (explode("\n", implode('', file($this->path))) as $line) { - $state = false; - foreach ($markerdata as $markerline) + if ($inside) { - if (strpos($markerline, '# END ' . self::$marker) !== false) + if (strpos($line, '# END '.self::$marker) !== false) { - $state = false; + $inside = false; } - if ($state) + else { // a file saved with Windows line ends (e.g. uploaded by FTP // in ASCII mode) has a \r at the end of every line - $result[] = rtrim($markerline, "\r"); - } - if (strpos($markerline, '# BEGIN ' . self::$marker) !== false) - { - $state = true; + $file['section'][] = rtrim($line, "\r"); } } + elseif (strpos($line, '# BEGIN '.self::$marker) !== false) + { + $inside = true; + $file['found'] = true; + } + else + { + $file[$file['found'] ? 'after' : 'before'][] = $line; + } } - - return $result; + $file['unterminated'] = $inside; + return $file; } /** - * Insert an array of strings into .htaccess, placing it between BEGIN and END markers. - * Replace existing marked info. Retain surrounding data. - * Create file if none exists. + * Writes $file (see load()) back with $lines as the block section: where + * the section was, or - if there was none - at the very beginning of the + * file, followed by an empty line. Creates the file if there is none. * - * @param string $insertion + * @param string[] $lines * @return bool True on write success, false on failure. */ - private function insert($insertion) + private function store(array $file, array $lines) { - if (!file_exists($this->path) || is_writeable($this->path)) + if (file_exists($this->path) && !is_writeable($this->path)) { - if (!file_exists($this->path)) - { - $markerdata = ''; - } - else - { - $markerdata = explode("\n", implode('', file($this->path))); - } - - $newContent = ''; - - $foundit = false; - if ($markerdata) + if (!is_null($this->logger)) { - $lineCount = count($markerdata); - - $state = true; - foreach ($markerdata as $n => $markerline) - { - if (strpos($markerline, '# BEGIN ' . self::$marker) !== false) - { - $state = false; - } - - if ($state) - { // Non-BFLP lines - if ($n + 1 < $lineCount) - { - $newContent .= "{$markerline}\n"; - } - else - { - $newContent .= "{$markerline}"; - } - } - - if (strpos($markerline, '# END ' . self::$marker) !== false) - { - $newContent .= "# BEGIN ".self::$marker."\n"; - if (is_array($insertion)) - { - foreach ($insertion as $insertline) - { - $newContent .= "{$insertline}\n"; - } - } - $newContent .= "# END ".self::$marker."\n"; - - $state = true; - $foundit = true; - } - } - - // If BEGIN marker found but missing END marker - if ($state === false) - { - if (!is_null($this->logger)) - { - $this->logger->log("corrupted .htaccess: BEGIN marker was found, but not END!", Log::ERROR); - } - return false; - } + $this->logger->log(".htaccess file is not writable!", Log::ERROR); } - - if (!$foundit) + return false; + } + if ($file['unterminated']) + { + if (!is_null($this->logger)) { - // insert at the very beginning: - $beginContent = "# BEGIN ".self::$marker."\n"; - foreach ($insertion as $insertline) - { - $beginContent .= "{$insertline}\n"; - } - $beginContent .= "# END ".self::$marker."\n\n"; - $newContent = $beginContent . $newContent; + $this->logger->log("corrupted .htaccess: BEGIN marker was found, but not END!", Log::ERROR); } - - return $this->write($newContent); + return false; + } + $section = array_merge(array('# BEGIN '.self::$marker), $lines, array('# END '.self::$marker)); + if (!$file['found']) + { + return $this->write(implode("\n", $section)."\n\n".implode("\n", $file['before'])); } - if (!is_null($this->logger)) + $after = $file['after']; + if (count($after) === 0) { - $this->logger->log(".htaccess file is not writable!", Log::ERROR); + // the END marker was the last line, without a line break after it + $after[] = ''; } - return false; + return $this->write(implode("\n", array_merge($file['before'], $section, $after))); } } diff --git a/tests/Integration/HtaccessHelperTest.php b/tests/Integration/HtaccessHelperTest.php index 86991b9..ace4f22 100644 --- a/tests/Integration/HtaccessHelperTest.php +++ b/tests/Integration/HtaccessHelperTest.php @@ -223,6 +223,18 @@ public function testCorruptMarkersAreNotOverwritten() $logger->errors = array(); // expected } + public function testSeveralSectionsBecomeOne() + { + // not meant to happen (a file merged by hand, say); the addresses of + // all of them are kept, and what is between and around them + file_put_contents($this->dir.'/.htaccess', "A\n# BEGIN BFStop Blocks\nRequire not ip 203.0.113.1\n# END BFStop Blocks\n". + "M\n# BEGIN BFStop Blocks\nRequire not ip 203.0.113.2\n# END BFStop Blocks\nZ\n"); + $this->assertTrue($this->helper()->denyIP('203.0.113.3')); + $this->assertSame("A\n# BEGIN BFStop Blocks\n". + self::ifLine("-R '203.0.113.1' || -R '203.0.113.2' || -R '203.0.113.3'")."\nRequire all denied\n\n". + "# END BFStop Blocks\nM\nZ\n", $this->content()); + } + public function testReadOnlyFileIsReported() { if (function_exists('posix_geteuid') && posix_geteuid() === 0) From 67bc330269c11865ea437e0ad11b12be22af7f2d Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 17:07:38 +0000 Subject: [PATCH 2/2] phpstan baseline: drop the two entries of HtaccessHelper::insert(), which is gone Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01AFJFMNpwNryanqvRcQvqDc --- phpstan-baseline.neon | 12 ------------ 1 file changed, 12 deletions(-) diff --git a/phpstan-baseline.neon b/phpstan-baseline.neon index cd5caa4..78f3a71 100644 --- a/phpstan-baseline.neon +++ b/phpstan-baseline.neon @@ -348,18 +348,6 @@ parameters: count: 1 path: library/src/Helper/DnsHelper.php - - - message: '#^Argument of an invalid type string supplied for foreach, only iterables are supported\.$#' - identifier: foreach.nonIterable - count: 1 - path: library/src/Helper/HtaccessHelper.php - - - - message: '#^Parameter \#1 \$insertion of method Codeling\\Library\\Bfstop\\Helper\\HtaccessHelper\:\:insert\(\) expects string, array\ given\.$#' - identifier: argument.type - count: 6 - path: library/src/Helper/HtaccessHelper.php - - message: '#^Property Codeling\\Library\\Bfstop\\Helper\\LoggerHelper\:\:\$maxBytes is never read, only written\.$#' identifier: property.onlyWritten