dolibarr 19.0.4
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."/cron/class/cronjob.class.php";
64require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php';
65
66// Check parameters
67if (!isset($argv[1]) || !$argv[1]) {
68 usage($path, $script_file);
69 exit(-1);
70}
71$key = $argv[1];
72
73if (!isset($argv[2]) || !$argv[2]) {
74 usage($path, $script_file);
75 exit(-1);
76}
77
78$userlogin = $argv[2];
79
80// Global variables
81$version = DOL_VERSION;
82$error = 0;
83
84$hookmanager->initHooks(array('cli'));
85
86
87/*
88 * Main
89 */
90
91// current date
92$now = dol_now();
93
94@set_time_limit(0);
95print "***** ".$script_file." (".$version.") pid=".dol_getmypid()." - userlogin=".$userlogin." - ".dol_print_date($now, 'dayhourrfc')." - ".gethostname()." *****\n";
96
97// Check module cron is activated
98if (!isModEnabled('cron')) {
99 print "Error: module Scheduled jobs (cron) not activated\n";
100 exit(-1);
101}
102
103// Check security key
104if ($key != getDolGlobalString('CRON_KEY')) {
105 print "Error: securitykey is wrong\n";
106 exit(-1);
107}
108
109if (!empty($dolibarr_main_db_readonly)) {
110 print "Error: instance in read-only mode\n";
111 exit(-1);
112}
113
114// If param userlogin is reserved word 'firstadmin'
115if ($userlogin == 'firstadmin') {
116 $sql = 'SELECT login, entity from '.MAIN_DB_PREFIX.'user WHERE admin = 1 and statut = 1 ORDER BY entity LIMIT 1';
117 $resql = $db->query($sql);
118 if ($resql) {
119 $obj = $db->fetch_object($resql);
120 if ($obj) {
121 $userlogin = $obj->login;
122 echo "First admin user found is login '".$userlogin."', entity ".$obj->entity."\n";
123 }
124 } else {
125 dol_print_error($db);
126 }
127}
128
129// Check user login
130$user = new User($db);
131$result = $user->fetch('', $userlogin, '', 1);
132if ($result < 0) {
133 echo "User Error: ".$user->error;
134 dol_syslog("cron_run_jobs.php:: User Error:".$user->error, LOG_ERR);
135 exit(-1);
136} else {
137 if (empty($user->id)) {
138 echo "User login: ".$userlogin." does not exists\n";
139 dol_syslog("User login:".$userlogin." does not exists", LOG_ERR);
140 exit(-1);
141 }
142}
143
144// Reload langs
145$langcode = getDolGlobalString('MAIN_LANG_DEFAULT', 'auto');
146if (!empty($user->conf->MAIN_LANG_DEFAULT)) {
147 $langcode = $user->conf->MAIN_LANG_DEFAULT;
148}
149if ($langs->getDefaultLang() != $langcode) {
150 $langs->setDefaultLang($langcode);
151 $langs->tab_translate = array();
152}
153// Language Management
154$langs->loadLangs(array('main', 'admin', 'cron', 'dict'));
155
156$user->getrights();
157
158if (isset($argv[3]) && $argv[3]) {
159 $id = $argv[3];
160}
161$forcequalified = 0;
162if (isset($argv[4]) && $argv[4] == '--force') {
163 $forcequalified = 1;
164}
165
166// create a jobs object
167$object = new Cronjob($db);
168
169$filter = array();
170if (!empty($id)) {
171 if (!is_numeric($id)) {
172 echo "Error: Bad value for parameter job id\n";
173 dol_syslog("cron_run_jobs.php Bad value for parameter job id", LOG_WARNING);
174 exit();
175 }
176 $filter['t.rowid'] = $id;
177}
178
179$result = $object->fetchAll('ASC,ASC,ASC', 't.priority,t.entity,t.rowid', 0, 0, 1, $filter, 0);
180if ($result < 0) {
181 echo "Error: ".$object->error;
182 dol_syslog("cron_run_jobs.php fetch Error ".$object->error, LOG_ERR);
183 exit(-1);
184}
185
186// TODO Duplicate code. This sequence of code must be shared with code into public/cron/cron_run_jobs.php php page.
187
188$nbofjobs = count($object->lines);
189$nbofjobslaunchedok = 0;
190$nbofjobslaunchedko = 0;
191
192if (is_array($object->lines) && (count($object->lines) > 0)) {
193 $savconf = dol_clone($conf);
194
195 // Loop over job
196 foreach ($object->lines as $line) {
197 dol_syslog("cron_run_jobs.php cronjobid: ".$line->id." priority=".$line->priority." entity=".$line->entity." label=".$line->label, LOG_DEBUG);
198 echo "cron_run_jobs.php cronjobid: ".$line->id." priority=".$line->priority." entity=".$line->entity." label=".$line->label;
199
200 // Force reload of setup for the current entity
201 if ((empty($line->entity) ? 1 : $line->entity) != $conf->entity) {
202 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);
203 echo " -> we change entity so we reload mysoc, langs, user and conf";
204
205 $conf->entity = (empty($line->entity) ? 1 : $line->entity);
206 $conf->setValues($db); // This make also the $mc->setValues($conf); that reload $mc->sharings
207 $mysoc->setMysoc($conf);
208
209 // Force recheck that user is ok for the entity to process and reload permission for entity
210 if ($conf->entity != $user->entity) {
211 $result = $user->fetch('', $userlogin, '', 1);
212 if ($result < 0) {
213 echo "\nUser Error: ".$user->error."\n";
214 dol_syslog("cron_run_jobs.php: User Error:".$user->error, LOG_ERR);
215 exit(-1);
216 } else {
217 if ($result == 0) {
218 echo "\nUser login: ".$userlogin." does not exist for entity ".$conf->entity."\n";
219 dol_syslog("cron_run_jobs.php: User login: ".$userlogin." does not exist", LOG_ERR);
220 exit(-1);
221 }
222 }
223 $user->getrights();
224 }
225
226 // Reload langs
227 $langcode = getDolGlobalString('MAIN_LANG_DEFAULT', 'auto');
228 if (!empty($user->conf->MAIN_LANG_DEFAULT)) {
229 $langcode = $user->conf->MAIN_LANG_DEFAULT;
230 }
231 if ($langs->getDefaultLang() != $langcode) {
232 $langs->setDefaultLang($langcode);
233 $langs->tab_translate = array();
234 $langs->loadLangs(array('main', 'admin', 'cron', 'dict'));
235 }
236 }
237
238 if (!verifCond($line->test)) {
239 continue;
240 }
241
242 //If date_next_jobs is less of current date, execute the program, and store the execution time of the next execution in database
243 if ($forcequalified || (($line->datenextrun < $now) && (empty($line->datestart) || $line->datestart <= $now) && (empty($line->dateend) || $line->dateend >= $now))) {
244 echo " - qualified";
245
246 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'));
247
248 $cronjob = new Cronjob($db);
249 $result = $cronjob->fetch($line->id);
250 if ($result < 0) {
251 echo " - Error cronjobid: ".$line->id." cronjob->fetch: ".$cronjob->error."\n";
252 echo "Failed to fetch job ".$line->id."\n";
253 dol_syslog("cron_run_jobs.php::fetch Error ".$cronjob->error, LOG_ERR);
254 exit(-1);
255 }
256 // Execute job
257 $result = $cronjob->run_jobs($userlogin);
258 if ($result < 0) {
259 echo " - Error cronjobid: ".$line->id." cronjob->run_job: ".$cronjob->error."\n";
260 echo "At least one job failed. Go on menu Home-Setup-Admin tools to see result for each job.\n";
261 echo "You can also enable module Log if not yet enabled, run again and take a look into dolibarr.log file\n";
262 dol_syslog("cron_run_jobs.php::run_jobs Error ".$cronjob->error, LOG_ERR);
263 $nbofjobslaunchedko++;
264 $resultstring = 'KO';
265 } else {
266 $nbofjobslaunchedok++;
267 $resultstring = 'OK';
268 }
269
270 echo " - run_jobs ".$resultstring." result = ".$result;
271
272 // We re-program the next execution and stores the last execution time for this job
273 $result = $cronjob->reprogram_jobs($userlogin, $now);
274 if ($result < 0) {
275 echo " - Error cronjobid: ".$line->id." cronjob->reprogram_job: ".$cronjob->error."\n";
276 echo "Enable module Log if not yet enabled, run again and take a look into dolibarr.log file\n";
277 dol_syslog("cron_run_jobs.php::reprogram_jobs Error ".$cronjob->error, LOG_ERR);
278 exit(-1);
279 }
280
281 echo " - reprogrammed\n";
282 } else {
283 echo " - not qualified\n";
284
285 dol_syslog("cron_run_jobs.php job 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'));
286 }
287 }
288
289 $conf = $savconf;
290} else {
291 echo "cron_run_jobs.php no qualified job found\n";
292}
293
294$db->close();
295
296if ($nbofjobslaunchedko) {
297 exit(1);
298}
299exit(0);
300
308function usage($path, $script_file)
309{
310 print "Usage: ".$script_file." securitykey userlogin|'firstadmin' [cronjobid] [--force]\n";
311 print "The script return 0 when everything worked successfully.\n";
312 print "\n";
313 print "On Linux system, you can have cron jobs ran automatically by adding an entry into cron.\n";
314 print "For example, to run pending tasks each day at 3:30, you can add this line:\n";
315 print "30 3 * * * ".$path.$script_file." securitykey userlogin > ".DOL_DATA_ROOT."/".$script_file.".log\n";
316 print "For example, to run pending tasks every 5mn, you can add this line:\n";
317 print "*/5 * * * * ".$path.$script_file." securitykey userlogin > ".DOL_DATA_ROOT."/".$script_file.".log\n";
318 print "\n";
319 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";
320}
Cron Job class.
Class to manage Dolibarr users.
usage($path, $script_file)
script cron usage
dol_getmypid()
Return getmypid() or random PID when function is disabled Some web hosts disable this php function fo...
dol_print_error($db='', $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs='', $encodetooutput=false)
Output date in a string format according to outputlangs (or langs if not defined).
dol_now($mode='auto')
Return date for now.
dol_clone($object, $native=0)
Create a clone of instance of object (new instance with same value for each properties) With native =...
verifCond($strToEvaluate)
Verify if condition in string is ok or not.
getDolGlobalString($key, $default='')
Return dolibarr global constant string value.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.