13.6.00 nettoyage de constantes inutiles liées à jsondb

Un quart de secondes entre deux tentatives
This commit is contained in:
Fred Tempez 2025-01-18 22:53:43 +01:00
parent 72a27d3ca7
commit 97fc8d13f0
2 changed files with 175 additions and 138 deletions

View File

@ -18,8 +18,6 @@ class JsonDb extends \Prowebcraft\Dot
protected $db = ''; protected $db = '';
protected $data = null; protected $data = null;
protected $config = []; protected $config = [];
// Tentative d'encodage après échec
const MAX_JSON_ENCODE_ATTEMPTS = 5;
// Tentative d'écriture après échec // Tentative d'écriture après échec
const MAX_FILE_WRITE_ATTEMPTS = 5; const MAX_FILE_WRITE_ATTEMPTS = 5;
// Délais entre deux tentaives // Délais entre deux tentaives
@ -136,8 +134,8 @@ class JsonDb extends \Prowebcraft\Dot
} }
$this->data = json_decode(file_get_contents($this->db), true); $this->data = json_decode(file_get_contents($this->db), true);
if (!$this->data === null) { if (!$this->data === null) {
throw new \InvalidArgumentException('Database file ' . $this->db throw new \InvalidArgumentException('Le fichier ' . $this->db
. ' contains invalid json object. Please validate or remove file'); . ' contient des données invalides.');
} }
} }
return $this->data; return $this->data;
@ -175,8 +173,8 @@ class JsonDb extends \Prowebcraft\Dot
// Incrémente le compteur de tentatives // Incrémente le compteur de tentatives
$attempt++; $attempt++;
// Attente // Attente 1/4 de seconde
sleep(1); usleep(0.25);
} }
// Vérifie si l'écriture a échoué même après plusieurs tentatives // Vérifie si l'écriture a échoué même après plusieurs tentatives

View File

