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
43 changes: 43 additions & 0 deletions bin/scheduler.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
#!/usr/bin/env php
<?php

/**
* phpMyFAQ task scheduler.
*
* This Source Code Form is subject to the terms of the Mozilla Public License,
* v. 2.0. If a copy of the MPL was not distributed with this file, You can
* obtain one at https://mozilla.org/MPL/2.0/.
*
* @package phpMyFAQ
* @author Thorsten Rinne <thorsten@phpmyfaq.de>
* @copyright 2026 phpMyFAQ Team
* @license https://www.mozilla.org/MPL/2.0/ Mozilla Public License Version 2.0
* @link https://www.phpmyfaq.de
* @since 2026-02-13
*/

declare(strict_types=1);

use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Loader\PhpFileLoader;

require __DIR__ . '/../phpmyfaq/src/Bootstrap.php';
require __DIR__ . '/../phpmyfaq/src/autoload.php';

$command = $argv[1] ?? '';
if ($command !== 'run') {
fwrite(STDERR, "Usage: php bin/scheduler.php run\n");
exit(1);
}

$container = new ContainerBuilder();
$loader = new PhpFileLoader($container, new FileLocator(__DIR__));
$loader->load('../phpmyfaq/src/services.php');
$container->compile();

$scheduler = $container->get('phpmyfaq.scheduler.task-scheduler');
$results = $scheduler->run();

echo "Task scheduler finished.\n";
echo json_encode($results, JSON_PRETTY_PRINT) . PHP_EOL;
238 changes: 238 additions & 0 deletions phpmyfaq/src/phpMyFAQ/Scheduler/TaskScheduler.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,238 @@
<?php

/**
* Scheduled background tasks for phpMyFAQ.
*
* This Source Code Form is subject to the terms of the Mozilla Public License,
* v. 2.0. If a copy of the MPL was not distributed with this file, You can
* obtain one at https://mozilla.org/MPL/2.0/.
*
* @package phpMyFAQ
* @author Thorsten Rinne <thorsten@phpmyfaq.de>
* @copyright 2026 phpMyFAQ Team
* @license https://www.mozilla.org/MPL/2.0/ Mozilla Public License Version 2.0
* @link https://www.phpmyfaq.de
* @since 2026-02-13
*/

declare(strict_types=1);

namespace phpMyFAQ\Scheduler;

use phpMyFAQ\Administration\Backup;
use phpMyFAQ\Administration\Session as AdminSession;
use phpMyFAQ\Configuration;
use phpMyFAQ\Enums\BackupType;
use phpMyFAQ\Faq\Statistics;
use Throwable;

class TaskScheduler
{
private const int DEFAULT_SESSION_RETENTION_SECONDS = 86400;

public function __construct(
private readonly Configuration $configuration,
private readonly AdminSession $adminSession,
private readonly Backup $backup,
private readonly Statistics $statistics,
) {
}

/**
* Runs all configured scheduler tasks.
*
* @return array<string, mixed>
*/
public function run(): array
{
$results = [];

try {
$results['sessionCleanup'] = $this->cleanupSessions();
} catch (Throwable $throwable) {
$this->configuration->getLogger()->error('Scheduled session cleanup threw an exception.', [
'message' => $throwable->getMessage(),
'trace' => $throwable->getTraceAsString(),
]);
$results['sessionCleanup'] = null;
}

try {
$results['searchOptimization'] = $this->optimizeSearchIndex();
} catch (Throwable $throwable) {
$this->configuration->getLogger()->error('Scheduled search optimization threw an exception.', [
'message' => $throwable->getMessage(),
'trace' => $throwable->getTraceAsString(),
]);
$results['searchOptimization'] = null;
}

try {
$results['statisticsAggregation'] = $this->aggregateStatistics();
} catch (Throwable $throwable) {
$this->configuration->getLogger()->error('Scheduled statistics aggregation threw an exception.', [
'message' => $throwable->getMessage(),
'trace' => $throwable->getTraceAsString(),
]);
$results['statisticsAggregation'] = null;
}

try {
$results['backupCreation'] = $this->createBackup();
} catch (Throwable $throwable) {
$this->configuration->getLogger()->error('Scheduled backup creation threw an exception.', [
'message' => $throwable->getMessage(),
'trace' => $throwable->getTraceAsString(),
]);
$results['backupCreation'] = null;
}

return $results;
}

/**
* @return array{success: bool, cutoffTimestamp: int, retentionSeconds: int}
*/
public function cleanupSessions(): array
{
$configuredRetention = (int) ($this->configuration->get('session.scheduler.retentionSeconds') ?? 0);
$retentionSeconds = $configuredRetention > 0 ? $configuredRetention : self::DEFAULT_SESSION_RETENTION_SECONDS;
$cutoffTimestamp = time() - $retentionSeconds;

try {
$success = $this->adminSession->deleteSessions(0, $cutoffTimestamp);
} catch (Throwable $throwable) {
$this->configuration->getLogger()->error('Scheduled session cleanup threw an exception.', [
'message' => $throwable->getMessage(),
'trace' => $throwable->getTraceAsString(),
'cutoffTimestamp' => $cutoffTimestamp,
'retentionSeconds' => $retentionSeconds,
]);
$success = false;
}

if (!$success) {
$this->configuration->getLogger()->warning('Scheduled session cleanup failed.', [
'cutoffTimestamp' => $cutoffTimestamp,
'retentionSeconds' => $retentionSeconds,
]);
}

return [
'success' => $success,
'cutoffTimestamp' => $cutoffTimestamp,
'retentionSeconds' => $retentionSeconds,
];
}

/**
* @return array{success: bool, skipped: bool, elasticsearch: bool|null, opensearch: bool|null}
*/
public function optimizeSearchIndex(): array
{
$elasticsearchResult = null;
$openSearchResult = null;

if ($this->configuration->get('search.enableElasticsearch')) {
try {
$this->configuration
->getElasticsearch()
->indices()
->forcemerge([
'index' => $this->configuration->getElasticsearchConfig()->getIndex(),
'max_num_segments' => 1,
]);
$elasticsearchResult = true;
} catch (Throwable $throwable) {
$elasticsearchResult = false;
$this->configuration->getLogger()->error('Scheduled Elasticsearch optimization failed.', [
'message' => $throwable->getMessage(),
'trace' => $throwable->getTraceAsString(),
]);
}
}

if ($this->configuration->get('search.enableOpenSearch')) {
try {
$this->configuration
->getOpenSearch()
->indices()
->forcemerge([
'index' => $this->configuration->getOpenSearchConfig()->getIndex(),
'max_num_segments' => 1,
]);
$openSearchResult = true;
} catch (Throwable $throwable) {
$openSearchResult = false;
$this->configuration->getLogger()->error('Scheduled OpenSearch optimization failed.', [
'message' => $throwable->getMessage(),
'trace' => $throwable->getTraceAsString(),
]);
}
}

$skipped = $elasticsearchResult === null && $openSearchResult === null;
$success = !$skipped && $elasticsearchResult !== false && $openSearchResult !== false;

return [
'success' => $success,
'skipped' => $skipped,
'elasticsearch' => $elasticsearchResult,
'opensearch' => $openSearchResult,
];
}

/**
* @return array{success: bool, generatedAt: int, totalFaqs: int|null, totalSessions: int|null, error: string|null}
*/
public function aggregateStatistics(): array
{
try {
return [
'success' => true,
'generatedAt' => time(),
'totalFaqs' => $this->statistics->totalFaqs(),
'totalSessions' => $this->adminSession->getNumberOfSessions(),
'error' => null,
];
} catch (Throwable $throwable) {
$this->configuration->getLogger()->error('Scheduled statistics aggregation failed.', [
'message' => $throwable->getMessage(),
'trace' => $throwable->getTraceAsString(),
]);

return [
'success' => false,
'generatedAt' => time(),
'totalFaqs' => null,
'totalSessions' => null,
'error' => $throwable->getMessage(),
];
}
}

/**
* @return array{success: bool, fileName: string|null}
*/
public function createBackup(): array
{
try {
$backupResult = $this->backup->export(BackupType::BACKUP_TYPE_DATA);

return [
'success' => true,
'fileName' => $backupResult->fileName,
];
} catch (Throwable $throwable) {
$this->configuration->getLogger()->error('Scheduled backup creation failed.', [
'message' => $throwable->getMessage(),
'trace' => $throwable->getTraceAsString(),
]);

return [
'success' => false,
'fileName' => null,
];
}
}
}
24 changes: 23 additions & 1 deletion phpmyfaq/src/phpMyFAQ/Search.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@

