dolibarr 25.0.0-alpha
cron_run_jobs.php
Go to the documentation of this file.
1#!/usr/bin/env php
2<?php
3/*
4 * Copyright (C) 2012 Nicolas Villa aka Boyquotes http://informetic.fr
5 * Copyright (C) 2013 Florian Henry <florian.henry@open-concept.pro
6 * Copyright (C) 2013-2015 Laurent Destailleur <eldy@users.sourceforge.net>
7 * Copyright (C) 2024-2025 Frédéric France <frederic.france@free.fr>
8 * Copyright (C) 2025-2026 MDW <mdeweerd@users.noreply.github.com>
9 *
10 * This program is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License as published by
12 * the Free Software Foundation; either version 3 of the License, or
13 * (at your option) any later version.
14 *
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
19 *
20 * You should have received a copy of the GNU General Public License
21 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 */
23
30if (!defined('NOTOKENRENEWAL')) {
31 define('NOTOKENRENEWAL', '1'); // Disables token renewal
32}
33if (!defined('NOREQUIREMENU')) {
34 define('NOREQUIREMENU', '1');
35}
36if (!defined('NOREQUIREHTML')) {
37 define('NOREQUIREHTML', '1');
38}
39if (!defined('NOREQUIREAJAX')) {
40 define('NOREQUIREAJAX', '1');
41}
42if (!defined('NOLOGIN')) {
43 define('NOLOGIN', '1');
44}
45if (!defined('NOSESSION')) {
46 define('NOSESSION', '1');
47}
48
49// So log file will have a suffix
50if (!defined('USESUFFIXINLOG')) {
51 define('USESUFFIXINLOG', '_cron');
52}
53
54$sapi_type = php_sapi_name();
55$script_file = basename(__FILE__);
56$path = __DIR__.'/';
57
58// Error if Web mode
59if (substr($sapi_type, 0, 3) == 'cgi') {
60 echo "Error: You are using PHP for CGI. To execute ".$script_file." from command line, you must use PHP for CLI mode.\n";
61 exit(1);
62}
63
64require_once $path."../../htdocs/master.inc.php";
74require_once DOL_DOCUMENT_ROOT.'/core/lib/functionscli.lib.php';
75require_once DOL_DOCUMENT_ROOT."/cron/class/cronjob.class.php";
76require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php';
77
78// Global variables
79$version = DOL_VERSION;
80$error = 0;
81
82// Check parameters
83if (!isset($argv[1]) || !$argv[1]) {
84 usageCron($path, $script_file, $version);
85 exit(1);
86}
87$key = $argv[1];
88
89if (!isset($argv[2]) || !$argv[2]) {
90 usageCron($path, $script_file, $version);
91 exit(1);
92}
93
94$userlogin = $argv[2];
95
96$hookmanager->initHooks(array('cli'));
97
98
99/*
100 * Main
101 */
102
103// current date
104$now = dol_now();
105
106@set_time_limit(0);
107print "***** ".$script_file." (".$version.") pid=".dol_getmypid()." - userlogin=".substr($userlogin, 0, 3)."... - ".$userlogin." - ".dol_print_date($now, 'dayhourrfc', 'gmt')." - ".gethostname()." *****\n";
108
109// Show TZ of the serveur when ran from command line.
110$ini_path = php_ini_loaded_file();
111print 'TZ server = '.getServerTimeZoneString()." - set in PHP ini ".$ini_path."\n";
112
113// Check security key
114if (!hash_equals(getDolGlobalString('CRON_KEY'), (string) $key)) {
115 print "Error: securitykey provided ".substr($key, 0, 5)."... does not match securitykey in setup.\n";
116 exit(1);
117}
118
119if (!empty($dolibarr_main_db_readonly)) {
120 print "Error: instance in read-only mode\n";
121 exit(1);
122}
123
124// If param userlogin is reserved word 'firstadmin'
125if ($userlogin == 'firstadmin') {
126 $sql = 'SELECT login, entity FROM '.MAIN_DB_PREFIX.'user WHERE admin = 1 and statut = 1 ORDER BY entity LIMIT 1';
127 $resql = $db->query($sql);
128 if ($resql) {
129 $obj = $db->fetch_object($resql);
130 if ($obj) {
131 $userlogin = $obj->login;
132 echo "First admin user found is login '".$userlogin."', entity ".$obj->entity."\n";
133 }
134 } else {
135 dol_print_error($db);
136 }
137}
138
139// Check user login
140$user = new User($db);
141$result = $user->fetch(0, $userlogin, '', 1);
142if ($result < 0) {
143 echo "User Error: ".$user->error;
144 dol_syslog("cron_run_jobs.php:: User Error:".$user->error, LOG_ERR);
145 exit(1);
146} else {
147 if (empty($user->id)) {
148 echo "User login: ".$userlogin." does not exists\n";
149 dol_syslog("User login:".$userlogin." does not exists", LOG_ERR);
150 exit(1);
151 }
152}
153
154// Reload langs
155$langcode = getDolGlobalString('MAIN_LANG_DEFAULT', 'auto');
156if (getDolUserString('MAIN_LANG_DEFAULT')) {
157 $langcode = getDolUserString('MAIN_LANG_DEFAULT');
158}
159if ($langs->getDefaultLang() != $langcode) {
160 $langs = new Translate('', $conf);
161 $langs->setDefaultLang($langcode);
162}
163// Language Management
164$langs->loadLangs(array('main', 'admin', 'cron', 'dict'));
165
166$user->loadRights();
167
168if (isset($argv[3]) && $argv[3]) {
169 $id = $argv[3];
170}
171$forcequalified = 0;
172if (isset($argv[4]) && $argv[4] == '--force') {
173 $forcequalified = 1;
174}
175
176// Create a jobs object
177$object = new Cronjob($db);
178
179$filter = array();
180if (!empty($id)) {
181 if (!is_numeric($id)) {
182 echo "Error: Bad value for parameter job id\n";
183 dol_syslog("cron_run_jobs.php Bad value for parameter job id", LOG_WARNING);
184 exit(2);
185 }
186 $filter['t.rowid'] = $id;
187}
188
189
190// Update old jobs that were not closed correctly so processing is moved from 1 to 0 (otherwise task stopped with fatal error are always in status "in progress")
191$sql = "UPDATE ".MAIN_DB_PREFIX."cronjob set processing = 0";
192$sql .= " WHERE processing = 1";
193$sql .= " AND datelastrun <= '".$db->idate(dol_now() - getDolGlobalInt('CRON_MAX_DELAY_FOR_JOBS', 24) * 3600, 'gmt')."'";
194$sql .= " AND datelastresult IS NULL";
195$db->query($sql);
196
197// Also unlock jobs that have a PID but the process does not exist anymore (SIGKILL, crash, segfault, ...).
198// Without this, such a job remains stuck in processing=1 until CRON_MAX_DELAY_FOR_JOBS kicks in.
199if (function_exists('posix_kill') && function_exists('posix_get_last_error')) {
200 $sql = "SELECT rowid, pid";
201 $sql .= " FROM ".MAIN_DB_PREFIX."cronjob";
202 $sql .= " WHERE processing = 1";
203 $sql .= " AND datelastresult IS NULL";
204 $sql .= " AND pid IS NOT NULL";
205 $resql = $db->query($sql);
206 if ($resql) {
207 while ($obj = $db->fetch_object($resql)) {
208 $pid = (int) $obj->pid;
209 if ($pid <= 0) {
210 continue;
211 }
212
213 $isalive = @posix_kill($pid, 0);
214 if (!$isalive) {
215 $errno = posix_get_last_error();
216 if ($errno === 3) { // ESRCH = No such process
217 $nowcleanup = dol_now();
218 $msg = 'Cron job unlocked: stale PID '.$pid;
219
220 $sqlu = "UPDATE ".MAIN_DB_PREFIX."cronjob";
221 $sqlu .= " SET processing = 0, pid = NULL, datelastresult = '".$db->idate($nowcleanup)."', lastresult = '-1', lastoutput = '".$db->escape($msg)."'";
222 $sqlu .= " WHERE rowid = ".((int) $obj->rowid)." AND processing = 1 AND pid = ".((int) $pid)." AND datelastresult IS NULL";
223 $db->query($sqlu);
224
225 dol_syslog("cron_run_jobs.php unlocked stuck job id=".$obj->rowid." (stale pid ".$pid.")", LOG_WARNING);
226 echo "cron_run_jobs.php unlocked stuck job id=".$obj->rowid." (stale pid ".$pid.")\n";
227 }
228 }
229 }
230 $db->free($resql);
231 }
232}
233
234dol_syslog("cron_run_jobs.php search qualified job using filter: ".json_encode($filter), LOG_DEBUG);
235echo "cron_run_jobs.php search qualified job using filter: ".json_encode($filter)."\n";
236
237$result = $object->fetchAll('ASC,ASC,ASC', 't.entity,t.priority,t.rowid', 0, 0, 1, $filter, ($forcequalified ? -1 : 0));
238if ($result < 0) {
239 echo "Error: ".$object->error;
240 dol_syslog("cron_run_jobs.php fetch Error ".$object->error, LOG_ERR);
241 exit(1);
242}
243
244// TODO Duplicate code. This sequence of code must be shared with code into public/cron/cron_run_jobs.php php page.
245
246$nbofjobs = count($object->lines);
247$nbofjobslaunchedok = 0;
248$nbofjobslaunchedko = 0;
249
250if (is_array($object->lines) && (count($object->lines) > 0)) {
251 $savconf = dol_clone($conf, 1); // Native mode 2 (default) drops object properties like $conf->db, so restoring $conf from it later would leave those undefined
252
253 // Loop over job
254 foreach ($object->lines as $line) {
256 '@phan-var-force Cronjob $line';
257
258 dol_syslog("cron_run_jobs.php cronjobid: ".$line->id." priority=".$line->priority." entity=".$line->entity." label=".$line->label, LOG_DEBUG);
259 echo "cron_run_jobs.php cronjobid: ".$line->id." priority=".$line->priority." entity=".$line->entity." label=".$line->label;
260
261 // Force reload of setup for the current entity
262 if ((empty($line->entity) ? 1 : $line->entity) != $conf->entity) {
263 dol_syslog("cron_run_jobs.php: we work on another entity conf than ".$conf->entity." so we reload mysoc, langs, user and conf", LOG_DEBUG);
264 echo " -> we change entity so we reload mysoc, langs, user and conf";
265
266 // if we switch to a different entity, we have to reset the $extrafields global var to
267 // make sure the extrafield definitions from this entity are properly loaded
268 if (($line->entity ?: 1) != $conf->entity && isset($extrafields) && !empty($extrafields->attributes)) {
269 $extrafields = new ExtraFields($db);
270 }
271 $conf->entity = (empty($line->entity) ? 1 : $line->entity);
272 $conf->setValues($db); // This make also the $mc->setValues($conf); that reload $mc->sharings
273 $mysoc->setMysoc($conf);
274
275 // Check module cron is activated
276 if (!isModEnabled('cron')) {
277 print "Canceled - Module Scheduled jobs (cron) not activated into entity ".$line->entity."\n";
278 dol_syslog("cron_run_jobs.php: Canceled - Module Scheduled jobs (cron) not activated into entity ".$line->entity, LOG_INFO);
279 continue;
280 }
281
282 // Force recheck that user is ok for the entity to process and reload permission for entity
283 if ($conf->entity != $user->entity) {
284 $result = $user->fetch(0, $userlogin, '', 1);
285 if ($result < 0) {
286 echo "\nUser Error: ".$user->error."\n";
287 dol_syslog("cron_run_jobs.php: User Error:".$user->error, LOG_ERR);
288 exit(1);
289 } else {
290 if ($result == 0) {
291 echo "\nUser login: ".$userlogin." does not exist for entity ".$conf->entity."\n";
292 dol_syslog("cron_run_jobs.php: User login: ".$userlogin." does not exist", LOG_ERR);
293 exit(1);
294 }
295 }
296 $user->loadRights('', 1); // We force rights reload to have the correct permissions for user in the entity we just switched in
297 }
298
299 // Reload langs
300 $langcode = getDolGlobalString('MAIN_LANG_DEFAULT', 'auto');
301 if (!empty($user->conf->MAIN_LANG_DEFAULT)) {
302 $langcode = $user->conf->MAIN_LANG_DEFAULT;
303 }
304 if ($langs->getDefaultLang() != $langcode) {
305 $langs = new Translate('', $conf);
306 $langs->setDefaultLang($langcode);
307 $langs->loadLangs(array('main', 'admin', 'cron', 'dict'));
308 }
309 }
310
311 if (!verifCond($line->test)) {
312 echo " - not qualified (testok=0)\n";
313 continue;
314 }
315
316 //If date_next_jobs is less of current date, execute the program, and store the execution time of the next execution in database
317 $datenextrunok = (empty($line->datenextrun) || (int) $line->datenextrun < $now);
318 $datestartok = (empty($line->datestart) || $line->datestart <= $now);
319 $dateendok = (empty($line->dateend) || $line->dateend >= $now);
320 if ($forcequalified || ($datenextrunok && $datestartok && $dateendok)) {
321 echo " - qualified";
322
323 dol_syslog("cron_run_jobs.php line->datenextrun:".dol_print_date($line->datenextrun, 'dayhourrfc')." line->datestart:".dol_print_date($line->datestart, 'dayhourrfc')." line->dateend:".dol_print_date($line->dateend, 'dayhourrfc')." now:".dol_print_date($now, 'dayhourrfc'));
324
325 $cronjob = new Cronjob($db);
326 $result = $cronjob->fetch($line->id);
327 if ($result < 0) {
328 echo " - Error cronjobid: ".$line->id." cronjob->fetch: ".$cronjob->error."\n";
329 echo "Failed to fetch job ".$line->id."\n";
330 dol_syslog("cron_run_jobs.php::fetch Error ".$cronjob->error, LOG_ERR);
331 exit(1);
332 }
333
334 $parameters = array('cronjob' => $cronjob, 'line' => $line);
335 $reshook = $hookmanager->executeHooks('beforeRunCronJob', $parameters, $object);
336
337 // Execute job
338 $result = $cronjob->run_jobs($userlogin);
339 if ($result < 0) {
340 echo " - Error cronjobid: ".$line->id." cronjob->run_job: ".$cronjob->error."\n";
341 echo "At least one job failed. Go on menu Home-Setup-Admin tools to see result for each job.\n";
342 echo "You can also enable module Log if not yet enabled, run again and take a look into dolibarr.log file\n";
343 dol_syslog("cron_run_jobs.php::run_jobs Error ".$cronjob->error, LOG_ERR);
344 $nbofjobslaunchedko++;
345 $resultstring = 'KO';
346 } else {
347 $nbofjobslaunchedok++;
348 $resultstring = 'OK';
349 echo " - ";
350 }
351
352 echo "Result of run_jobs ".$resultstring." result = ".$result;
353
354 // We re-program the next execution and stores the last execution time for this job
355 $result = $cronjob->reprogram_jobs($userlogin, $now);
356 if ($result < 0) {
357 echo " - Error cronjobid: ".$line->id." cronjob->reprogram_job: ".$cronjob->error."\n";
358 echo "Enable module Log if not yet enabled, run again and take a look into dolibarr.log file\n";
359 dol_syslog("cron_run_jobs.php::reprogram_jobs Error ".$cronjob->error, LOG_ERR);
360 exit(1);
361 }
362
363 echo " - Job re-scheduled\n";
364
365 $parameters = array('cronjob' => $cronjob, 'line' => $line);
366 $reshook = $hookmanager->executeHooks('afterRunCronJob', $parameters, $object);
367 } else {
368 echo " - not qualified (datenextrunok=".($datenextrunok ?: 0).", datestartok=".($datestartok ?: 0).", dateendok=".($dateendok ?: 0).")\n";
369
370 dol_syslog("cron_run_jobs.php job ".$line->id." not qualified line->datenextrun:".dol_print_date($line->datenextrun, 'dayhourrfc')." line->datestart:".dol_print_date($line->datestart, 'dayhourrfc')." line->dateend:".dol_print_date($line->dateend, 'dayhourrfc')." now:".dol_print_date($now, 'dayhourrfc'));
371 }
372 }
373
374 $conf = $savconf;
375} else {
376 echo "cron_run_jobs.php no qualified job found\n";
377}
378
379$db->close();
380
381print "***** ".$script_file." end - ".dol_print_date($now, 'dayhourrfc', 'gmt')." - ".gethostname()." *****\n";
382
383if ($nbofjobslaunchedko) {
384 exit(1);
385}
386exit(0);
387
388
397function usageCron($path, $script_file, $version)
398{
399 $now = dol_now();
400
401 print "***** ".$script_file." (".$version.") pid=".dol_getmypid()." - ".dol_print_date($now, 'dayhourrfc', 'gmt')." - ".gethostname()." *****\n";
402 print "Usage: ".$script_file." securitykey userlogin|'firstadmin' [cronjobid] [--force]\n";
403 print "\n";
404 print "The script return 0 when everything worked successfully.\n";
405 print "\n";
406 print "On Linux system, you can have cron jobs ran automatically by adding an entry into cron file.\n";
407 print "For example, to run this script each day at 3:30, you can add this line:\n";
408 print "30 3 * * * ".$path.$script_file." securitykey userlogin > ".DOL_DATA_ROOT."/".$script_file.".log\n";
409 print "For example, to run this script every 5mn, you can add this line:\n";
410 print "*/5 * * * * ".$path.$script_file." securitykey userlogin > ".DOL_DATA_ROOT."/".$script_file.".log\n";
411 print "\n";
412 print "The option --force allow to bypass the check on date of execution so job will be executed even if date is not yet reached.\n";
413 print "\n";
414}
$id
Support class for third parties, contacts, members, users or resources.
Definition account.php:47
if(! $sortfield) if(! $sortorder) $object
Definition account.php:100
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
Cron Job class.
Class to manage standard extra fields.
Class to manage translations.
Class to manage Dolibarr users.
global $mysoc
usageCron($path, $script_file, $version)
script cron usageCron
dol_now($mode='gmt')
Return date for now.
verifCond($strToEvaluate, $onlysimplestring='1')
Verify if condition in string is ok or not.
getDolUserString($key, $default='', $tmpuser=null)
Return Dolibarr user constant string value.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
dol_clone($srcobject, $native=2)
Create a clone of instance of object (new instance with same value for each properties) With native =...
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs=null, $encodetooutput=false, $decorate=0)
Output date in a string format according to outputlangs (or langs if not defined).
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
isModEnabled($module)
Is Dolibarr module enabled.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.