dolibarr  13.0.2
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')) define('NOTOKENRENEWAL', '1'); // Disables token renewal
29 if (!defined('NOREQUIREMENU')) define('NOREQUIREMENU', '1');
30 if (!defined('NOREQUIREHTML')) define('NOREQUIREHTML', '1');
31 if (!defined('NOREQUIREAJAX')) define('NOREQUIREAJAX', '1');
32 if (!defined('NOLOGIN')) define('NOLOGIN', '1');
33 if (!defined('NOSESSION')) define('NOSESSION', '1');
34 
35 $sapi_type = php_sapi_name();
36 $script_file = basename(__FILE__);
37 $path = __DIR__.'/';
38 
39 // Error if Web mode
40 if (substr($sapi_type, 0, 3) == 'cgi') {
41  echo "Error: You are using PHP for CGI. To execute ".$script_file." from command line, you must use PHP for CLI mode.\n";
42  exit(-1);
43 }
44 
45 require_once $path."../../htdocs/master.inc.php";
46 require_once DOL_DOCUMENT_ROOT."/cron/class/cronjob.class.php";
47 require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php';
48 
49 // Check parameters
50 if (!isset($argv[1]) || !$argv[1]) {
51  usage($path, $script_file);
52  exit(-1);
53 }
54 $key = $argv[1];
55 
56 if (!isset($argv[2]) || !$argv[2]) {
57  usage($path, $script_file);
58  exit(-1);
59 }
60 
61 $userlogin = $argv[2];
62 
63 // Global variables
64 $version = DOL_VERSION;
65 $error = 0;
66 
67 // Language Management
68 $langs->loadLangs(array('main', 'admin', 'cron', 'dict'));
69 
70 
71 /*
72  * Main
73  */
74 
75 // current date
76 $now = dol_now();
77 
78 @set_time_limit(0);
79 print "***** ".$script_file." (".$version.") pid=".dol_getmypid()." ***** userlogin=".$userlogin." ***** ".dol_print_date($now, 'dayhourrfc')." *****\n";
80 
81 // Check module cron is activated
82 if (empty($conf->cron->enabled)) {
83  print "Error: module Scheduled jobs (cron) not activated\n";
84  exit(-1);
85 }
86 
87 // Check module cron is activated
88 if (empty($conf->cron->enabled)) {
89  print "Error: module Scheduled jobs (cron) not activated\n";
90  exit(-1);
91 }
92 
93 // Check security key
94 if ($key != $conf->global->CRON_KEY) {
95  print "Error: securitykey is wrong\n";
96  exit(-1);
97 }
98 
99 // If param userlogin is reserved word 'firstadmin'
100 if ($userlogin == 'firstadmin') {
101  $sql = 'SELECT login, entity from '.MAIN_DB_PREFIX.'user WHERE admin = 1 and statut = 1 ORDER BY entity LIMIT 1';
102  $resql = $db->query($sql);
103  if ($resql) {
104  $obj = $db->fetch_object($resql);
105  if ($obj) {
106  $userlogin = $obj->login;
107  echo "First admin user found is login '".$userlogin."', entity ".$obj->entity."\n";
108  }
109  } else dol_print_error($db);
110 }
111 
112 // Check user login
113 $user = new User($db);
114 $result = $user->fetch('', $userlogin);
115 if ($result < 0) {
116  echo "User Error: ".$user->error;
117  dol_syslog("cron_run_jobs.php:: User Error:".$user->error, LOG_ERR);
118  exit(-1);
119 } else {
120  if (empty($user->id)) {
121  echo "User login: ".$userlogin." does not exists";
122  dol_syslog("User login:".$userlogin." does not exists", LOG_ERR);
123  exit(-1);
124  }
125 }
126 $user->getrights();
127 
128 if (isset($argv[3]) || $argv[3]) {
129  $id = $argv[3];
130 }
131 
132 // create a jobs object
133 $object = new Cronjob($db);
134 
135 $filter = array();
136 if (!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 $result = $object->fetch_all('ASC,ASC,ASC', 't.priority,t.entity,t.rowid', 0, 0, 1, $filter, 0);
146 if ($result < 0) {
147  echo "Error: ".$object->error;
148  dol_syslog("cron_run_jobs.php fetch Error ".$object->error, LOG_ERR);
149  exit(-1);
150 }
151 
152 $qualifiedjobs = array();
153 foreach ($object->lines as $val) {
154  if (!verifCond($val->test))
155  {
156  continue;
157  }
158  $qualifiedjobs[] = $val;
159 }
160 
161 // TODO Duplicate code. This sequence of code must be shared with code into public/cron/cron_run_jobs.php php page.
162 
163 $nbofjobs = count($qualifiedjobs);
164 $nbofjobslaunchedok = 0;
165 $nbofjobslaunchedko = 0;
166 
167 if (is_array($qualifiedjobs) && (count($qualifiedjobs) > 0)) {
168  $savconf = dol_clone($conf);
169 
170  // Loop over job
171  foreach ($qualifiedjobs as $line) {
172  dol_syslog("cron_run_jobs.php cronjobid: ".$line->id." priority=".$line->priority." entity=".$line->entity." label=".$line->label, LOG_DEBUG);
173  echo "cron_run_jobs.php cronjobid: ".$line->id." priority=".$line->priority." entity=".$line->entity." label=".$line->label;
174 
175  // Force reload of setup for the current entity
176  if ((empty($line->entity) ? 1 : $line->entity) != $conf->entity)
177  {
178  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);
179  echo " -> we change entity so we reload mysoc, langs, user and conf";
180 
181  $conf->entity = (empty($line->entity) ? 1 : $line->entity);
182  $conf->setValues($db); // This make also the $mc->setValues($conf); that reload $mc->sharings
183  $mysoc->setMysoc($conf);
184 
185  // Force recheck that user is ok for the entity to process and reload permission for entity
186  if ($conf->entity != $user->entity && $user->entity != 0)
187  {
188  $result = $user->fetch('', $userlogin, '', 0, $conf->entity);
189  if ($result < 0)
190  {
191  echo "\nUser Error: ".$user->error."\n";
192  dol_syslog("cron_run_jobs.php:: User Error:".$user->error, LOG_ERR);
193  exit(-1);
194  } else {
195  if ($result == 0)
196  {
197  echo "\nUser login: ".$userlogin." does not exists for entity ".$conf->entity."\n";
198  dol_syslog("User login:".$userlogin." does not exists", LOG_ERR);
199  exit(-1);
200  }
201  }
202  $user->getrights();
203  }
204 
205  // Reload langs
206  $langcode = (empty($conf->global->MAIN_LANG_DEFAULT) ? 'auto' : $conf->global->MAIN_LANG_DEFAULT);
207  if (!empty($user->conf->MAIN_LANG_DEFAULT)) $langcode = $user->conf->MAIN_LANG_DEFAULT;
208  if ($langs->getDefaultLang() != $langcode) $langs->setDefaultLang($langcode);
209  }
210 
211  //If date_next_jobs is less of current date, execute the program, and store the execution time of the next execution in database
212  if (($line->datenextrun < $now) && (empty($line->datestart) || $line->datestart <= $now) && (empty($line->dateend) || $line->dateend >= $now)) {
213  echo " - qualified";
214 
215  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'));
216 
217  $cronjob = new Cronjob($db);
218  $result = $cronjob->fetch($line->id);
219  if ($result < 0) {
220  echo "Error cronjobid: ".$line->id." cronjob->fetch: ".$cronjob->error."\n";
221  echo "Failed to fetch job ".$line->id."\n";
222  dol_syslog("cron_run_jobs.php::fetch Error ".$cronjob->error, LOG_ERR);
223  exit(-1);
224  }
225  // Execute job
226  $result = $cronjob->run_jobs($userlogin);
227  if ($result < 0) {
228  echo "Error cronjobid: ".$line->id." cronjob->run_job: ".$cronjob->error."\n";
229  echo "At least one job failed. Go on menu Home-Setup-Admin tools to see result for each job.\n";
230  echo "You can also enable module Log if not yet enabled, run again and take a look into dolibarr.log file\n";
231  dol_syslog("cron_run_jobs.php::run_jobs Error ".$cronjob->error, LOG_ERR);
232  $nbofjobslaunchedko++;
233  $resultstring = 'KO';
234  } else {
235  $nbofjobslaunchedok++;
236  $resultstring = 'OK';
237  }
238 
239  echo " - run_jobs ".$resultstring." result = ".$result;
240 
241  // We re-program the next execution and stores the last execution time for this job
242  $result = $cronjob->reprogram_jobs($userlogin, $now);
243  if ($result < 0) {
244  echo "Error cronjobid: ".$line->id." cronjob->reprogram_job: ".$cronjob->error."\n";
245  echo "Enable module Log if not yet enabled, run again and take a look into dolibarr.log file\n";
246  dol_syslog("cron_run_jobs.php::reprogram_jobs Error ".$cronjob->error, LOG_ERR);
247  exit(-1);
248  }
249 
250  echo " - reprogrammed\n";
251  } else {
252  echo " - not qualified\n";
253 
254  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'));
255  }
256  }
257 
258  $conf = $savconf;
259 } else {
260  echo "cron_run_jobs.php no qualified job found\n";
261 }
262 
263 $db->close();
264 
265 if ($nbofjobslaunchedko)
266  exit(1);
267 exit(0);
268 
276 function usage($path, $script_file)
277 {
278  print "Usage: ".$script_file." securitykey userlogin|'firstadmin' [cronjobid]\n";
279  print "The script return 0 when everything worked successfully.\n";
280  print "\n";
281  print "On Linux system, you can have cron jobs ran automatically by adding an entry into cron.\n";
282  print "For example, to run pending tasks each day at 3:30, you can add this line:\n";
283  print "30 3 * * * ".$path.$script_file." securitykey userlogin > ".DOL_DATA_ROOT."/".$script_file.".log\n";
284  print "For example, to run pending tasks every 5mn, you can add this line:\n";
285  print "*/5 * * * * ".$path.$script_file." securitykey userlogin > ".DOL_DATA_ROOT."/".$script_file.".log\n";
286 }
verifCond($strRights)
Verify if condition in string is ok or not.
dol_now($mode= 'auto')
Return date for now.
Class to manage Dolibarr users.
Definition: user.class.php:44
dol_clone($object, $native=0)
Create a clone of instance of object (new instance with same value for properties) With native = 0: P...
dol_getmypid()
Return getmypid() or random PID when function is disabled Some web hosts disable this php function fo...
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename= '', $restricttologhandler= '', $logcontext=null)
Write log message into outputs.
print
Draft customers invoices.
Definition: index.php:89
dol_print_date($time, $format= '', $tzoutput= 'auto', $outputlangs= '', $encodetooutput=false)
Output date in a string format according to outputlangs (or langs if not defined).
if(!empty($conf->facture->enabled)&&$user->rights->facture->lire) if((!empty($conf->fournisseur->enabled)&&empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD)||!empty($conf->supplier_invoice->enabled))&&$user->rights->fournisseur->facture->lire) if(!empty($conf->don->enabled)&&$user->rights->don->lire) if(!empty($conf->tax->enabled)&&$user->rights->tax->charges->lire) if(!empty($conf->facture->enabled)&&!empty($conf->commande->enabled)&&$user->rights->commande->lire &&empty($conf->global->WORKFLOW_DISABLE_CREATE_INVOICE_FROM_ORDER)) if(!empty($conf->facture->enabled)&&$user->rights->facture->lire) if((!empty($conf->fournisseur->enabled)&&empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD)||!empty($conf->supplier_invoice->enabled))&&$user->rights->fournisseur->facture->lire) $resql
Social contributions to pay.
Definition: index.php:1232
dol_print_error($db= '', $error= '', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
Cron Job class.
if(!defined('CSRFCHECK_WITH_TOKEN')) define('CSRFCHECK_WITH_TOKEN'
Draft customers invoices.
usage($path, $script_file)
script cron usage