implement an api for auto update of modules, to fetch the latest release of a module etc
Assistant
Based on the provided repository content, I'll help outline how to implement an API for auto-updating modules in Dolibarr. Here's a comprehensive solution drawing from the marketplace module's structure:
First, let's define the core API endpoints we'll need in a new class:
php
User
provide full implementation
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
$api = new ModuleUpdateAPI($db, 'mymodule');
$updateStatus = $api->checkForUpdates();
Perform update:
php
if ($updateStatus['update_available']) {
$result = $api->performUpdate();
}
Key features of this implementation:
Secure authentication using API keys
Version comparison to detect available updates
Automatic backup before updating
Package integrity verification
Cron job support for automatic update checks
Error handling and logging
Support for multiple modules
Database tracking of module versions
To enhance this further, you could add:
Rollback functionality
Update notifications via email
Update scheduling
Dependencies checking
Progressive download for large modules
Update history logging
Remember to implement proper error handling and logging throughout the API, and ensure secure communication between your Dolibarr instance and the marketplace API.
The actual implementation details of some methods (like downloadModule, verifyPackage, etc.) would depend on your specific marketplace structure and security requirements.
I'll provide a complete implementation of the module auto-update system. Here's the full code structure:
First, create the main API class file:
php
<?php
// htdocs/marketplace/class/moduleupdateapi.class.php
require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
require_once DOL_DOCUMENT_ROOT.'/core/lib/geturl.lib.php';
class ModuleUpdateAPI
{
private $db;
private $version;
private $moduleKey;
private $error;
private $errors = array();
private $logFile;
/**
* Constructor
*
* @param DoliDB $db Database handler
* @param string $moduleKey Module unique identifier
*/
public function __construct($db, $moduleKey)
{
global $conf;
$this->db = $db;
$this->moduleKey = $moduleKey;
$this->version = $this->getCurrentVersion();
$this->logFile = $conf->marketplace->dir_temp . '/update_' . dol_sanitizeFileName($moduleKey) . '.log';
}
/**
* Check if module update is available
*
* @return array Array containing update status and latest version
*/
public function checkForUpdates()
{
$this->log("Checking for updates for module: " . $this->moduleKey);
try {
$latestVersion = $this->getLatestVersionFromAPI();
if (!$latestVersion) {
throw new Exception("Could not fetch latest version information");
}
$updateAvailable = version_compare($latestVersion['version'], $this->version, '>');
$result = array(
'current_version' => $this->version,
'latest_version' => $latestVersion['version'],
'update_available' => $updateAvailable,
'release_notes' => $latestVersion['release_notes'],
'download_url' => $latestVersion['download_url'],
'requires' => $latestVersion['requires']
);
$this->log("Update check completed. Update available: " . ($updateAvailable ? 'Yes' : 'No'));
return $result;
} catch (Exception $e) {
$this->error = $e->getMessage();
$this->errors[] = $this->error;
$this->log("Error checking updates: " . $this->error, 'ERROR');
return false;
}
}
/**
* Perform complete update process
*
* @return array Status of update operation
*/
public function performUpdate()
{
global $conf;
$this->log("Starting update process for module: " . $this->moduleKey);
try {
// Check if update is available
$updateInfo = $this->checkForUpdates();
if (!$updateInfo['update_available']) {
throw new Exception('No update available');
}
// Check requirements
if (!$this->checkRequirements($updateInfo['requires'])) {
throw new Exception('System requirements not met');
}
// Create temp directory
$tempDir = $conf->marketplace->dir_temp . '/' . uniqid('update_');
dol_mkdir($tempDir);
// Download package
$zipFile = $this->downloadModule($updateInfo['download_url'], $tempDir);
if (!$zipFile) {
throw new Exception('Failed to download update package');
}
// Verify package
if (!$this->verifyPackage($zipFile)) {
throw new Exception('Package verification failed');
}
// Backup current version
$backupFile = $this->backupCurrentVersion();
if (!$backupFile) {
throw new Exception('Backup creation failed');
}
// Install new version
if (!$this->installNewVersion($zipFile)) {
// Attempt rollback if installation fails
$this->rollback($backupFile);
throw new Exception('Installation failed');
}
// Update version in database
$this->updateVersionInDB($updateInfo['latest_version']);
// Cleanup
$this->cleanup($tempDir);
$this->log("Update completed successfully");
return array(
'success' => true,
'message' => 'Module updated successfully',
'version' => $updateInfo['latest_version']
);
} catch (Exception $e) {
$this->error = $e->getMessage();
$this->errors[] = $this->error;
$this->log("Update failed: " . $this->error, 'ERROR');
return array(
'success' => false,
'message' => $this->error
);
}
}
/**
* Download module package
*
* @param string $url Download URL
* @param string $destDir Destination directory
* @return string|false Path to downloaded file or false on failure
*/
private function downloadModule($url, $destDir)
{
$this->log("Downloading module from: " . $url);
$fileName = $destDir . '/package.zip';
$result = getURLContent($url, 'GET', '', 1, array(), array('timeout' => 60));
if ($result['curl_error_no']) {
$this->log("Download failed: " . $result['curl_error_msg'], 'ERROR');
return false;
}
if (!file_put_contents($fileName, $result['content'])) {
$this->log("Failed to save downloaded file", 'ERROR');
return false;
}
return $fileName;
}
/**
* Verify package integrity
*
* @param string $zipFile Path to ZIP file
* @return bool
*/
private function verifyPackage($zipFile)
{
$this->log("Verifying package integrity");
if (!file_exists($zipFile)) {
$this->log("Package file not found", 'ERROR');
return false;
}
$zip = new ZipArchive();
if ($zip->open($zipFile) !== true) {
$this->log("Invalid ZIP file", 'ERROR');
return false;
}
// Check for required files
$requiredFiles = array(
'core/modules/mod' . ucfirst($this->moduleKey) . '.class.php',
'README.md',
'ChangeLog.md'
);
foreach ($requiredFiles as $file) {
if ($zip->locateName($file) === false) {
$this->log("Missing required file: " . $file, 'ERROR');
$zip->close();
return false;
}
}
$zip->close();
return true;
}
/**
* Backup current version
*
* @return string|false Path to backup file or false on failure
*/
private function backupCurrentVersion()
{
global $conf;
$this->log("Creating backup of current version");
$moduleDir = DOL_DOCUMENT_ROOT . '/custom/' . $this->moduleKey;
$backupDir = $conf->marketplace->dir_temp . '/backups';
$backupFile = $backupDir . '/' . $this->moduleKey . '_' . $this->version . '_' . date('Y-m-d_His') . '.zip';
dol_mkdir($backupDir);
$zip = new ZipArchive();
if ($zip->open($backupFile, ZipArchive::CREATE) !== true) {
$this->log("Failed to create backup archive", 'ERROR');
return false;
}
$this->addDirToZip($moduleDir, $zip);
$zip->close();
return $backupFile;
}
/**