dolibarr 23.0.3
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 <forian.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 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=".$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 ($key != getDolGlobalString('CRON_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->setDefaultLang($langcode);
161 $langs->tab_translate = array();
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
197dol_syslog("cron_run_jobs.php search qualified job using filter: ".json_encode($filter), LOG_DEBUG);
198echo "cron_run_jobs.php search qualified job using filter: ".json_encode($filter)."\n";
199
200$result = $object->fetchAll('ASC,ASC,ASC', 't.entity,t.priority,t.rowid', 0, 0, 1, $filter, ($forcequalified ? -1 : 0));
201if ($result < 0) {
202 echo "Error: ".$object->error;
203 dol_syslog("cron_run_jobs.php fetch Error ".$object->error, LOG_ERR);
204 exit(1);
205}
206
207// TODO Duplicate code. This sequence of code must be shared with code into public/cron/cron_run_jobs.php php page.
208
209$nbofjobs = count($object->lines);
210$nbofjobslaunchedok = 0;
211$nbofjobslaunchedko = 0;
212
213if (is_array($object->lines) && (count($object->lines) > 0)) {
214 $savconf = dol_clone($conf);
215
216 // Loop over job
217 foreach ($object->lines as $line) {
219 '@phan-var-force Cronjob $line';
220
221 dol_syslog("cron_run_jobs.php cronjobid: ".$line->id." priority=".$line->priority." entity=".$line->entity." label=".$line->label, LOG_DEBUG);
222 echo "cron_run_jobs.php cronjobid: ".$line->id." priority=".$line->priority." entity=".$line->entity." label=".$line->label;
223
224 // Force reload of setup for the current entity
225 if ((empty($line->entity) ? 1 : $line->entity) != $conf->entity) {
226 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);
227 echo " -> we change entity so we reload mysoc, langs, user and conf";
228
229 // if we switch to a different entity, we have to reset the $extrafields global var to
230 // make sure the extrafield definitions from this entity are properly loaded
231 if (($line->entity ?: 1) != $conf->entity && isset($extrafields) && !empty($extrafields->attributes)) {
232 $extrafields = new ExtraFields($db);
233 }
234 $conf->entity = (empty($line->entity) ? 1 : $line->entity);
235 $conf->setValues($db); // This make also the $mc->setValues($conf); that reload $mc->sharings
236 $mysoc->setMysoc($conf);
237
238 // Check module cron is activated
239 if (!isModEnabled('cron')) {
240 print "Canceled - Module Scheduled jobs (cron) not activated into entity ".$line->entity."\n";
241 dol_syslog("cron_run_jobs.php: Canceled - Module Scheduled jobs (cron) not activated into entity ".$line->entity, LOG_INFO);
242 continue;
243 }
244
245 // Force recheck that user is ok for the entity to process and reload permission for entity
246 if ($conf->entity != $user->entity) {
247 $result = $user->fetch(0, $userlogin, '', 1);
248 if ($result < 0) {
249 echo "\nUser Error: ".$user->error."\n";
250 dol_syslog("cron_run_jobs.php: User Error:".$user->error, LOG_ERR);
251 exit(1);
252 } else {
253 if ($result == 0) {
254 echo "\nUser login: ".$userlogin." does not exist for entity ".$conf->entity."\n";
255 dol_syslog("cron_run_jobs.php: User login: ".$userlogin." does not exist", LOG_ERR);
256 exit(1);
257 }
258 }
259 $user->loadRights('', 1); // We force rights reload to have the correct permissions for user in the entity we just switched in
260 }
261
262 // Reload langs
263 $langcode = getDolGlobalString('MAIN_LANG_DEFAULT', 'auto');
264 if (!empty($user->conf->MAIN_LANG_DEFAULT)) {
265 $langcode = $user->conf->MAIN_LANG_DEFAULT;
266 }
267 if ($langs->getDefaultLang() != $langcode) {
268 $langs->setDefaultLang($langcode);
269 $langs->tab_translate = array();
270 $langs->loadLangs(array('main', 'admin', 'cron', 'dict'));
271 }
272 }
273
274 if (!verifCond($line->test)) {
275 continue;
276 }
277
278 //If date_next_jobs is less of current date, execute the program, and store the execution time of the next execution in database
279 $datenextrunok = (empty($line->datenextrun) || (int) $line->datenextrun < $now);
280 $datestartok = (empty($line->datestart) || $line->datestart <= $now);
281 $dateendok = (empty($line->dateend) || $line->dateend >= $now);
282 if ($forcequalified || ($datenextrunok && $datestartok && $dateendok)) {
283 echo " - qualified";
284
285 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'));
286
287 $cronjob = new Cronjob($db);
288 $result = $cronjob->fetch($line->id);
289 if ($result < 0) {
290 echo " - Error cronjobid: ".$line->id." cronjob->fetch: ".$cronjob->error."\n";
291 echo "Failed to fetch job ".$line->id."\n";
292 dol_syslog("cron_run_jobs.php::fetch Error ".$cronjob->error, LOG_ERR);
293 exit(1);
294 }
295
296 $parameters = array('cronjob' => $cronjob, 'line' => $line);
297 $reshook = $hookmanager->executeHooks('beforeRunCronJob', $parameters, $object);
298
299 // Execute job
300 $result = $cronjob->run_jobs($userlogin);
301 if ($result < 0) {
302 echo " - Error cronjobid: ".$line->id." cronjob->run_job: ".$cronjob->error."\n";
303 echo "At least one job failed. Go on menu Home-Setup-Admin tools to see result for each job.\n";
304 echo "You can also enable module Log if not yet enabled, run again and take a look into dolibarr.log file\n";
305 dol_syslog("cron_run_jobs.php::run_jobs Error ".$cronjob->error, LOG_ERR);
306 $nbofjobslaunchedko++;
307 $resultstring = 'KO';
308 } else {
309 $nbofjobslaunchedok++;
310 $resultstring = 'OK';
311 echo " - ";
312 }
313
314 echo "Result of run_jobs ".$resultstring." result = ".$result;
315
316 // We re-program the next execution and stores the last execution time for this job
317 $result = $cronjob->reprogram_jobs($userlogin, $now);
318 if ($result < 0) {
319 echo " - Error cronjobid: ".$line->id." cronjob->reprogram_job: ".$cronjob->error."\n";
320 echo "Enable module Log if not yet enabled, run again and take a look into dolibarr.log file\n";
321 dol_syslog("cron_run_jobs.php::reprogram_jobs Error ".$cronjob->error, LOG_ERR);
322 exit(1);
323 }
324
325 echo " - Job re-scheduled\n";
326
327 $parameters = array('cronjob' => $cronjob, 'line' => $line);
328 $reshook = $hookmanager->executeHooks('afterRunCronJob', $parameters, $object);
329 } else {
330 echo " - not qualified (datenextrunok=".($datenextrunok ?: 0).", datestartok=".($datestartok ?: 0).", dateendok=".($dateendok ?: 0).")\n";
331
332 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'));
333 }
334 }
335
336 $conf = $savconf;
337} else {
338 echo "cron_run_jobs.php no qualified job found\n";
339}
340
341$db->close();
342
343print "***** ".$script_file." end - ".dol_print_date($now, 'dayhourrfc', 'gmt')." - ".gethostname()." *****\n";
344
345if ($nbofjobslaunchedko) {
346 exit(1);
347}
348exit(0);
349
350
359function usageCron($path, $script_file, $version)
360{
361 $now = dol_now();
362
363 print "***** ".$script_file." (".$version.") pid=".dol_getmypid()." - ".dol_print_date($now, 'dayhourrfc', 'gmt')." - ".gethostname()." *****\n";
364 print "Usage: ".$script_file." securitykey userlogin|'firstadmin' [cronjobid] [--force]\n";
365 print "\n";
366 print "The script return 0 when everything worked successfully.\n";
367 print "\n";
368 print "On Linux system, you can have cron jobs ran automatically by adding an entry into cron file.\n";
369 print "For example, to run this script each day at 3:30, you can add this line:\n";
370 print "30 3 * * * ".$path.$script_file." securitykey userlogin > ".DOL_DATA_ROOT."/".$script_file.".log\n";
371 print "For example, to run this script every 5mn, you can add this line:\n";
372 print "*/5 * * * * ".$path.$script_file." securitykey userlogin > ".DOL_DATA_ROOT."/".$script_file.".log\n";
373 print "\n";
374 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";
375 print "\n";
376}
$id
Support class for third parties, contacts, members, users or resources.
Definition account.php:47
if(! $sortfield) if(! $sortorder) $object
Definition account.php:100
Cron Job class.
Class to manage standard extra fields.
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).
dol_print_error($db=null, $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
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.