dolibarr  16.0.5
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')." *****\n";
96 
97 // Check module cron is activated
98 if (empty($conf->cron->enabled)) {
99  print "Error: module Scheduled jobs (cron) not activated\n";
100  exit(-1);
101 }
102 
103 // Check module cron is activated
104 if (empty($conf->cron->enabled)) {
105  print "Error: module Scheduled jobs (cron) not activated\n";
106  exit(-1);
107 }
108 
109 // Check security key
110 if ($key != $conf->global->CRON_KEY) {
111  print "Error: securitykey is wrong\n";
112  exit(-1);
113 }
114 
115 if (!empty($dolibarr_main_db_readonly)) {
116  print "Error: instance in read-only mode\n";
117  exit(-1);
118 }
119 
120 // If param userlogin is reserved word 'firstadmin'
121 if ($userlogin == 'firstadmin') {
122  $sql = 'SELECT login, entity from '.MAIN_DB_PREFIX.'user WHERE admin = 1 and statut = 1 ORDER BY entity LIMIT 1';
123  $resql = $db->query($sql);
124  if ($resql) {
125  $obj = $db->fetch_object($resql);
126  if ($obj) {
127  $userlogin = $obj->login;
128  echo "First admin user found is login '".$userlogin."', entity ".$obj->entity."\n";
129  }
130  } else {
131  dol_print_error($db);
132  }
133 }
134 
135 // Check user login
136 $user = new User($db);
137 $result = $user->fetch('', $userlogin, '', 1);
138 if ($result < 0) {
139  echo "User Error: ".$user->error;
140  dol_syslog("cron_run_jobs.php:: User Error:".$user->error, LOG_ERR);
141  exit(-1);
142 } else {
143  if (empty($user->id)) {
144  echo "User login: ".$userlogin." does not exists";
145  dol_syslog("User login:".$userlogin." does not exists", LOG_ERR);
146  exit(-1);
147  }
148 }
149 
150 // Reload langs
151 $langcode = (empty($conf->global->MAIN_LANG_DEFAULT) ? 'auto' : $conf->global->MAIN_LANG_DEFAULT);
152 if (!empty($user->conf->MAIN_LANG_DEFAULT)) {
153  $langcode = $user->conf->MAIN_LANG_DEFAULT;
154 }
155 if ($langs->getDefaultLang() != $langcode) {
156  $langs->setDefaultLang($langcode);
157  $langs->tab_translate = array();
158 }
159 // Language Management
160 $langs->loadLangs(array('main', 'admin', 'cron', 'dict'));
161 
162 $user->getrights();
163 
164 if (isset($argv[3]) && $argv[3]) {
165  $id = $argv[3];
166 }
167 
168 // create a jobs object
169 $object = new Cronjob($db);
170 
171 $filter = array();
172 if (!empty($id)) {
173  if (!is_numeric($id)) {
174  echo "Error: Bad value for parameter job id";
175  dol_syslog("cron_run_jobs.php Bad value for parameter job id", LOG_WARNING);
176  exit();
177  }
178  $filter['t.rowid'] = $id;
179 }
180 
181 $result = $object->fetchAll('ASC,ASC,ASC', 't.priority,t.entity,t.rowid', 0, 0, 1, $filter, 0);
182 if ($result < 0) {
183  echo "Error: ".$object->error;
184  dol_syslog("cron_run_jobs.php fetch Error ".$object->error, LOG_ERR);
185  exit(-1);
186 }
187 
188 // TODO Duplicate code. This sequence of code must be shared with code into public/cron/cron_run_jobs.php php page.
189 
190 $nbofjobs = count($object->lines);
191 $nbofjobslaunchedok = 0;
192 $nbofjobslaunchedko = 0;
193 
194 if (is_array($object->lines) && (count($object->lines) > 0)) {
195  $savconf = dol_clone($conf);
196 
197  // Loop over job
198  foreach ($object->lines as $line) {
199  dol_syslog("cron_run_jobs.php cronjobid: ".$line->id." priority=".$line->priority." entity=".$line->entity." label=".$line->label, LOG_DEBUG);
200  echo "cron_run_jobs.php cronjobid: ".$line->id." priority=".$line->priority." entity=".$line->entity." label=".$line->label;
201 
202  // Force reload of setup for the current entity
203  if ((empty($line->entity) ? 1 : $line->entity) != $conf->entity) {
204  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);
205  echo " -> we change entity so we reload mysoc, langs, user and conf";
206 
207  $conf->entity = (empty($line->entity) ? 1 : $line->entity);
208  $conf->setValues($db); // This make also the $mc->setValues($conf); that reload $mc->sharings
209  $mysoc->setMysoc($conf);
210 
211  // Force recheck that user is ok for the entity to process and reload permission for entity
212  if ($conf->entity != $user->entity) {
213  $result = $user->fetch('', $userlogin, '', 1);
214  if ($result < 0) {
215  echo "\nUser Error: ".$user->error."\n";
216  dol_syslog("cron_run_jobs.php:: User Error:".$user->error, LOG_ERR);
217  exit(-1);
218  } else {
219  if ($result == 0) {
220  echo "\nUser login: ".$userlogin." does not exists for entity ".$conf->entity."\n";
221  dol_syslog("User login:".$userlogin." does not exists", LOG_ERR);
222  exit(-1);
223  }
224  }
225  $user->getrights();
226  }
227 
228  // Reload langs
229  $langcode = (empty($conf->global->MAIN_LANG_DEFAULT) ? 'auto' : $conf->global->MAIN_LANG_DEFAULT);
230  if (!empty($user->conf->MAIN_LANG_DEFAULT)) {
231  $langcode = $user->conf->MAIN_LANG_DEFAULT;
232  }
233  if ($langs->getDefaultLang() != $langcode) {
234  $langs->setDefaultLang($langcode);
235  $langs->tab_translate = array();
236  $langs->loadLangs(array('main', 'admin', 'cron', 'dict'));
237  }
238  }
239 
240  if (!verifCond($line->test)) {
241  continue;
242  }
243 
244  //If date_next_jobs is less of current date, execute the program, and store the execution time of the next execution in database
245  if (($line->datenextrun < $now) && (empty($line->datestart) || $line->datestart <= $now) && (empty($line->dateend) || $line->dateend >= $now)) {
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(-1);
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 " - 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 " - reprogrammed\n";
284  } else {
285  echo " - not qualified\n";
286 
287  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'));
288  }
289  }
290 
291  $conf = $savconf;
292 } else {
293  echo "cron_run_jobs.php no qualified job found\n";
294 }
295 
296 $db->close();
297 
298 if ($nbofjobslaunchedko) {
299  exit(1);
300 }
301 exit(0);
302 
310 function usage($path, $script_file)
311 {
312  print "Usage: ".$script_file." securitykey userlogin|'firstadmin' [cronjobid]\n";
313  print "The script return 0 when everything worked successfully.\n";
314  print "\n";
315  print "On Linux system, you can have cron jobs ran automatically by adding an entry into cron.\n";
316  print "For example, to run pending tasks each day at 3:30, you can add this line:\n";
317  print "30 3 * * * ".$path.$script_file." securitykey userlogin > ".DOL_DATA_ROOT."/".$script_file.".log\n";
318  print "For example, to run pending tasks every 5mn, you can add this line:\n";
319  print "*/5 * * * * ".$path.$script_file." securitykey userlogin > ".DOL_DATA_ROOT."/".$script_file.".log\n";
320 }
Cronjob
Cron Job class.
Definition: cronjob.class.php:31
dol_print_error
dol_print_error($db='', $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
Definition: functions.lib.php:4844
dol_getmypid
dol_getmypid()
Return getmypid() or random PID when function is disabled Some web hosts disable this php function fo...
Definition: functions.lib.php:9393
verifCond
verifCond($strToEvaluate)
Verify if condition in string is ok or not.
Definition: functions.lib.php:8582
dol_clone
dol_clone($object, $native=0)
Create a clone of instance of object (new instance with same value for each properties) With native =...
Definition: functions.lib.php:1158
dol_print_date
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs='', $encodetooutput=false)
Output date in a string format according to outputlangs (or langs if not defined).
Definition: functions.lib.php:2514
dol_syslog
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
Definition: functions.lib.php:1603
usage
usage($path, $script_file)
script cron usage
Definition: cron_run_jobs.php:310
User
Class to manage Dolibarr users.
Definition: user.class.php:44
dol_now
dol_now($mode='auto')
Return date for now.
Definition: functions.lib.php:2845
$resql
if(isModEnabled('facture') &&!empty($user->rights->facture->lire)) if((isModEnabled('fournisseur') &&empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) && $user->rights->fournisseur->facture->lire)||(isModEnabled('supplier_invoice') && $user->rights->supplier_invoice->lire)) if(isModEnabled('don') &&!empty($user->rights->don->lire)) if(isModEnabled('tax') &&!empty($user->rights->tax->charges->lire)) if(isModEnabled('facture') &&isModEnabled('commande') && $user->rights->commande->lire &&empty($conf->global->WORKFLOW_DISABLE_CREATE_INVOICE_FROM_ORDER)) $resql
Social contributions to pay.
Definition: index.php:742