use DateTime;
use Exception;
use phpMyFAQ\Database\DatabaseDriver;
use phpMyFAQ\Search\Search\Elasticsearch;
use phpMyFAQ\Search\Search\OpenSearch;
use phpMyFAQ\Search\SearchFactory;
Expand Down Expand Up @@ -137,7 +138,8 @@ public function searchDatabase(string $searchTerm, bool $allLanguages = true): a
$fdTable = Database::getTablePrefix() . 'faqdata AS fd';
$fcrTable = Database::getTablePrefix() . 'faqcategoryrelations';
$condition = ['fd.active' => "'yes'"];
$searchDatabase = SearchFactory::create($this->configuration, ['database' => Database::getType()]);
$searchDatabase = SearchFactory::create($this->configuration, ['database' =>
$this->resolveSearchDatabaseType()]);

if (!is_null($this->getCategoryId()) && 0 < $this->getCategoryId()) {
if ($this->getCategory() instanceof Category) {
Expand Down Expand Up @@ -199,6 +201,26 @@ public function searchDatabase(string $searchTerm, bool $allLanguages = true): a
return array_merge($faqResults, $pageResults);
}

private function resolveSearchDatabaseType(): string
{
$driverClass = strtolower($this->getDatabaseDriverClassName($this->configuration->getDb()));

return match ($driverClass) {
'pdomysql' => 'pdo_mysql',
'pdopgsql' => 'pdo_pgsql',
'pdosqlite' => 'pdo_sqlite',
'pdosqlsrv' => 'pdo_sqlsrv',
default => $driverClass,
};
}

private function getDatabaseDriverClassName(DatabaseDriver $databaseDriver): string
{
$classNameParts = explode('\\', $databaseDriver::class);

return (string) end($classNameParts);
}

/**
* Search custom pages for the given search term.
*
Expand Down
8 changes: 8 additions & 0 deletions phpmyfaq/src/services.php
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,7 @@
use phpMyFAQ\Question;
use phpMyFAQ\Rating;
use phpMyFAQ\Search;
use phpMyFAQ\Scheduler\TaskScheduler;
use phpMyFAQ\Seo;
use phpMyFAQ\Seo\SeoRepository;
use phpMyFAQ\Service\Gravatar;
Expand Down Expand Up @@ -373,6 +374,13 @@
service('phpmyfaq.queue.handler.export'),
]);

$services->set('phpmyfaq.scheduler.task-scheduler', TaskScheduler::class)->args([
service('phpmyfaq.configuration'),
service('phpmyfaq.admin.session'),
service('phpmyfaq.admin.backup'),
service('phpmyfaq.faq.statistics'),
]);

$services->set('phpmyfaq.helper.category-helper', CategoryHelper::class);

$services->set('phpmyfaq.helper.faq', FaqHelper::class)->args([
Expand Down
Loading