Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,12 @@ The format is based on Keep a Changelog and this project follows Semantic Versio
method no longer carries on after the failed query.
- `Common\Db::fieldExists()`, `cloneRecord()` and `enumerate()` refuse a table or column name
that ends in a line feed. `fieldExists()` still takes a table name in backticks.
- `Module\Installer::copyTestFolders()` and `Common\TestdataSample::loadData()` skip a configured
sample folder that the module does not ship. Installing such a module used to raise
`Warning: Test data folder "…/testdata/uploads" was not copied to "…"`, and "Import Sample
Data" reported the folder as not copied. A source is skipped only when a readable parent folder
confirms it is absent; a folder that exists and cannot be copied, a file in its place, and a
path the copier refuses are reported as before.

## [1.7.2] — 2026-11-18

Expand Down
12 changes: 3 additions & 9 deletions src/Common/TestdataSample.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
use Xmf\Database\TableLoad;
use Xoops\Helpers\Utility\HtmlBuilder;
use Xoops\ModuleTools\Internal\PackageLanguage;
use Xoops\ModuleTools\Internal\SampleFolders;
use Xoops\ModuleTools\Utility;

/**
Expand Down Expand Up @@ -64,7 +65,6 @@ private function dataFile(string $table): string
public function loadData(): void
{
$this->assertAuthorized();
$utility = new Utility();
$configurator = new Configurator($this->modHelper->path());
$tables = $this->modHelper->getModule()->getInfo('tables');

Expand All @@ -83,14 +83,8 @@ public function loadData(): void

// --- COPY test folder files ---------------
if (\is_array($configurator->copyTestFolders) && \count($configurator->copyTestFolders) > 0) {
$failed = [];
foreach (\array_keys($configurator->copyTestFolders) as $i) {
$src = $configurator->copyTestFolders[$i][0];
$dest = $configurator->copyTestFolders[$i][1];
if (!$utility::rcopy($src, $dest)) {
$failed[] = (string) $dest;
}
}
// A sample folder the module does not ship is skipped, as at install time.
$failed = \array_column(SampleFolders::copy($configurator->copyTestFolders), 1);
// rcopy() is webmaster-only: a module-only admin gets the rows but not the files,
// and must be told so instead of seeing a success message.
if ([] !== $failed) {
Expand Down
70 changes: 70 additions & 0 deletions src/Internal/SampleFolders.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
<?php

declare(strict_types=1);

namespace Xoops\ModuleTools\Internal;

use Xoops\ModuleTools\Common\SysUtility;

/**
* Copies the `[source, destination]` sample-data folder pairs of a module's `config/config.php`
* (`copyTestFolders`), for the install hook and for "Import Sample Data" alike.
*
* Sample data is optional: most modules keep the skeleton's `testdata/uploads` entry without
* shipping that folder. Nothing to copy is not a failed copy.
*
* @internal
*/
final class SampleFolders
{
/**
* Copy every pair whose source folder the module ships.
*
* @param array<int|string, mixed> $pairs
*
* @return list<array{string, string}> the pairs that were not copied
*/
public static function copy(array $pairs): array
{
$failed = [];
foreach ($pairs as $pair) {
[$source, $destination] = $pair;
if (self::isAbsent((string)$source)) {
continue;
}
if (!SysUtility::rcopy($source, $destination)) {
$failed[] = [(string)$source, (string)$destination];
}
}

return $failed;
}

/**
* Whether $source is a plain local path that a readable ancestor folder confirms is not there.
*
* A false is_dir() alone does not say so: it is also false for a folder that exists below a
* parent PHP may not search. Such a source goes to the copier, whose refusal is reported.
*/
private static function isAbsent(string $source): bool
{
// A NUL byte or a URI is rcopy()'s to refuse: is_dir() throws on the first as of
// PHP 8.6 and would ask a stream wrapper about the second.
if ('' === $source || \str_contains($source, "\0") || \str_contains($source, '://') || \is_dir($source)) {
return false;
}

// Walk up to the nearest ancestor that is a folder and ask it for the missing entry.
// The path stays as configured: dirname() and basename() split it the way the copier
// will, and both ignore a trailing separator.
$path = $source;
$parent = \dirname($path);
while ($parent !== $path && !\is_dir($parent)) {
$path = $parent;
$parent = \dirname($path);
}
$entries = $parent !== $path && \is_readable($parent) ? \scandir($parent) : false;

return \is_array($entries) && !\in_array(\basename($path), $entries, true);
}
}
9 changes: 4 additions & 5 deletions src/Module/Installer.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
use Xoops\ModuleTools\Common\Configurator;
use Xoops\ModuleTools\Common\SysUtility;
use Xoops\ModuleTools\Internal\Installation\InstallationPlan;
use Xoops\ModuleTools\Internal\SampleFolders;

