dolibarr 24.0.0-beta
purge_logs.php
1<?php
2/* Copyright (C) 2026 Laurent Destailleur <eldy@users.sourceforge.net>
3 * Copyright (C) 2026 Nick Fragoulis
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 3 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY, without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see <https://www.gnu.org/licenses/>.
17 * or see https://www.gnu.org/
18 */
19
26if (php_sapi_name() === 'cli') {
27 if (!defined('NOLOGIN')) {
28 define('NOLOGIN', 1);
29 }
30}
31if (!defined('NOTOKENRENEWAL')) {
32 define('NOTOKENRENEWAL', 1);
33}
34if (!defined('NOREQUIREMENU')) {
35 define('NOREQUIREMENU', 1);
36}
37if (!defined('NOREQUIREHTML')) {
38 define('NOREQUIREHTML', 1);
39}
40
41require __DIR__ . '/../../main.inc.php';
42
45// Security check for web access
46if (php_sapi_name() !== 'cli') {
47 if (!isModEnabled('ai')) {
48 accessforbidden('Module not allowed');
49 }
50 if (empty($user->admin)) {
51 accessforbidden('Admin access required');
52 }
53}
54
55$retention = getDolGlobalInt('AI_LOG_RETENTION');
56
57if ($retention > 0) {
58 $limitDate = dol_now() - ($retention * 86400);
59 $chunkSize = 1000; // Delete 1000 rows at a time
60 $totalDeleted = 0;
61
62 $db->begin();
63
64 while (true) {
65 $sql = "DELETE FROM " . MAIN_DB_PREFIX . "ai_request_log";
66 $sql .= " WHERE date_request < '" . $db->idate($limitDate) . "'";
67 $sql .= " AND entity IN (" . getEntity('airequestlog') . ")";
68 $sql .= " LIMIT " . ((int) $chunkSize);
69
70 $resql = $db->query($sql);
71 if (!$resql) {
72 $db->rollback();
73 print "ERROR: " . $db->lasterror() . "\n";
74 exit(1);
75 }
76
77 $rowsAffected = $db->affected_rows($resql);
78 $totalDeleted += $rowsAffected;
79
80 // If no rows were deleted, we are done
81 if ($rowsAffected < 1) {
82 break;
83 }
84
85 // Sleep briefly to reduce server load
86 usleep(50000); // 0.05 seconds
87 }
88
89 $db->commit();
90 print "OK: Purged {$totalDeleted} log(s) older than {$retention} days.\n";
91}
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $db
API class for accounts.
dol_now($mode='gmt')
Return date for now.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
isModEnabled($module)
Is Dolibarr module enabled.
getEntity($element, $shared=1, $currentobject=null)
Get list of entity id to use.
accessforbidden($message='', $printheader=1, $printfooter=1, $showonlymessage=0, $params=null)
Show a message to say access is forbidden and stop program.