@ -67,18 +67,9 @@ class common
// Valeurs possibles multiple de 10, 10 autorise 9 profils, 100 autorise 99 profils // Valeurs possibles multiple de 10, 10 autorise 9 profils, 100 autorise 99 profils
const MAX_PROFILS = 10; const MAX_PROFILS = 10;
const MAX_FILE_WRITE_ATTEMPTS = 5; // Taille et rotation des journaux
const LOG_MAXSIZE = 4 * 1024 * 1024;
/** const LOG_MAXARCHIVE = 5;
* Nombre maximal de tentatives d'encodage JSON
*/
const MAX_JSON_ENCODE_ATTEMPTS = 3;
/**
* Temps d'attente entre les tentatives en secondes
*/
const RETRY_DELAY_SECONDS = 1;
public static $actions = []; public static $actions = [];
public static $coreModuleIds = [ public static $coreModuleIds = [
@ -1135,122 +1126,121 @@ class common
* @param string Valeurs possibles * @param string Valeurs possibles
*/ */
public function updateSitemap() public function updateSitemap()
{ {
// Le drapeau prend true quand au moins une page est trouvée // Le drapeau prend true quand au moins une page est trouvée
$flag = false; $flag = false;
// Rafraîchit la liste des pages après une modification de pageId notamment // Rafraîchit la liste des pages après une modification de pageId notamment
$this->buildHierarchy(); $this->buildHierarchy();
// Actualise la liste des pages pour TinyMCE // Actualise la liste des pages pour TinyMCE
$this->tinyMcePages(); $this->tinyMcePages();
//require_once 'core/vendor/sitemap/SitemapGenerator.php'; //require_once 'core/vendor/sitemap/SitemapGenerator.php';
$timezone = $this->getData(['config', 'timezone']); $timezone = $this->getData(['config', 'timezone']);
$outputDir = getcwd(); $outputDir = getcwd();
$sitemap = new \Icamys\SitemapGenerator\SitemapGenerator(helper::baseurl(false), $outputDir); $sitemap = new \Icamys\SitemapGenerator\SitemapGenerator(helper::baseurl(false), $outputDir);
// will create also compressed (gzipped) sitemap : option buguée // will create also compressed (gzipped) sitemap : option buguée
// $sitemap->enableCompression(); // $sitemap->enableCompression();
// determine how many urls should be put into one file // determine how many urls should be put into one file
// according to standard protocol 50000 is maximum value (see http://www.sitemaps.org/protocol.html) // according to standard protocol 50000 is maximum value (see http://www.sitemaps.org/protocol.html)
$sitemap->setMaxUrlsPerSitemap(50000); $sitemap->setMaxUrlsPerSitemap(50000);
// sitemap file name // sitemap file name
$sitemap->setSitemapFileName('sitemap.xml'); $sitemap->setSitemapFileName('sitemap.xml');
// Set the sitemap index file name // Set the sitemap index file name
$sitemap->setSitemapIndexFileName('sitemap-index.xml'); $sitemap->setSitemapIndexFileName('sitemap-index.xml');
$datetime = new DateTime(date('c')); $datetime = new DateTime(date('c'));
$datetime->format(DateTime::ATOM); // Updated ISO8601 $datetime->format(DateTime::ATOM); // Updated ISO8601
foreach ($this->getHierarchy() as $parentPageId => $childrenPageIds) { foreach ($this->getHierarchy() as $parentPageId => $childrenPageIds) {
// Exclure les barres et les pages non publiques et les pages masquées // Exclure les barres et les pages non publiques et les pages masquées
if ( if (
$this->getData(['page', $parentPageId, 'group']) !== 0 || $this->getData(['page', $parentPageId, 'group']) !== 0 ||
$this->getData(['page', $parentPageId, 'block']) === 'bar' $this->getData(['page', $parentPageId, 'block']) === 'bar'
) { ) {
continue; continue;
} }
// Page désactivée, traiter les sous-pages sans prendre en compte la page parente. // Page désactivée, traiter les sous-pages sans prendre en compte la page parente.
if ($this->getData(['page', $parentPageId, 'disable']) !== true) { if ($this->getData(['page', $parentPageId, 'disable']) !== true) {
// Cas de la page d'accueil ne pas dupliquer l'URL // Cas de la page d'accueil ne pas dupliquer l'URL
$pageId = ($parentPageId !== $this->getData(['locale', 'homePageId'])) ? $parentPageId : ''; $pageId = ($parentPageId !== $this->getData(['locale', 'homePageId'])) ? $parentPageId : '';
$sitemap->addUrl('/' . $pageId, $datetime); $sitemap->addUrl('/' . $pageId, $datetime);
$flag = true; $flag = true;
} }
// Articles du blog // Articles du blog
if ( if (
$this->getData(['page', $parentPageId, 'moduleId']) === 'blog' $this->getData(['page', $parentPageId, 'moduleId']) === 'blog'
&& !empty($this->getData(['module', $parentPageId])) && !empty($this->getData(['module', $parentPageId]))
&& $this->getData(['module', $parentPageId, 'posts']) && $this->getData(['module', $parentPageId, 'posts'])
) { ) {
foreach ($this->getData(['module', $parentPageId, 'posts']) as $articleId => $article) { foreach ($this->getData(['module', $parentPageId, 'posts']) as $articleId => $article) {
if ($this->getData(['module', $parentPageId, 'posts', $articleId, 'state']) === true) { if ($this->getData(['module', $parentPageId, 'posts', $articleId, 'state']) === true) {
$date = $this->getData(['module', $parentPageId, 'posts', $articleId, 'publishedOn']); $date = $this->getData(['module', $parentPageId, 'posts', $articleId, 'publishedOn']);
$sitemap->addUrl('/' . $parentPageId . '/' . $articleId, DateTime::createFromFormat('U', $date)); $sitemap->addUrl('/' . $parentPageId . '/' . $articleId, DateTime::createFromFormat('U', $date));
} }
} }
} }
// Sous-pages // Sous-pages
foreach ($childrenPageIds as $childKey) { foreach ($childrenPageIds as $childKey) {
if ($this->getData(['page', $childKey, 'group']) !== 0 || $this->getData(['page', $childKey, 'disable']) === true) { if ($this->getData(['page', $childKey, 'group']) !== 0 || $this->getData(['page', $childKey, 'disable']) === true) {
continue; continue;
} }
// Cas de la page d'accueil ne pas dupliquer l'URL // Cas de la page d'accueil ne pas dupliquer l'URL
$pageId = ($childKey !== $this->getData(['locale', 'homePageId'])) ? $childKey : ''; $pageId = ($childKey !== $this->getData(['locale', 'homePageId'])) ? $childKey : '';
$sitemap->addUrl('/' . $childKey, $datetime); $sitemap->addUrl('/' . $childKey, $datetime);
$flag = true; $flag = true;
// La sous-page est un blog // La sous-page est un blog
if ( if (
$this->getData(['page', $childKey, 'moduleId']) === 'blog' && $this->getData(['page', $childKey, 'moduleId']) === 'blog' &&
!empty($this->getData(['module', $childKey])) !empty($this->getData(['module', $childKey]))
) { ) {
foreach ($this->getData(['module', $childKey, 'posts']) as $articleId => $article) { foreach ($this->getData(['module', $childKey, 'posts']) as $articleId => $article) {
if ($this->getData(['module', $childKey, 'posts', $articleId, 'state']) === true) { if ($this->getData(['module', $childKey, 'posts', $articleId, 'state']) === true) {
$date = $this->getData(['module', $childKey, 'posts', $articleId, 'publishedOn']); $date = $this->getData(['module', $childKey, 'posts', $articleId, 'publishedOn']);
$sitemap->addUrl('/' . $childKey . '/' . $articleId, new DateTime("@{$date}", new DateTimeZone($timezone))); $sitemap->addUrl('/' . $childKey . '/' . $articleId, new DateTime("@{$date}", new DateTimeZone($timezone)));
} }
} }
} }
} }
} }
if ($flag === false) { if ($flag === false) {
return false; return false;
} }
// Flush all stored urls from memory to the disk and close all necessary tags. // Flush all stored urls from memory to the disk and close all necessary tags.
$sitemap->flush(); $sitemap->flush();
// Move flushed files to their final location. Compress if the option is enabled. // Move flushed files to their final location. Compress if the option is enabled.
$sitemap->finalize(); $sitemap->finalize();
// Update robots.txt file in output directory // Update robots.txt file in output directory
if ($this->getData(['config', 'seo', 'robots']) === true) { if ($this->getData(['config', 'seo', 'robots']) === true) {
if (file_exists('robots.txt')) { if (file_exists('robots.txt')) {
unlink('robots.txt'); unlink('robots.txt');
} }
$sitemap->updateRobots(); $sitemap->updateRobots();
} else { } else {
$this->secure_file_put_contents('robots.txt', 'User-agent: *' . PHP_EOL . 'Disallow: /'); $this->secure_file_put_contents('robots.txt', 'User-agent: *' . PHP_EOL . 'Disallow: /');
} }
// Submit your sitemaps to Google, Yahoo, Bing and Ask.com // Submit your sitemaps to Google, Yahoo, Bing and Ask.com
if (empty($this->getData(['config', 'proxyType']) . $this->getData(['config', 'proxyUrl']) . ':' . $this->getData(['config', 'proxyPort']))) { if (empty($this->getData(['config', 'proxyType']) . $this->getData(['config', 'proxyUrl']) . ':' . $this->getData(['config', 'proxyPort']))) {
$sitemap->submitSitemap(); $sitemap->submitSitemap();
} }
return (file_exists('sitemap.xml') && file_exists('robots.txt')); return (file_exists('sitemap.xml') && file_exists('robots.txt'));
}
}
/* /*
@ -1505,18 +1495,67 @@ class common
/** /**
* Journalisation * Journalisation avec gestion de la taille maximale et compression
*/ */
public function saveLog($message = '') public function saveLog($message = '')
{ {
// Journalisation // Chemin du fichier journal
$dataLog = helper::dateUTF8('%Y%m%d', time(), self::$i18nUI) . ';' . helper::dateUTF8('%H:%M', time(), self::$i18nUI) . ';'; $logFile = self::DATA_DIR . 'journal.log';
// Vérifier la taille du fichier
if (file_exists($logFile) && filesize($logFile) > self::LOG_MAXSIZE) {
$this->rotateLogFile();
}
// Création de l'entrée de journal
$dataLog = helper::dateUTF8('%Y%m%d', time(), self::$i18nUI) . ';' .
helper::dateUTF8('%H:%M', time(), self::$i18nUI) . ';';
$dataLog .= helper::getIp($this->getData(['config', 'connect', 'anonymousIp'])) . ';'; $dataLog .= helper::getIp($this->getData(['config', 'connect', 'anonymousIp'])) . ';';
$dataLog .= empty($this->getUser('id')) ? 'visitor;' : $this->getUser('id') . ';'; $dataLog .= empty($this->getUser('id')) ? 'visitor;' : $this->getUser('id') . ';';
$dataLog .= $message ? $this->getUrl() . ';' . $message : $this->getUrl(); $dataLog .= $message ? $this->getUrl() . ';' . $message : $this->getUrl();
$dataLog .= PHP_EOL; $dataLog .= PHP_EOL;
// Écriture dans le fichier si la journalisation est activée
if ($this->getData(['config', 'connect', 'log'])) { if ($this->getData(['config', 'connect', 'log'])) {
$this->secure_file_put_contents(self::DATA_DIR . 'journal.log', $dataLog, FILE_APPEND); file_put_contents($logFile, $dataLog, FILE_APPEND);
}
}
/**
* Gère la rotation et la compression des fichiers journaux
*/
private function rotateLogFile()
{
$logFile = self::DATA_DIR . 'journal.log';
// Décaler tous les fichiers d'archive existants
for ($i = self::LOG_MAXARCHIVE - 1; $i > 0; $i--) {
$oldFile = self::DATA_DIR . 'journal-' . $i . '.log.gz';
$newFile = self::DATA_DIR . 'journal-' . ($i + 1) . '.log.gz';
if (file_exists($oldFile)) {
if ($i == self::LOG_MAXARCHIVE - 1) {
unlink($oldFile); // Supprimer le plus ancien
} else {
rename($oldFile, $newFile);
}
}
}
// Compresser le fichier journal actuel
if (file_exists($logFile)) {
$gz = gzopen(self::DATA_DIR . 'journal-1.log.gz', 'w9');
$handle = fopen($logFile, 'r');
while (!feof($handle)) {
gzwrite($gz, fread($handle, 8192));
}
fclose($handle);
gzclose($gz);
// Créer un nouveau fichier journal vide
file_put_contents($logFile, '');
} }
} }