cron_run_jobs.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  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. /**
  22. * \file scripts/cron/cron_run_jobs.php
  23. * \ingroup cron
  24. * \brief Execute pendings jobs from command line
  25. */
  26. if (!defined('NOTOKENRENEWAL')) {
  27. define('NOTOKENRENEWAL', '1'); // Disables token renewal
  28. }
  29. if (!defined('NOREQUIREMENU')) {
  30. define('NOREQUIREMENU', '1');
  31. }
  32. if (!defined('NOREQUIREHTML')) {
  33. define('NOREQUIREHTML', '1');
  34. }
  35. if (!defined('NOREQUIREAJAX')) {
  36. define('NOREQUIREAJAX', '1');
  37. }
  38. if (!defined('NOLOGIN')) {
  39. define('NOLOGIN', '1');
  40. }
  41. if (!defined('NOSESSION')) {
  42. define('NOSESSION', '1');
  43. }
  44. // So log file will have a suffix
  45. if (!defined('USESUFFIXINLOG')) {
  46. define('USESUFFIXINLOG', '_cron');
  47. }
  48. $sapi_type = php_sapi_name();
  49. $script_file = basename(__FILE__);
  50. $path = __DIR__.'/';
  51. // Error if Web mode
  52. if (substr($sapi_type, 0, 3) == 'cgi') {
  53. echo "Error: You are using PHP for CGI. To execute ".$script_file." from command line, you must use PHP for CLI mode.\n";
  54. exit(-1);
  55. }
  56. require_once $path."../../htdocs/master.inc.php";
  57. require_once DOL_DOCUMENT_ROOT."/cron/class/cronjob.class.php";
  58. require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php';
  59. // Check parameters
  60. if (!isset($argv[1]) || !$argv[1]) {
  61. usage($path, $script_file);
  62. exit(-1);
  63. }
  64. $key = $argv[1];
  65. if (!isset($argv[2]) || !$argv[2]) {
  66. usage($path, $script_file);
  67. exit(-1);
  68. }
  69. $userlogin = $argv[2];
  70. // Global variables
  71. $version = DOL_VERSION;
  72. $error = 0;
  73. $hookmanager->initHooks(array('cli'));
  74. /*
  75. * Main
  76. */
  77. // current date
  78. $now = dol_now();
  79. @set_time_limit(0);
  80. print "***** ".$script_file." (".$version.") pid=".dol_getmypid()." - userlogin=".$userlogin." - ".dol_print_date($now, 'dayhourrfc')." - ".gethostname()." *****\n";
  81. // Check module cron is activated
  82. if (!isModEnabled('cron')) {
  83. print "Error: module Scheduled jobs (cron) not activated\n";
  84. exit(-1);
  85. }
  86. // Check security key
  87. if ($key != getDolGlobalString('CRON_KEY')) {
  88. print "Error: securitykey is wrong\n";
  89. exit(-1);
  90. }
  91. if (!empty($dolibarr_main_db_readonly)) {
  92. print "Error: instance in read-only mode\n";
  93. exit(-1);
  94. }
  95. // If param userlogin is reserved word 'firstadmin'
  96. if ($userlogin == 'firstadmin') {
  97. $sql = 'SELECT login, entity from '.MAIN_DB_PREFIX.'user WHERE admin = 1 and statut = 1 ORDER BY entity LIMIT 1';
  98. $resql = $db->query($sql);
  99. if ($resql) {
  100. $obj = $db->fetch_object($resql);
  101. if ($obj) {
  102. $userlogin = $obj->login;
  103. echo "First admin user found is login '".$userlogin."', entity ".$obj->entity."\n";
  104. }
  105. } else {
  106. dol_print_error($db);
  107. }
  108. }
  109. // Check user login
  110. $user = new User($db);
  111. $result = $user->fetch('', $userlogin, '', 1);
  112. if ($result < 0) {
  113. echo "User Error: ".$user->error;
  114. dol_syslog("cron_run_jobs.php:: User Error:".$user->error, LOG_ERR);
  115. exit(-1);
  116. } else {
  117. if (empty($user->id)) {
  118. echo "User login: ".$userlogin." does not exists\n";
  119. dol_syslog("User login:".$userlogin." does not exists", LOG_ERR);
  120. exit(-1);
  121. }
  122. }
  123. // Reload langs
  124. $langcode = getDolGlobalString('MAIN_LANG_DEFAULT', 'auto');
  125. if (!empty($user->conf->MAIN_LANG_DEFAULT)) {
  126. $langcode = $user->conf->MAIN_LANG_DEFAULT;
  127. }
  128. if ($langs->getDefaultLang() != $langcode) {
  129. $langs->setDefaultLang($langcode);
  130. $langs->tab_translate = array();
  131. }
  132. // Language Management
  133. $langs->loadLangs(array('main', 'admin', 'cron', 'dict'));
  134. $user->getrights();
  135. if (isset($argv[3]) && $argv[3]) {
  136. $id = $argv[3];
  137. }
  138. $forcequalified = 0;
  139. if (isset($argv[4]) && $argv[4] == '--force') {
  140. $forcequalified = 1;
  141. }
  142. // create a jobs object
  143. $object = new Cronjob($db);
  144. $filter = array();
  145. if (!empty($id)) {
  146. if (!is_numeric($id)) {
  147. echo "Error: Bad value for parameter job id\n";
  148. dol_syslog("cron_run_jobs.php Bad value for parameter job id", LOG_WARNING);
  149. exit();
  150. }
  151. $filter['t.rowid'] = $id;
  152. }
  153. $result = $object->fetchAll('ASC,ASC,ASC', 't.priority,t.entity,t.rowid', 0, 0, 1, $filter, 0);
  154. if ($result < 0) {
  155. echo "Error: ".$object->error;
  156. dol_syslog("cron_run_jobs.php fetch Error ".$object->error, LOG_ERR);
  157. exit(-1);
  158. }
  159. // TODO Duplicate code. This sequence of code must be shared with code into public/cron/cron_run_jobs.php php page.
  160. $nbofjobs = count($object->lines);
  161. $nbofjobslaunchedok = 0;
  162. $nbofjobslaunchedko = 0;
  163. if (is_array($object->lines) && (count($object->lines) > 0)) {
  164. $savconf = dol_clone($conf);
  165. // Loop over job
  166. foreach ($object->lines as $line) {
  167. dol_syslog("cron_run_jobs.php cronjobid: ".$line->id." priority=".$line->priority." entity=".$line->entity." label=".$line->label, LOG_DEBUG);
  168. echo "cron_run_jobs.php cronjobid: ".$line->id." priority=".$line->priority." entity=".$line->entity." label=".$line->label;
  169. // Force reload of setup for the current entity
  170. if ((empty($line->entity) ? 1 : $line->entity) != $conf->entity) {
  171. 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);
  172. echo " -> we change entity so we reload mysoc, langs, user and conf";
  173. $conf->entity = (empty($line->entity) ? 1 : $line->entity);
  174. $conf->setValues($db); // This make also the $mc->setValues($conf); that reload $mc->sharings
  175. $mysoc->setMysoc($conf);
  176. // Force recheck that user is ok for the entity to process and reload permission for entity
  177. if ($conf->entity != $user->entity) {
  178. $result = $user->fetch('', $userlogin, '', 1);
  179. if ($result < 0) {
  180. echo "\nUser Error: ".$user->error."\n";
  181. dol_syslog("cron_run_jobs.php: User Error:".$user->error, LOG_ERR);
  182. exit(-1);
  183. } else {
  184. if ($result == 0) {
  185. echo "\nUser login: ".$userlogin." does not exist for entity ".$conf->entity."\n";
  186. dol_syslog("cron_run_jobs.php: User login: ".$userlogin." does not exist", LOG_ERR);
  187. exit(-1);
  188. }
  189. }
  190. $user->getrights('', 1); // We force rights reload to have the correct permissions for user in the entity we just switched in
  191. }
  192. // Reload langs
  193. $langcode = getDolGlobalString('MAIN_LANG_DEFAULT', 'auto');
  194. if (!empty($user->conf->MAIN_LANG_DEFAULT)) {
  195. $langcode = $user->conf->MAIN_LANG_DEFAULT;
  196. }
  197. if ($langs->getDefaultLang() != $langcode) {
  198. $langs->setDefaultLang($langcode);
  199. $langs->tab_translate = array();
  200. $langs->loadLangs(array('main', 'admin', 'cron', 'dict'));
  201. }
  202. }
  203. if (!verifCond($line->test)) {
  204. continue;
  205. }
  206. //If date_next_jobs is less of current date, execute the program, and store the execution time of the next execution in database
  207. if ($forcequalified || (($line->datenextrun < $now) && (empty($line->datestart) || $line->datestart <= $now) && (empty($line->dateend) || $line->dateend >= $now))) {
  208. echo " - qualified";
  209. 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'));
  210. $cronjob = new Cronjob($db);
  211. $result = $cronjob->fetch($line->id);
  212. if ($result < 0) {
  213. echo " - Error cronjobid: ".$line->id." cronjob->fetch: ".$cronjob->error."\n";
  214. echo "Failed to fetch job ".$line->id."\n";
  215. dol_syslog("cron_run_jobs.php::fetch Error ".$cronjob->error, LOG_ERR);
  216. exit(-1);
  217. }
  218. // Execute job
  219. $result = $cronjob->run_jobs($userlogin);
  220. if ($result < 0) {
  221. echo " - Error cronjobid: ".$line->id." cronjob->run_job: ".$cronjob->error."\n";
  222. echo "At least one job failed. Go on menu Home-Setup-Admin tools to see result for each job.\n";
  223. echo "You can also enable module Log if not yet enabled, run again and take a look into dolibarr.log file\n";
  224. dol_syslog("cron_run_jobs.php::run_jobs Error ".$cronjob->error, LOG_ERR);
  225. $nbofjobslaunchedko++;
  226. $resultstring = 'KO';
  227. } else {
  228. $nbofjobslaunchedok++;
  229. $resultstring = 'OK';
  230. }
  231. echo " - run_jobs ".$resultstring." result = ".$result;
  232. // We re-program the next execution and stores the last execution time for this job
  233. $result = $cronjob->reprogram_jobs($userlogin, $now);
  234. if ($result < 0) {
  235. echo " - Error cronjobid: ".$line->id." cronjob->reprogram_job: ".$cronjob->error."\n";
  236. echo "Enable module Log if not yet enabled, run again and take a look into dolibarr.log file\n";
  237. dol_syslog("cron_run_jobs.php::reprogram_jobs Error ".$cronjob->error, LOG_ERR);
  238. exit(-1);
  239. }
  240. echo " - reprogrammed\n";
  241. } else {
  242. echo " - not qualified\n";
  243. 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'));
  244. }
  245. }
  246. $conf = $savconf;
  247. } else {
  248. echo "cron_run_jobs.php no qualified job found\n";
  249. }
  250. $db->close();
  251. if ($nbofjobslaunchedko) {
  252. exit(1);
  253. }
  254. exit(0);
  255. /**
  256. * script cron usage
  257. *
  258. * @param string $path Path
  259. * @param string $script_file Filename
  260. * @return void
  261. */
  262. function usage($path, $script_file)
  263. {
  264. print "Usage: ".$script_file." securitykey userlogin|'firstadmin' [cronjobid] [--force]\n";
  265. print "The script return 0 when everything worked successfully.\n";
  266. print "\n";
  267. print "On Linux system, you can have cron jobs ran automatically by adding an entry into cron.\n";
  268. print "For example, to run pending tasks each day at 3:30, you can add this line:\n";
  269. print "30 3 * * * ".$path.$script_file." securitykey userlogin > ".DOL_DATA_ROOT."/".$script_file.".log\n";
  270. print "For example, to run pending tasks every 5mn, you can add this line:\n";
  271. print "*/5 * * * * ".$path.$script_file." securitykey userlogin > ".DOL_DATA_ROOT."/".$script_file.".log\n";
  272. print "\n";
  273. 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";
  274. }