dolibarr 21.0.0-beta
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 *
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 3 of the License, or
12 * (at your option) any later version.
13 *
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
18 *
19 * You should have received a copy of the GNU General Public License
20 * along with this program. If not, see <https://www.gnu.org/licenses/>.
21 */
22
29if (!defined('NOTOKENRENEWAL')) {
30 define('NOTOKENRENEWAL', '1'); // Disables token renewal
31}
32if (!defined('NOREQUIREMENU')) {
33 define('NOREQUIREMENU', '1');
34}
35if (!defined('NOREQUIREHTML')) {
36 define('NOREQUIREHTML', '1');
37}
38if (!defined('NOREQUIREAJAX')) {
39 define('NOREQUIREAJAX', '1');
40}
41if (!defined('NOLOGIN')) {
42 define('NOLOGIN', '1');
43}
44if (!defined('NOSESSION')) {
45 define('NOSESSION', '1');
46}
47
48// So log file will have a suffix
49if (!defined('USESUFFIXINLOG')) {
50 define('USESUFFIXINLOG', '_cron');
51}
52
53$sapi_type = php_sapi_name();
54$script_file = basename(__FILE__);
55$path = __DIR__.'/';
56
57// Error if Web mode
58if (substr($sapi_type, 0, 3) == 'cgi') {
59 echo "Error: You are using PHP for CGI. To execute ".$script_file." from command line, you must use PHP for CLI mode.\n";
60 exit(1);
61}
62
63require_once $path."../../htdocs/master.inc.php";
64require_once DOL_DOCUMENT_ROOT.'/core/lib/functionscli.lib.php';
65require_once DOL_DOCUMENT_ROOT."/cron/class/cronjob.class.php";
66require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php';
67
76// Check parameters
77if (!isset($argv[1]) || !$argv[1]) {
78 usage($path, $script_file);
79 exit(1);
80}
81$key = $argv[1];
82
83if (!isset($argv[2]) || !$argv[2]) {
84 usage($path, $script_file);
85 exit(1);
86}
87
88$userlogin = $argv[2];
89
90// Global variables
91$version = DOL_VERSION;
92$error = 0;
93
94$hookmanager->initHooks(array('cli'));
95
96
97/*
98 * Main
99 */
100
101// current date
102$now = dol_now();
103
104@set_time_limit(0);
105print "***** ".$script_file." (".$version.") pid=".dol_getmypid()." - userlogin=".$userlogin." - ".dol_print_date($now, 'dayhourrfc', 'gmt')." - ".gethostname()." *****\n";
106
107// Show TZ of the serveur when ran from command line.
108$ini_path = php_ini_loaded_file();
109print 'TZ server = '.getServerTimeZoneString()." - set in PHP ini ".$ini_path."\n";
110
111// Check module cron is activated
112if (!isModEnabled('cron')) {
113 print "Error: module Scheduled jobs (cron) not activated\n";
114 exit(1);
115}
116
117// Check security key
118if ($key != getDolGlobalString('CRON_KEY')) {
119 print "Error: securitykey provided ".substr($key, 0, 5)."... does not match securitykey in setup.\n";
120 exit(1);
121}
122
123if (!empty($dolibarr_main_db_readonly)) {
124 print "Error: instance in read-only mode\n";
125 exit(1);
126}
127
128// If param userlogin is reserved word 'firstadmin'
129if ($userlogin == 'firstadmin') {
130 $sql = 'SELECT login, entity from '.MAIN_DB_PREFIX.'user WHERE admin = 1 and statut = 1 ORDER BY entity LIMIT 1';
131 $resql = $db->query($sql);
132 if ($resql) {
133 $obj = $db->fetch_object($resql);
134 if ($obj) {
135 $userlogin = $obj->login;
136 echo "First admin user found is login '".$userlogin."', entity ".$obj->entity."\n";
137 }
138 } else {
139 dol_print_error($db);
140 }
141}
142
143// Check user login
144$user = new User($db);
145$result = $user->fetch('', $userlogin, '', 1);
146if ($result < 0) {
147 echo "User Error: ".$user->error;
148 dol_syslog("cron_run_jobs.php:: User Error:".$user->error, LOG_ERR);
149 exit(1);
150} else {
151 if (empty($user->id)) {
152 echo "User login: ".$userlogin." does not exists\n";
153 dol_syslog("User login:".$userlogin." does not exists", LOG_ERR);
154 exit(1);
155 }
156}
157
158// Reload langs
159$langcode = getDolGlobalString('MAIN_LANG_DEFAULT', 'auto');
160if (getDolUserString('MAIN_LANG_DEFAULT')) {
161 $langcode = getDolUserString('MAIN_LANG_DEFAULT');
162}
163if ($langs->getDefaultLang() != $langcode) {
164 $langs->setDefaultLang($langcode);
165 $langs->tab_translate = array();
166}
167// Language Management
168$langs->loadLangs(array('main', 'admin', 'cron', 'dict'));
169
170$user->loadRights();
171
172if (isset($argv[3]) && $argv[3]) {
173 $id = $argv[3];
174}
175$forcequalified = 0;
176if (isset($argv[4]) && $argv[4] == '--force') {
177 $forcequalified = 1;
178}
179
180// Create a jobs object
181$object = new Cronjob($db);
182
183$filter = array();
184if (!empty($id)) {
185 if (!is_numeric($id)) {
186 echo "Error: Bad value for parameter job id\n";
187 dol_syslog("cron_run_jobs.php Bad value for parameter job id", LOG_WARNING);
188 exit(2);
189 }
190 $filter['t.rowid'] = $id;
191}
192
193
194// 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")
195$sql = "UPDATE ".MAIN_DB_PREFIX."cronjob set processing = 0";
196$sql .= " WHERE processing = 1";
197$sql .= " AND datelastrun <= '".$db->idate(dol_now() - getDolGlobalInt('CRON_MAX_DELAY_FOR_JOBS', 24) * 3600, 'gmt')."'";
198$sql .= " AND datelastresult IS NULL";
199$db->query($sql);
200
201dol_syslog("cron_run_jobs.php search qualified job using filter: ".json_encode($filter), LOG_DEBUG);
202echo "cron_run_jobs.php search qualified job using filter: ".json_encode($filter)."\n";
203
204$result = $object->fetchAll('ASC,ASC,ASC', 't.priority,t.entity,t.rowid', 0, 0, 1, $filter, ($forcequalified ? -1 : 0));
205if ($result < 0) {
206 echo "Error: ".$object->error;
207 dol_syslog("cron_run_jobs.php fetch Error ".$object->error, LOG_ERR);
208 exit(1);
209}
210
211// TODO Duplicate code. This sequence of code must be shared with code into public/cron/cron_run_jobs.php php page.
212
213$nbofjobs = count($object->lines);
214$nbofjobslaunchedok = 0;
215$nbofjobslaunchedko = 0;
216
217if (is_array($object->lines) && (count($object->lines) > 0)) {
218 $savconf = dol_clone($conf);
219
220 // Loop over job
221 foreach ($object->lines as $line) {
222 dol_syslog("cron_run_jobs.php cronjobid: ".$line->id." priority=".$line->priority." entity=".$line->entity." label=".$line->label, LOG_DEBUG);
223 echo "cron_run_jobs.php cronjobid: ".$line->id." priority=".$line->priority." entity=".$line->entity." label=".$line->label;
224
225 // Force reload of setup for the current entity
226 if ((empty($line->entity) ? 1 : $line->entity) != $conf->entity) {
227 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);
228 echo " -> we change entity so we reload mysoc, langs, user and conf";
229
230 $conf->entity = (empty($line->entity) ? 1 : $line->entity);
231 $conf->setValues($db); // This make also the $mc->setValues($conf); that reload $mc->sharings
232 $mysoc->setMysoc($conf);
233
234 // Force recheck that user is ok for the entity to process and reload permission for entity
235 if ($conf->entity != $user->entity) {
236 $result = $user->fetch('', $userlogin, '', 1);
237 if ($result < 0) {
238 echo "\nUser Error: ".$user->error."\n";
239 dol_syslog("cron_run_jobs.php: User Error:".$user->error, LOG_ERR);
240 exit(1);
241 } else {
242 if ($result == 0) {
243 echo "\nUser login: ".$userlogin." does not exist for entity ".$conf->entity."\n";
244 dol_syslog("cron_run_jobs.php: User login: ".$userlogin." does not exist", LOG_ERR);
245 exit(1);
246 }
247 }
248 $user->loadRights();
249 }
250
251 // Reload langs
252 $langcode = getDolGlobalString('MAIN_LANG_DEFAULT', 'auto');
253 if (!empty($user->conf->MAIN_LANG_DEFAULT)) {
254 $langcode = $user->conf->MAIN_LANG_DEFAULT;
255 }
256 if ($langs->getDefaultLang() != $langcode) {
257 $langs->setDefaultLang($langcode);
258 $langs->tab_translate = array();
259 $langs->loadLangs(array('main', 'admin', 'cron', 'dict'));
260 }
261 }
262
263 if (!verifCond($line->test)) {
264 continue;
265 }
266
267 //If date_next_jobs is less of current date, execute the program, and store the execution time of the next execution in database
268 $datenextrunok = (empty($line->datenextrun) || (int) $line->datenextrun < $now);
269 $datestartok = (empty($line->datestart) || $line->datestart <= $now);
270 $dateendok = (empty($line->dateend) || $line->dateend >= $now);
271 if ($forcequalified || ($datenextrunok && $datestartok && $dateendok)) {
272 echo " - qualified";
273
274 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'));
275
276 $cronjob = new Cronjob($db);
277 $result = $cronjob->fetch($line->id);
278 if ($result < 0) {
279 echo " - Error cronjobid: ".$line->id." cronjob->fetch: ".$cronjob->error."\n";
280 echo "Failed to fetch job ".$line->id."\n";
281 dol_syslog("cron_run_jobs.php::fetch Error ".$cronjob->error, LOG_ERR);
282 exit(1);
283 }
284
285 $parameters = array('cronjob' => $cronjob, 'line' => $line);
286 $reshook = $hookmanager->executeHooks('beforeRunCronJob', $parameters, $object);
287
288 // Execute job
289 $result = $cronjob->run_jobs($userlogin);
290 if ($result < 0) {
291 echo " - Error cronjobid: ".$line->id." cronjob->run_job: ".$cronjob->error."\n";
292 echo "At least one job failed. Go on menu Home-Setup-Admin tools to see result for each job.\n";
293 echo "You can also enable module Log if not yet enabled, run again and take a look into dolibarr.log file\n";
294 dol_syslog("cron_run_jobs.php::run_jobs Error ".$cronjob->error, LOG_ERR);
295 $nbofjobslaunchedko++;
296 $resultstring = 'KO';
297 } else {
298 $nbofjobslaunchedok++;
299 $resultstring = 'OK';
300 }
301
302 echo "Result of run_jobs ".$resultstring." result = ".$result;
303
304 // We re-program the next execution and stores the last execution time for this job
305 $result = $cronjob->reprogram_jobs($userlogin, $now);
306 if ($result < 0) {
307 echo " - Error cronjobid: ".$line->id." cronjob->reprogram_job: ".$cronjob->error."\n";
308 echo "Enable module Log if not yet enabled, run again and take a look into dolibarr.log file\n";
309 dol_syslog("cron_run_jobs.php::reprogram_jobs Error ".$cronjob->error, LOG_ERR);
310 exit(1);
311 }
312
313 echo " - Job re-scheduled\n";
314
315 $parameters = array('cronjob' => $cronjob, 'line' => $line);
316 $reshook = $hookmanager->executeHooks('afterRunCronJob', $parameters, $object);
317 } else {
318 echo " - not qualified (datenextrunok=".($datenextrunok ?: 0).", datestartok=".($datestartok ?: 0).", dateendok=".($dateendok ?: 0).")\n";
319
320 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'));
321 }
322 }
323
324 $conf = $savconf;
325} else {
326 echo "cron_run_jobs.php no qualified job found\n";
327}
328
329$db->close();
330
331print "***** ".$script_file." end - ".dol_print_date($now, 'dayhourrfc', 'gmt')." - ".gethostname()." *****\n";
332
333if ($nbofjobslaunchedko) {
334 exit(1);
335}
336exit(0);
337
338
346function usage($path, $script_file)
347{
348 print "Usage: ".$script_file." securitykey userlogin|'firstadmin' [cronjobid] [--force]\n";
349 print "The script return 0 when everything worked successfully.\n";
350 print "\n";
351 print "On Linux system, you can have cron jobs ran automatically by adding an entry into cron.\n";
352 print "For example, to run pending tasks each day at 3:30, you can add this line:\n";
353 print "30 3 * * * ".$path.$script_file." securitykey userlogin > ".DOL_DATA_ROOT."/".$script_file.".log\n";
354 print "For example, to run pending tasks every 5mn, you can add this line:\n";
355 print "*/5 * * * * ".$path.$script_file." securitykey userlogin > ".DOL_DATA_ROOT."/".$script_file.".log\n";
356 print "\n";
357 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";
358}
$id
Definition account.php:48
if( $user->socid > 0) if(! $user->hasRight('accounting', 'chartofaccount')) $object
Definition card.php:66
Cron Job class.
Class to manage Dolibarr users.
usage($path, $script_file)
script cron usage
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