dolibarr 22.0.5
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 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// Check parameters
79if (!isset($argv[1]) || !$argv[1]) {
80 usageCron($path, $script_file);
81 exit(1);
82}
83$key = $argv[1];
84
85if (!isset($argv[2]) || !$argv[2]) {
86 usageCron($path, $script_file);
87 exit(1);
88}
89
90$userlogin = $argv[2];
91
92// Global variables
93$version = DOL_VERSION;
94$error = 0;
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 module cron is activated
114if (!isModEnabled('cron')) {
115 print "Error: module Scheduled jobs (cron) not activated\n";
116 exit(1);
117}
118
119// Check security key
120if ($key != getDolGlobalString('CRON_KEY')) {
121 print "Error: securitykey provided ".substr($key, 0, 5)."... does not match securitykey in setup.\n";
122 exit(1);
123}
124
125if (!empty($dolibarr_main_db_readonly)) {
126 print "Error: instance in read-only mode\n";
127 exit(1);
128}
129
130// If param userlogin is reserved word 'firstadmin'
131if ($userlogin == 'firstadmin') {
132 $sql = 'SELECT login, entity FROM '.MAIN_DB_PREFIX.'user WHERE admin = 1 and statut = 1 ORDER BY entity LIMIT 1';
133 $resql = $db->query($sql);
134 if ($resql) {
135 $obj = $db->fetch_object($resql);
136 if ($obj) {
137 $userlogin = $obj->login;
138 echo "First admin user found is login '".$userlogin."', entity ".$obj->entity."\n";
139 }
140 } else {
141 dol_print_error($db);
142 }
143}
144
145// Check user login
146$user = new User($db);
147$result = $user->fetch(0, $userlogin, '', 1);
148if ($result < 0) {
149 echo "User Error: ".$user->error;
150 dol_syslog("cron_run_jobs.php:: User Error:".$user->error, LOG_ERR);
151 exit(1);
152} else {
153 if (empty($user->id)) {
154 echo "User login: ".$userlogin." does not exists\n";
155 dol_syslog("User login:".$userlogin." does not exists", LOG_ERR);
156 exit(1);
157 }
158}
159
160// Reload langs
161$langcode = getDolGlobalString('MAIN_LANG_DEFAULT', 'auto');
162if (getDolUserString('MAIN_LANG_DEFAULT')) {
163 $langcode = getDolUserString('MAIN_LANG_DEFAULT');
164}
165if ($langs->getDefaultLang() != $langcode) {
166 $langs->setDefaultLang($langcode);
167 $langs->tab_translate = array();
168}
169// Language Management
170$langs->loadLangs(array('main', 'admin', 'cron', 'dict'));
171
172$user->loadRights();
173
174if (isset($argv[3]) && $argv[3]) {
175 $id = $argv[3];
176}
177$forcequalified = 0;
178if (isset($argv[4]) && $argv[4] == '--force') {
179 $forcequalified = 1;
180}
181
182// Create a jobs object
183$object = new Cronjob($db);
184
185$filter = array();
186if (!empty($id)) {
187 if (!is_numeric($id)) {
188 echo "Error: Bad value for parameter job id\n";
189 dol_syslog("cron_run_jobs.php Bad value for parameter job id", LOG_WARNING);
190 exit(2);
191 }
192 $filter['t.rowid'] = $id;
193}
194
195
196// 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")
197$sql = "UPDATE ".MAIN_DB_PREFIX."cronjob set processing = 0";
198$sql .= " WHERE processing = 1";
199$sql .= " AND datelastrun <= '".$db->idate(dol_now() - getDolGlobalInt('CRON_MAX_DELAY_FOR_JOBS', 24) * 3600, 'gmt')."'";
200$sql .= " AND datelastresult IS NULL";
201$db->query($sql);
202
203dol_syslog("cron_run_jobs.php search qualified job using filter: ".json_encode($filter), LOG_DEBUG);
204echo "cron_run_jobs.php search qualified job using filter: ".json_encode($filter)."\n";
205
206$result = $object->fetchAll('ASC,ASC,ASC', 't.entity,t.priority,t.rowid', 0, 0, 1, $filter, ($forcequalified ? -1 : 0));
207if ($result < 0) {
208 echo "Error: ".$object->error;
209 dol_syslog("cron_run_jobs.php fetch Error ".$object->error, LOG_ERR);
210 exit(1);
211}
212
213// TODO Duplicate code. This sequence of code must be shared with code into public/cron/cron_run_jobs.php php page.
214
215$nbofjobs = count($object->lines);
216$nbofjobslaunchedok = 0;
217$nbofjobslaunchedko = 0;
218
219if (is_array($object->lines) && (count($object->lines) > 0)) {
220 $savconf = dol_clone($conf);
221
222 // Loop over job
223 foreach ($object->lines as $line) {
225 '@phan-var-force Cronjob $line';
226
227 dol_syslog("cron_run_jobs.php cronjobid: ".$line->id." priority=".$line->priority." entity=".$line->entity." label=".$line->label, LOG_DEBUG);
228 echo "cron_run_jobs.php cronjobid: ".$line->id." priority=".$line->priority." entity=".$line->entity." label=".$line->label;
229
230 // Force reload of setup for the current entity
231 if ((empty($line->entity) ? 1 : $line->entity) != $conf->entity) {
232 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);
233 echo " -> we change entity so we reload mysoc, langs, user and conf";
234
235 // if we switch to a different entity, we have to reset the $extrafields global var to
236 // make sure the extrafield definitions from this entity are properly loaded
237 if (($line->entity ?: 1) != $conf->entity && isset($extrafields) && !empty($extrafields->attributes)) {
238 $extrafields = new ExtraFields($db);
239 }
240 $conf->entity = (empty($line->entity) ? 1 : $line->entity);
241 $conf->setValues($db); // This make also the $mc->setValues($conf); that reload $mc->sharings
242 $mysoc->setMysoc($conf);
243
244 // Force recheck that user is ok for the entity to process and reload permission for entity
245 if ($conf->entity != $user->entity) {
246 $result = $user->fetch(0, $userlogin, '', 1);
247 if ($result < 0) {
248 echo "\nUser Error: ".$user->error."\n";
249 dol_syslog("cron_run_jobs.php: User Error:".$user->error, LOG_ERR);
250 exit(1);
251 } else {
252 if ($result == 0) {
253 echo "\nUser login: ".$userlogin." does not exist for entity ".$conf->entity."\n";
254 dol_syslog("cron_run_jobs.php: User login: ".$userlogin." does not exist", LOG_ERR);
255 exit(1);
256 }
257 }
258 $user->loadRights('', 1); // We force rights reload to have the correct permissions for user in the entity we just switched in
259 }
260
261 // Reload langs
262 $langcode = getDolGlobalString('MAIN_LANG_DEFAULT', 'auto');
263 if (!empty($user->conf->MAIN_LANG_DEFAULT)) {
264 $langcode = $user->conf->MAIN_LANG_DEFAULT;
265 }
266 if ($langs->getDefaultLang() != $langcode) {
267 $langs->setDefaultLang($langcode);
268 $langs->tab_translate = array();
269 $langs->loadLangs(array('main', 'admin', 'cron', 'dict'));
270 }
271 }
272
273 if (!verifCond($line->test)) {
274 continue;
275 }
276
277 //If date_next_jobs is less of current date, execute the program, and store the execution time of the next execution in database
278 $datenextrunok = (empty($line->datenextrun) || (int) $line->datenextrun < $now);
279 $datestartok = (empty($line->datestart) || $line->datestart <= $now);
280 $dateendok = (empty($line->dateend) || $line->dateend >= $now);
281 if ($forcequalified || ($datenextrunok && $datestartok && $dateendok)) {
282 echo " - qualified";
283
284 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'));
285
286 $cronjob = new Cronjob($db);
287 $result = $cronjob->fetch($line->id);
288 if ($result < 0) {
289 echo " - Error cronjobid: ".$line->id." cronjob->fetch: ".$cronjob->error."\n";
290 echo "Failed to fetch job ".$line->id."\n";
291 dol_syslog("cron_run_jobs.php::fetch Error ".$cronjob->error, LOG_ERR);
292 exit(1);
293 }
294
295 $parameters = array('cronjob' => $cronjob, 'line' => $line);
296 $reshook = $hookmanager->executeHooks('beforeRunCronJob', $parameters, $object);
297
298 // Execute job
299 $result = $cronjob->run_jobs($userlogin);
300 if ($result < 0) {
301 echo " - Error cronjobid: ".$line->id." cronjob->run_job: ".$cronjob->error."\n";
302 echo "At least one job failed. Go on menu Home-Setup-Admin tools to see result for each job.\n";
303 echo "You can also enable module Log if not yet enabled, run again and take a look into dolibarr.log file\n";
304 dol_syslog("cron_run_jobs.php::run_jobs Error ".$cronjob->error, LOG_ERR);
305 $nbofjobslaunchedko++;
306 $resultstring = 'KO';
307 } else {
308 $nbofjobslaunchedok++;
309 $resultstring = 'OK';
310 echo " - ";
311 }
312
313 echo "Result of run_jobs ".$resultstring." result = ".$result;
314
315 // We re-program the next execution and stores the last execution time for this job
316 $result = $cronjob->reprogram_jobs($userlogin, $now);
317 if ($result < 0) {
318 echo " - Error cronjobid: ".$line->id." cronjob->reprogram_job: ".$cronjob->error."\n";
319 echo "Enable module Log if not yet enabled, run again and take a look into dolibarr.log file\n";
320 dol_syslog("cron_run_jobs.php::reprogram_jobs Error ".$cronjob->error, LOG_ERR);
321 exit(1);
322 }
323
324 echo " - Job re-scheduled\n";
325
326 $parameters = array('cronjob' => $cronjob, 'line' => $line);
327 $reshook = $hookmanager->executeHooks('afterRunCronJob', $parameters, $object);
328 } else {
329 echo " - not qualified (datenextrunok=".($datenextrunok ?: 0).", datestartok=".($datestartok ?: 0).", dateendok=".($dateendok ?: 0).")\n";
330
331 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'));
332 }
333 }
334
335 $conf = $savconf;
336} else {
337 echo "cron_run_jobs.php no qualified job found\n";
338}
339
340$db->close();
341
342print "***** ".$script_file." end - ".dol_print_date($now, 'dayhourrfc', 'gmt')." - ".gethostname()." *****\n";
343
344if ($nbofjobslaunchedko) {
345 exit(1);
346}
347exit(0);
348
349
357function usageCron($path, $script_file)
358{
359 print "Usage: ".$script_file." securitykey userlogin|'firstadmin' [cronjobid] [--force]\n";
360 print "The script return 0 when everything worked successfully.\n";
361 print "\n";
362 print "On Linux system, you can have cron jobs ran automatically by adding an entry into cron.\n";
363 print "For example, to run pending tasks each day at 3:30, you can add this line:\n";
364 print "30 3 * * * ".$path.$script_file." securitykey userlogin > ".DOL_DATA_ROOT."/".$script_file.".log\n";
365 print "For example, to run pending tasks every 5mn, you can add this line:\n";
366 print "*/5 * * * * ".$path.$script_file." securitykey userlogin > ".DOL_DATA_ROOT."/".$script_file.".log\n";
367 print "\n";
368 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";
369}
$id
Support class for third parties, contacts, members, users or resources.
Definition account.php:48
if( $user->socid > 0) if(! $user->hasRight('accounting', 'chartofaccount')) $object
Definition card.php:67
Cron Job class.
Class to manage standard extra fields.
Class to manage Dolibarr users.
usageCron($path, $script_file)
script cron usageCron
verifCond($strToEvaluate, $onlysimplestring='1')
Verify if condition in string is ok or not.
dol_getmypid()
Return getmypid() or random PID when function is disabled Some web hosts disable this php function fo...
getDolUserString($key, $default='', $tmpuser=null)
Return Dolibarr user constant string value.
dol_now($mode='auto')
Return date for now.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs=null, $encodetooutput=false)
Output date in a string format according to outputlangs (or langs if not defined).
dol_clone($object, $native=2)
Create a clone of instance of object (new instance with same value for each properties) With native =...
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.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
global $conf
The following vars must be defined: $type2label $form $conf, $lang, The following vars may also be de...
Definition member.php:79