/**
* Shared module install/update filesystem helper.
Expand Down Expand Up @@ -81,14 +82,12 @@ public static function copyBlankFiles(Configurator $configurator): void

/**
* Recursively copy each configured `[source, destination]` test-data folder pair.
* A pair whose source folder the module does not ship is skipped.
*/
public static function copyTestFolders(Configurator $configurator): void
{
foreach (self::plan($configurator)->testFolderCopies as $pair) {
[$src, $dest] = $pair;
if (!SysUtility::rcopy($src, $dest)) {
\trigger_error(\sprintf('Test data folder "%s" was not copied to "%s"', $src, $dest), \E_USER_WARNING);
}
foreach (SampleFolders::copy(self::plan($configurator)->testFolderCopies) as [$src, $dest]) {
\trigger_error(\sprintf('Test data folder "%s" was not copied to "%s"', $src, $dest), \E_USER_WARNING);
}
}

Expand Down
115 changes: 115 additions & 0 deletions tests/Internal/SampleFoldersTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
<?php declare(strict_types=1);

namespace Xoops\ModuleTools\Tests\Internal;

use PHPUnit\Framework\TestCase;
use Xoops\Helpers\Utility\Filesystem;
use Xoops\ModuleTools\Internal\SampleFolders;

defined('XOOPS_GROUP_ADMIN') || define('XOOPS_GROUP_ADMIN', '1');

final class SampleFoldersTest extends TestCase
{
private string $dir;

protected function setUp(): void
{
$this->dir = sys_get_temp_dir() . '/moduletools-sample-' . bin2hex(random_bytes(6));
self::assertTrue(Filesystem::mkdir($this->dir . '/module/testdata/images'));
file_put_contents($this->dir . '/module/testdata/images/a.txt', 'a');
$GLOBALS['xoopsUser'] = new \XoopsUser(false, ['2', '1']); // a webmaster
}

protected function tearDown(): void
{
unset($GLOBALS['xoopsUser']);
if (is_dir($this->dir . '/module/locked')) {
chmod($this->dir . '/module/locked', 0700);
}
if (is_dir($this->dir)) {
Filesystem::deleteDirectory($this->dir);
}
}

public function testAFolderTheModuleShipsIsCopied(): void
{
$failed = SampleFolders::copy([[$this->dir . '/module/testdata/images', $this->dir . '/uploads/images']]);

self::assertSame([], $failed);
self::assertFileExists($this->dir . '/uploads/images/a.txt');
}

public function testAFolderTheModuleDoesNotShipIsSkipped(): void
{
$failed = SampleFolders::copy([
// the skeleton's entry, beside a testdata folder that holds other things
[$this->dir . '/module/testdata/uploads', $this->dir . '/uploads'],
// a module without the parent folder either
[$this->dir . '/module/samples/deep/uploads', $this->dir . '/uploads'],
[$this->dir . '/module/testdata/uploads/', $this->dir . '/uploads'],
]);

self::assertSame([], $failed);
self::assertDirectoryDoesNotExist($this->dir . '/uploads');
}

public function testARefusedCopyOfAnExistingFolderIsReported(): void
{
// A module-only admin is not a webmaster, so the copier refuses.
$GLOBALS['xoopsUser'] = new \XoopsUser(true, ['2', '4']);
$pair = [$this->dir . '/module/testdata/images', $this->dir . '/uploads/images'];

self::assertSame([$pair], SampleFolders::copy([$pair]));
}

public function testAFileWhereAFolderIsExpectedIsReported(): void
{
$pair = [$this->dir . '/module/testdata/images/a.txt', $this->dir . '/uploads/images'];

self::assertSame([$pair], SampleFolders::copy([$pair]));
}

public function testAPathTheCopierRefusesIsReportedAndNeverProbed(): void
{
// is_dir() throws on a NUL byte as of PHP 8.6 and would ask a stream wrapper about a URI.
$pairs = [
[$this->dir . "/module/testdata/up\0loads", $this->dir . '/uploads'],
['sample://example.invalid/testdata/uploads', $this->dir . '/uploads'],
['', $this->dir . '/uploads'],
];

self::assertSame($pairs, SampleFolders::copy($pairs));
}

public function testABackslashInTheConfiguredPathIsNotReadAsASeparatorWhereItIsNone(): void
{
if ('\\' === \DIRECTORY_SEPARATOR) {
self::markTestSkipped('A backslash separates folders on Windows.');
}

// "testdata\images" names one entry of the module folder here, and there is none.
$failed = SampleFolders::copy([[$this->dir . '/module/testdata\\images', $this->dir . '/uploads/images']]);

self::assertSame([], $failed);
self::assertDirectoryDoesNotExist($this->dir . '/uploads');
}

public function testAFolderBelowAParentThatCannotBeSearchedIsReported(): void
{
if ('\\' === \DIRECTORY_SEPARATOR || (\function_exists('posix_geteuid') && 0 === posix_geteuid())) {
self::markTestSkipped('Needs POSIX permissions and a user they apply to.');
}
self::assertTrue(Filesystem::mkdir($this->dir . '/module/locked/uploads'));
$pair = [$this->dir . '/module/locked/uploads', $this->dir . '/uploads'];

// Readable but not searchable: the entry is listed, is_dir() on it is false.
chmod($this->dir . '/module/locked', 0400);
clearstatcache();
self::assertSame([$pair], SampleFolders::copy([$pair]));

// Neither readable nor searchable: nothing confirms the folder is absent.
chmod($this->dir . '/module/locked', 0000);
clearstatcache();
self::assertSame([$pair], SampleFolders::copy([$pair]));
}
}
71 changes: 71 additions & 0 deletions tests/Module/InstallerTestFoldersTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
<?php declare(strict_types=1);

namespace Xoops\ModuleTools\Tests\Module;

use PHPUnit\Framework\TestCase;
use Xoops\Helpers\Utility\Filesystem;
use Xoops\ModuleTools\Common\Configurator;
use Xoops\ModuleTools\Module\Installer;

defined('XOOPS_GROUP_ADMIN') || define('XOOPS_GROUP_ADMIN', '1');

final class InstallerTestFoldersTest extends TestCase
{
private string $dir;

/** @var list<string> */
private array $warnings = [];

protected function setUp(): void
{
$this->dir = sys_get_temp_dir() . '/moduletools-installer-' . bin2hex(random_bytes(6));
self::assertTrue(Filesystem::mkdir($this->dir . '/module/config'));
self::assertTrue(Filesystem::mkdir($this->dir . '/module/testdata/images'));
file_put_contents($this->dir . '/module/testdata/images/a.txt', 'a');

// The skeleton's config: one sample folder the module ships, one it does not.
$config = ['copyTestFolders' => [
[$this->dir . '/module/testdata/uploads', $this->dir . '/uploads'],
[$this->dir . '/module/testdata/images', $this->dir . '/uploads/images'],
]];
file_put_contents($this->dir . '/module/config/config.php', '<?php return ' . var_export($config, true) . ';');

$this->warnings = [];
set_error_handler(function (int $level, string $message): bool {
$this->warnings[] = $message;

return true;
}, E_USER_WARNING);
}

protected function tearDown(): void
{
restore_error_handler();
unset($GLOBALS['xoopsUser']);
if (is_dir($this->dir)) {
Filesystem::deleteDirectory($this->dir);
}
}

public function testADeclaredSampleFolderTheModuleDoesNotShipIsSkippedQuietly(): void
{
$GLOBALS['xoopsUser'] = new \XoopsUser(false, ['2', '1']);

Installer::copyTestFolders(new Configurator($this->dir . '/module'));

self::assertSame([], $this->warnings);
self::assertFileExists($this->dir . '/uploads/images/a.txt');
}

public function testAFolderThatExistsButIsNotCopiedStillWarns(): void
{
// A module-only admin is not a webmaster, so the copy of the existing folder is refused.
$GLOBALS['xoopsUser'] = new \XoopsUser(true, ['2', '4']);

Installer::copyTestFolders(new Configurator($this->dir . '/module'));

self::assertCount(1, $this->warnings);
self::assertStringContainsString('/module/testdata/images" was not copied', $this->warnings[0]);
self::assertFileDoesNotExist($this->dir . '/uploads/images/a.txt');
}
}