dolibarr 24.0.0-beta
cron_run_jobs_by_url.php
Go to the documentation of this file.
1<?php
2/* Copyright (C) 2012 Nicolas Villa aka Boyquotes http://informetic.fr
3 * Copyright (C) 2013 Florian Henry <forian.henry@open-cocnept.pro>
4 * Copyright (C) 2013-2015 Laurent Destailleur <eldy@users.sourceforge.net>
5 * Copyright (C) 2017 Regis Houssin <regis.houssin@inodbox.com>
6 * Copyright (C) 2024-2025 MDW <mdeweerd@users.noreply.github.com>
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('NOIPCHECK')) {
45 define('NOIPCHECK', '1'); // Do not check IP defined into conf $dolibarr_main_restrict_ip
46}
47
48// So log file will have a suffix
49if (!defined('USESUFFIXINLOG')) {
50 define('USESUFFIXINLOG', '_cron');
51}
52
53// For MultiCompany module.
54// Do not use GETPOST here, function is not defined and define must be done before including main.inc.php
55// Because 2 entities can have the same ref
56$entity = (!empty($_GET['entity']) ? (int) $_GET['entity'] : (!empty($_POST['entity']) ? (int) $_POST['entity'] : 1));
57if (is_numeric($entity)) {
58 define("DOLENTITY", $entity);
59}
60
61// Error if CLI mode
62if (php_sapi_name() == "cli") {
63 echo "Error: This page can't be used as a CLI script. For the CLI version of script, launch cron_run_job.php available into scripts/cron/ directory.\n";
64 exit(1);
65}
66
67// core library
68// Dolibarr environment
69require '../../main.inc.php';
70
71// cron jobs library
72dol_include_once("/cron/class/cronjob.class.php");
78global $langs, $conf, $db;
79
80// Language Management
81$langs->loadLangs(array("admin", "cron", "dict"));
82
83// Security check
84if (!isModEnabled('cron')) {
85 httponly_accessforbidden('Module Cron not enabled');
86}
87
88
89
90/*
91 * View
92 */
93
94// current date
95$now = dol_now();
96
97// Check the key, avoid that a stranger starts cron
98$key = GETPOST('securitykey', 'alpha');
99if (empty($key)) {
100 echo 'Securitykey is required. Check setup of cron jobs module.';
101 exit;
102}
103if ($key != getDolGlobalString('CRON_KEY')) {
104 echo 'Securitykey is wrong.';
105 exit;
106}
107// Check the key, avoid that a stranger starts cron
108$userlogin = GETPOST('userlogin', 'alpha');
109if (empty($userlogin)) {
110 echo 'Userlogin is required.';
111 exit;
112}
113require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php';
114$user = new User($db);
115$result = $user->fetch(0, $userlogin);
116if ($result < 0) {
117 echo "User Error:".$user->error;
118 dol_syslog("cron_run_jobs.php:: User Error:".$user->error, LOG_ERR);
119 exit;
120} else {
121 if (empty($user->id)) {
122 echo " User login:".$userlogin." do not exists";
123 dol_syslog(" User login:".$userlogin." do not exists", LOG_ERR);
124 exit;
125 }
126}
127$user->loadRights();
128
129$id = GETPOST('id', 'alpha'); // We accept non numeric id. We will filter later.
130
131
132// create a jobs object
133$object = new Cronjob($db);
134
135$filter = array();
136if (!empty($id)) {
137 if (!is_numeric($id)) {
138 echo "Error: Bad value for parameter job id";
139 dol_syslog("cron_run_jobs.php Bad value for parameter job id", LOG_WARNING);
140 exit;
141 }
142 $filter['t.rowid'] = $id;
143}
144
145// 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")
146$sql = "UPDATE ".MAIN_DB_PREFIX."cronjob set processing = 0";
147$sql .= " WHERE processing = 1";
148$sql .= " AND datelastrun <= '".$db->idate(dol_now() - getDolGlobalInt('CRON_MAX_DELAY_FOR_JOBS', 24) * 3600, 'gmt')."'";
149$sql .= " AND datelastresult IS NULL";
150$db->query($sql);
151
152// Also unlock jobs that have a PID but the process does not exist anymore (SIGKILL, crash, segfault, ...).
153if (function_exists('posix_kill') && function_exists('posix_get_last_error')) {
154 $sql = "SELECT rowid, pid";
155 $sql .= " FROM ".MAIN_DB_PREFIX."cronjob";
156 $sql .= " WHERE processing = 1";
157 $sql .= " AND datelastresult IS NULL";
158 $sql .= " AND pid IS NOT NULL";
159 $resql = $db->query($sql);
160 if ($resql) {
161 while ($obj = $db->fetch_object($resql)) {
162 $pid = (int) $obj->pid;
163 if ($pid <= 0) {
164 continue;
165 }
166
167 $isalive = @posix_kill($pid, 0);
168 if (!$isalive) {
169 $errno = posix_get_last_error();
170 if ($errno === 3) { // ESRCH = No such process
171 $nowcleanup = dol_now();
172 $msg = 'Cron job unlocked: stale PID '.$pid;
173
174 $sqlu = "UPDATE ".MAIN_DB_PREFIX."cronjob";
175 $sqlu .= " SET processing = 0, pid = NULL, datelastresult = '".$db->idate($nowcleanup)."', lastresult = '-1', lastoutput = '".$db->escape($msg)."'";
176 $sqlu .= " WHERE rowid = ".((int) $obj->rowid)." AND processing = 1 AND pid = ".((int) $pid)." AND datelastresult IS NULL";
177 $db->query($sqlu);
178
179 dol_syslog("cron_run_jobs_by_url.php unlocked stuck job id=".$obj->rowid." (stale pid ".$pid.")", LOG_WARNING);
180 echo "Unlocked stuck job id=".$obj->rowid." (stale pid ".$pid.")\n";
181 }
182 }
183 }
184 $db->free($resql);
185 }
186}
187
188$result = $object->fetchAll('ASC,ASC,ASC', 't.priority,t.entity,t.rowid', 0, 0, 1, $filter, 0);
189if ($result < 0) {
190 echo "Error: ".$object->error;
191 dol_syslog("cron_run_jobs.php fetch Error".$object->error, LOG_ERR);
192 exit;
193}
194
195// TODO Duplicate code. This sequence of code must be shared with code into cron_run_jobs.php script.
196
197// current date
198$nbofjobs = count($object->lines);
199$nbofjobslaunchedok = 0;
200$nbofjobslaunchedko = 0;
201
202if (is_array($object->lines) && (count($object->lines) > 0)) {
203 $savconf = dol_clone($conf, 0);
204
205 // Loop over job
206 foreach ($object->lines as $line) {
207 '@phan-var-force Cronjob $line';
208 dol_syslog("cron_run_jobs.php cronjobid: ".$line->id." priority=".$line->priority." entity=".$line->entity." label=".$line->label, LOG_DEBUG);
209 echo "cron_run_jobs.php cronjobid: ".$line->id." priority=".$line->priority." entity=".$line->entity." label=".$line->label;
210
211 // Force reload of setup for the current entity
212 if ($line->entity != $conf->entity) {
213 dol_syslog("cron_run_jobs.php we work on another entity so we reload user and conf", LOG_DEBUG);
214 echo " -> we change entity so we reload user and conf";
215
216 $conf->entity = (empty($line->entity) ? 1 : $line->entity);
217 $conf->setValues($db); // This make also the $mc->setValues($conf); that reload $mc->sharings
218
219 // Force recheck that user is ok for the entity to process and reload permission for entity
220 if ($conf->entity != $user->entity && $user->entity != 0) {
221 $result = $user->fetch(0, $userlogin, '', 0, $conf->entity);
222 if ($result < 0) {
223 echo "\nUser Error: ".$user->error."\n";
224 dol_syslog("cron_run_jobs.php:: User Error:".$user->error, LOG_ERR);
225 exit(1);
226 } else {
227 if ($result == 0) {
228 echo "\nUser login: ".$userlogin." does not exists for entity ".$conf->entity."\n";
229 dol_syslog("User login:".$userlogin." does not exists", LOG_ERR);
230 exit(1);
231 }
232 }
233 $user->loadRights();
234 }
235 }
236
237 if (!verifCond($line->test)) {
238 continue;
239 }
240
241 //If date_next_jobs is less of current date, execute the program, and store the execution time of the next execution in database
242 $datenextrunok = (empty($line->datenextrun) || (int) $line->datenextrun < $now);
243 $datestartok = (empty($line->datestart) || $line->datestart <= $now);
244 $dateendok = (empty($line->dateend) || $line->dateend >= $now);
245 if ($datenextrunok && $datestartok && $dateendok) {
246 echo " - qualified";
247
248 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'));
249
250 $cronjob = new Cronjob($db);
251 $result = $cronjob->fetch($line->id);
252 if ($result < 0) {
253 echo "Error cronjobid: ".$line->id." cronjob->fetch: ".$cronjob->error."\n";
254 echo "Failed to fetch job ".$line->id."\n";
255 dol_syslog("cron_run_jobs.php::fetch Error".$cronjob->error, LOG_ERR);
256 exit;
257 }
258 // Execute job
259 $result = $cronjob->run_jobs($userlogin);
260 if ($result < 0) {
261 echo "Error cronjobid: ".$line->id." cronjob->run_job: ".$cronjob->error."\n";
262 echo "At least one job failed. Go on menu Home-Setup-Admin tools to see result for each job.\n";
263 echo "You can also enable module Log if not yet enabled, run again and take a look into dolibarr.log file\n";
264 dol_syslog("cron_run_jobs.php::run_jobs Error".$cronjob->error, LOG_ERR);
265 $nbofjobslaunchedko++;
266 $resultstring = 'KO';
267 } else {
268 $nbofjobslaunchedok++;
269 $resultstring = 'OK';
270 }
271
272 echo "Result of run_jobs = ".$resultstring." result = ".$result;
273
274 // We re-program the next execution and stores the last execution time for this job
275 $result = $cronjob->reprogram_jobs($userlogin, $now);
276 if ($result < 0) {
277 echo " - Error cronjobid: ".$line->id." cronjob->reprogram_job: ".$cronjob->error."\n";
278 echo "Enable module Log if not yet enabled, run again and take a look into dolibarr.log file\n";
279 dol_syslog("cron_run_jobs.php::reprogram_jobs Error".$cronjob->error, LOG_ERR);
280 exit(1);
281 }
282
283 echo " - Job re-scheduled\n";
284 } else {
285 echo " - not qualified (datenextrunok=".($datenextrunok ?: 0).", datestartok=".($datestartok ?: 0).", dateendok=".($dateendok ?: 0).")\n";
286
287 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'));
288 }
289 }
290
291 $conf = $savconf;
292
293 echo "Result: ".($nbofjobs)." jobs - ".($nbofjobslaunchedok + $nbofjobslaunchedko)." launched = ".$nbofjobslaunchedok." OK + ".$nbofjobslaunchedko." KO";
294} else {
295 echo "Result: No active jobs found.";
296}
297
298$db->close();
$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 Dolibarr users.
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $db
API class for accounts.
dol_now($mode='gmt')
Return date for now.
verifCond($strToEvaluate, $onlysimplestring='1')
Verify if condition in string is ok or not.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
if(!function_exists( 'dol_getprefix')) dol_include_once($relpath, $classname='')
Make an include_once using default root and alternate root if it fails.
GETPOST($paramname, $check='alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0)
Return value of a param into GET or POST supervariable.
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.
httponly_accessforbidden($message='1', $http_response_code=403, $stringalreadysanitized=0)
Show a message to say access is forbidden and stop program.