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