dolibarr  20.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  *
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 
28 if (!defined('NOTOKENRENEWAL')) {
29  define('NOTOKENRENEWAL', '1'); // Disables token renewal
30 }
31 if (!defined('NOREQUIREMENU')) {
32  define('NOREQUIREMENU', '1');
33 }
34 if (!defined('NOREQUIREHTML')) {
35  define('NOREQUIREHTML', '1');
36 }
37 if (!defined('NOREQUIREAJAX')) {
38  define('NOREQUIREAJAX', '1');
39 }
40 if (!defined('NOLOGIN')) {
41  define('NOLOGIN', '1');
42 }
43 if (!defined('NOSESSION')) {
44  define('NOSESSION', '1');
45 }
46 
47 // So log file will have a suffix
48 if (!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
57 if (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 
62 require_once $path."../../htdocs/master.inc.php";
63 require_once DOL_DOCUMENT_ROOT."/cron/class/cronjob.class.php";
64 require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php';
65 
66 // Check parameters
67 if (!isset($argv[1]) || !$argv[1]) {
68  usage($path, $script_file);
69  exit(1);
70 }
71 $key = $argv[1];
72 
73 if (!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);
95 print "***** ".$script_file." (".$version.") pid=".dol_getmypid()." - userlogin=".$userlogin." - ".dol_print_date($now, 'dayhourrfc', 'gmt')." - ".gethostname()." *****\n";
96 
97 // Show TZ of the serveur when ran from command line.
98 $ini_path = php_ini_loaded_file();
99 print 'TZ server = '.getServerTimeZoneString()." - set in PHP ini ".$ini_path."\n";
100 
101 // Check module cron is activated
102 if (!isModEnabled('cron')) {
103  print "Error: module Scheduled jobs (cron) not activated\n";
104  exit(1);
105 }
106 
107 // Check security key
108 if ($key != getDolGlobalString('CRON_KEY')) {
109  print "Error: securitykey provided ".substr($key, 0, 5)."... does not match securitykey in setup.\n";
110  exit(1);
111 }
112 
113 if (!empty($dolibarr_main_db_readonly)) {
114  print "Error: instance in read-only mode\n";
115  exit(1);
116 }
117 
118 // If param userlogin is reserved word 'firstadmin'
119 if ($userlogin == 'firstadmin') {
120  $sql = 'SELECT login, entity from '.MAIN_DB_PREFIX.'user WHERE admin = 1 and statut = 1 ORDER BY entity LIMIT 1';
121  $resql = $db->query($sql);
122  if ($resql) {
123  $obj = $db->fetch_object($resql);
124  if ($obj) {
125  $userlogin = $obj->login;
126  echo "First admin user found is login '".$userlogin."', entity ".$obj->entity."\n";
127  }
128  } else {
129  dol_print_error($db);
130  }
131 }
132 
133 // Check user login
134 $user = new User($db);
135 $result = $user->fetch('', $userlogin, '', 1);
136 if ($result < 0) {
137  echo "User Error: ".$user->error;
138  dol_syslog("cron_run_jobs.php:: User Error:".$user->error, LOG_ERR);
139  exit(1);
140 } else {
141  if (empty($user->id)) {
142  echo "User login: ".$userlogin." does not exists\n";
143  dol_syslog("User login:".$userlogin." does not exists", LOG_ERR);
144  exit(1);
145  }
146 }
147 
148 // Reload langs
149 $langcode = getDolGlobalString('MAIN_LANG_DEFAULT', 'auto');
150 if (!empty($user->conf->MAIN_LANG_DEFAULT)) {
151  $langcode = $user->conf->MAIN_LANG_DEFAULT;
152 }
153 if ($langs->getDefaultLang() != $langcode) {
154  $langs->setDefaultLang($langcode);
155  $langs->tab_translate = array();
156 }
157 // Language Management
158 $langs->loadLangs(array('main', 'admin', 'cron', 'dict'));
159 
160 $user->getrights();
161 
162 if (isset($argv[3]) && $argv[3]) {
163  $id = $argv[3];
164 }
165 $forcequalified = 0;
166 if (isset($argv[4]) && $argv[4] == '--force') {
167  $forcequalified = 1;
168 }
169 
170 // create a jobs object
171 $object = new Cronjob($db);
172 
173 $filter = array();
174 if (!empty($id)) {
175  if (!is_numeric($id)) {
176  echo "Error: Bad value for parameter job id\n";
177  dol_syslog("cron_run_jobs.php Bad value for parameter job id", LOG_WARNING);
178  exit(2);
179  }
180  $filter['t.rowid'] = $id;
181 }
182 
183 $result = $object->fetchAll('ASC,ASC,ASC', 't.priority,t.entity,t.rowid', 0, 0, 1, $filter, 0);
184 if ($result < 0) {
185  echo "Error: ".$object->error;
186  dol_syslog("cron_run_jobs.php fetch Error ".$object->error, LOG_ERR);
187  exit(1);
188 }
189 
190 // TODO Duplicate code. This sequence of code must be shared with code into public/cron/cron_run_jobs.php php page.
191 
192 $nbofjobs = count($object->lines);
193 $nbofjobslaunchedok = 0;
194 $nbofjobslaunchedko = 0;
195 
196 if (is_array($object->lines) && (count($object->lines) > 0)) {
197  $savconf = dol_clone($conf);
198 
199  // Loop over job
200  foreach ($object->lines as $line) {
201  dol_syslog("cron_run_jobs.php cronjobid: ".$line->id." priority=".$line->priority." entity=".$line->entity." label=".$line->label, LOG_DEBUG);
202  echo "cron_run_jobs.php cronjobid: ".$line->id." priority=".$line->priority." entity=".$line->entity." label=".$line->label;
203 
204  // Force reload of setup for the current entity
205  if ((empty($line->entity) ? 1 : $line->entity) != $conf->entity) {
206  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);
207  echo " -> we change entity so we reload mysoc, langs, user and conf";
208 
209  $conf->entity = (empty($line->entity) ? 1 : $line->entity);
210  $conf->setValues($db); // This make also the $mc->setValues($conf); that reload $mc->sharings
211  $mysoc->setMysoc($conf);
212 
213  // Force recheck that user is ok for the entity to process and reload permission for entity
214  if ($conf->entity != $user->entity) {
215  $result = $user->fetch('', $userlogin, '', 1);
216  if ($result < 0) {
217  echo "\nUser Error: ".$user->error."\n";
218  dol_syslog("cron_run_jobs.php: User Error:".$user->error, LOG_ERR);
219  exit(1);
220  } else {
221  if ($result == 0) {
222  echo "\nUser login: ".$userlogin." does not exist for entity ".$conf->entity."\n";
223  dol_syslog("cron_run_jobs.php: User login: ".$userlogin." does not exist", LOG_ERR);
224  exit(1);
225  }
226  }
227  $user->getrights();
228  }
229 
230  // Reload langs
231  $langcode = getDolGlobalString('MAIN_LANG_DEFAULT', 'auto');
232  if (!empty($user->conf->MAIN_LANG_DEFAULT)) {
233  $langcode = $user->conf->MAIN_LANG_DEFAULT;
234  }
235  if ($langs->getDefaultLang() != $langcode) {
236  $langs->setDefaultLang($langcode);
237  $langs->tab_translate = array();
238  $langs->loadLangs(array('main', 'admin', 'cron', 'dict'));
239  }
240  }
241 
242  if (!verifCond($line->test)) {
243  continue;
244  }
245 
246  //If date_next_jobs is less of current date, execute the program, and store the execution time of the next execution in database
247  $datenextrunok = (empty($line->datenextrun) || (int) $line->datenextrun < $now);
248  $datestartok = (empty($line->datestart) || $line->datestart <= $now);
249  $dateendok = (empty($line->dateend) || $line->dateend >= $now);
250  if ($forcequalified || ($datenextrunok && $datestartok && $dateendok)) {
251  echo " - qualified";
252 
253  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'));
254 
255  $cronjob = new Cronjob($db);
256  $result = $cronjob->fetch($line->id);
257  if ($result < 0) {
258  echo " - Error cronjobid: ".$line->id." cronjob->fetch: ".$cronjob->error."\n";
259  echo "Failed to fetch job ".$line->id."\n";
260  dol_syslog("cron_run_jobs.php::fetch Error ".$cronjob->error, LOG_ERR);
261  exit(1);
262  }
263  // Execute job
264  $result = $cronjob->run_jobs($userlogin);
265  if ($result < 0) {
266  echo " - Error cronjobid: ".$line->id." cronjob->run_job: ".$cronjob->error."\n";
267  echo "At least one job failed. Go on menu Home-Setup-Admin tools to see result for each job.\n";
268  echo "You can also enable module Log if not yet enabled, run again and take a look into dolibarr.log file\n";
269  dol_syslog("cron_run_jobs.php::run_jobs Error ".$cronjob->error, LOG_ERR);
270  $nbofjobslaunchedko++;
271  $resultstring = 'KO';
272  } else {
273  $nbofjobslaunchedok++;
274  $resultstring = 'OK';
275  }
276 
277  echo "Result of run_jobs ".$resultstring." result = ".$result;
278 
279  // We re-program the next execution and stores the last execution time for this job
280  $result = $cronjob->reprogram_jobs($userlogin, $now);
281  if ($result < 0) {
282  echo " - Error cronjobid: ".$line->id." cronjob->reprogram_job: ".$cronjob->error."\n";
283  echo "Enable module Log if not yet enabled, run again and take a look into dolibarr.log file\n";
284  dol_syslog("cron_run_jobs.php::reprogram_jobs Error ".$cronjob->error, LOG_ERR);
285  exit(1);
286  }
287 
288  echo "Job re-scheduled\n";
289  } else {
290  echo " - not qualified (datenextrunok=".($datenextrunok ?: 0).", datestartok=".($datestartok ?: 0).", dateendok=".($dateendok ?: 0).")\n";
291 
292  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'));
293  }
294  }
295 
296  $conf = $savconf;
297 } else {
298  echo "cron_run_jobs.php no qualified job found\n";
299 }
300 
301 $db->close();
302 
303 print "***** ".$script_file." end - ".dol_print_date($now, 'dayhourrfc', 'gmt')." - ".gethostname()." *****\n";
304 
305 if ($nbofjobslaunchedko) {
306  exit(1);
307 }
308 exit(0);
309 
310 
318 function usage($path, $script_file)
319 {
320  print "Usage: ".$script_file." securitykey userlogin|'firstadmin' [cronjobid] [--force]\n";
321  print "The script return 0 when everything worked successfully.\n";
322  print "\n";
323  print "On Linux system, you can have cron jobs ran automatically by adding an entry into cron.\n";
324  print "For example, to run pending tasks each day at 3:30, you can add this line:\n";
325  print "30 3 * * * ".$path.$script_file." securitykey userlogin > ".DOL_DATA_ROOT."/".$script_file.".log\n";
326  print "For example, to run pending tasks every 5mn, you can add this line:\n";
327  print "*/5 * * * * ".$path.$script_file." securitykey userlogin > ".DOL_DATA_ROOT."/".$script_file.".log\n";
328  print "\n";
329  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";
330 }
if($user->socid > 0) if(! $user->hasRight('accounting', 'chartofaccount')) $object
Definition: card.php:58
Cron Job class.
Class to manage Dolibarr users.
Definition: user.class.php:50
if(isModEnabled('invoice') && $user->hasRight('facture', 'lire')) if((isModEnabled('fournisseur') &&!getDolGlobalString('MAIN_USE_NEW_SUPPLIERMOD') && $user->hasRight("fournisseur", "facture", "lire"))||(isModEnabled('supplier_invoice') && $user->hasRight("supplier_invoice", "lire"))) if(isModEnabled('don') && $user->hasRight('don', 'lire')) if(isModEnabled('tax') && $user->hasRight('tax', 'charges', 'lire')) if(isModEnabled('invoice') &&isModEnabled('order') && $user->hasRight("commande", "lire") &&!getDolGlobalString('WORKFLOW_DISABLE_CREATE_INVOICE_FROM_ORDER')) $sql
Social contributions to pay.
Definition: index.php:745
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...
dol_now($mode='auto')
Return date for now.
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 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.