ManageScheduledTasks.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558
  1. <?php
  2. /**
  3. * Simple Machines Forum (SMF)
  4. *
  5. * @package SMF
  6. * @author Simple Machines http://www.simplemachines.org
  7. * @copyright 2011 Simple Machines
  8. * @license http://www.simplemachines.org/about/smf/license.php BSD
  9. *
  10. * @version 2.0
  11. */
  12. if (!defined('SMF'))
  13. die('Hacking attempt...');
  14. /* /!!!
  15. void ManageScheduledTasks()
  16. // !!!
  17. void ScheduledTasks()
  18. // !!!
  19. array list_getScheduledTasks()
  20. // !!!
  21. void EditTask()
  22. // !!!
  23. void TaskLog()
  24. // !!!
  25. array list_getTaskLogEntries()
  26. // !!!
  27. array list_getNumTaskLog()
  28. // !!!
  29. */
  30. // !!!
  31. function ManageScheduledTasks()
  32. {
  33. global $context, $txt, $modSettings;
  34. isAllowedTo('admin_forum');
  35. loadLanguage('ManageScheduledTasks');
  36. loadTemplate('ManageScheduledTasks');
  37. $subActions = array(
  38. 'taskedit' => 'EditTask',
  39. 'tasklog' => 'TaskLog',
  40. 'tasks' => 'ScheduledTasks',
  41. );
  42. // We need to find what's the action.
  43. if (isset($_REQUEST['sa']) && isset($subActions[$_REQUEST['sa']]))
  44. $context['sub_action'] = $_REQUEST['sa'];
  45. else
  46. $context['sub_action'] = 'tasks';
  47. // Now for the lovely tabs. That we all love.
  48. $context[$context['admin_menu_name']]['tab_data'] = array(
  49. 'title' => $txt['scheduled_tasks_title'],
  50. 'help' => '',
  51. 'description' => $txt['maintain_info'],
  52. 'tabs' => array(
  53. 'tasks' => array(
  54. 'description' => $txt['maintain_tasks_desc'],
  55. ),
  56. 'tasklog' => array(
  57. 'description' => $txt['scheduled_log_desc'],
  58. ),
  59. ),
  60. );
  61. // Call it.
  62. $subActions[$context['sub_action']]();
  63. }
  64. // List all the scheduled task in place on the forum.
  65. function ScheduledTasks()
  66. {
  67. global $context, $txt, $sourcedir, $smcFunc, $user_info, $modSettings, $scripturl;
  68. // Mama, setup the template first - cause it's like the most important bit, like pickle in a sandwich.
  69. // ... ironically I don't like pickle. </grudge>
  70. $context['sub_template'] = 'view_scheduled_tasks';
  71. $context['page_title'] = $txt['maintain_tasks'];
  72. // Saving changes?
  73. if (isset($_REQUEST['save']) && isset($_POST['enable_task']))
  74. {
  75. checkSession();
  76. // We'll recalculate the dates at the end!
  77. require_once($sourcedir . '/ScheduledTasks.php');
  78. // Enable and disable as required.
  79. $enablers = array(0);
  80. foreach ($_POST['enable_task'] as $id => $enabled)
  81. if ($enabled)
  82. $enablers[] = (int) $id;
  83. // Do the update!
  84. $smcFunc['db_query']('', '
  85. UPDATE {db_prefix}scheduled_tasks
  86. SET disabled = CASE WHEN id_task IN ({array_int:id_task_enable}) THEN 0 ELSE 1 END',
  87. array(
  88. 'id_task_enable' => $enablers,
  89. )
  90. );
  91. // Pop along...
  92. CalculateNextTrigger();
  93. }
  94. // Want to run any of the tasks?
  95. if (isset($_REQUEST['run']) && isset($_POST['run_task']))
  96. {
  97. // Lets figure out which ones they want to run.
  98. $tasks = array();
  99. foreach ($_POST['run_task'] as $task => $dummy)
  100. $tasks[] = (int) $task;
  101. // Load up the tasks.
  102. $request = $smcFunc['db_query']('', '
  103. SELECT id_task, task
  104. FROM {db_prefix}scheduled_tasks
  105. WHERE id_task IN ({array_int:tasks})
  106. LIMIT ' . count($tasks),
  107. array(
  108. 'tasks' => $tasks,
  109. )
  110. );
  111. // Lets get it on!
  112. require_once($sourcedir . '/ScheduledTasks.php');
  113. ignore_user_abort(true);
  114. while ($row = $smcFunc['db_fetch_assoc']($request))
  115. {
  116. $start_time = microtime();
  117. // The functions got to exist for us to use it.
  118. if (!function_exists('scheduled_' . $row['task']))
  119. continue;
  120. // Try to stop a timeout, this would be bad...
  121. @set_time_limit(300);
  122. if (function_exists('apache_reset_timeout'))
  123. @apache_reset_timeout();
  124. // Do the task...
  125. $completed = call_user_func('scheduled_' . $row['task']);
  126. // Log that we did it ;)
  127. if ($completed)
  128. {
  129. $total_time = round(array_sum(explode(' ', microtime())) - array_sum(explode(' ', $start_time)), 3);
  130. $smcFunc['db_insert']('',
  131. '{db_prefix}log_scheduled_tasks',
  132. array('id_task' => 'int', 'time_run' => 'int', 'time_taken' => 'float'),
  133. array($row['id_task'], time(), $total_time),
  134. array('id_task')
  135. );
  136. }
  137. }
  138. $smcFunc['db_free_result']($request);
  139. redirectexit('action=admin;area=scheduledtasks;done');
  140. }
  141. $listOptions = array(
  142. 'id' => 'scheduled_tasks',
  143. 'title' => $txt['maintain_tasks'],
  144. 'base_href' => $scripturl . '?action=admin;area=scheduledtasks',
  145. 'get_items' => array(
  146. 'function' => 'list_getScheduledTasks',
  147. ),
  148. 'columns' => array(
  149. 'name' => array(
  150. 'header' => array(
  151. 'value' => $txt['scheduled_tasks_name'],
  152. 'style' => 'width: 40%;',
  153. ),
  154. 'data' => array(
  155. 'sprintf' => array(
  156. 'format' => '
  157. <a href="' . $scripturl . '?action=admin;area=scheduledtasks;sa=taskedit;tid=%1$d">%2$s</a><br /><span class="smalltext">%3$s</span>',
  158. 'params' => array(
  159. 'id' => false,
  160. 'name' => false,
  161. 'desc' => false,
  162. ),
  163. ),
  164. ),
  165. ),
  166. 'next_due' => array(
  167. 'header' => array(
  168. 'value' => $txt['scheduled_tasks_next_time'],
  169. ),
  170. 'data' => array(
  171. 'db' => 'next_time',
  172. 'class' => 'smalltext',
  173. ),
  174. ),
  175. 'regularity' => array(
  176. 'header' => array(
  177. 'value' => $txt['scheduled_tasks_regularity'],
  178. ),
  179. 'data' => array(
  180. 'db' => 'regularity',
  181. 'class' => 'smalltext',
  182. ),
  183. ),
  184. 'enabled' => array(
  185. 'header' => array(
  186. 'value' => $txt['scheduled_tasks_enabled'],
  187. 'style' => 'width: 6%;',
  188. ),
  189. 'data' => array(
  190. 'sprintf' => array(
  191. 'format' =>
  192. '<input type="hidden" name="enable_task[%1$d]" id="task_%1$d" value="0" /><input type="checkbox" name="enable_task[%1$d]" id="task_check_%1$d" %2$s class="input_check" />',
  193. 'params' => array(
  194. 'id' => false,
  195. 'checked_state' => false,
  196. ),
  197. ),
  198. 'style' => 'text-align: center;',
  199. ),
  200. ),
  201. 'run_now' => array(
  202. 'header' => array(
  203. 'value' => $txt['scheduled_tasks_run_now'],
  204. 'style' => 'width: 12%;',
  205. ),
  206. 'data' => array(
  207. 'sprintf' => array(
  208. 'format' =>
  209. '<input type="checkbox" name="run_task[%1$d]" id="run_task_%1$d" class="input_check" />',
  210. 'params' => array(
  211. 'id' => false,
  212. ),
  213. ),
  214. 'style' => 'text-align: center;',
  215. ),
  216. ),
  217. ),
  218. 'form' => array(
  219. 'href' => $scripturl . '?action=admin;area=scheduledtasks',
  220. ),
  221. 'additional_rows' => array(
  222. array(
  223. 'position' => 'below_table_data',
  224. 'value' => '
  225. <input type="submit" name="save" value="' . $txt['scheduled_tasks_save_changes'] . '" class="button_submit" />
  226. <input type="submit" name="run" value="' . $txt['scheduled_tasks_run_now'] . '" class="button_submit" />',
  227. 'class' => 'floatright',
  228. 'style' => 'text-align: right;',
  229. ),
  230. array(
  231. 'position' => 'after_title',
  232. 'value' => '
  233. <span class="smalltext">' . $txt['scheduled_tasks_time_offset'] . '</span>',
  234. 'class' => 'windowbg2',
  235. ),
  236. ),
  237. );
  238. require_once($sourcedir . '/Subs-List.php');
  239. createList($listOptions);
  240. $context['sub_template'] = 'view_scheduled_tasks';
  241. $context['tasks_were_run'] = isset($_GET['done']);
  242. }
  243. function list_getScheduledTasks($start, $items_per_page, $sort)
  244. {
  245. global $smcFunc, $txt, $scripturl;
  246. $request = $smcFunc['db_query']('', '
  247. SELECT id_task, next_time, time_offset, time_regularity, time_unit, disabled, task
  248. FROM {db_prefix}scheduled_tasks',
  249. array(
  250. )
  251. );
  252. $known_tasks = array();
  253. while ($row = $smcFunc['db_fetch_assoc']($request))
  254. {
  255. // Find the next for regularity - don't offset as it's always server time!
  256. $offset = sprintf($txt['scheduled_task_reg_starting'], date('H:i', $row['time_offset']));
  257. $repeating = sprintf($txt['scheduled_task_reg_repeating'], $row['time_regularity'], $txt['scheduled_task_reg_unit_' . $row['time_unit']]);
  258. $known_tasks[] = array(
  259. 'id' => $row['id_task'],
  260. 'function' => $row['task'],
  261. 'name' => isset($txt['scheduled_task_' . $row['task']]) ? $txt['scheduled_task_' . $row['task']] : $row['task'],
  262. 'desc' => isset($txt['scheduled_task_desc_' . $row['task']]) ? $txt['scheduled_task_desc_' . $row['task']] : '',
  263. 'next_time' => $row['disabled'] ? $txt['scheduled_tasks_na'] : timeformat(($row['next_time'] == 0 ? time() : $row['next_time']), true, 'server'),
  264. 'disabled' => $row['disabled'],
  265. 'checked_state' => $row['disabled'] ? '' : 'checked="checked"',
  266. 'regularity' => $offset . ', ' . $repeating,
  267. );
  268. }
  269. $smcFunc['db_free_result']($request);
  270. return $known_tasks;
  271. }
  272. // Function for editing a task.
  273. function EditTask()
  274. {
  275. global $context, $txt, $sourcedir, $smcFunc, $user_info, $modSettings;
  276. // Just set up some lovely context stuff.
  277. $context[$context['admin_menu_name']]['current_subsection'] = 'tasks';
  278. $context['sub_template'] = 'edit_scheduled_tasks';
  279. $context['page_title'] = $txt['scheduled_task_edit'];
  280. $context['server_time'] = timeformat(time(), false, 'server');
  281. // Cleaning...
  282. if (!isset($_GET['tid']))
  283. fatal_lang_error('no_access', false);
  284. $_GET['tid'] = (int) $_GET['tid'];
  285. // Saving?
  286. if (isset($_GET['save']))
  287. {
  288. checkSession();
  289. // We'll need this for calculating the next event.
  290. require_once($sourcedir . '/ScheduledTasks.php');
  291. // Do we have a valid offset?
  292. preg_match('~(\d{1,2}):(\d{1,2})~', $_POST['offset'], $matches);
  293. // If a half is empty then assume zero offset!
  294. if (!isset($matches[2]) || $matches[2] > 59)
  295. $matches[2] = 0;
  296. if (!isset($matches[1]) || $matches[1] > 23)
  297. $matches[1] = 0;
  298. // Now the offset is easy; easy peasy - except we need to offset by a few hours...
  299. $offset = $matches[1] * 3600 + $matches[2] * 60 - date('Z');
  300. // The other time bits are simple!
  301. $interval = max((int) $_POST['regularity'], 1);
  302. $unit = in_array(substr($_POST['unit'], 0, 1), array('m', 'h', 'd', 'w')) ? substr($_POST['unit'], 0, 1) : 'd';
  303. // Don't allow one minute intervals.
  304. if ($interval == 1 && $unit == 'm')
  305. $interval = 2;
  306. // Is it disabled?
  307. $disabled = !isset($_POST['enabled']) ? 1 : 0;
  308. // Do the update!
  309. $smcFunc['db_query']('', '
  310. UPDATE {db_prefix}scheduled_tasks
  311. SET disabled = {int:disabled}, time_offset = {int:time_offset}, time_unit = {string:time_unit},
  312. time_regularity = {int:time_regularity}
  313. WHERE id_task = {int:id_task}',
  314. array(
  315. 'disabled' => $disabled,
  316. 'time_offset' => $offset,
  317. 'time_regularity' => $interval,
  318. 'id_task' => $_GET['tid'],
  319. 'time_unit' => $unit,
  320. )
  321. );
  322. // Check the next event.
  323. CalculateNextTrigger($_GET['tid'], true);
  324. // Return to the main list.
  325. redirectexit('action=admin;area=scheduledtasks');
  326. }
  327. // Load the task, understand? Que? Que?
  328. $request = $smcFunc['db_query']('', '
  329. SELECT id_task, next_time, time_offset, time_regularity, time_unit, disabled, task
  330. FROM {db_prefix}scheduled_tasks
  331. WHERE id_task = {int:id_task}',
  332. array(
  333. 'id_task' => $_GET['tid'],
  334. )
  335. );
  336. // Should never, ever, happen!
  337. if ($smcFunc['db_num_rows']($request) == 0)
  338. fatal_lang_error('no_access', false);
  339. while ($row = $smcFunc['db_fetch_assoc']($request))
  340. {
  341. $context['task'] = array(
  342. 'id' => $row['id_task'],
  343. 'function' => $row['task'],
  344. 'name' => isset($txt['scheduled_task_' . $row['task']]) ? $txt['scheduled_task_' . $row['task']] : $row['task'],
  345. 'desc' => isset($txt['scheduled_task_desc_' . $row['task']]) ? $txt['scheduled_task_desc_' . $row['task']] : '',
  346. 'next_time' => $row['disabled'] ? $txt['scheduled_tasks_na'] : timeformat($row['next_time'] == 0 ? time() : $row['next_time'], true, 'server'),
  347. 'disabled' => $row['disabled'],
  348. 'offset' => $row['time_offset'],
  349. 'regularity' => $row['time_regularity'],
  350. 'offset_formatted' => date('H:i', $row['time_offset']),
  351. 'unit' => $row['time_unit'],
  352. );
  353. }
  354. $smcFunc['db_free_result']($request);
  355. }
  356. // Show the log of all tasks that have taken place.
  357. function TaskLog()
  358. {
  359. global $scripturl, $context, $txt, $smcFunc, $sourcedir;
  360. // Lets load the language just incase we are outside the Scheduled area.
  361. loadLanguage('ManageScheduledTasks');
  362. // Empty the log?
  363. if (!empty($_POST['removeAll']))
  364. {
  365. checkSession();
  366. $smcFunc['db_query']('truncate_table', '
  367. TRUNCATE {db_prefix}log_scheduled_tasks',
  368. array(
  369. )
  370. );
  371. }
  372. // Setup the list.
  373. $listOptions = array(
  374. 'id' => 'task_log',
  375. 'items_per_page' => 30,
  376. 'title' => $txt['scheduled_log'],
  377. 'no_items_label' => $txt['scheduled_log_empty'],
  378. 'base_href' => $context['admin_area'] == 'scheduledtasks' ? $scripturl . '?action=admin;area=scheduledtasks;sa=tasklog' : $scripturl . '?action=admin;area=logs;sa=tasklog',
  379. 'default_sort_col' => 'date',
  380. 'get_items' => array(
  381. 'function' => 'list_getTaskLogEntries',
  382. ),
  383. 'get_count' => array(
  384. 'function' => 'list_getNumTaskLogEntries',
  385. ),
  386. 'columns' => array(
  387. 'name' => array(
  388. 'header' => array(
  389. 'value' => $txt['scheduled_tasks_name'],
  390. ),
  391. 'data' => array(
  392. 'db' => 'name'
  393. ),
  394. ),
  395. 'date' => array(
  396. 'header' => array(
  397. 'value' => $txt['scheduled_log_time_run'],
  398. ),
  399. 'data' => array(
  400. 'function' => create_function('$rowData', '
  401. return timeformat($rowData[\'time_run\'], true);
  402. '),
  403. ),
  404. 'sort' => array(
  405. 'default' => 'lst.id_log DESC',
  406. 'reverse' => 'lst.id_log',
  407. ),
  408. ),
  409. 'time_taken' => array(
  410. 'header' => array(
  411. 'value' => $txt['scheduled_log_time_taken'],
  412. ),
  413. 'data' => array(
  414. 'sprintf' => array(
  415. 'format' => $txt['scheduled_log_time_taken_seconds'],
  416. 'params' => array(
  417. 'time_taken' => false,
  418. ),
  419. ),
  420. ),
  421. 'sort' => array(
  422. 'default' => 'lst.time_taken',
  423. 'reverse' => 'lst.time_taken DESC',
  424. ),
  425. ),
  426. ),
  427. 'form' => array(
  428. 'href' => $context['admin_area'] == 'scheduledtasks' ? $scripturl . '?action=admin;area=scheduledtasks;sa=tasklog' : $scripturl . '?action=admin;area=logs;sa=tasklog',
  429. ),
  430. 'additional_rows' => array(
  431. array(
  432. 'position' => 'below_table_data',
  433. 'value' => '
  434. <input type="submit" name="removeAll" value="' . $txt['scheduled_log_empty_log'] . '" class="button_submit" />',
  435. 'style' => 'text-align: right;',
  436. ),
  437. array(
  438. 'position' => 'after_title',
  439. 'value' => $txt['scheduled_tasks_time_offset'],
  440. 'class' => 'smalltext',
  441. ),
  442. ),
  443. );
  444. require_once($sourcedir . '/Subs-List.php');
  445. createList($listOptions);
  446. $context['sub_template'] = 'show_list';
  447. $context['default_list'] = 'task_log';
  448. // Make it all look tify.
  449. $context[$context['admin_menu_name']]['current_subsection'] = 'tasklog';
  450. $context['page_title'] = $txt['scheduled_log'];
  451. }
  452. function list_getTaskLogEntries($start, $items_per_page, $sort)
  453. {
  454. global $smcFunc, $txt;
  455. $request = $smcFunc['db_query']('', '
  456. SELECT lst.id_log, lst.id_task, lst.time_run, lst.time_taken, st.task
  457. FROM {db_prefix}log_scheduled_tasks AS lst
  458. INNER JOIN {db_prefix}scheduled_tasks AS st ON (st.id_task = lst.id_task)
  459. ORDER BY ' . $sort . '
  460. LIMIT ' . $start . ', ' . $items_per_page,
  461. array(
  462. )
  463. );
  464. $log_entries = array();
  465. while ($row = $smcFunc['db_fetch_assoc']($request))
  466. $log_entries[] = array(
  467. 'id' => $row['id_log'],
  468. 'name' => isset($txt['scheduled_task_' . $row['task']]) ? $txt['scheduled_task_' . $row['task']] : $row['task'],
  469. 'time_run' => $row['time_run'],
  470. 'time_taken' => $row['time_taken'],
  471. );
  472. $smcFunc['db_free_result']($request);
  473. return $log_entries;
  474. }
  475. function list_getNumTaskLogEntries()
  476. {
  477. global $smcFunc;
  478. $request = $smcFunc['db_query']('', '
  479. SELECT COUNT(*)
  480. FROM {db_prefix}log_scheduled_tasks',
  481. array(
  482. )
  483. );
  484. list ($num_entries) = $smcFunc['db_fetch_row']($request);
  485. $smcFunc['db_free_result']($request);
  486. return $num_entries;
  487. }
  488. ?>