elysia_cron.module 59 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042
  1. <?php
  2. /**
  3. * @file
  4. * Elysia cron primary module file.
  5. */
  6. require_once 'elysia_cron_scheduler.inc';
  7. require_once 'elysia_cron.admin.inc';
  8. require_once 'elysia_cron.ctools.inc';
  9. /**
  10. * Implements hook_menu().
  11. */
  12. function elysia_cron_menu() {
  13. $items['admin/config/system/cron'] = array(
  14. 'title' => 'Cron Settings',
  15. 'description' => 'View and manage cron table',
  16. 'page callback' => 'elysia_cron_admin_page',
  17. 'access callback' => 'elysia_cron_access',
  18. 'access arguments' => array('view elysia_cron'),
  19. );
  20. $items['admin/config/system/cron/status'] = array(
  21. 'type' => MENU_DEFAULT_LOCAL_TASK,
  22. 'title' => 'Status',
  23. 'weight' => 1,
  24. );
  25. $items['admin/config/system/cron/settings'] = array(
  26. 'type' => MENU_LOCAL_TASK,
  27. 'title' => 'Settings',
  28. 'page callback' => 'drupal_get_form',
  29. 'page arguments' => array('elysia_cron_settings_form'),
  30. 'access callback' => 'elysia_cron_access',
  31. 'access arguments' => array('administer elysia_cron'),
  32. 'weight' => 2,
  33. );
  34. $items['admin/config/system/cron/maintenance'] = array(
  35. 'type' => MENU_LOCAL_TASK,
  36. 'title' => 'Maintenance',
  37. 'page callback' => 'drupal_get_form',
  38. 'page arguments' => array('elysia_cron_reset_statistics_form'),
  39. 'access callback' => 'elysia_cron_access',
  40. 'access arguments' => array('administer elysia_cron'),
  41. 'weight' => 3,
  42. );
  43. $items['admin/config/system/cron/execute/%'] = array(
  44. 'type' => MENU_CALLBACK,
  45. 'page callback' => 'elysia_cron_execute_page',
  46. 'page arguments' => array(5),
  47. 'access callback' => 'elysia_cron_access',
  48. 'access arguments' => array('execute elysia_cron'),
  49. );
  50. $items['admin/build/cron/ping'] = array(
  51. 'type' => MENU_CALLBACK,
  52. 'page callback' => 'elysia_cron_ping_page',
  53. 'access callback' => TRUE,
  54. );
  55. return $items;
  56. }
  57. /**
  58. * Implements hook_menu_alter().
  59. */
  60. function elysia_cron_menu_alter(&$items) {
  61. // Override default cron page.
  62. $items['admin/config/system/cron']['title'] = 'Cron Settings';
  63. $items['admin/config/system/cron']['description'] = 'View and manage cron table';
  64. $items['admin/config/system/cron']['page callback'] = 'elysia_cron_admin_page';
  65. $items['admin/config/system/cron']['access callback'] = 'elysia_cron_access';
  66. $items['admin/config/system/cron']['access arguments'] = array('view elysia_cron');
  67. $items['admin/config/system/cron']['file'] = NULL;
  68. $items['admin/reports/status/run-cron']['page callback'] = 'elysia_cron_run_manually';
  69. $items['admin/reports/status/run-cron']['file'] = NULL;
  70. }
  71. /**
  72. * Check access to operation inside elysia cron module.
  73. *
  74. * Permission have nested structure, for example: "administer elysia_cron" allow
  75. * to do anything: view, execute and configure cron jobs.
  76. *
  77. * @param string $perm
  78. * Permission name.
  79. *
  80. * @return bool
  81. * Access granted or not.
  82. */
  83. function elysia_cron_access($perm) {
  84. $access = FALSE;
  85. switch ($perm) {
  86. case 'administer elysia_cron':
  87. $access = user_access($perm);
  88. break;
  89. case 'execute elysia_cron':
  90. $access = user_access($perm) || user_access('administer elysia_cron');
  91. break;
  92. case 'view elysia_cron';
  93. $access = user_access($perm) || user_access('execute elysia_cron') || user_access('administer elysia_cron');
  94. }
  95. return $access;
  96. }
  97. /**
  98. * Implements hook_permission().
  99. */
  100. function elysia_cron_permission() {
  101. return array(
  102. 'administer elysia_cron' => array(
  103. 'title' => t('Administer elysia cron'),
  104. 'description' => t('Perform changes to cron jobs timings, disable cron or single jobs and access cron execution statistics'),
  105. 'restrict access' => TRUE,
  106. ),
  107. 'execute elysia_cron' => array(
  108. 'title' => t('Execute elysia cron jobs'),
  109. 'description' => t('Allow users to view statistics, execution status and do manually execute cron jobs'),
  110. ),
  111. 'view elysia_cron' => array(
  112. 'title' => t('View elysia cron stats'),
  113. 'description' => t('Allows users to view statistics and execution status of cron jobs'),
  114. ),
  115. );
  116. }
  117. /**
  118. * Implements hook_exit().
  119. */
  120. function elysia_cron_exit() {
  121. global $_elysia_cron_exit_phase;
  122. $_elysia_cron_exit_phase = TRUE;
  123. }
  124. /**
  125. * Implements hook_cron().
  126. *
  127. * Hook cron is invoked only by standard drupal cron.
  128. * It's used to replace drupal cron.
  129. */
  130. function elysia_cron_cron() {
  131. global $_elysia_cron_exit_phase, $_elysia_cron_drush;
  132. // First cron run is executed in standard drupal way.
  133. // This is to enable the use of install profiles.
  134. if (variable_get('cron_last', 0) <= variable_get('install_time', 0)) {
  135. return;
  136. }
  137. // If cron has been executed via "drush core-cron" or any other custom drush
  138. // command then we run internal cron handler which is designed to handle
  139. // cron executions from drush.
  140. if (function_exists('elysia_cron_drush_detect') && elysia_cron_drush_detect()) {
  141. elysia_cron_drush_invoke();
  142. }
  143. // If the path is 'admin/*', or if the user is not anonymous,
  144. // this is a manual cron run (probably by admin/logs/status),
  145. // but not if we are in the exit phase (= this a "poormanscron" run).
  146. $manual_run = empty($_elysia_cron_exit_phase) && ((arg(0) == 'admin') || !empty($GLOBALS['user']->uid));
  147. $result = elysia_cron_run($manual_run);
  148. if ($manual_run) {
  149. if ($result) {
  150. elysia_cron_message('Cron ran successfully');
  151. }
  152. else {
  153. elysia_cron_message('Cron run failed, disabled or nothing to do');
  154. }
  155. // In manual execution it's better to set cron_last variable in standard way
  156. // (so the user sees the execution time updates).
  157. // This invalidates variable cache, but it's a manual execution,
  158. // it should be not a great performance problem.
  159. if (empty($_elysia_cron_drush)) {
  160. variable_set('cron_last', time());
  161. }
  162. drupal_goto('admin/reports/status');
  163. }
  164. // If we are in "poormanscron" mode it's better to force setting of cron_last.
  165. // This invalidates variable cache, but is needed for right execution check.
  166. // @see system_run_automated_cron() in system.module
  167. if (!empty($_elysia_cron_exit_phase)) {
  168. variable_set('cron_last', time());
  169. }
  170. drupal_exit();
  171. }
  172. /**
  173. * Implements hook_cron().
  174. *
  175. * I use help section for admin/build/modules page to check if elysia_cron
  176. * is the module with the smallest weight.
  177. * If it's not i'll set it and print a message.
  178. */
  179. function elysia_cron_help($section, $arg = FALSE) {
  180. if ($section == 'admin/modules') {
  181. $query = db_select('system', 's');
  182. $query->addExpression('MIN(weight)');
  183. $min = $query->condition('s.name', 'elysia_cron', '!=')
  184. ->execute()
  185. ->fetchField();
  186. $weight = db_select('system', 's')
  187. ->fields('s', array('weight'))
  188. ->condition('s.name', 'elysia_cron')
  189. ->execute()
  190. ->fetchField();
  191. if ($min <= $weight) {
  192. elysia_cron_message('Elysia cron module is not the module with the smallest weight (and it must be). Updating weight...');
  193. db_update('system')
  194. ->fields(array('weight' => $min - 1))
  195. ->condition('name', 'elysia_cron')
  196. ->execute();
  197. }
  198. }
  199. }
  200. // Variables managed by _ec_variable method,
  201. // because are setted during cron execution handling
  202. // (with standard variable_set this will invalidate variable
  203. // cache in EVERY cron clock).
  204. $GLOBALS['_ec_variables_allowed'] = array(
  205. 'elysia_cron_semaphore',
  206. 'elysia_cron_last_run',
  207. 'elysia_cron_last_channel',
  208. 'cron_semaphore',
  209. 'cron_last',
  210. );
  211. /**
  212. * Initialise global variables.
  213. */
  214. function _ec_variable_init() {
  215. global $_ec_variables, $_ec_variables_allowed;
  216. $_ec_variables = array();
  217. foreach ($_ec_variables_allowed as $name) {
  218. $_ec_variables[$name] = variable_get($name);
  219. }
  220. }
  221. /**
  222. * A substitute for variable_get to avoid cache management.
  223. *
  224. * Use ONLY for variables set during cron execution:
  225. * elysia_cron_semaphore, elysia_cron_last_run, elysia_cron_last_channel,
  226. * cron_semaphore, cron_last
  227. * WARN_UPGRADE.
  228. */
  229. function _ec_variable_get($name, $default) {
  230. global $_ec_variables, $_ec_variables_allowed;
  231. if (!in_array($name, $_ec_variables_allowed)) {
  232. elysia_cron_error('Wrong variable passed to _ec_variable_get: !var', array('!var' => $name), TRUE);
  233. return variable_get($name, $default);
  234. }
  235. if (!is_array($_ec_variables)) {
  236. _ec_variable_init();
  237. }
  238. // If there is a $GLOBALS['original_conf'] = $conf; at the end of settings.php
  239. // i consider it.
  240. global $_original_conf;
  241. if (isset($_original_conf[$name])) {
  242. return $_original_conf[$name];
  243. }
  244. if (isset($_ec_variables[$name])) {
  245. return $_ec_variables[$name];
  246. }
  247. return $default;
  248. }
  249. /**
  250. * A substitute for variable_set to avoid cache management.
  251. *
  252. * Use ONLY for variables set during cron execution:
  253. * elysia_cron_semaphore, elysia_cron_last_run, elysia_cron_last_channel,
  254. * cron_semaphore, cron_last.
  255. * WARN_UPGRADE.
  256. */
  257. function _ec_variable_set($name, $value) {
  258. global $_ec_variables, $_ec_variables_allowed;
  259. if (!in_array($name, $_ec_variables_allowed)) {
  260. elysia_cron_error('Wrong variable passed to _ec_variable_set: !var', array('!var' => $name), TRUE);
  261. variable_set($name, $value);
  262. }
  263. if (!is_array($_ec_variables)) {
  264. _ec_variable_init();
  265. }
  266. db_merge('variable')->key(array('name' => $name))->fields(array('value' => serialize($value)))->execute();
  267. $_ec_variables[$name] = $value;
  268. }
  269. /**
  270. * A substitute for variable_del to avoid cache management.
  271. *
  272. * Use ONLY for variables set during cron execution:
  273. * elysia_cron_semaphore, elysia_cron_last_run, elysia_cron_last_channel,
  274. * cron_semaphore, cron_last
  275. * WARN_UPGRADE.
  276. */
  277. function _ec_variable_del($name) {
  278. global $_ec_variables, $_ec_variables_allowed;
  279. if (!in_array($name, $_ec_variables_allowed)) {
  280. elysia_cron_error('Wrong variable passed to _ec_variable_del: !var', array('!var' => $name), TRUE);
  281. variable_del($name);
  282. return;
  283. }
  284. if (!is_array($_ec_variables)) {
  285. _ec_variable_init();
  286. }
  287. db_delete('variable')->condition('name', $name)->execute();
  288. unset($_ec_variables[$name]);
  289. }
  290. function _ec_get_name($name) {
  291. $maxlen = 120;
  292. if (strlen($name) < $maxlen) {
  293. return $name;
  294. }
  295. $border = ($maxlen - 32) / 2;
  296. return substr($name, 0, $border) . md5($name) . substr($name, -$border);
  297. }
  298. function elysia_cron_set($name, $channel = FALSE, $values = array()) {
  299. if ($channel) {
  300. $name = ':' . $name;
  301. }
  302. db_merge('elysia_cron')->key(array('name' => $name))->fields($values)->execute();
  303. global $_elysia_cron_db_cache;
  304. unset($_elysia_cron_db_cache[$name]);
  305. }
  306. function elysia_cron_get($name, $channel = FALSE, $key = FALSE, $default = FALSE, $refresh = FALSE) {
  307. global $_elysia_cron_db_cache;
  308. static $elysia_cron_defaults;
  309. if (!isset($elysia_cron_defaults)) {
  310. $elysia_cron_defaults = function_exists('elysia_cron_get_ctools_defaults') ? elysia_cron_get_ctools_defaults() : array();
  311. }
  312. if ($channel) {
  313. $name = ':' . $name;
  314. }
  315. if ($refresh || !isset($_elysia_cron_db_cache[$name])) {
  316. $_elysia_cron_db_cache[$name] = db_select('elysia_cron', 'ec')
  317. ->fields('ec', _elysia_cron_columns())
  318. ->condition('name', $name)
  319. ->execute()
  320. ->fetchAssoc();
  321. if (!$_elysia_cron_db_cache[$name] && isset($elysia_cron_defaults[$name])) {
  322. $_elysia_cron_db_cache[$name] = (array) $elysia_cron_defaults[$name];
  323. }
  324. elseif ($_elysia_cron_db_cache[$name] && isset($elysia_cron_defaults[$name])) {
  325. foreach ($elysia_cron_defaults[$name] as $k => $v) {
  326. if (!isset($_elysia_cron_db_cache[$name][$k]) || is_null($_elysia_cron_db_cache[$name][$k])) {
  327. $_elysia_cron_db_cache[$name][$k] = $v;
  328. }
  329. }
  330. }
  331. }
  332. 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];
  333. }
  334. /**
  335. * Get status of specified channel.
  336. *
  337. * @param string $channel
  338. * Channel name.
  339. * @param bool $default
  340. * Default value for channel status.
  341. * @param bool $refresh
  342. * If TRUE - fresh status will be get from database.
  343. *
  344. * @return bool
  345. * Channel status.
  346. */
  347. function elysia_cron_is_channel_disabled($channel, $default = FALSE, $refresh = FALSE) {
  348. // May be overridden by a static conf.
  349. if (isset($GLOBALS['conf'][$n = 'ecc_' . _ec_get_name($channel) . '_d'])) {
  350. return $GLOBALS['conf'][$n];
  351. }
  352. return elysia_cron_get($channel, TRUE, 'disable', $default, $refresh);
  353. }
  354. /**
  355. * Update channel status.
  356. *
  357. * @param string $channel
  358. * Channel name.
  359. * @param bool $value
  360. * New channel status:
  361. * TRUE - enabled
  362. * FALSE - disabled.
  363. */
  364. function elysia_cron_set_channel_disabled($channel, $value) {
  365. elysia_cron_set($channel, TRUE, array('disable' => $value ? 1 : 0));
  366. }
  367. /**
  368. * Reset channel status to default (disabled).
  369. *
  370. * @param string $channel
  371. * Channel name.
  372. */
  373. function elysia_cron_reset_channel_disabled($channel) {
  374. elysia_cron_set($channel, TRUE, array('disable' => 0));
  375. }
  376. /**
  377. * Get channel's rule.
  378. *
  379. * @param string $channel
  380. * Channel name.
  381. * @param string $default
  382. * Default rule.
  383. * @param bool $refresh
  384. * If TRUE - fresh status will be get from database.
  385. *
  386. * @return string
  387. * Formatted rule for specified channel.
  388. */
  389. function elysia_cron_get_channel_rule($channel, $default = '', $refresh = FALSE) {
  390. // May be overridden by a static conf.
  391. if (isset($GLOBALS['conf'][$n = 'ecc_' . _ec_get_name($channel) . '_rul'])) {
  392. return $GLOBALS['conf'][$n];
  393. }
  394. return elysia_cron_get($channel, TRUE, 'rule', $default, $refresh);
  395. }
  396. /**
  397. * Set new rule for channel.
  398. *
  399. * @param string $channel
  400. * Channel name.
  401. * @param string $rule
  402. * Crontab formatted rule.
  403. */
  404. function elysia_cron_set_channel_rule($channel, $rule) {
  405. elysia_cron_set($channel, TRUE, array('rule' => $rule));
  406. }
  407. /**
  408. * Reset channel's rule to default.
  409. *
  410. * @param string $channel
  411. * Channel name.
  412. */
  413. function elysia_cron_reset_channel_rule($channel) {
  414. elysia_cron_set($channel, TRUE, array('rule' => NULL));
  415. }
  416. /**
  417. * Check if channel is running now.
  418. *
  419. * @param string $channel
  420. * Channel name.
  421. * @param int $default
  422. * Default value.
  423. * @param bool $refresh
  424. * If TRUE - fresh status will be get from database.
  425. *
  426. * @return int
  427. * Timestamp from beginning of running or zero.
  428. */
  429. function elysia_cron_is_channel_running($channel, $default = 0, $refresh = FALSE) {
  430. return elysia_cron_get($channel, TRUE, 'running', $default, $refresh);
  431. }
  432. /**
  433. * Updated channel running value.
  434. *
  435. * @param string $channel
  436. * Channel name.
  437. * @param int $value
  438. * New running value.
  439. */
  440. function elysia_cron_set_channel_running($channel, $value) {
  441. elysia_cron_set($channel, TRUE, array('running' => $value));
  442. }
  443. /**
  444. * Get channel's last run value.
  445. *
  446. * @param string $channel
  447. * Channel name.
  448. * @param int $default
  449. * Default value.
  450. * @param bool $refresh
  451. * If TRUE - fresh status will be get from database.
  452. *
  453. * @return int
  454. * Last run timestamp or zero.
  455. *
  456. * @todo Not used, to delete?
  457. */
  458. function elysia_cron_get_channel_last_run($channel, $default = 0, $refresh = FALSE) {
  459. return elysia_cron_get($channel, TRUE, 'last_run', $default, $refresh);
  460. }
  461. /**
  462. * Set channel's last run value.
  463. *
  464. * @param string $channel
  465. * Channel name.
  466. * @param int $value
  467. * New last run timestamp.
  468. *
  469. * @todo Not used, to delete?
  470. */
  471. function elysia_cron_set_channel_last_run($channel, $value) {
  472. elysia_cron_set($channel, TRUE, array('last_run' => $value));
  473. }
  474. /**
  475. * Get channel's last aborted value.
  476. *
  477. * @param string $channel
  478. * Channel name.
  479. * @param int $default
  480. * Default value.
  481. * @param bool $refresh
  482. * If TRUE - fresh status will be get from database.
  483. *
  484. * @return int
  485. * Last aborted timestamp or zero.
  486. *
  487. * @todo Not used, to delete?
  488. */
  489. function elysia_cron_get_channel_last_aborted($channel, $default = 0, $refresh = FALSE) {
  490. return elysia_cron_get($channel, TRUE, 'last_aborted', $default, $refresh);
  491. }
  492. /**
  493. * Set channel's last aborted value.
  494. *
  495. * @param string $channel
  496. * Channel name.
  497. * @param int $value
  498. * New last aborted timestamp.
  499. *
  500. * @todo Not used, to delete?
  501. */
  502. function elysia_cron_set_channel_last_aborted($channel, $value) {
  503. elysia_cron_set($channel, TRUE, array('last_aborted' => $value ? 1 : 0));
  504. }
  505. /**
  506. * Get channel's about count.
  507. *
  508. * @param string $channel
  509. * Channel name.
  510. * @param int $default
  511. * Default value.
  512. * @param bool $refresh
  513. * If TRUE - fresh status will be get from database.
  514. *
  515. * @return int
  516. * Abort count for specified channel.
  517. */
  518. function elysia_cron_get_channel_abort_count($channel, $default = 0, $refresh = FALSE) {
  519. return elysia_cron_get($channel, TRUE, 'abort_count', $default, $refresh);
  520. }
  521. /**
  522. * Set channel's abort count.
  523. *
  524. * @param string $channel
  525. * Channel name.
  526. * @param int $value
  527. * New abort count.
  528. *
  529. * @todo Not used, to delete?
  530. */
  531. function elysia_cron_set_channel_abort_count($channel, $value) {
  532. elysia_cron_set($channel, TRUE, array('abort_count' => $value));
  533. }
  534. /**
  535. * Get channel's last about function.
  536. *
  537. * @param string $channel
  538. * Channel name.
  539. * @param string $default
  540. * Default value.
  541. * @param bool $refresh
  542. * If TRUE - fresh status will be get from database.
  543. *
  544. * @return string
  545. * Last abort function or empty string.
  546. *
  547. * @todo Not used, to delete?
  548. */
  549. function elysia_cron_get_channel_last_abort_function($channel, $default = '', $refresh = FALSE) {
  550. return elysia_cron_get($channel, TRUE, 'last_abort_function', $default, $refresh);
  551. }
  552. /**
  553. * Set channel's last abort function.
  554. *
  555. * @param string $channel
  556. * Channel name.
  557. * @param string $value
  558. * Last abort function name.
  559. *
  560. * @todo Not used, to delete?
  561. */
  562. function elysia_cron_set_channel_last_abort_function($channel, $value) {
  563. elysia_cron_set($channel, TRUE, array('last_abort_function' => $value));
  564. }
  565. /**
  566. * Grab statistics by channel.
  567. *
  568. * @param string $channel
  569. * Channel name.
  570. * @param bool $refresh
  571. * If TRUE - fresh status will be get from database.
  572. *
  573. * @return array
  574. * Statistics for specified channel.
  575. */
  576. function elysia_cron_get_channel_stats($channel, $refresh = FALSE) {
  577. return array(
  578. 'last_run' => elysia_cron_get($channel, TRUE, 'last_run', 0, $refresh),
  579. 'last_execution_time' => elysia_cron_get($channel, TRUE, 'last_execution_time', 0, $refresh),
  580. 'execution_count' => elysia_cron_get($channel, TRUE, 'execution_count', 0, $refresh),
  581. 'avg_execution_time' => elysia_cron_get($channel, TRUE, 'avg_execution_time', 0, $refresh),
  582. 'max_execution_time' => elysia_cron_get($channel, TRUE, 'max_execution_time', 0, $refresh),
  583. 'last_shutdown_time' => elysia_cron_get($channel, TRUE, 'last_shutdown_time', 0, $refresh),
  584. 'last_aborted' => elysia_cron_get($channel, TRUE, 'last_aborted', 0, $refresh),
  585. 'abort_count' => elysia_cron_get($channel, TRUE, 'abort_count', 0, $refresh),
  586. 'last_abort_function' => elysia_cron_get($channel, TRUE, 'last_abort_function', 0, ''),
  587. );
  588. }
  589. /**
  590. * Update channel's stats.
  591. *
  592. * @param string $channel
  593. * Channel name.
  594. * @param array $data
  595. * Associative array of values.
  596. */
  597. function elysia_cron_set_channel_stats($channel, array $data = array()) {
  598. elysia_cron_set($channel, TRUE, $data);
  599. }
  600. /**
  601. * Get formatted crontab rule for specified job.
  602. *
  603. * @param string $job
  604. * Job name.
  605. * @param string $default
  606. * Default rule.
  607. * @param bool $refresh
  608. * If TRUE - fresh status will be get from database.
  609. *
  610. * @return string
  611. * Formatted job rule.
  612. */
  613. function elysia_cron_get_job_rule($job, $default = '', $refresh = FALSE) {
  614. // May be overridden by a static conf.
  615. if (isset($GLOBALS['conf'][$n = 'ec_' . _ec_get_name($job) . '_rul'])) {
  616. return $GLOBALS['conf'][$n];
  617. }
  618. return elysia_cron_get($job, FALSE, 'rule', $default, $refresh);
  619. }
  620. /**
  621. * Set formatted crontab rule for specified job.
  622. *
  623. * @param string $job
  624. * Job name.
  625. * @param string $value
  626. * New crontab rule for job.
  627. */
  628. function elysia_cron_set_job_rule($job, $value) {
  629. elysia_cron_set($job, FALSE, array('rule' => $value));
  630. }
  631. /**
  632. * Reset crontab job rule to default.
  633. *
  634. * @param string $job
  635. * Job name.
  636. */
  637. function elysia_cron_reset_job_rule($job) {
  638. elysia_cron_set($job, FALSE, array('rule' => NULL));
  639. }
  640. /**
  641. * Get weight of specified job.
  642. *
  643. * @param string $job
  644. * Job name.
  645. * @param string $default
  646. * Default weight.
  647. * @param bool $refresh
  648. * If TRUE - fresh status will be get from database.
  649. *
  650. * @return string
  651. * Job weight or empty string.
  652. */
  653. function elysia_cron_get_job_weight($job, $default = '', $refresh = FALSE) {
  654. // May be overridden by a static conf.
  655. if (isset($GLOBALS['conf'][$n = 'ec_' . _ec_get_name($job) . '_w'])) {
  656. return $GLOBALS['conf'][$n];
  657. }
  658. return elysia_cron_get($job, FALSE, 'weight', $default, $refresh);
  659. }
  660. /**
  661. * Set weight specified job.
  662. *
  663. * @param string $job
  664. * Job name.
  665. * @param string $value
  666. * New weight for job.
  667. */
  668. function elysia_cron_set_job_weight($job, $value) {
  669. elysia_cron_set($job, FALSE, array('weight' => $value));
  670. }
  671. /**
  672. * Reset job weight to default.
  673. *
  674. * @param string $job
  675. * Job name.
  676. */
  677. function elysia_cron_reset_job_weight($job) {
  678. elysia_cron_set($job, FALSE, array('weight' => NULL));
  679. }
  680. function elysia_cron_is_job_disabled($job, $default = FALSE, $refresh = FALSE) {
  681. // May be overridden by a static conf.
  682. if (isset($GLOBALS['conf'][$n = 'ec_' . _ec_get_name($job) . '_d'])) {
  683. return $GLOBALS['conf'][$n];
  684. }
  685. return elysia_cron_get($job, FALSE, 'disable', $default, $refresh);
  686. }
  687. function elysia_cron_set_job_disabled($job, $value) {
  688. elysia_cron_set($job, FALSE, array('disable' => $value ? 1 : 0));
  689. }
  690. function elysia_cron_reset_job_disabled($job) {
  691. elysia_cron_set($job, FALSE, array('disable' => NULL));
  692. }
  693. function elysia_cron_get_job_channel($job, $default = '', $refresh = FALSE) {
  694. // May be overridden by a static conf.
  695. if (isset($GLOBALS['conf'][$n = 'ec_' . _ec_get_name($job) . '_c'])) {
  696. $c = $GLOBALS['conf'][$n];
  697. }
  698. else {
  699. // In this place, 'context' means 'channel'.
  700. $c = elysia_cron_get($job, FALSE, 'context', $default, $refresh);
  701. }
  702. return !$c ? $default : $c;
  703. }
  704. function elysia_cron_set_job_channel($job, $value) {
  705. // In this place, 'context' means 'channel'.
  706. elysia_cron_set($job, FALSE, array('context' => $value));
  707. }
  708. function elysia_cron_reset_job_channel($job) {
  709. // In this place, 'context' means 'channel'.
  710. elysia_cron_set($job, FALSE, array('context' => NULL));
  711. }
  712. function elysia_cron_is_job_running($job, $default = 0, $refresh = FALSE) {
  713. return elysia_cron_get($job, FALSE, 'running', $default, $refresh);
  714. }
  715. function elysia_cron_set_job_running($job, $value) {
  716. elysia_cron_set($job, FALSE, array('running' => $value));
  717. }
  718. function elysia_cron_get_job_last_run($job, $default = 0, $refresh = FALSE) {
  719. return elysia_cron_get($job, FALSE, 'last_run', $default, $refresh);
  720. }
  721. function elysia_cron_set_job_last_run($job, $value) {
  722. elysia_cron_set($job, FALSE, array('last_run' => $value));
  723. }
  724. function elysia_cron_get_job_stats($job, $refresh = FALSE) {
  725. return array(
  726. 'last_run' => elysia_cron_get($job, FALSE, 'last_run', 0, $refresh),
  727. 'last_execution_time' => elysia_cron_get($job, FALSE, 'last_execution_time', 0, $refresh),
  728. 'execution_count' => elysia_cron_get($job, FALSE, 'execution_count', 0, $refresh),
  729. 'avg_execution_time' => elysia_cron_get($job, FALSE, 'avg_execution_time', 0, $refresh),
  730. 'max_execution_time' => elysia_cron_get($job, FALSE, 'max_execution_time', 0, $refresh),
  731. );
  732. }
  733. function elysia_cron_set_job_stats(
  734. $job,
  735. $last_run = -1,
  736. $last_execution_time = -1,
  737. $execution_count = -1,
  738. $avg_execution_time = -1,
  739. $max_execution_time = -1,
  740. $data = array()
  741. ) {
  742. if ($last_run != -1) {
  743. $data['last_run'] = $last_run;
  744. }
  745. if ($last_execution_time != -1) {
  746. $data['last_execution_time'] = $last_execution_time;
  747. }
  748. if ($execution_count != -1) {
  749. $data['execution_count'] = $execution_count;
  750. }
  751. if ($avg_execution_time != -1) {
  752. $data['avg_execution_time'] = $avg_execution_time;
  753. }
  754. if ($max_execution_time != -1) {
  755. $data['max_execution_time'] = $max_execution_time;
  756. }
  757. elysia_cron_set($job, FALSE, $data);
  758. }
  759. function elysia_cron_last_channel() {
  760. return _ec_variable_get('elysia_cron_last_channel', '');
  761. }
  762. function elysia_cron_set_last_channel($channel) {
  763. _ec_variable_set('elysia_cron_last_channel', $channel);
  764. }
  765. function elysia_cron_reset_stats() {
  766. global $_elysia_cron_settings, $_elysia_cron_settings_by_channel;
  767. elysia_cron_initialize();
  768. foreach ($_elysia_cron_settings as $job => $conf) {
  769. elysia_cron_set_job_stats($job, 0, 0, 0, 0, 0);
  770. }
  771. $channel_reset_data = array(
  772. 'last_run' => 0,
  773. 'last_execution_time' => 0,
  774. 'execution_count' => 0,
  775. 'avg_execution_time' => 0,
  776. 'max_execution_time' => 0,
  777. 'last_shutdown_time' => 0,
  778. 'last_aborted' => 0,
  779. 'abort_count' => 0,
  780. 'last_abort_function' => 0,
  781. );
  782. foreach ($_elysia_cron_settings_by_channel as $channel => $conf) {
  783. elysia_cron_set_channel_stats($channel, $channel_reset_data);
  784. }
  785. }
  786. /*******************************************************************************
  787. * INTERNAL
  788. *
  789. * WARN: Below this point the word "context" should be avoided (use channel)
  790. * Disabled should always be referenced as "disabled" (in db is "disable" for
  791. * compatibility with Ctools )
  792. *******************************************************************************/
  793. /**
  794. * Sends a standard message to user.
  795. *
  796. * Drush see it.
  797. */
  798. function elysia_cron_message($message, $vars = array()) {
  799. global $_elysia_cron_drush;
  800. if (empty($_elysia_cron_drush)) {
  801. drupal_set_message(t($message, $vars));
  802. }
  803. else {
  804. drush_log(strip_tags(dt($message, $vars)), 'ok');
  805. }
  806. }
  807. /**
  808. * Send an error message to user (and log also an error).
  809. *
  810. * Drush see it (even if $skip_user_message)
  811. */
  812. function elysia_cron_error($message, $vars = array(), $skip_user_message = FALSE) {
  813. global $_elysia_cron_drush;
  814. if (empty($_elysia_cron_drush) && !$skip_user_message) {
  815. drupal_set_message(t($message, $vars), 'error');
  816. }
  817. /* @todo remove following code if not necessary.
  818. if (!empty($_elysia_cron_drush)) {
  819. drush_log(strip_tags(dt($message, $vars)), "error");
  820. }*/
  821. watchdog('cron', $message, $vars, WATCHDOG_ERROR);
  822. }
  823. /**
  824. * Log a debug in watchdog (do not print an user message).
  825. *
  826. * Drush see it in verbose mode.
  827. */
  828. function elysia_cron_debug($message, $vars = array(), $type = WATCHDOG_NOTICE) {
  829. global $_elysia_cron_drush;
  830. if ($type < WATCHDOG_NOTICE || variable_get('elysia_cron_debug_messages', 0)) {
  831. watchdog('cron', $message, $vars, $type);
  832. }
  833. if (!empty($_elysia_cron_drush) && $_elysia_cron_drush >= 2 && ($type >= WATCHDOG_NOTICE || drush_get_option("verbose", FALSE))) {
  834. if ($type >= WATCHDOG_NOTICE) {
  835. drush_print(strip_tags(dt($message, $vars)));
  836. }
  837. else {
  838. drush_log(strip_tags(dt($message, $vars)), $type == WATCHDOG_ERROR ? "error" : (($type == WATCHDOG_ERROR ? "warning" : "notice")));
  839. }
  840. }
  841. }
  842. /**
  843. * Log a warning (do not print an user message).
  844. *
  845. * Drush see it in verbose mode.
  846. */
  847. function elysia_cron_warning($message, $vars = array()) {
  848. elysia_cron_debug($message, $vars, WATCHDOG_WARNING);
  849. }
  850. function elysia_cron_decode_script($text, $apply = TRUE) {
  851. global $_elysia_cron_settings;
  852. $lines = explode(PHP_EOL, $text);
  853. $lastcomment = '';
  854. $errors = array();
  855. foreach ($lines as $line) {
  856. $line = trim($line);
  857. if (!empty($line)) {
  858. if ($line{0} == '#') {
  859. $lastcomment = trim(substr($line, 1));
  860. }
  861. elseif (preg_match('/^(-[ ]*|)([0-9*,\/-]+[ ]+[0-9*,\/-]+[ ]+[0-9*,\/-]+[ ]+[0-9*,\/-]+[ ]+[0-9*,\/-]+)[ ]+((?:ctx|ch):([a-zA-Z0-9_-]+)[ ]+|)([^(:]+)(\(.*\);|)$/', $line, $r)) {
  862. $c = array(
  863. 'disabled' => !empty($r[1]),
  864. 'rule' => $r[2],
  865. 'description' => $lastcomment,
  866. 'channel' => $r[4] ? $r[4] : 'default',
  867. );
  868. $lastcomment = '';
  869. if (empty($r[6])) {
  870. if (!isset($_elysia_cron_settings[$r[5]])) {
  871. // Referring a module function that not exists.
  872. $errors[] = $line;
  873. continue;
  874. }
  875. $name = $r[5];
  876. }
  877. else {
  878. // Custom expression, generate a unique name.
  879. $postfix = '';
  880. while (isset($_elysia_cron_settings[$r[5] . $postfix])) {
  881. $postfix = ($postfix ? $postfix : 0) + 1;
  882. }
  883. $name = $r[5] . $postfix;
  884. $c['expression'] = $r[5] . $r[6];
  885. }
  886. if ($apply) {
  887. $_elysia_cron_settings[$name] = isset($_elysia_cron_settings[$name]) ? array_merge($_elysia_cron_settings[$name], $c) : $c;
  888. }
  889. }
  890. else {
  891. $errors[] = $line;
  892. }
  893. }
  894. else {
  895. $lastcomment = '';
  896. }
  897. }
  898. return count($errors) ? $errors : FALSE;
  899. }
  900. /**
  901. * Fetch information about cron jobs from modules.
  902. *
  903. * @return array
  904. * Array with jobs information.
  905. */
  906. function elysia_cron_module_jobs() {
  907. static $jobs;
  908. if (!isset($jobs)) {
  909. $jobs = array();
  910. foreach (module_implements('cron') as $module) {
  911. if ($module != 'elysia_cron') {
  912. $jobs[$module . '_cron'] = array(
  913. 'module' => $module,
  914. 'callback' => $module . '_cron',
  915. 'arguments' => array(),
  916. );
  917. }
  918. }
  919. foreach (module_implements('cronapi') as $module) {
  920. $function = $module . '_cronapi';
  921. if (function_exists($function)) {
  922. $job_list = $function('list');
  923. if (is_array($job_list)) {
  924. foreach ($job_list as $job => $data) {
  925. if (is_array($data)) {
  926. $jobs[$job] = $data;
  927. }
  928. else {
  929. // Compatibility with v1.x settings.
  930. $jobs[$job] = array(
  931. 'description' => $data,
  932. 'rule' => ($rule = $function('rule', $job)) ? $rule : FALSE,
  933. 'weight' => ($weight = $function('weight', $job)) ? $weight : 0,
  934. );
  935. }
  936. $jobs[$job] = $jobs[$job] + array(
  937. 'module' => $module,
  938. 'callback' => $job,
  939. 'arguments' => array(),
  940. );
  941. }
  942. }
  943. }
  944. }
  945. if (function_exists('drupal_alter')) {
  946. drupal_alter('cron', $jobs);
  947. }
  948. }
  949. return $jobs;
  950. }
  951. function elysia_cron_initialize($skipscript = FALSE) {
  952. global $_elysia_cron_settings, $_elysia_cron_settings_by_channel;
  953. if (empty($_elysia_cron_settings)) {
  954. $_elysia_cron_settings = array();
  955. $_elysia_cron_settings_by_channel = array();
  956. foreach (elysia_cron_module_jobs() as $job => $jobpars) {
  957. $channel = elysia_cron_get_job_channel($job, 'default');
  958. $defrule = !empty($jobpars['rule']) ? $jobpars['rule'] : elysia_cron_get_channel_rule($channel);
  959. if (!$defrule) {
  960. $defrule = variable_get('elysia_cron_default_rule', '0 * * * *');
  961. }
  962. $defweight = !empty($jobpars['weight']) ? $jobpars['weight'] : 0;
  963. if (!is_numeric($defweight)) {
  964. $defweight = 0;
  965. }
  966. $_elysia_cron_settings[$job] = array(
  967. 'key' => $job,
  968. 'channel' => $channel,
  969. 'rule' => elysia_cron_get_job_rule($job, $defrule),
  970. 'default_rule' => $defrule,
  971. 'weight' => elysia_cron_get_job_weight($job, $defweight),
  972. 'default_weight' => $defweight,
  973. 'disabled' => elysia_cron_is_job_disabled($job),
  974. 'running' => elysia_cron_is_job_running($job),
  975. ) + $jobpars;
  976. }
  977. if (!$skipscript) {
  978. $script = variable_get('elysia_cron_script', FALSE);
  979. if ($script) {
  980. elysia_cron_decode_script($script);
  981. }
  982. }
  983. uasort($_elysia_cron_settings, '_elysia_cron_sort');
  984. foreach ($_elysia_cron_settings as $job => &$conf) {
  985. $stats = elysia_cron_get_job_stats($job);
  986. foreach ($stats as $sk => $sv) {
  987. $conf[$sk] = $sv;
  988. }
  989. $_elysia_cron_settings_by_channel[$conf['channel']][$job] = &$_elysia_cron_settings[$job];
  990. }
  991. foreach ($_elysia_cron_settings_by_channel as $channel => $data) {
  992. uasort($_elysia_cron_settings_by_channel[$channel], '_elysia_cron_sort');
  993. $_elysia_cron_settings_by_channel[$channel]['#data'] = elysia_cron_get_channel_stats($channel);
  994. $_elysia_cron_settings_by_channel[$channel]['#data']['disabled'] = elysia_cron_is_channel_disabled($channel);
  995. }
  996. }
  997. }
  998. function _elysia_cron_sort($a, $b) {
  999. if ((isset($a['weight']) ? $a['weight'] : 0) == (isset($b['weight']) ? $b['weight'] : 0)) {
  1000. return strcmp((isset($a['key']) ? $a['key'] : ''), (isset($b['key']) ? $b['key'] : ''));
  1001. }
  1002. return (isset($a['weight']) ? $a['weight'] : 0) - (isset($b['weight']) ? $b['weight'] : 0);
  1003. }
  1004. /**
  1005. * Prepare system for a cron execution.
  1006. *
  1007. * This should be called at the start of a cron execution:
  1008. * prepare_run
  1009. * lock_env
  1010. * look for channel/jobs ready for execution and change internal states ...
  1011. * unlock_env
  1012. * before_execution
  1013. * .. execute channel/jobs ..
  1014. * after_execution
  1015. * unprepare_run.
  1016. */
  1017. function elysia_cron_prepare_run($manual_run, $start = TRUE) {
  1018. static $original_user;
  1019. if ($start) {
  1020. // Allow execution to continue even if the request gets canceled.
  1021. @ignore_user_abort(TRUE);
  1022. // Try to allocate enough time to run all the hook_cron implementations.
  1023. if (!ini_get('safe_mode') && _elysia_cron_function_available('set_time_limit')) {
  1024. @set_time_limit(variable_get('elysia_cron_time_limit', 240));
  1025. }
  1026. // Prevent session information from being saved while cron is running.
  1027. drupal_save_session(FALSE);
  1028. // Force the current user to anonymous to ensure consistent permissions on
  1029. // cron runs (only if run by interface).
  1030. if ($manual_run) {
  1031. $original_user = $GLOBALS['user'];
  1032. $GLOBALS['user'] = drupal_anonymous_user();
  1033. }
  1034. }
  1035. else {
  1036. if ($manual_run) {
  1037. // Restore the user.
  1038. $GLOBALS['user'] = $original_user;
  1039. /*if (EC_DRUPAL_VERSION >= 7) {
  1040. drupal_save_session(TRUE);
  1041. }*/
  1042. }
  1043. }
  1044. }
  1045. /**
  1046. * Call this after a cron execution, prepared with elysia_cron_prepare_run()
  1047. *
  1048. * @see: elysia_cron_prepare_run()
  1049. */
  1050. function elysia_cron_unprepare_run($manual_run) {
  1051. elysia_cron_prepare_run($manual_run, FALSE);
  1052. }
  1053. /**
  1054. * Use this before checking and modifying environment variables.
  1055. *
  1056. * @see: elysia_cron_prepare_run()
  1057. */
  1058. function elysia_cron_lock_env($channel = NULL) {
  1059. $execute = TRUE;
  1060. $semaphore_name = elysia_cron_build_semaphore_name($channel);
  1061. if (!lock_acquire($semaphore_name, 240)) {
  1062. elysia_cron_warning('Attempting to re-run cron while it is already running.');
  1063. $execute = FALSE;
  1064. }
  1065. return $execute;
  1066. }
  1067. /**
  1068. * Unlock system locked with elysia_cron_lock_env.
  1069. *
  1070. * @see: elysia_cron_prepare_run().
  1071. */
  1072. function elysia_cron_unlock_env($channel = NULL) {
  1073. $semaphore_name = elysia_cron_build_semaphore_name($channel);
  1074. lock_release($semaphore_name);
  1075. }
  1076. /**
  1077. * Return semaphore name by channel.
  1078. *
  1079. * @param string|null $channel
  1080. * Channel name or NULL if channel not set.
  1081. *
  1082. * @return string
  1083. * Semaphore name trimmed by 255 chars length.
  1084. */
  1085. function elysia_cron_build_semaphore_name($channel) {
  1086. $semaphore_name = 'elysia_cron_semaphore';
  1087. if (isset($channel)) {
  1088. $semaphore_name .= ':' . $channel;
  1089. }
  1090. return drupal_substr($semaphore_name, 0, 255);
  1091. }
  1092. /**
  1093. * Public function to invoke a complete cron_run.
  1094. *
  1095. * @param bool $manual_run
  1096. * Consider launched by a user command
  1097. * (don't check for key/ip, protect current user...).
  1098. * @param bool $ignore_disable
  1099. * Run the channel (and all it's jobs) even if disabled.
  1100. * @param bool $ignore_time
  1101. * Run channel (and all it's jobs) job even if not ready.
  1102. * @param bool $ignore_running
  1103. * Run the channel (and all it's jobs) even if already running.
  1104. */
  1105. function elysia_cron_run($manual_run = FALSE, $ignore_disable = FALSE, $ignore_time = FALSE, $ignore_running = FALSE) {
  1106. global $_elysia_cron_exit_phase;
  1107. // If DISABLED block the execution.
  1108. if (!$ignore_disable && variable_get('elysia_cron_disabled', FALSE)) {
  1109. elysia_cron_debug('Cron globally disabled, skipping run');
  1110. return;
  1111. }
  1112. if (!empty($_elysia_cron_exit_phase)) {
  1113. // We on "poormanscron" mode,
  1114. // not necessary to do checks for cron_key or host or permission.
  1115. }
  1116. elseif (!$manual_run) {
  1117. // Check for CRON_KEY or ALLOWED_HOSTS.
  1118. if (!drupal_is_cli()) {
  1119. $cron_key = variable_get('cron_key', '');
  1120. if ($cron_key && (empty($_GET['cron_key']) || $_GET['cron_key'] != $cron_key)) {
  1121. elysia_cron_debug('Cron key mismatch, skipping run');
  1122. return;
  1123. }
  1124. $allowed_hosts = variable_get('elysia_cron_allowed_hosts', FALSE);
  1125. if ($allowed_hosts && !in_array(ip_address(), explode(',', $allowed_hosts))) {
  1126. elysia_cron_debug('Cron ip address mismatch, skipping run');
  1127. return;
  1128. }
  1129. }
  1130. }
  1131. elseif (!elysia_cron_access('execute elysia_cron')) {
  1132. elysia_cron_debug('Access denied for cron launching');
  1133. return;
  1134. }
  1135. elysia_cron_prepare_run($manual_run);
  1136. _ec_variable_set('elysia_cron_last_run', time());
  1137. _ec_variable_set('cron_last', time());
  1138. if ($execute = elysia_cron_lock_env()) {
  1139. elysia_cron_initialize();
  1140. $available_channel = elysia_cron_run_available_channel($ignore_disable, $ignore_time, $ignore_running);
  1141. if ($available_channel) {
  1142. // There are jobs ready to be executed
  1143. // elysia_cron_internal_execute_channel calls elysia_cron_unlock_env.
  1144. elysia_cron_internal_execute_channel($available_channel['name'], $available_channel['jobs'], $ignore_running);
  1145. }
  1146. else {
  1147. // No jobs should be executed, i must unlock cron semaphore.
  1148. elysia_cron_unlock_env();
  1149. elysia_cron_debug('No channels ready to be executed, skipping cron.');
  1150. }
  1151. }
  1152. elysia_cron_unprepare_run($manual_run);
  1153. return $execute;
  1154. }
  1155. /**
  1156. * Menu callback: run cron manually.
  1157. */
  1158. function elysia_cron_run_manually() {
  1159. // Run cron manually
  1160. if (elysia_cron_run(TRUE)) {
  1161. drupal_set_message(t('Cron ran successfully.'));
  1162. }
  1163. else {
  1164. drupal_set_message(t('Cron run failed.'), 'error');
  1165. }
  1166. drupal_goto('admin/reports/status');
  1167. }
  1168. /**
  1169. * Public function to execute all jobs in a channel.
  1170. *
  1171. * @param bool $ignore_disable
  1172. * Run the channel (and all it's jobs) even if disabled.
  1173. * @param bool $ignore_time
  1174. * Run channel (and all it's jobs) job even if not ready.
  1175. * @param bool $ignore_running
  1176. * Run the channel (and all it's jobs) even if already running.
  1177. *
  1178. * @return bool
  1179. * Result of execution.
  1180. */
  1181. function elysia_cron_run_channel($channel, $ignore_disable = FALSE, $ignore_time = FALSE, $ignore_running = FALSE) {
  1182. global $_elysia_cron_settings_by_channel;
  1183. // Always $manual_run.
  1184. elysia_cron_prepare_run(TRUE);
  1185. if ($execute = elysia_cron_lock_env($channel)) {
  1186. elysia_cron_initialize();
  1187. $jobs = FALSE;
  1188. if (isset($_elysia_cron_settings_by_channel[$channel])) {
  1189. if ($ignore_disable || empty($_elysia_cron_settings_by_channel[$channel]['#data']['disabled'])) {
  1190. $jobs = elysia_cron_check_run_channel($channel, $ignore_disable, $ignore_time, $ignore_running);
  1191. if ($jobs && count($jobs)) {
  1192. // elysia_cron_internal_execute_channel calls elysia_cron_unlock_env.
  1193. elysia_cron_internal_execute_channel($channel, $jobs, $ignore_running);
  1194. }
  1195. else {
  1196. elysia_cron_debug('Channel already running or no jobs ready to be executed, skipping');
  1197. }
  1198. }
  1199. else {
  1200. elysia_cron_warning('Channel is disabled, skipping');
  1201. }
  1202. }
  1203. else {
  1204. elysia_cron_warning('Channel not found, skipping');
  1205. }
  1206. if (!$jobs) {
  1207. // No jobs should be executed, i must unlock cron semaphore.
  1208. elysia_cron_unlock_env();
  1209. }
  1210. }
  1211. elysia_cron_unprepare_run(TRUE);
  1212. return $execute;
  1213. }
  1214. /**
  1215. * Public function to execute a single job.
  1216. *
  1217. * @param bool $ignore_disable
  1218. * Run the job even if disabled.
  1219. * @param bool $ignore_time
  1220. * Run the job even if not ready.
  1221. * @param bool $ignore_running
  1222. * Run the job even if already running.
  1223. */
  1224. function elysia_cron_run_job($job, $ignore_disable = FALSE, $ignore_time = FALSE, $ignore_running = FALSE) {
  1225. global $_cron_completed, $_cron_executing_job, $_elysia_cron_settings;
  1226. elysia_cron_initialize();
  1227. if (isset($_elysia_cron_settings[$job])) {
  1228. if (elysia_cron_should_run($_elysia_cron_settings[$job], -1, $ignore_disable, $ignore_time)) {
  1229. if ($ignore_running || !elysia_cron_check_run_job($job)) {
  1230. $_cron_completed = FALSE;
  1231. $_cron_executing_job = $job;
  1232. // Register shutdown callback.
  1233. register_shutdown_function('elysia_cron_run_job_cleanup');
  1234. elysia_cron_internal_execute_job($job);
  1235. $_cron_completed = TRUE;
  1236. elysia_cron_message('Job executed');
  1237. }
  1238. else {
  1239. elysia_cron_debug('Job is already running, skipping');
  1240. }
  1241. }
  1242. else {
  1243. elysia_cron_debug('Job is disabled or not ready to be executed, skipping');
  1244. }
  1245. }
  1246. else {
  1247. elysia_cron_warning('Job not found, skipping');
  1248. }
  1249. }
  1250. function elysia_cron_run_job_cleanup() {
  1251. global $_cron_completed, $_cron_executing_job;
  1252. if ($_cron_completed) {
  1253. return;
  1254. }
  1255. // See if the semaphore is still locked.
  1256. if (elysia_cron_is_job_running($_cron_executing_job)) {
  1257. elysia_cron_warning('Unexpected termination of cron job %job manually started, aborted.', array('%job' => $_cron_executing_job));
  1258. elysia_cron_set_job_running($_cron_executing_job, 0);
  1259. }
  1260. }
  1261. /**
  1262. * Internal function to execute all jobs in a channel.
  1263. *
  1264. * Function elysia_cron_lock_env() must be called BEFORE calling this method.
  1265. */
  1266. function elysia_cron_internal_execute_channel($channel, $jobs, $ignore_running = FALSE) {
  1267. global $_elysia_cron_current_channel, $_cron_completed, $_cron_completed_time;
  1268. elysia_cron_debug('Cron channel %channel run started.', array('%channel' => $channel));
  1269. $_elysia_cron_current_channel = $channel;
  1270. elysia_cron_set($_elysia_cron_current_channel, TRUE, array(
  1271. 'running' => time(),
  1272. 'last_run' => time(),
  1273. ));
  1274. // Register shutdown callback.
  1275. register_shutdown_function('elysia_cron_internal_execute_channel_cleanup');
  1276. // Now I can unlock cron semaphore.
  1277. elysia_cron_unlock_env();
  1278. foreach ($jobs as $job) {
  1279. if ($ignore_running || !elysia_cron_check_run_job($job)) {
  1280. elysia_cron_internal_execute_job($job);
  1281. }
  1282. }
  1283. $_cron_completed = TRUE;
  1284. $_cron_completed_time = time();
  1285. // Cron is really completed after shutdown functions.
  1286. register_shutdown_function('elysia_cron_internal_execute_channel_completed');
  1287. }
  1288. /**
  1289. * Internal function to execute a single job.
  1290. */
  1291. function elysia_cron_internal_execute_job($job) {
  1292. global $_elysia_cron_settings;
  1293. elysia_cron_debug('Cron job %job started.', array('%job' => $job));
  1294. $time = time();
  1295. elysia_cron_set($job, FALSE, array(
  1296. 'running' => $time,
  1297. 'last_run' => $time,
  1298. ));
  1299. try {
  1300. if (!empty($_elysia_cron_settings[$job]['file'])) {
  1301. $file_path = !empty($_elysia_cron_settings[$job]['file path']) ? $_elysia_cron_settings[$job]['file path'] : drupal_get_path('module', $_elysia_cron_settings[$job]['module']);
  1302. $file_path .= DIRECTORY_SEPARATOR . $_elysia_cron_settings[$job]['file'];
  1303. include_once $file_path;
  1304. }
  1305. if (!empty($_elysia_cron_settings[$job]['expression'])) {
  1306. eval($_elysia_cron_settings[$job]['expression']);
  1307. }
  1308. elseif (!empty($_elysia_cron_settings[$job]['callback']) && is_callable($_elysia_cron_settings[$job]['callback'])) {
  1309. call_user_func_array($_elysia_cron_settings[$job]['callback'], $_elysia_cron_settings[$job]['arguments']);
  1310. }
  1311. else {
  1312. $function = $_elysia_cron_settings[$job]['module'] . '_cronapi';
  1313. $arguments = array('execute', $job);
  1314. if (is_callable($function)) {
  1315. call_user_func_array($function, $arguments);
  1316. }
  1317. else {
  1318. elysia_cron_error('Execution of ' . $job . ' failed, can\'t find function!', array(), TRUE);
  1319. }
  1320. }
  1321. }
  1322. catch (Exception $e) {
  1323. watchdog_exception('cron', $e);
  1324. }
  1325. $stats = elysia_cron_get_job_stats($job);
  1326. $time = time() - $time;
  1327. elysia_cron_set_job_stats(
  1328. $job,
  1329. -1,
  1330. $time,
  1331. ($c = $stats['execution_count'] + 1),
  1332. round((($stats['avg_execution_time'] * ($c - 1)) + $time) / $c, 2),
  1333. $time > $stats['max_execution_time'] ? $time : -1,
  1334. array('running' => 0)
  1335. );
  1336. elysia_cron_debug('Cron job %job ended in %time secs.', array('%job' => $job, '%time' => $time));
  1337. }
  1338. /**
  1339. * Check if the channel is idle (not running, or stuck). If so set returns available jobs.
  1340. *
  1341. * @return array of jobs ready to be executed, or FALSE if channel is running
  1342. */
  1343. function elysia_cron_check_run_channel($channel, $ignore_disable = FALSE, $ignore_time = FALSE, $ignore_running = FALSE) {
  1344. global $_elysia_cron_settings_by_channel;
  1345. $jobs = FALSE;
  1346. $stuck_time = variable_get('elysia_cron_stuck_time', 3600);
  1347. $sem = elysia_cron_is_channel_running($channel);
  1348. if ($sem && (time() - $sem > $stuck_time)) {
  1349. elysia_cron_set_channel_running($channel, 0);
  1350. $last_job = elysia_cron_execute_aborted($channel);
  1351. unset($sem);
  1352. 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);
  1353. }
  1354. if (($ignore_running || empty($sem)) && ($ignore_disable || !$_elysia_cron_settings_by_channel[$channel]['#data']['disabled'])) {
  1355. $jobs = elysia_cron_active_jobs($channel, $ignore_disable, $ignore_time);
  1356. }
  1357. return $jobs;
  1358. }
  1359. function elysia_cron_check_run_job($job) {
  1360. $job_running = FALSE;
  1361. if (elysia_cron_is_job_running($job)) {
  1362. if (time() - elysia_cron_get_job_last_run($job, 0) > variable_get('elysia_cron_stuck_time', 3600)) {
  1363. elysia_cron_warning('Job %job is already running, but is probably stuck, so i consider it as terminated', array('%job' => $job));
  1364. }
  1365. else {
  1366. elysia_cron_warning('Job %job is already running', array('%job' => $job));
  1367. $job_running = TRUE;
  1368. }
  1369. }
  1370. return $job_running;
  1371. }
  1372. /**
  1373. * Find an idle channel (not running, or stuck). If found one, set it as running and returns available jobs.
  1374. *
  1375. * @return array|bool
  1376. * If found returns array { 'name' => name of channel, 'jobs' => array of active jobs }, else return FALSE.
  1377. */
  1378. function elysia_cron_run_available_channel($ignore_disable = FALSE, $ignore_time = FALSE, $ignore_running = FALSE) {
  1379. global $_elysia_cron_settings_by_channel;
  1380. $channels = array_keys($_elysia_cron_settings_by_channel);
  1381. $channel = elysia_cron_last_channel();
  1382. $i = array_search($channel, $channels);
  1383. if ($i === FALSE) {
  1384. $i = -1;
  1385. }
  1386. $k = 0;
  1387. $jobs = FALSE;
  1388. for ($j = ($i + 1) % count($channels); $k < count($channels); $j = ($j + 1) % count($channels)) {
  1389. $jobs = elysia_cron_check_run_channel($channels[$j], $ignore_disable, $ignore_time, $ignore_running);
  1390. if ($jobs && count($jobs)) {
  1391. break;
  1392. }
  1393. $k++;
  1394. }
  1395. if ($jobs) {
  1396. elysia_cron_set_last_channel($channels[$j]);
  1397. }
  1398. return $jobs ? array('name' => $channels[$j], 'jobs' => $jobs) : FALSE;
  1399. }
  1400. function elysia_cron_execute_aborted($channel) {
  1401. global $_elysia_cron_settings_by_channel;
  1402. $last_job = '';
  1403. foreach ($_elysia_cron_settings_by_channel[$channel] as $job => $conf) {
  1404. if ($job != '#data') {
  1405. if (elysia_cron_is_job_running($job)) {
  1406. $last_job .= ' ' . $job;
  1407. elysia_cron_set_job_running($job, 0);
  1408. }
  1409. }
  1410. }
  1411. // In case the last function to run is longer than 128 chars, we cap the
  1412. // length prior to placing in the database.
  1413. $last_job = trim($last_job);
  1414. if (strlen($last_job) > 128) {
  1415. $last_job = substr($last_job, 0, 128);
  1416. }
  1417. elysia_cron_set($channel, TRUE, array(
  1418. 'running' => 0, //time(),.
  1419. 'last_aborted' => 1,
  1420. 'abort_count' => elysia_cron_get_channel_abort_count($channel) + 1,
  1421. 'last_abort_function' => $last_job,
  1422. ));
  1423. return $last_job;
  1424. }
  1425. /**
  1426. * Shutdown function for cron cleanup.
  1427. *
  1428. * Used for unexpected termination of code.
  1429. */
  1430. function elysia_cron_internal_execute_channel_cleanup() {
  1431. global $_elysia_cron_current_channel, $_cron_completed;
  1432. if ($_cron_completed) {
  1433. return;
  1434. }
  1435. // See if the semaphore is still locked.
  1436. if (elysia_cron_is_channel_running($_elysia_cron_current_channel)) {
  1437. $last_job = elysia_cron_execute_aborted($_elysia_cron_current_channel);
  1438. elysia_cron_warning('Unexpected termination of cron channel %channel, aborted. Last job executed: %job', array('%channel' => $_elysia_cron_current_channel, '%job' => $last_job));
  1439. }
  1440. }
  1441. /**
  1442. * Successful termination (after all shutdown hooks invoked by cron functions).
  1443. */
  1444. function elysia_cron_internal_execute_channel_completed() {
  1445. global $_elysia_cron_current_channel, $_cron_completed_time;
  1446. // Record cron time.
  1447. _ec_variable_set('cron_last', time());
  1448. elysia_cron_debug('Cron channel %channel run completed.', array('%channel' => $_elysia_cron_current_channel));
  1449. $stats = elysia_cron_get_channel_stats($_elysia_cron_current_channel);
  1450. $time = time() - $stats['last_run'];
  1451. $exec_count = $stats['execution_count'] + 1;
  1452. $channel_stats_data = array(
  1453. 'last_execution_time' => $time,
  1454. 'execution_count' => $exec_count,
  1455. 'avg_execution_time' => round((($stats['avg_execution_time'] * ($exec_count - 1)) + $time) / $exec_count, 2),
  1456. 'max_execution_time' => $time > $stats['max_execution_time'] ? $time : $stats['max_execution_time'],
  1457. 'last_shutdown_time' => time() - $_cron_completed_time,
  1458. 'last_aborted' => 0,
  1459. 'running' => 0,
  1460. );
  1461. elysia_cron_set_channel_stats($_elysia_cron_current_channel, $channel_stats_data);
  1462. }
  1463. /**
  1464. * Get all jobs that needs to be executed in a channel
  1465. */
  1466. function elysia_cron_active_jobs($channel, $ignore_disable = FALSE, $ignore_time = FALSE) {
  1467. global $_elysia_cron_settings_by_channel;
  1468. $jobs = array();
  1469. foreach ($_elysia_cron_settings_by_channel[$channel] as $job => $conf) {
  1470. if ($job != '#data') {
  1471. if (elysia_cron_should_run($conf, -1, $ignore_disable, $ignore_time)) {
  1472. $jobs[] = $job;
  1473. }
  1474. }
  1475. }
  1476. return $jobs;
  1477. }
  1478. /**
  1479. * Check if cron is currently running.
  1480. * (Not used by elysia_cron, can be used by external modules)
  1481. */
  1482. function elysia_cron_is_running() {
  1483. global $_elysia_cron_settings_by_channel;
  1484. elysia_cron_initialize();
  1485. $running = array();
  1486. foreach ($_elysia_cron_settings_by_channel as $channel => $data) {
  1487. if (elysia_cron_is_channel_running($channel)) {
  1488. $running[] = $channel;
  1489. }
  1490. }
  1491. return $running;
  1492. }
  1493. function elysia_cron_job_exists($job) {
  1494. global $_elysia_cron_settings;
  1495. return isset($_elysia_cron_settings[$job]);
  1496. }
  1497. function elysia_cron_channel_exists($channel) {
  1498. global $_elysia_cron_settings_by_channel;
  1499. return isset($_elysia_cron_settings_by_channel[$channel]);
  1500. }
  1501. /**
  1502. * Obtain job description (translated)
  1503. */
  1504. function elysia_cron_description($job) {
  1505. global $_elysia_cron_settings;
  1506. if (!empty($_elysia_cron_settings[$job]['description'])) {
  1507. $desc = $_elysia_cron_settings[$job]['description'];
  1508. }
  1509. else {
  1510. $desc = theme('elysia_cron_description', array('job' => $job));
  1511. }
  1512. return t($desc);
  1513. }
  1514. /*******************************************************************************
  1515. * THEMING
  1516. ******************************************************************************/
  1517. /**
  1518. * Implementation of hook_theme().
  1519. */
  1520. function elysia_cron_theme() {
  1521. return array(
  1522. 'elysia_cron_description' => array(
  1523. 'variables' => array('job' => NULL),
  1524. ),
  1525. 'elysia_cron_settings_form' => array(
  1526. 'render element' => 'form',
  1527. ),
  1528. );
  1529. }
  1530. /**
  1531. * You can theme this function to provide your (untranslated) descriptions for cron functions, if they do not provide one.
  1532. */
  1533. function theme_elysia_cron_description($variables) {
  1534. switch ($variables['job']) {
  1535. case 'search_cron':
  1536. return 'Update search database index';
  1537. case 'activitystream_cron':
  1538. return 'Fetch RSS feeds and web calls for activitystream';
  1539. case 'mailhandler_cron':
  1540. return 'Fetch POP3/IMAP accounts managed by MailHandler';
  1541. case 'watchdog_cron':
  1542. return 'Remove expired log messages and flood control events';
  1543. case 'filter_cron':
  1544. return 'Expire outdated filter cache entries';
  1545. case 'node_cron':
  1546. return 'History table cleanup';
  1547. case 'system_cron':
  1548. return 'Remove older rows from flood and batch table. Remove old temporary files.';
  1549. case 'aggregation_cron':
  1550. return 'Fetch RSS feeds for aggregation module';
  1551. case 'amazon_cron':
  1552. return 'Refresh Amazon products';
  1553. case 'image_cron':
  1554. return 'Deletes old temp images';
  1555. case 'persistent_login_cron':
  1556. return 'Expire persistent login';
  1557. case 'trackback_cron':
  1558. return 'Process trackback ping queue';
  1559. case 'update_status_cron':
  1560. return 'Checks for drupal module updates (Note: own frequency check ignore cron rules)';
  1561. case 'user_karma_cron':
  1562. return 'User karma expiration / rebuild (Note: own frequency check ignore cron rules)';
  1563. case 'votingapi_cron':
  1564. return 'Update votes (if not configured for immediate calculation)';
  1565. case 'statistics_cron':
  1566. return 'Reset day counts / Clean expired access logs';
  1567. case 'googleanalytics_cron':
  1568. return 'Delete cached version of ga.js/urchin.js.';
  1569. case 'xmlsitemap_cron':
  1570. return 'XML sitemap ping.';
  1571. case 'xmlsitemap_node_cron':
  1572. return 'Update XML sitemap with new nodes';
  1573. case 'xmlsitemap_term_cron':
  1574. return 'Update XML sitemap with new terms';
  1575. case 'lm_paypal_cron':
  1576. return 'Remove old IPN records';
  1577. case 'user_import_cron':
  1578. return 'Continue partial imports';
  1579. case 'dblog_cron':
  1580. return 'Remove expired log messages and flood control events';
  1581. case 'field_cron':
  1582. return 'Purges some deleted Field API data, if any exists';
  1583. case 'trigger_cron':
  1584. return 'Triggers cron actions';
  1585. case 'update_cron':
  1586. return 'Checks for available updates of Drupal core, contributed modules and themes';
  1587. case 'search_api_cron':
  1588. return 'Will index items for each enabled index.';
  1589. case 'redirect_cron':
  1590. return 'Purge inactive self-managed redirects from the database.';
  1591. case 'ctools_cron':
  1592. return 'Clean up old caches';
  1593. case 'l10n_update_cron':
  1594. return 'Check one project/language at a time, download and import if update available';
  1595. default:
  1596. return '-';
  1597. }
  1598. }
  1599. /*******************************************************************************
  1600. * PING SUPPORT
  1601. ******************************************************************************/
  1602. /**
  1603. * Page callback for ping page. Throws 404 if cron hasn't been called within configured time period.
  1604. */
  1605. function elysia_cron_ping_page() {
  1606. $last_run = _ec_variable_get('elysia_cron_last_run', 0);
  1607. $diff = time() - $last_run;
  1608. $max_interval = variable_get('elysia_cron_alert_interval', 60) * 60;
  1609. if ($diff > $max_interval) {
  1610. drupal_not_found();
  1611. drupal_exit();
  1612. }
  1613. $aoutput = array();
  1614. $aoutput[] = array(
  1615. '#type' => 'markup',
  1616. '#markup' => t('Cron has been called within maximum lapse time.'),
  1617. );
  1618. return $aoutput;
  1619. }
  1620. /*******************************************************************************
  1621. * DRUPAL QUEUE SUPPORT
  1622. * ONLY FOR D7
  1623. ******************************************************************************/
  1624. /**
  1625. * Implements hook_cronapi().
  1626. */
  1627. function elysia_cron_cronapi($op, $job = FALSE) {
  1628. $items = array();
  1629. $queues = module_invoke_all('cron_queue_info');
  1630. drupal_alter('cron_queue_info', $queues);
  1631. foreach ($queues as $queue_name => $info) {
  1632. if (!empty($info['skip on cron'])) {
  1633. // Do not run if queue wants to skip.
  1634. continue;
  1635. }
  1636. // Make sure every queue exists. There is no harm in trying to recreate an
  1637. // existing queue.
  1638. $queue = DrupalQueue::get($queue_name);
  1639. $queue->createQueue();
  1640. // Some queue backends may have performance issues with counting items.
  1641. if (variable_get('elysia_cron_queue_show_count', TRUE)) {
  1642. $queue_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>)';
  1643. }
  1644. else {
  1645. $queue_description = $queue_name . ' queue processing (Worker max duration: <strong>' . (isset($info['time']) ? $info['time'] . 's' : t('unspecified') . ' (15s)') . '</strong>)';
  1646. }
  1647. $items['queue_' . $queue_name] = array(
  1648. 'description' => $queue_description,
  1649. 'rule' => variable_get('elysia_cron_queue_default_rule', FALSE),
  1650. 'weight' => variable_get('elysia_cron_queue_default_weight', 100),
  1651. 'callback' => 'elysia_cron_queue_exec',
  1652. 'arguments' => array($queue_name, $info),
  1653. );
  1654. }
  1655. return $items;
  1656. }
  1657. /**
  1658. * Callback for cronapi.
  1659. *
  1660. * @param string $queue_name
  1661. * Queue name.
  1662. * @param array $info
  1663. * Info about queue.
  1664. */
  1665. function elysia_cron_queue_exec($queue_name, $info) {
  1666. $function = $info['worker callback'];
  1667. $end = time() + (isset($info['time']) ? $info['time'] : 15);
  1668. $queue = DrupalQueue::get($queue_name);
  1669. while (time() < $end && ($item = $queue->claimItem())) {
  1670. try {
  1671. $function($item->data);
  1672. $queue->deleteItem($item);
  1673. }
  1674. catch (Exception $e) {
  1675. // In case of exception log it and leave the item in the queue
  1676. // to be processed again later.
  1677. watchdog_exception('cron', $e);
  1678. }
  1679. }
  1680. }
  1681. /*******************************************************************************
  1682. * ADMIN_MENU SUPPORT
  1683. ******************************************************************************/
  1684. // @todo Deve gestire hook_admin_menu_map, vedi hook_admin_menu.php e admin_menu.map.inc
  1685. /**
  1686. * Implements hook_admin_menu().
  1687. *
  1688. * @param array &$deleted
  1689. * Array of links under admin/* that were removed by
  1690. * admin_menu_adjust_items(). If one of these links is added back,
  1691. * it should be removed from the array.
  1692. *
  1693. * @return array
  1694. * Links array.
  1695. */
  1696. function elysia_cron_admin_menu(&$deleted) {
  1697. $links = array();
  1698. elysia_cron_initialize();
  1699. global $_elysia_cron_settings_by_channel;
  1700. // Add link to manually run cron.
  1701. $links[] = array(
  1702. 'title' => 'Elysia cron manual',
  1703. 'path' => 'admin/config/system/cron',
  1704. 'weight' => 50,
  1705. 'has_children' => FALSE,
  1706. 'parent_path' => '<front>',
  1707. );
  1708. foreach ($_elysia_cron_settings_by_channel as $channel => $data) {
  1709. foreach ($data as $job => $conf) {
  1710. if ($job != '#data') {
  1711. $links[] = array(
  1712. 'title' => "Elysia cron run manual !title",
  1713. 'path' => 'admin/config/system/cron/execute/' . $job,
  1714. 'weight' => -50,
  1715. 'query' => 'destination',
  1716. 'parent_path' => 'admin/config/system/cron',
  1717. 'options' => array('t' => array('!title' => $conf['module'])),
  1718. );
  1719. }
  1720. }
  1721. }
  1722. return $links;
  1723. }
  1724. /**
  1725. * Check if function available to use.
  1726. *
  1727. * Some native php function can be disabled by configuration,
  1728. * to avoid a lot of notices we check availability of such functions.
  1729. *
  1730. * @param string $func
  1731. * Function to check.
  1732. *
  1733. * @return bool
  1734. * TRUE if function available for use, FALSE otherwise.
  1735. */
  1736. function _elysia_cron_function_available($func) {
  1737. $disabled = explode(',', ini_get('disable_functions'));
  1738. return !in_array($func, $disabled);
  1739. }
  1740. /**
  1741. * Get list of columns from elysia_cron table.
  1742. *
  1743. * @return array
  1744. * List of columns.
  1745. */
  1746. function _elysia_cron_columns() {
  1747. return array(
  1748. 'name',
  1749. 'disable',
  1750. 'rule',
  1751. 'weight',
  1752. 'context',
  1753. 'running',
  1754. 'last_run',
  1755. 'last_aborted',
  1756. 'abort_count',
  1757. 'last_abort_function',
  1758. 'last_execution_time',
  1759. 'execution_count',
  1760. 'avg_execution_time',
  1761. 'max_execution_time',
  1762. 'last_shutdown_time',
  1763. );
  1764. }
  1765. /**
  1766. * Get list of predefined cron rules.
  1767. *
  1768. * @return array
  1769. * List of predefined rules.
  1770. */
  1771. function _elysia_cron_default_rules() {
  1772. return array(
  1773. '*/15 * * * *' => 'Every 15 minutes',
  1774. '*/30 * * * *' => 'Every 30 minutes',
  1775. '0 * * * *' => 'Every hour',
  1776. '0 */6 * * *' => 'Every 6 hours',
  1777. '4 0 * * *' => 'Once a day',
  1778. '4 0 * * 0' => 'Once a week',
  1779. '4 0 1 * *' => 'Once a month',
  1780. );
  1781. }