elysia_cron.module 56 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680
  1. <?php
  2. // $Id: cron.php,v 1.1 2008/06/25 15:38:55 gotheric Exp $
  3. /**
  4. * ELYSIA_CRON
  5. * by Eric Berdondini (gotheric)
  6. * <eric@void.it>
  7. *
  8. * Features:
  9. * - crontab-like scheduling configuration of each job.
  10. * - grouping of jobs in channels (parallel lines of execution).
  11. * - you can disable all jobs, an entire channel or a single job via configuration.
  12. * - time statistics of each job and of the whole channel.
  13. * - modules can define extra cron tasks, each one with own default cron-rules
  14. * (site administrators can override them by configuration).
  15. * - administrators can define custom jobs (call to functions with parameters)
  16. * - protection from external cron calling by cron_key or allowed host list.
  17. * - ensure all shutdown hook functions launched by cron jobs are launched inside
  18. * cron protection (ex: search_cron() will launch search_update_totals() in a
  19. * shutdown hook).
  20. *
  21. * This file is cross-version (the same for D5, D6, D7).
  22. * (Needs elysia_drupalconv.php)
  23. *
  24. */
  25. require_once('elysia_drupalconv.php');
  26. require_once('elysia_cron_update.php');
  27. require_once('elysia_cron_scheduler.inc');
  28. require_once('elysia_cron.admin.inc');
  29. if (EC_DRUPAL_VERSION >= 6) {
  30. require_once('elysia_cron.ctools.inc');
  31. }
  32. $GLOBALS['elysia_cron_default_rules'] = array(
  33. '*/15 * * * *' => 'Every 15 minutes',
  34. '*/30 * * * *' => 'Every 30 minutes',
  35. '0 * * * *' => 'Every hour',
  36. '0 */6 * * *' => 'Every 6 hours',
  37. '4 0 * * *' => 'Once a day',
  38. '4 0 * * 0' => 'Once a week',
  39. '4 0 1 * *' => 'Once a month',
  40. );
  41. function elysia_cron_version() {
  42. return 20111020;
  43. }
  44. /*******************************************************************************
  45. * DRUPAL HOOKS
  46. ******************************************************************************/
  47. function elysia_cron_menu($_dcr_maycache = true) {
  48. $items = array();
  49. $items['admin/config/system/cron'] = array(
  50. 'title' => _dcf_t('Cron Settings'),
  51. 'description' => _dcf_t('View and manage cron table'),
  52. 'page callback' => 'elysia_cron_admin_page',
  53. 'access arguments' => array('administer elysia_cron'),
  54. );
  55. $items['admin/config/system/cron/status'] = array(
  56. 'type' => MENU_DEFAULT_LOCAL_TASK,
  57. 'title' => _dcf_t('Status'),
  58. 'weight' => 1,
  59. );
  60. $items['admin/config/system/cron/settings'] = array(
  61. 'type' => MENU_LOCAL_TASK,
  62. 'title' => _dcf_t('Settings'),
  63. 'page callback' => 'drupal_get_form',
  64. 'page arguments' => array('elysia_cron_settings_form'),
  65. 'access arguments' => array('administer elysia_cron'),
  66. 'weight' => 2,
  67. );
  68. $items['admin/config/system/cron/maintenance'] = array(
  69. 'type' => MENU_LOCAL_TASK,
  70. 'title' => _dcf_t('Maintenance'),
  71. 'page callback' => 'elysia_cron_maintenance_page',
  72. 'access arguments' => array('administer elysia_cron'),
  73. 'weight' => 3,
  74. );
  75. $items['admin/config/system/cron/execute'] = array(
  76. 'type' => MENU_CALLBACK,
  77. 'page callback' => 'elysia_cron_execute_page',
  78. 'access arguments' => array('administer elysia_cron'),
  79. );
  80. $items['admin/build/cron/ping'] = array(
  81. 'type' => MENU_CALLBACK,
  82. 'page callback' => 'elysia_cron_ping_page',
  83. 'access callback' => TRUE,
  84. );
  85. return _dcf_hook_menu($items, $_dcr_maycache);
  86. }
  87. if (EC_DRUPAL_VERSION >= 7) {
  88. // Override standard cron page
  89. function elysia_cron_menu_alter(&$items) {
  90. $items['admin/config/system/cron'] = array(
  91. 'title' => _dcf_t('Cron Settings'),
  92. 'description' => 'View and manage cron table',
  93. 'page callback' => 'elysia_cron_admin_page',
  94. 'access arguments' => array('administer elysia_cron'),
  95. );
  96. }
  97. }
  98. function elysia_cron_perm() { // For D5-D6
  99. return array('administer elysia_cron');
  100. }
  101. function elysia_cron_permission() { // For D7
  102. return array(
  103. 'administer elysia_cron' => array('title' => t('Administer elysia cron'), 'description' => t('Perform changes to cron jobs timings, disable cron or single jobs and access cron execution statistics')),
  104. );
  105. }
  106. function elysia_cron_boot() {
  107. if (!_dcf_hook_boot('elysia_cron')) {
  108. return;
  109. }
  110. drupal_disable_standard_cron();
  111. }
  112. function elysia_cron_init() {
  113. if (!_dcf_hook_init('elysia_cron')) {
  114. return;
  115. }
  116. }
  117. function elysia_cron_exit() {
  118. global $elysia_cron_exit_phase;
  119. $elysia_cron_exit_phase = true;
  120. }
  121. /**
  122. * Hook cron is invoked only by standard drupal cron.
  123. * It's used to replace drupal cron.
  124. */
  125. function elysia_cron_cron() {
  126. global $elysia_cron_exit_phase, $elysia_cron_drush;
  127. // If invoked "core-cron" via drush i'll redirect to elysia-cron handler
  128. if (function_exists('elysia_cron_drush_detect') && elysia_cron_drush_detect()) {
  129. elysia_cron_drush_invoke(true);
  130. }
  131. // First cron run is executed in standard drupal way. This is to enable the use of install profiles
  132. if (variable_get('cron_last', 0) == 0) {
  133. return;
  134. }
  135. // If the path is 'admin/*', or if the user is not anonymous, this is a manual cron run (probably by admin/logs/status), but not if we are in the exit phase (= this a "poormanscron" run)
  136. $manual_run = empty($elysia_cron_exit_phase) && ((arg(0) == 'admin') || !empty($GLOBALS['user']->uid));
  137. $result = elysia_cron_run($manual_run);
  138. drupal_clean_after_cron_run();
  139. if ($manual_run) {
  140. if ($result) {
  141. elysia_cron_message('Cron ran successfully');
  142. }
  143. else {
  144. elysia_cron_message('Cron run failed, disabled or nothing to do');
  145. }
  146. // In manual execution it's better to set cron_last variable in standard way (so the user sees the execution time updates). This invalidates variable cache, but it's a manual execution, it should be not a great performance problem.
  147. if (empty($elysia_cron_drush))
  148. variable_set('cron_last', time());
  149. drupal_goto(_dcf_internal_path('admin/reports/status'));
  150. }
  151. // If we are in "poormanscron" mode it's better to force setting of cron_last. This invalidates variable cache, but is needed for right execution check.
  152. // @see system_run_automated_cron() in system.module
  153. if (!empty($elysia_cron_exit_phase)) {
  154. variable_set('cron_last', time());
  155. }
  156. exit();
  157. }
  158. /**
  159. * I use help section for admin/build/modules page to check if elysia_cron
  160. * is the module with the smallest weight.
  161. * If it's not i'll set it and print a message
  162. */
  163. function elysia_cron_help($section, $arg = false) {
  164. if ($section == _dcf_internal_path('admin/modules')) {
  165. $min = drupal_module_get_min_weight('elysia_cron');
  166. $weight = drupal_module_get_weight('elysia_cron');
  167. if ($min <= $weight) {
  168. elysia_cron_message('Elysia cron module is not the module with the smallest weight (and it must be). Updating weight...');
  169. drupal_module_set_weight('elysia_cron', $min - 1);
  170. }
  171. }
  172. }
  173. /*******************************************************************************
  174. * SETTINGS API
  175. *
  176. * WARN: DB and Variable name for "channel" is "context"!
  177. ******************************************************************************/
  178. // Variables managed by _ec_variable method, because are setted during cron execution handling (with standard variable_set this will invalidate variable cache in EVERY cron clock)
  179. $GLOBALS['_ec_variables_allowed'] = array(
  180. 'elysia_cron_version', // Just for compatibility purpose during elysia_cron_update phase
  181. 'elysia_cron_semaphore',
  182. 'elysia_cron_last_run',
  183. 'elysia_cron_last_context',
  184. 'cron_semaphore',
  185. 'cron_last',
  186. );
  187. $GLOBALS['_ec_columns'] = array(
  188. 'name', ' disable', ' rule', ' weight', ' context', ' running', ' last_run', ' last_aborted', ' abort_count', ' last_abort_function', ' last_execution_time', ' execution_count', ' avg_execution_time', ' max_execution_time', ' last_shutdown_time'
  189. );
  190. function _ec_variable_init() {
  191. global $_ec_variables, $_ec_variables_allowed;
  192. $_ec_variables = array();
  193. if (EC_DRUPAL_VERSION >= 7) {
  194. $_ec_variables = array_map('unserialize', db_query("SELECT name, value FROM {variable} where name like '" . implode("' or name like '", $_ec_variables_allowed) . "'")->fetchAllKeyed());
  195. }
  196. else {
  197. $result = db_query("select * from {variable} where name like '" . implode("' or name like '", $_ec_variables_allowed) . "'");
  198. while ($variable = db_fetch_object($result)) {
  199. $_ec_variables[$variable->name] = unserialize($variable->value);
  200. }
  201. }
  202. }
  203. /**
  204. * A substitute for variable_get to avoid cache management
  205. * Use ONLY for variables setted during cron execution: elysia_cron_semaphore, elysia_cron_last_run, elysia_cron_last_context, cron_semaphore, cron_last
  206. * WARN_UPGRADE
  207. */
  208. function _ec_variable_get($name, $default) {
  209. global $_ec_variables, $_ec_variables_allowed;
  210. if (!in_array($name, $_ec_variables_allowed)) {
  211. elysia_cron_error('Wrong variable passed to _ec_variable_get: !var', array('!var' => $name), true);
  212. return variable_get($name, $default);
  213. }
  214. if (!is_array($_ec_variables)) {
  215. _ec_variable_init();
  216. }
  217. // If there is a $GLOBALS['original_conf'] = $conf; at the end of settings.php i consider it.
  218. global $original_conf;
  219. if (isset($original_conf[$name])) {
  220. return $original_conf[$name];
  221. }
  222. if (isset($_ec_variables[$name])) {
  223. return $_ec_variables[$name];
  224. }
  225. return $default;
  226. }
  227. /**
  228. * A substitute for variable_set to avoid cache management
  229. * Use ONLY for variables setted during cron execution: elysia_cron_semaphore, elysia_cron_last_run, elysia_cron_last_context, cron_semaphore, cron_last
  230. * WARN_UPGRADE
  231. */
  232. function _ec_variable_set($name, $value) {
  233. global $_ec_variables, $_ec_variables_allowed;
  234. if (!in_array($name, $_ec_variables_allowed)) {
  235. elysia_cron_error('Wrong variable passed to _ec_variable_set: !var', array('!var' => $name), true);
  236. return variable_set($name, $value);
  237. }
  238. if (!is_array($_ec_variables)) {
  239. _ec_variable_init();
  240. }
  241. if (EC_DRUPAL_VERSION >= 7) {
  242. db_merge('variable')->key(array('name' => $name))->fields(array('value' => serialize($value)))->execute();
  243. }
  244. else {
  245. if (!variable_get('elysia_cron_alternate_var_handler', false)) {
  246. db_lock_table('variable');
  247. db_query("DELETE FROM {variable} WHERE name = '%s'", $name);
  248. db_query("INSERT INTO {variable} (name, value) VALUES ('%s', '%s')", $name, serialize($value));
  249. db_unlock_tables();
  250. }
  251. else {
  252. db_query("REPLACE INTO {variable} (name, value) VALUES ('%s', '%s')", $name, serialize($value));
  253. }
  254. }
  255. $_ec_variables[$name] = $value;
  256. }
  257. /**
  258. * A substitute for variable_del to avoid cache management
  259. * Use ONLY for variables setted during cron execution: elysia_cron_semaphore, elysia_cron_last_run, elysia_cron_last_context, cron_semaphore, cron_last
  260. * WARN_UPGRADE
  261. */
  262. function _ec_variable_del($name) {
  263. global $_ec_variables, $_ec_variables_allowed;
  264. if (!in_array($name, $_ec_variables_allowed)) {
  265. elysia_cron_error('Wrong variable passed to _ec_variable_del: !var', array('!var' => $name), true);
  266. return variable_del($name);
  267. }
  268. if (!is_array($_ec_variables)) {
  269. _ec_variable_init();
  270. }
  271. if (EC_DRUPAL_VERSION >= 7) {
  272. db_delete('variable')->condition('name', $name)->execute();
  273. }
  274. else {
  275. if (!variable_get('elysia_cron_alternate_var_handler', false)) {
  276. db_lock_table('variable');
  277. db_query("DELETE FROM {variable} WHERE name = '%s'", $name);
  278. db_unlock_tables();
  279. }
  280. else {
  281. db_query("DELETE FROM {variable} WHERE name = '%s'", $name);
  282. }
  283. }
  284. unset($_ec_variables[$name]);
  285. }
  286. if (EC_DRUPAL_VERSION < 7) {
  287. function _ec_semaphore_get($name = 'elysia_cron_semaphore', $timeout = 120) {
  288. if (function_exists('elysia_cron_semaphore_get_alternative')) {
  289. return elysia_cron_semaphore_get_alternative($name, $timeout);
  290. }
  291. db_lock_table('variable');
  292. $semglob = db_result(db_query("select value from {variable} where name = '%s'", 'elysia_cron_semaphore'));
  293. $semglob = $semglob ? unserialize($semglob) : false;
  294. $stuck = $semglob && (time() - $semglob > $timeout);
  295. if ($stuck || !$semglob) {
  296. db_query("DELETE FROM {variable} WHERE name = '%s'", 'elysia_cron_semaphore');
  297. db_query("INSERT INTO {variable} (name, value) VALUES ('%s', '%s')", 'elysia_cron_semaphore', serialize(time()));
  298. $semglob = false; // We must return TRUE
  299. }
  300. db_unlock_tables();
  301. if ($stuck) {
  302. elysia_cron_warning('Global semaphore has been active for more than 2 minutes, probably stuck, reset.');
  303. }
  304. return !$semglob;
  305. }
  306. }
  307. function _ec_get_name($name) {
  308. $maxlen = EC_DRUPAL_VERSION >= 6 ? 120 : 40;
  309. if (strlen($name) < $maxlen) {
  310. return $name;
  311. }
  312. $border = ($maxlen - 32) / 2;
  313. return substr($name, 0, $border) . md5($name) . substr($name, -$border);
  314. }
  315. function elysia_cron_set($name, $channel = false, $values = array()) {
  316. if ($channel) {
  317. $name = ':' . $name;
  318. }
  319. if (EC_DRUPAL_VERSION >= 7) {
  320. db_merge('elysia_cron')->key(array('name' => $name))->fields($values)->execute();
  321. } else {
  322. $fields = array("name" => "'%s'", "disable" => "%d", "rule" => "'%s'", "weight" => "%d", "context" => "'%s'", "running" => "%d", "last_run" => "%d", "last_aborted" => "%d", "abort_count" => "%d", "last_abort_function" => "'%s'", "last_execution_time" => "%d", "execution_count" => "%d", "avg_execution_time" => "%f", "max_execution_time" => "%d", "last_shutdown_time" => "%d");
  323. $ifields = array('disable', 'running', 'last_run', 'last_aborted', 'abort_count', 'last_execution_time', 'execution_count', 'avg_execution_time', 'max_execution_time', 'last_shutdown_time');
  324. if (db_result(db_query("SELECT 1 FROM {elysia_cron} WHERE name = '%s'", $name))) {
  325. $uquery = array();
  326. $uvalues = array();
  327. foreach ($values as $k => $v) {
  328. if (is_null($v) && !in_array($k, $ifields)) {
  329. $uquery[] = $k . ' = NULL';
  330. }
  331. else {
  332. $uquery[] = $k . ' = ' . $fields[$k];
  333. $uvalues[] = $v;
  334. }
  335. }
  336. $uvalues[] = $name;
  337. db_query("update {elysia_cron} set " . implode(', ', $uquery) . " where name = '%s'", $uvalues);
  338. } else {
  339. foreach ($ifields as $f) {
  340. if (empty($values[$f])) {
  341. $values[$f] = 0;
  342. }
  343. }
  344. $values['name'] = $name;
  345. $iquery1 = array();
  346. $iquery2 = array();
  347. $ivalues = array();
  348. foreach ($values as $k => $v) {
  349. if (!is_null($v)) {
  350. $iquery1[] = $k;
  351. $iquery2[] = $fields[$k];
  352. $ivalues[] = $v;
  353. }
  354. }
  355. db_query("insert into {elysia_cron} (" . implode(', ', $iquery1) . ") values (" . implode(', ', $iquery2) . ")", $ivalues);
  356. }
  357. }
  358. global $elysia_cron_db_cache;
  359. unset($elysia_cron_db_cache[$name]);
  360. }
  361. function elysia_cron_get($name, $channel = false, $key = false, $default = false, $refresh = false) {
  362. global $elysia_cron_db_cache;
  363. static $elysia_cron_defaults;
  364. if (!isset($elysia_cron_defaults)) {
  365. $elysia_cron_defaults = function_exists('elysia_cron_get_ctools_defaults') ? elysia_cron_get_ctools_defaults() : array();
  366. }
  367. if ($channel) {
  368. $name = ':' . $name;
  369. }
  370. if ($refresh || !isset($elysia_cron_db_cache[$name])) {
  371. if (EC_DRUPAL_VERSION >= 7) {
  372. $elysia_cron_db_cache[$name] = db_query("select " . implode(", ", $GLOBALS['_ec_columns']) . " from {elysia_cron} where name = :name", array(':name' => $name))->fetchAssoc();
  373. }
  374. else {
  375. $elysia_cron_db_cache[$name] = db_fetch_array(db_query("select " . implode(", ", $GLOBALS['_ec_columns']) . " from {elysia_cron} where name = '%s'", $name));
  376. }
  377. if (!$elysia_cron_db_cache[$name] && isset($elysia_cron_defaults[$name])) {
  378. $elysia_cron_db_cache[$name] = (array)$elysia_cron_defaults[$name];
  379. }
  380. elseif ($elysia_cron_db_cache[$name] && isset($elysia_cron_defaults[$name])) {
  381. foreach($elysia_cron_defaults[$name] as $k => $v) {
  382. if (!isset($elysia_cron_db_cache[$name][$k]) || is_null($elysia_cron_db_cache[$name][$k])) {
  383. $elysia_cron_db_cache[$name][$k] = $v;
  384. }
  385. }
  386. }
  387. }
  388. return !$elysia_cron_db_cache[$name] || !isset($elysia_cron_db_cache[$name][$key]) || is_null($elysia_cron_db_cache[$name][$key]) ? $default : $elysia_cron_db_cache[$name][$key];
  389. }
  390. function elysia_cron_is_channel_disabled($channel, $default = false, $refresh = false) {
  391. // May be overriden by a static conf
  392. if (isset($GLOBALS['conf'][$n = 'ecc_' . _ec_get_name($channel) . '_d'])) {
  393. return $GLOBALS['conf'][$n];
  394. }
  395. return elysia_cron_get($channel, true, 'disable', $default, $refresh);
  396. }
  397. function elysia_cron_set_channel_disabled($channel, $v) {
  398. return elysia_cron_set($channel, true, array('disable' => $v ? 1 : 0));
  399. }
  400. function elysia_cron_reset_channel_disabled($channel) {
  401. return elysia_cron_set($channel, true, array('disable' => 0));
  402. }
  403. function elysia_cron_get_channel_rule($channel, $default = '', $refresh = false) {
  404. // May be overriden by a static conf
  405. if (isset($GLOBALS['conf'][$n = 'ecc_' . _ec_get_name($channel) . '_rul'])) {
  406. return $GLOBALS['conf'][$n];
  407. }
  408. return elysia_cron_get($channel, true, 'rule', $default, $refresh);
  409. }
  410. function elysia_cron_set_channel_rule($channel, $v) {
  411. return elysia_cron_set($channel, true, array('rule' => $v));
  412. }
  413. function elysia_cron_reset_channel_rule($channel) {
  414. return elysia_cron_set($channel, true, array('rule' => NULL));
  415. }
  416. function elysia_cron_is_channel_running($channel, $default = 0, $refresh = false) {
  417. return elysia_cron_get($channel, true, 'running', $default, $refresh);
  418. }
  419. function elysia_cron_set_channel_running($channel, $v) {
  420. return elysia_cron_set($channel, true, array('running' => $v));
  421. }
  422. function elysia_cron_get_channel_last_run($channel, $default = false, $refresh = false) {
  423. return elysia_cron_get($channel, true, 'last_run', $default, $refresh);
  424. }
  425. function elysia_cron_set_channel_last_run($channel, $v) {
  426. return elysia_cron_set($channel, true, array('last_run' => $v));
  427. }
  428. function elysia_cron_get_channel_last_aborted($channel, $default = 0, $refresh = false) {
  429. return elysia_cron_get($channel, true, 'last_aborted', $default, $refresh);
  430. }
  431. function elysia_cron_set_channel_last_aborted($channel, $v) {
  432. return elysia_cron_set($channel, true, array('last_aborted' => $v ? 1 : 0));
  433. }
  434. function elysia_cron_get_channel_abort_count($channel, $default = 0, $refresh = false) {
  435. return elysia_cron_get($channel, true, 'abort_count', $default, $refresh);
  436. }
  437. function elysia_cron_set_channel_abort_count($channel, $v) {
  438. return elysia_cron_set($channel, true, array('abort_count' => $v));
  439. }
  440. function elysia_cron_get_channel_last_abort_function($channel, $default = '', $refresh = false) {
  441. return elysia_cron_get($channel, true, 'last_abort_function', $default, $refresh);
  442. }
  443. function elysia_cron_set_channel_last_abort_function($channel, $job) {
  444. return elysia_cron_set($channel, true, array('last_abort_function' => $job));
  445. }
  446. function elysia_cron_get_channel_stats($channel, $refresh = false) {
  447. return array(
  448. 'last_run' => elysia_cron_get($channel, true, 'last_run', 0, $refresh),
  449. 'last_execution_time' => elysia_cron_get($channel, true, 'last_execution_time', 0, $refresh),
  450. 'execution_count' => elysia_cron_get($channel, true, 'execution_count', 0, $refresh),
  451. 'avg_execution_time' => elysia_cron_get($channel, true, 'avg_execution_time', 0, $refresh),
  452. 'max_execution_time' => elysia_cron_get($channel, true, 'max_execution_time', 0, $refresh),
  453. 'last_shutdown_time' => elysia_cron_get($channel, true, 'last_shutdown_time', 0, $refresh),
  454. 'last_aborted' => elysia_cron_get($channel, true, 'last_aborted', 0, $refresh),
  455. 'abort_count' => elysia_cron_get($channel, true, 'abort_count', 0, $refresh),
  456. 'last_abort_function' => elysia_cron_get($channel, true, 'last_abort_function', 0, ''),
  457. );
  458. }
  459. function elysia_cron_set_channel_stats($channel, $last_run = -1, $last_execution_time = -1, $execution_count = -1,
  460. $avg_execution_time = -1, $max_execution_time = -1, $last_shutdown_time = -1, $last_aborted = -1,
  461. $abort_count = -1, $last_abort_function = -1, $data = array()) {
  462. if ($last_run != -1) {
  463. $data['last_run'] = $last_run;
  464. }
  465. if ($last_execution_time != -1) {
  466. $data['last_execution_time'] = $last_execution_time;
  467. }
  468. if ($execution_count != -1) {
  469. $data['execution_count'] = $execution_count;
  470. }
  471. if ($avg_execution_time != -1) {
  472. $data['avg_execution_time'] = $avg_execution_time;
  473. }
  474. if ($max_execution_time != -1) {
  475. $data['max_execution_time'] = $max_execution_time;
  476. }
  477. if ($last_shutdown_time != -1) {
  478. $data['last_shutdown_time'] = $last_shutdown_time;
  479. }
  480. if ($last_aborted != -1) {
  481. $data['last_aborted'] = $last_aborted;
  482. }
  483. if ($abort_count != -1) {
  484. $data['abort_count'] = $abort_count;
  485. }
  486. if ($last_abort_function != -1) {
  487. $data['last_abort_function'] = $last_abort_function;
  488. }
  489. elysia_cron_set($channel, true, $data);
  490. }
  491. function elysia_cron_get_job_rule($job, $default = '', $refresh = false) {
  492. // May be overriden by a static conf
  493. if (isset($GLOBALS['conf'][$n = 'ec_' . _ec_get_name($job) . '_rul'])) {
  494. return $GLOBALS['conf'][$n];
  495. }
  496. return elysia_cron_get($job, false, 'rule', $default, $refresh);
  497. }
  498. function elysia_cron_set_job_rule($job, $v) {
  499. return elysia_cron_set($job, false, array('rule' => $v));
  500. }
  501. function elysia_cron_reset_job_rule($job) {
  502. return elysia_cron_set($job, false, array('rule' => null));
  503. }
  504. function elysia_cron_get_job_weight($job, $default = '', $refresh = false) {
  505. // May be overriden by a static conf
  506. if (isset($GLOBALS['conf'][$n = 'ec_' . _ec_get_name($job) . '_w'])) {
  507. return $GLOBALS['conf'][$n];
  508. }
  509. return elysia_cron_get($job, false, 'weight', $default, $refresh);
  510. }
  511. function elysia_cron_set_job_weight($job, $v) {
  512. return elysia_cron_set($job, false, array('weight' => $v));
  513. }
  514. function elysia_cron_reset_job_weight($job) {
  515. return elysia_cron_set($job, false, array('weight' => null));
  516. }
  517. function elysia_cron_is_job_disabled($job, $default = false, $refresh = false) {
  518. // May be overriden by a static conf
  519. if (isset($GLOBALS['conf'][$n = 'ec_' . _ec_get_name($job) . '_d'])) {
  520. return $GLOBALS['conf'][$n];
  521. }
  522. return elysia_cron_get($job, false, 'disable', $default, $refresh);
  523. }
  524. function elysia_cron_set_job_disabled($job, $v) {
  525. return elysia_cron_set($job, false, array('disable' => $v ? 1 : 0));
  526. }
  527. function elysia_cron_reset_job_disabled($job) {
  528. return elysia_cron_set($job, false, array('disable' => null));
  529. }
  530. function elysia_cron_get_job_channel($job, $default = '', $refresh = false) {
  531. // May be overriden by a static conf
  532. if (isset($GLOBALS['conf'][$n = 'ec_' . _ec_get_name($job) . '_c'])) {
  533. $c = $GLOBALS['conf'][$n];
  534. }
  535. else {
  536. $c = elysia_cron_get($job, false, 'context', $default, $refresh);
  537. }
  538. return !$c ? $default : $c;
  539. }
  540. function elysia_cron_set_job_channel($job, $v) {
  541. return elysia_cron_set($job, false, array('context' => $v));
  542. }
  543. function elysia_cron_reset_job_channel($job) {
  544. return elysia_cron_set($job, false, array('context' => null));
  545. }
  546. function elysia_cron_is_job_running($job, $default = 0, $refresh = false) {
  547. return elysia_cron_get($job, false, 'running', $default, $refresh);
  548. }
  549. function elysia_cron_set_job_running($job, $v) {
  550. return elysia_cron_set($job, false, array('running' => $v));
  551. }
  552. function elysia_cron_get_job_last_run($job, $default = 0, $refresh = false) {
  553. return elysia_cron_get($job, false, 'last_run', $default, $refresh);
  554. }
  555. function elysia_cron_set_job_last_run($job, $v) {
  556. return elysia_cron_set($job, false, array('last_run' => $v));
  557. }
  558. function elysia_cron_get_job_stats($job, $refresh = false) {
  559. return array(
  560. 'last_run' => elysia_cron_get($job, false, 'last_run', 0, $refresh),
  561. 'last_execution_time' => elysia_cron_get($job, false, 'last_execution_time', 0, $refresh),
  562. 'execution_count' => elysia_cron_get($job, false, 'execution_count', 0, $refresh),
  563. 'avg_execution_time' => elysia_cron_get($job, false, 'avg_execution_time', 0, $refresh),
  564. 'max_execution_time' => elysia_cron_get($job, false, 'max_execution_time', 0, $refresh),
  565. );
  566. }
  567. function elysia_cron_set_job_stats($job, $last_run = -1, $last_execution_time = -1, $execution_count = -1,
  568. $avg_execution_time = -1, $max_execution_time = -1, $data = array()) {
  569. if ($last_run != -1) {
  570. $data['last_run'] = $last_run;
  571. }
  572. if ($last_execution_time != -1) {
  573. $data['last_execution_time'] = $last_execution_time;
  574. }
  575. if ($execution_count != -1) {
  576. $data['execution_count'] = $execution_count;
  577. }
  578. if ($avg_execution_time != -1) {
  579. $data['avg_execution_time'] = $avg_execution_time;
  580. }
  581. if ($max_execution_time != -1) {
  582. $data['max_execution_time'] = $max_execution_time;
  583. }
  584. elysia_cron_set($job, false, $data);
  585. }
  586. function elysia_cron_last_channel() {
  587. return _ec_variable_get('elysia_cron_last_context', '');
  588. }
  589. function elysia_cron_set_last_channel($channel) {
  590. _ec_variable_set('elysia_cron_last_context', $channel);
  591. }
  592. function elysia_cron_reset_stats() {
  593. global $elysia_cron_settings, $elysia_cron_settings_by_channel;
  594. elysia_cron_initialize();
  595. foreach ($elysia_cron_settings as $job => $conf) {
  596. elysia_cron_set_job_stats($job, -1, 0, 0, 0, 0);
  597. }
  598. foreach ($elysia_cron_settings_by_channel as $channel => $conf) {
  599. elysia_cron_set_channel_stats($channel, -1, 0, 0, 0, 0, 0, 0, 0, 0);
  600. }
  601. }
  602. /*******************************************************************************
  603. * INTERNAL
  604. *
  605. * WARN: Below this point the word "context" should be avoided (use channel)
  606. * Disabled should always be referenced as "disabled" (in db is "disable" for
  607. * compatibility with Ctools )
  608. *******************************************************************************/
  609. /**
  610. * Sends a standard message to user
  611. * Drush see it
  612. */
  613. function elysia_cron_message($message, $vars = array()) {
  614. global $elysia_cron_drush;
  615. if (empty($elysia_cron_drush)) {
  616. drupal_set_message(t($message, $vars));
  617. } else {
  618. drush_log(strip_tags(dt($message, $vars)), "ok");
  619. }
  620. }
  621. /**
  622. * Send an error message to user (and log also an error)
  623. * Drush see it (even if $skip_user_message)
  624. */
  625. function elysia_cron_error($message, $vars = array(), $skip_user_message = false) {
  626. global $elysia_cron_drush;
  627. if (empty($elysia_cron_drush) && !$skip_user_message) {
  628. drupal_set_message(t($message, $vars), 'error');
  629. }
  630. /*if (!empty($elysia_cron_drush)) {
  631. drush_log(strip_tags(dt($message, $vars)), "error");
  632. }*/
  633. _dco_watchdog('cron', $message, $vars, WATCHDOG_ERROR);
  634. }
  635. /**
  636. * Log a debug in watchdog (do not print an user message)
  637. * Drush see it in verbose mode
  638. */
  639. function elysia_cron_debug($message, $vars = array(), $type = WATCHDOG_NOTICE) {
  640. global $elysia_cron_drush;
  641. if ($type < WATCHDOG_NOTICE || variable_get('elysia_cron_debug_messages', 0)) {
  642. _dco_watchdog('cron', $message, $vars, $type);
  643. }
  644. if (!empty($elysia_cron_drush) && $elysia_cron_drush >= 2 && ($type >= WATCHDOG_NOTICE || !drush_get_option("verbose", false))) {
  645. if ($type >= WATCHDOG_NOTICE) {
  646. drush_print(strip_tags(dt($message, $vars)));
  647. } else {
  648. drush_log(strip_tags(dt($message, $vars)), $type == WATCHDOG_ERROR ? "error" : (($type == WATCHDOG_ERROR ? "warning" : "notice")));
  649. }
  650. }
  651. }
  652. /**
  653. * Log a warning (do not print an user message)
  654. * Drush see it in verbose mode
  655. */
  656. function elysia_cron_warning($message, $vars = array()) {
  657. elysia_cron_debug($message, $vars, WATCHDOG_WARNING);
  658. }
  659. function elysia_cron_decode_script($text, $apply = true) {
  660. global $elysia_cron_settings;
  661. $lines = explode("\n", $text);
  662. $lastcomment = '';
  663. $errors = array();
  664. $conf = array();
  665. foreach ($lines as $line) {
  666. $line = trim($line);
  667. if (!empty($line)) {
  668. if ($line{0} == '#') {
  669. $lastcomment = trim(substr($line, 1));
  670. }
  671. else if (preg_match('/^(-[ ]*|)([0-9*,\/-]+[ ]+[0-9*,\/-]+[ ]+[0-9*,\/-]+[ ]+[0-9*,\/-]+[ ]+[0-9*,\/-]+)[ ]+((?:ctx|ch):([a-zA-Z0-9_-]+)[ ]+|)([^(:]+)(\(.*\);|)$/', $line, $r)) {
  672. $c = array(
  673. 'disabled' => !empty($r[1]),
  674. 'rule' => $r[2],
  675. 'description' => $lastcomment,
  676. 'channel' => $r[4] ? $r[4] : 'default',
  677. );
  678. $lastcomment = '';
  679. if (empty($r[6])) {
  680. if (!isset($elysia_cron_settings[$r[5]])) {
  681. // Referring a module function that not exists
  682. $errors[] = $line;
  683. continue;
  684. }
  685. $name = $r[5];
  686. }
  687. else {
  688. // custom expression, generate a unique name
  689. $postfix = '';
  690. while (isset($elysia_cron_settings[$r[5] . $postfix])) {
  691. $postfix = ($postfix ? $postfix : 0) + 1;
  692. }
  693. $name = $r[5] . $postfix;
  694. $c['expression'] = $r[5] . $r[6];
  695. }
  696. if ($apply) {
  697. $elysia_cron_settings[$name] = isset($elysia_cron_settings[$name]) ? array_merge($elysia_cron_settings[$name], $c) : $c;
  698. }
  699. }
  700. else {
  701. $errors[] = $line;
  702. }
  703. }
  704. else {
  705. $lastcomment = '';
  706. }
  707. }
  708. return count($errors) ? $errors : false;
  709. }
  710. function elysia_cron_module_jobs() {
  711. static $jobs;
  712. if (!isset($jobs)) {
  713. $jobs = array();
  714. foreach (module_implements('cron') as $module) {
  715. if ($module != 'elysia_cron') {
  716. $jobs[$module . '_cron'] = array(
  717. 'module' => $module,
  718. 'callback' => $module . '_cron',
  719. 'arguments' => array(),
  720. );
  721. }
  722. }
  723. foreach (module_implements('cronapi') as $module) {
  724. $fn = $module . '_cronapi';
  725. $l = $fn('list');
  726. if (is_array($l)) {
  727. foreach ($l as $job => $data) {
  728. if (is_array($data)) {
  729. $jobs[$job] = $data;
  730. } else {
  731. // Compatibility with v1.x settings
  732. $jobs[$job] = array(
  733. 'description' => $data,
  734. 'rule' => ($d = $fn('rule', $job)) ? $d : false,
  735. 'weight' => ($d = $fn('weight', $job)) ? $d : 0,
  736. );
  737. }
  738. $jobs[$job] = $jobs[$job] + array(
  739. 'module' => $module,
  740. 'callback' => function_exists($job) ? $job : $fn,
  741. 'arguments' => function_exists($job) ? array() : array('execute', $job),
  742. );
  743. }
  744. }
  745. }
  746. if (function_exists('drupal_alter'))
  747. drupal_alter('cron', $jobs);
  748. }
  749. return $jobs;
  750. }
  751. function elysia_cron_initialize($skipscript = false) {
  752. global $elysia_cron_settings, $elysia_cron_settings_by_channel;
  753. if (empty($elysia_cron_settings)) {
  754. elysia_cron_check_version_update();
  755. $elysia_cron_settings = array();
  756. $elysia_cron_settings_by_channel = array();
  757. foreach (elysia_cron_module_jobs() as $job => $jobpars) {
  758. $channel = elysia_cron_get_job_channel($job, 'default');
  759. $defrule = !empty($jobpars['rule']) ? $jobpars['rule'] : elysia_cron_get_channel_rule($channel);
  760. if (!$defrule) {
  761. $defrule = variable_get('elysia_cron_default_rule', '0 * * * *');
  762. }
  763. $defweight = !empty($jobpars['weight']) ? $jobpars['weight'] : 0;
  764. if (!is_numeric($defweight)) {
  765. $defweight = 0;
  766. }
  767. $elysia_cron_settings[$job] = array(
  768. 'key' => $job,
  769. 'channel' => $channel,
  770. 'rule' => elysia_cron_get_job_rule($job, $defrule),
  771. 'default_rule' => $defrule,
  772. 'weight' => elysia_cron_get_job_weight($job, $defweight),
  773. 'default_weight' => $defweight,
  774. 'disabled' => elysia_cron_is_job_disabled($job),
  775. 'running' => elysia_cron_is_job_running($job),
  776. ) + $jobpars;
  777. }
  778. if (!$skipscript) {
  779. $script = variable_get('elysia_cron_script', false);
  780. if ($script) {
  781. elysia_cron_decode_script($script);
  782. }
  783. }
  784. uasort($elysia_cron_settings, '_elysia_cron_sort');
  785. foreach ($elysia_cron_settings as $job => &$conf) {
  786. $stats = elysia_cron_get_job_stats($job);
  787. foreach ($stats as $sk => $sv) {
  788. $conf[$sk] = $sv;
  789. }
  790. $elysia_cron_settings_by_channel[$conf['channel']][$job] = &$elysia_cron_settings[$job];
  791. }
  792. foreach ($elysia_cron_settings_by_channel as $channel => $data) {
  793. uasort($elysia_cron_settings_by_channel[$channel], '_elysia_cron_sort');
  794. $elysia_cron_settings_by_channel[$channel]['#data'] = elysia_cron_get_channel_stats($channel);
  795. $elysia_cron_settings_by_channel[$channel]['#data']['disabled'] = elysia_cron_is_channel_disabled($channel);
  796. }
  797. }
  798. }
  799. function _elysia_cron_sort($a, $b) {
  800. if ((isset($a['weight']) ? $a['weight'] : 0) == (isset($b['weight']) ? $b['weight'] : 0)) {
  801. return strcmp((isset($a['key']) ? $a['key'] : ''), (isset($b['key']) ? $b['key'] : ''));
  802. }
  803. return (isset($a['weight']) ? $a['weight'] : 0) - (isset($b['weight']) ? $b['weight'] : 0);
  804. }
  805. /**
  806. * Prepare system for a cron execution
  807. *
  808. * This should be called at the start of a cron execution:
  809. * prepare_run
  810. * lock_env
  811. * ... look for channel/jobs ready for execution and change internal states ...
  812. * unlock_env
  813. * before_execution
  814. * .. execute channel/jobs ..
  815. * after_execution
  816. * unprepare_run
  817. *
  818. */
  819. function elysia_cron_prepare_run($manual_run, $start = true) {
  820. static $original_user;
  821. if ($start) {
  822. // Allow execution to continue even if the request gets canceled.
  823. @ignore_user_abort(true);
  824. // Try to allocate enough time to run all the hook_cron implementations.
  825. if (!ini_get('safe_mode')) {
  826. set_time_limit(variable_get('elysia_cron_time_limit', 240));
  827. }
  828. // Prevent session information from being saved while cron is running.
  829. drupal_save_session(FALSE);
  830. // Force the current user to anonymous to ensure consistent permissions on
  831. // cron runs (only if run by interface)
  832. if ($manual_run) {
  833. $original_user = $GLOBALS['user'];
  834. $GLOBALS['user'] = drupal_anonymous_user();
  835. }
  836. } else {
  837. if ($manual_run) {
  838. // Restore the user.
  839. $GLOBALS['user'] = $original_user;
  840. /*if (EC_DRUPAL_VERSION >= 7) {
  841. drupal_save_session(TRUE);
  842. }*/
  843. }
  844. }
  845. }
  846. /**
  847. * Call this after a cron execution, prepared with elysia_cron_prepare_run()
  848. *
  849. * @see: elysia_cron_prepare_run()
  850. */
  851. function elysia_cron_unprepare_run($manual_run) {
  852. elysia_cron_prepare_run($manual_run, false);
  853. }
  854. /**
  855. * Use this before checking and modifying environment variables.
  856. *
  857. * @see: elysia_cron_prepare_run()
  858. */
  859. function elysia_cron_lock_env() {
  860. $execute = true;
  861. if (EC_DRUPAL_VERSION >= 7) {
  862. if (!lock_acquire('cron', 240.0)) {
  863. elysia_cron_warning('Attempting to re-run cron while it is already running.');
  864. $execute = false;
  865. }
  866. }
  867. else {
  868. // Global Semaphore to avoid concurrent execution of cron preparation code
  869. $execute = _ec_semaphore_get('elysia_cron_semaphore', 120);
  870. }
  871. return $execute;
  872. }
  873. /**
  874. * Unlock system locked with elysia_cron_lock_env
  875. *
  876. * @see: elysia_cron_prepare_run()
  877. */
  878. function elysia_cron_unlock_env() {
  879. // Release cron lock.
  880. if (EC_DRUPAL_VERSION >= 7) {
  881. lock_release('cron');
  882. } else {
  883. _ec_variable_del('elysia_cron_semaphore');
  884. }
  885. }
  886. /**
  887. * Use this before executing a cron handler
  888. *
  889. * @see: elysia_cron_prepare_run()
  890. */
  891. function elysia_cron_before_execution() {
  892. global $conf;
  893. if (EC_DRUPAL_VERSION < 7) {
  894. // Some modules (feedapi, ipaper...) uses the internal "cron_semaphore" variable to detect
  895. // start time of cron process. I'll set this only in memory for that purpose.
  896. // (In normal drupal cron execution that is done by a variable_set just before this call,
  897. // but i need to set this manually if drupal cron is bypassed)
  898. $conf['cron_semaphore'] = time();
  899. }
  900. }
  901. /**
  902. * Use this after executing a cron handler
  903. *
  904. * @see: elysia_cron_prepare_run()
  905. */
  906. function elysia_cron_after_execution() {
  907. global $conf;
  908. if (EC_DRUPAL_VERSION < 7) {
  909. _ec_variable_del('cron_semaphore');
  910. $conf['cron_semaphore'] = false;
  911. }
  912. }
  913. /**
  914. * Public function to invoke a complete cron_run
  915. * @param $manual_run Consider launched by a user command (don't check for key/ip, protect current user...)
  916. * @param $ignore_disable Run the channel (and all it's jobs) even if disabled
  917. * @param $ignore_time Run channel (and all it's jobs) job even if not ready
  918. * @param $ignore_running Run the channel (and all it's jobs) even if already running
  919. */
  920. function elysia_cron_run($manual_run = false, $ignore_disable = false, $ignore_time = false, $ignore_running = false) {
  921. // If DISABLED block the execution
  922. if (!$ignore_disable && variable_get('elysia_cron_disabled', false)) {
  923. elysia_cron_debug("Cron globally disabled, skipping run");
  924. return;
  925. }
  926. // Check for CRON_KEY or ALLOWED_HOSTS
  927. if (!$manual_run) {
  928. $cron_key = variable_get('cron_key', '');
  929. if ($cron_key && !user_access('administer elysia_cron') && (empty($_GET['cron_key']) || $_GET['cron_key'] != $cron_key)) {
  930. elysia_cron_debug("Cron key mismatch, skipping run");
  931. return;
  932. }
  933. $allowed_hosts = variable_get('elysia_cron_allowed_hosts', false);
  934. if ($allowed_hosts && !user_access('administer elysia_cron') && !in_array(ip_address(), explode(",", $allowed_hosts))) {
  935. elysia_cron_debug("Cron ip address mismatch, skipping run");
  936. return;
  937. }
  938. }
  939. elysia_cron_prepare_run($manual_run);
  940. _ec_variable_set('elysia_cron_last_run', time());
  941. _ec_variable_set('cron_last', time());
  942. if ($execute = elysia_cron_lock_env()) {
  943. elysia_cron_initialize();
  944. $available_channel = elysia_cron_run_available_channel($ignore_disable, $ignore_time, $ignore_running);
  945. if ($available_channel) {
  946. // There are jobs ready to be executed
  947. // elysia_cron_internal_execute_channel calls elysia_cron_unlock_env
  948. elysia_cron_internal_execute_channel($available_channel['name'], $available_channel['jobs'], $ignore_running);
  949. }
  950. else {
  951. // No jobs should be executed, i must unlock cron semaphore
  952. elysia_cron_unlock_env();
  953. elysia_cron_debug('No channels ready to be executed, skipping cron.');
  954. }
  955. }
  956. elysia_cron_unprepare_run($manual_run);
  957. return $execute;
  958. }
  959. /**
  960. * Public function to execute all jobs in a channel
  961. * @param $ignore_disable Run the channel (and all it's jobs) even if disabled
  962. * @param $ignore_time Run channel (and all it's jobs) job even if not ready
  963. * @param $ignore_running Run the channel (and all it's jobs) even if already running
  964. */
  965. function elysia_cron_run_channel($channel, $ignore_disable = false, $ignore_time = false, $ignore_running = false) {
  966. global $elysia_cron_settings_by_channel;
  967. elysia_cron_prepare_run(true); // Always $manual_run
  968. if ($execute = elysia_cron_lock_env()) {
  969. elysia_cron_initialize();
  970. $jobs = false;
  971. if (isset($elysia_cron_settings_by_channel[$channel])) {
  972. if ($ignore_disable || empty($elysia_cron_settings_by_channel[$channel]['#data']['disabled'])) {
  973. $jobs = elysia_cron_check_run_channel($channel, $ignore_disable, $ignore_time, $ignore_running);
  974. if ($jobs && count($jobs)) {
  975. // elysia_cron_internal_execute_channel calls elysia_cron_unlock_env
  976. elysia_cron_internal_execute_channel($channel, $jobs, $ignore_running);
  977. } else {
  978. elysia_cron_debug('Channel already running or no jobs ready to be executed, skipping');
  979. }
  980. } else {
  981. elysia_cron_warning('Channel is disabled, skipping');
  982. }
  983. } else {
  984. elysia_cron_warning('Channel not found, skipping');
  985. }
  986. if (!$jobs) {
  987. // No jobs should be executed, i must unlock cron semaphore
  988. elysia_cron_unlock_env();
  989. }
  990. }
  991. elysia_cron_unprepare_run(true);
  992. return $execute;
  993. }
  994. /**
  995. * Public function to execute a single job
  996. * @param $ignore_disable Run the job even if disabled
  997. * @param $ignore_time Run the job even if not ready
  998. * @param $ignore_running Run the job even if already running
  999. */
  1000. function elysia_cron_run_job($job, $ignore_disable = false, $ignore_time = false, $ignore_running = false) {
  1001. global $cron_completed, $cron_executing_job, $elysia_cron_settings;
  1002. elysia_cron_initialize();
  1003. if (isset($elysia_cron_settings[$job])) {
  1004. if (elysia_cron_should_run($elysia_cron_settings[$job], -1, $ignore_disable, $ignore_time)) {
  1005. if ($ignore_running || !elysia_cron_check_run_job($job)) {
  1006. $cron_completed = false;
  1007. $cron_executing_job = $job;
  1008. elysia_cron_before_execution();
  1009. // Register shutdown callback
  1010. register_shutdown_function('elysia_cron_run_job_cleanup');
  1011. elysia_cron_internal_execute_job($job);
  1012. elysia_cron_after_execution();
  1013. $cron_completed = true;
  1014. elysia_cron_message('Job executed');
  1015. } else {
  1016. elysia_cron_debug('Job is already running, skipping');
  1017. }
  1018. } else {
  1019. elysia_cron_debug('Job is disabled or not ready to be executed, skipping');
  1020. }
  1021. } else {
  1022. elysia_cron_warning('Job not found, skipping');
  1023. }
  1024. }
  1025. function elysia_cron_run_job_cleanup() {
  1026. global $cron_completed, $cron_executing_job;
  1027. if ($cron_completed) {
  1028. return;
  1029. }
  1030. // See if the semaphore is still locked.
  1031. if (elysia_cron_is_job_running($cron_executing_job)) {
  1032. elysia_cron_warning('Unexpected termination of cron job %job manually started, aborted.', array('%job' => $cron_executing_job));
  1033. elysia_cron_set_job_running($cron_executing_job, 0);
  1034. }
  1035. }
  1036. /**
  1037. * Internal function to execute all jobs in a channel
  1038. * elysia_cron_lock_env() must be called BEFORE calling this method
  1039. */
  1040. function elysia_cron_internal_execute_channel($channel, $jobs, $ignore_running = false) {
  1041. global $elysia_cron_current_channel, $cron_completed, $cron_completed_time;
  1042. elysia_cron_debug('Cron channel %channel run started.', array('%channel' => $channel));
  1043. $elysia_cron_current_channel = $channel;
  1044. elysia_cron_set($elysia_cron_current_channel, true, array(
  1045. 'running' => time(),
  1046. 'last_run' => time(),
  1047. ));
  1048. // Register shutdown callback
  1049. register_shutdown_function('elysia_cron_internal_execute_channel_cleanup');
  1050. // Now I can unlock cron semaphore
  1051. elysia_cron_unlock_env();
  1052. elysia_cron_before_execution();
  1053. foreach ($jobs as $job) {
  1054. if ($ignore_running || !elysia_cron_check_run_job($job)) {
  1055. elysia_cron_internal_execute_job($job);
  1056. }
  1057. }
  1058. elysia_cron_after_execution();
  1059. $cron_completed = true;
  1060. $cron_completed_time = time();
  1061. // Cron is really completed after shutdown functions
  1062. register_shutdown_function('elysia_cron_internal_execute_channel_completed');
  1063. }
  1064. /**
  1065. * Internal function to execute a single job
  1066. */
  1067. function elysia_cron_internal_execute_job($job) {
  1068. global $elysia_cron_settings;
  1069. elysia_cron_debug('Cron job %job started.', array('%job' => $job));
  1070. $time = time();
  1071. elysia_cron_set($job, false, array(
  1072. 'running' => $time,
  1073. 'last_run' => $time,
  1074. ));
  1075. try {
  1076. if (!empty($elysia_cron_settings[$job]['file'])) {
  1077. include_once((!empty($elysia_cron_settings[$job]['file path']) ? $elysia_cron_settings[$job]['file path'] : drupal_get_path('module', $elysia_cron_settings[$job]['module'])) . DIRECTORY_SEPARATOR . $elysia_cron_settings[$job]['file']);
  1078. }
  1079. if (!empty($elysia_cron_settings[$job]['expression'])) {
  1080. eval($elysia_cron_settings[$job]['expression']);
  1081. }
  1082. elseif (!empty($elysia_cron_settings[$job]['callback']) && function_exists($elysia_cron_settings[$job]['callback'])) {
  1083. call_user_func_array($elysia_cron_settings[$job]['callback'], $elysia_cron_settings[$job]['arguments']);
  1084. }
  1085. else {
  1086. elysia_cron_error('Execution of ' . $job . ' failed, can\'t find function!', array(), true);
  1087. }
  1088. }
  1089. catch (Exception $e) {
  1090. elysia_cron_error('Exception: ' . $e, array(), true);
  1091. $exception = true;
  1092. //TODO Manage it
  1093. }
  1094. $stats = elysia_cron_get_job_stats($job);
  1095. $time = time() - $time;
  1096. elysia_cron_set_job_stats($job,
  1097. -1,
  1098. $time,
  1099. ($c = $stats['execution_count'] + 1),
  1100. round((($stats['avg_execution_time'] * ($c - 1)) + $time) / $c, 2),
  1101. $time > $stats['max_execution_time'] ? $time : -1,
  1102. array('running' => 0)
  1103. );
  1104. elysia_cron_debug('Cron job %job ended in %time secs.', array('%job' => $job, '%time' => $time));
  1105. }
  1106. /**
  1107. * Check if the channel is idle (not running, or stuck). If so set returns available jobs.
  1108. *
  1109. * @return array of jobs ready to be executed, or FALSE if channel is running
  1110. */
  1111. function elysia_cron_check_run_channel($channel, $ignore_disable = false, $ignore_time = false, $ignore_running = false) {
  1112. global $elysia_cron_settings_by_channel;
  1113. $jobs = false;
  1114. $stuck_time = variable_get('elysia_cron_stuck_time', 3600);
  1115. $sem = elysia_cron_is_channel_running($channel);
  1116. if ($sem && (time() - $sem > $stuck_time)) {
  1117. elysia_cron_set_channel_running($channel, 0);
  1118. $last_job = elysia_cron_execute_aborted($channel);
  1119. unset($sem);
  1120. elysia_cron_error('Cron channel (%channel) has been running for more than an %stuck_time secs and is most likely stuck. Last job executed: %job', array('%channel' => $channel, '%stuck_time' => $stuck_time, '%job' => $last_job), true);
  1121. }
  1122. if (($ignore_running || empty($sem)) && ($ignore_disable || !$elysia_cron_settings_by_channel[$channel]['#data']['disabled'])) {
  1123. $jobs = elysia_cron_active_jobs($channel, $ignore_disable, $ignore_time);
  1124. }
  1125. return $jobs;
  1126. }
  1127. function elysia_cron_check_run_job($job) {
  1128. $job_running = false;
  1129. if (elysia_cron_is_job_running($job)) {
  1130. if (time() - elysia_cron_get_job_last_run($job, 0) > variable_get('elysia_cron_stuck_time', 3600)) {
  1131. elysia_cron_warning('Job %job is already running, but is probably stuck, so i consider it as terminated', array('%job' => $job));
  1132. }
  1133. else {
  1134. elysia_cron_warning('Job %job is already running', array('%job' => $job));
  1135. $job_running = true;
  1136. }
  1137. }
  1138. return $job_running;
  1139. }
  1140. /**
  1141. * Find an idle channel (not running, or stuck). If found one, set it as running and returns available jobs.
  1142. *
  1143. * @return if found returns array { 'name' => name of channel, 'jobs' => array of active jobs }, else return FALSE
  1144. */
  1145. function elysia_cron_run_available_channel($ignore_disable = false, $ignore_time = false, $ignore_running = false) {
  1146. global $elysia_cron_settings_by_channel;
  1147. $channels = array_keys($elysia_cron_settings_by_channel);
  1148. $channel = elysia_cron_last_channel();
  1149. $i = array_search($channel, $channels);
  1150. if ($i === FALSE) {
  1151. $i = -1;
  1152. }
  1153. $k = 0;
  1154. $jobs = false;
  1155. for ($j = ($i + 1) % count($channels); $k < count($channels); $j = ($j + 1) % count($channels)) {
  1156. $jobs = elysia_cron_check_run_channel($channels[$j], $ignore_disable, $ignore_time, $ignore_running);
  1157. if ($jobs && count($jobs)) {
  1158. break;
  1159. }
  1160. $k++;
  1161. }
  1162. if ($jobs) {
  1163. elysia_cron_set_last_channel($channels[$j]);
  1164. }
  1165. return $jobs ? array('name' => $channels[$j], 'jobs' => $jobs) : false;
  1166. }
  1167. function elysia_cron_execute_aborted($channel) {
  1168. global $elysia_cron_settings_by_channel;
  1169. $last_job = '';
  1170. foreach ($elysia_cron_settings_by_channel[$channel] as $job => $conf) {
  1171. if ($job != '#data') {
  1172. if (elysia_cron_is_job_running($job)) {
  1173. $last_job .= ' ' . $job;
  1174. elysia_cron_set_job_running($job, 0);
  1175. }
  1176. }
  1177. }
  1178. elysia_cron_set($channel, true, array(
  1179. 'running' => 0, //time(),
  1180. 'last_aborted' => 1,
  1181. 'abort_count' => elysia_cron_get_channel_abort_count($channel) + 1,
  1182. 'last_abort_function' => $last_job,
  1183. ));
  1184. return trim($last_job);
  1185. }
  1186. /**
  1187. * Shutdown function for cron cleanup.
  1188. *
  1189. * Used for unexpected termination of code.
  1190. */
  1191. function elysia_cron_internal_execute_channel_cleanup() {
  1192. global $elysia_cron_settings, $elysia_cron_current_channel, $cron_completed, $cron_completed_time;
  1193. if ($cron_completed) {
  1194. return;
  1195. }
  1196. // See if the semaphore is still locked.
  1197. if (elysia_cron_is_channel_running($elysia_cron_current_channel)) {
  1198. $last_job = elysia_cron_execute_aborted($elysia_cron_current_channel);
  1199. elysia_cron_warning('Unexpected termination of cron channel %channel, aborted. Last job executed: %job', array('%channel' => $elysia_cron_current_channel, '%job' => $last_job));
  1200. }
  1201. }
  1202. /**
  1203. * Successful termination (after all shutdown hooks invoked by cron functions).
  1204. */
  1205. function elysia_cron_internal_execute_channel_completed() {
  1206. global $elysia_cron_settings, $elysia_cron_current_channel, $cron_completed, $cron_completed_time;
  1207. // Record cron time
  1208. _ec_variable_set('cron_last', time());
  1209. elysia_cron_debug('Cron channel %channel run completed.', array('%channel' => $elysia_cron_current_channel));
  1210. $stats = elysia_cron_get_channel_stats($elysia_cron_current_channel);
  1211. $time = time() - $stats['last_run'];
  1212. elysia_cron_set_channel_stats($elysia_cron_current_channel,
  1213. -1, // last_run
  1214. $time, // last_execution_time
  1215. ($c = $stats['execution_count'] + 1), // execution_count
  1216. round((($stats['avg_execution_time'] * ($c - 1)) + $time) / $c, 2), // avg_execution_time
  1217. $time > $stats['max_execution_time'] ? $time : -1, // max_execution_time
  1218. time() - $cron_completed_time, // last_shutdown_time
  1219. 0, -1, -1, // last_aborted, abort_count, last_abort_function
  1220. array('running' => 0)
  1221. );
  1222. }
  1223. /**
  1224. * Get all jobs that needs to be executed in a channel
  1225. */
  1226. function elysia_cron_active_jobs($channel, $ignore_disable = false, $ignore_time = false) {
  1227. global $elysia_cron_settings_by_channel;
  1228. $jobs = array();
  1229. foreach ($elysia_cron_settings_by_channel[$channel] as $job => $conf) {
  1230. if ($job != '#data') {
  1231. if (elysia_cron_should_run($conf, -1, $ignore_disable, $ignore_time)) {
  1232. $jobs[] = $job;
  1233. }
  1234. }
  1235. }
  1236. return $jobs;
  1237. }
  1238. /**
  1239. * Check if cron is currently running.
  1240. * (Not used by elysia_cron, can be used by external modules)
  1241. */
  1242. function elysia_cron_is_running() {
  1243. global $elysia_cron_settings_by_channel;
  1244. elysia_cron_initialize();
  1245. $running = array();
  1246. foreach ($elysia_cron_settings_by_channel as $channel => $data) {
  1247. if (elysia_cron_is_channel_running($channel)) {
  1248. $running[] = $channel;
  1249. }
  1250. }
  1251. return $running;
  1252. }
  1253. function elysia_cron_job_exists($job) {
  1254. global $elysia_cron_settings;
  1255. return isset($elysia_cron_settings[$job]);
  1256. }
  1257. function elysia_cron_channel_exists($channel) {
  1258. global $elysia_cron_settings_by_channel;
  1259. return isset($elysia_cron_settings_by_channel[$channel]);
  1260. }
  1261. /**
  1262. * Obtain job description (translated)
  1263. */
  1264. function elysia_cron_description($job) {
  1265. global $elysia_cron_settings;
  1266. if (!empty($elysia_cron_settings[$job]['description'])) {
  1267. $desc = $elysia_cron_settings[$job]['description'];
  1268. }
  1269. else {
  1270. $desc = _dco_theme('elysia_cron_description', array('job' => $job));
  1271. }
  1272. return t($desc);
  1273. }
  1274. /*******************************************************************************
  1275. * THEMING
  1276. ******************************************************************************/
  1277. /**
  1278. * Implementation of hook_theme(). [Only D6+D7]
  1279. */
  1280. function elysia_cron_theme() {
  1281. return _dcr_hook_theme(array(
  1282. 'elysia_cron_description' => array(
  1283. 'variables' => array('job' => NULL),
  1284. ),
  1285. 'elysia_cron_settings_form' => array(
  1286. 'render element' => 'form',
  1287. ),
  1288. ));
  1289. }
  1290. /**
  1291. * You can theme this function to provide your (untranslated) descriptions for cron functions, if they do not provide one.
  1292. */
  1293. function theme_elysia_cron_description($variables) {
  1294. extract(_dcf_theme_signature(array('job' => $variables)));
  1295. switch ($variables['job']) {
  1296. case 'search_cron':
  1297. return 'Update search database index';
  1298. case 'activitystream_cron':
  1299. return 'Fetch RSS feeds and web calls for activitystream';
  1300. case 'mailhandler_cron':
  1301. return 'Fetch POP3/IMAP accounts managed by MailHandler';
  1302. case 'watchdog_cron':
  1303. return 'Remove expired log messages and flood control events';
  1304. case 'filter_cron':
  1305. return 'Expire outdated filter cache entries';
  1306. case 'node_cron':
  1307. return 'History table cleanup';
  1308. case 'system_cron':
  1309. return 'Remove older rows from flood and batch table. Remove old temporary files.';
  1310. case 'aggregation_cron':
  1311. return 'Fetch RSS feeds for aggregation module';
  1312. case 'amazon_cron':
  1313. return 'Refresh Amazon products';
  1314. case 'image_cron':
  1315. return 'Deletes old temp images';
  1316. case 'persistent_login_cron':
  1317. return 'Expire persistent login';
  1318. case 'trackback_cron':
  1319. return 'Process trackback ping queue';
  1320. case 'update_status_cron':
  1321. return 'Checks for drupal module updates (Note: own frequency check ignore cron rules)';
  1322. case 'user_karma_cron':
  1323. return 'User karma expiration / rebuild (Note: own frequency check ignore cron rules)';
  1324. case 'votingapi_cron':
  1325. return 'Update votes (if not configured for immediate calculation)';
  1326. case 'statistics_cron':
  1327. return 'Reset day counts / Clean expired access logs';
  1328. case 'googleanalytics_cron':
  1329. return 'Delete cached version of ga.js/urchin.js.';
  1330. case 'xmlsitemap_cron':
  1331. return 'XML sitemap ping.';
  1332. case 'xmlsitemap_node_cron':
  1333. return 'Update XML sitemap with new nodes';
  1334. case 'xmlsitemap_term_cron':
  1335. return 'Update XML sitemap with new terms';
  1336. case 'lm_paypal_cron':
  1337. return 'Remove old IPN records';
  1338. case 'user_import_cron':
  1339. return 'Continue partial imports';
  1340. case 'dblog_cron':
  1341. return 'Remove expired log messages and flood control events';
  1342. case 'field_cron':
  1343. return 'Purges some deleted Field API data, if any exists';
  1344. case 'trigger_cron':
  1345. return 'Triggers cron actions';
  1346. case 'update_cron':
  1347. return 'Checks for available updates of Drupal core, contributed modules and themes';
  1348. case 'search_api_cron':
  1349. return 'Will index items for each enabled index.';
  1350. case 'redirect_cron':
  1351. return 'Purge inactive self-managed redirects from the database.';
  1352. case 'ctools_cron':
  1353. return 'Clean up old caches';
  1354. case 'l10n_update_cron':
  1355. return 'Check one project/language at a time, download and import if update available';
  1356. default:
  1357. return '-';
  1358. }
  1359. }
  1360. /*******************************************************************************
  1361. * PING SUPPORT
  1362. ******************************************************************************/
  1363. /**
  1364. * Page callback for ping page. Throws 404 if cron hasn't been called within configured time period.
  1365. */
  1366. function elysia_cron_ping_page() {
  1367. $last_run = _ec_variable_get('elysia_cron_last_run', 0);
  1368. $diff = time() - $last_run;
  1369. $max_interval = variable_get('elysia_cron_alert_interval', 60) * 60;
  1370. if ($diff > $max_interval) {
  1371. return drupal_not_found();
  1372. }
  1373. else {
  1374. $aoutput = array();
  1375. $aoutput[] = array(
  1376. '#type' => 'markup',
  1377. '#markup' => t('Cron has been called within maximum lapse time.'),
  1378. );
  1379. return _dcr_render_array($aoutput);
  1380. }
  1381. }
  1382. /*******************************************************************************
  1383. * DRUPAL QUEUE SUPPORT
  1384. * ONLY FOR D7
  1385. ******************************************************************************/
  1386. function elysia_cron_cronapi($op, $job = false) {
  1387. $items = array();
  1388. if (EC_DRUPAL_VERSION >= 7) {
  1389. $queues = module_invoke_all('cron_queue_info');
  1390. drupal_alter('cron_queue_info', $queues);
  1391. foreach ($queues as $queue_name => $info) {
  1392. // Make sure every queue exists. There is no harm in trying to recreate an
  1393. // existing queue.
  1394. $queue = DrupalQueue::get($queue_name);
  1395. $queue->createQueue();
  1396. $items['queue_' . $queue_name] = array(
  1397. 'description' => $queue_name . ' queue processing (Items count: <strong>' . $queue->numberOfItems() . '</strong>, worker max duration: <strong>' . (isset($info['time']) ? $info['time'] . 's' : t('unspecified') . ' (15s)') . '</strong>)',
  1398. 'rule' => variable_get('elysia_cron_queue_default_rule', false),
  1399. 'weight' => variable_get('elysia_cron_queue_default_weight', 100),
  1400. 'callback' => 'elysia_cron_queue_exec',
  1401. 'arguments' => array($queue_name, $info),
  1402. );
  1403. }
  1404. }
  1405. return $items;
  1406. }
  1407. function elysia_cron_queue_exec($queue_name, $info) {
  1408. $function = $info['worker callback'];
  1409. $end = time() + (isset($info['time']) ? $info['time'] : 15);
  1410. $queue = DrupalQueue::get($queue_name);
  1411. while (time() < $end && ($item = $queue->claimItem())) {
  1412. $function($item->data);
  1413. $queue->deleteItem($item);
  1414. }
  1415. }
  1416. /*******************************************************************************
  1417. * ADMIN_MENU SUPPORT
  1418. ******************************************************************************/
  1419. // TODO: Deve gestire hook_admin_menu_map, vedi hook_admin_menu.php e admin_menu.map.inc
  1420. /**
  1421. * Implementation of hook_admin_menu().
  1422. *
  1423. * @param &$deleted
  1424. * Array of links under admin/* that were removed by admin_menu_adjust_items().
  1425. * If one of these links is added back, it should be removed from the array.
  1426. */
  1427. function elysia_cron_admin_menu(&$deleted) {
  1428. $links = array();
  1429. elysia_cron_initialize();
  1430. global $elysia_cron_settings_by_channel;
  1431. // Add link to manually run cron.
  1432. $links[] = array(
  1433. 'title' => 'Elysia cron manual',
  1434. 'path' => _dcf_internal_path('admin/config/system/cron'),
  1435. 'weight' => 50,
  1436. 'has_children' => FALSE,
  1437. 'parent_path' => '<front>',
  1438. );
  1439. foreach ($elysia_cron_settings_by_channel as $channel => $data) {
  1440. foreach ($data as $job => $conf) {
  1441. if ($job != '#data') {
  1442. $links[] = array(
  1443. 'title' => "Elysia cron run manual !title",
  1444. 'path' => _dcf_internal_path('admin/config/system/cron/execute/' . $job),
  1445. 'weight' => -50,
  1446. 'query' => 'destination',
  1447. 'parent_path' => _dcf_internal_path('admin/config/system/cron'),
  1448. 'options' => array('t' => array('!title' => $conf['module'])),
  1449. );
  1450. }
  1451. }
  1452. }
  1453. return $links;
  1454. }