Friendica Communications Platform (please note that this is a clone of the repository at github, issues are handled there) https://friendi.ca
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

458 lines
13KB

  1. <?php
  2. if (!file_exists("boot.php") AND (sizeof($_SERVER["argv"]) != 0)) {
  3. $directory = dirname($_SERVER["argv"][0]);
  4. if (substr($directory, 0, 1) != "/")
  5. $directory = $_SERVER["PWD"]."/".$directory;
  6. $directory = realpath($directory."/..");
  7. chdir($directory);
  8. }
  9. require_once("boot.php");
  10. function cron_run(&$argv, &$argc){
  11. global $a, $db;
  12. if(is_null($a)) {
  13. $a = new App;
  14. }
  15. if(is_null($db)) {
  16. @include(".htconfig.php");
  17. require_once("include/dba.php");
  18. $db = new dba($db_host, $db_user, $db_pass, $db_data);
  19. unset($db_host, $db_user, $db_pass, $db_data);
  20. };
  21. require_once('include/session.php');
  22. require_once('include/datetime.php');
  23. require_once('include/items.php');
  24. require_once('include/Contact.php');
  25. require_once('include/email.php');
  26. require_once('include/socgraph.php');
  27. require_once('mod/nodeinfo.php');
  28. require_once('include/post_update.php');
  29. load_config('config');
  30. load_config('system');
  31. // Don't check this stuff if the function is called by the poller
  32. if (App::callstack() != "poller_run") {
  33. if (App::maxload_reached())
  34. return;
  35. if (App::is_already_running('cron', 'include/cron.php', 540))
  36. return;
  37. }
  38. $last = get_config('system','last_cron');
  39. $poll_interval = intval(get_config('system','cron_interval'));
  40. if(! $poll_interval)
  41. $poll_interval = 10;
  42. if($last) {
  43. $next = $last + ($poll_interval * 60);
  44. if($next > time()) {
  45. logger('cron intervall not reached');
  46. return;
  47. }
  48. }
  49. $a->set_baseurl(get_config('system','url'));
  50. load_hooks();
  51. logger('cron: start');
  52. // run queue delivery process in the background
  53. proc_run(PRIORITY_NEGLIGIBLE,"include/queue.php");
  54. // run the process to discover global contacts in the background
  55. proc_run(PRIORITY_LOW,"include/discover_poco.php");
  56. // run the process to update locally stored global contacts in the background
  57. proc_run(PRIORITY_LOW,"include/discover_poco.php", "checkcontact");
  58. // Expire and remove user entries
  59. cron_expire_and_remove_users();
  60. // If the worker is active, split the jobs in several sub processes
  61. if (get_config("system", "worker")) {
  62. // Check OStatus conversations
  63. proc_run(PRIORITY_MEDIUM, "include/cronjobs.php", "ostatus_mentions");
  64. // Check every conversation
  65. proc_run(PRIORITY_MEDIUM, "include/cronjobs.php", "ostatus_conversations");
  66. // Call possible post update functions
  67. proc_run(PRIORITY_LOW, "include/cronjobs.php", "post_update");
  68. // update nodeinfo data
  69. proc_run(PRIORITY_LOW, "include/cronjobs.php", "nodeinfo");
  70. } else {
  71. // Check OStatus conversations
  72. // Check only conversations with mentions (for a longer time)
  73. ostatus::check_conversations(true);
  74. // Check every conversation
  75. ostatus::check_conversations(false);
  76. // Call possible post update functions
  77. // see include/post_update.php for more details
  78. post_update();
  79. // update nodeinfo data
  80. nodeinfo_cron();
  81. }
  82. // once daily run birthday_updates and then expire in background
  83. $d1 = get_config('system','last_expire_day');
  84. $d2 = intval(datetime_convert('UTC','UTC','now','d'));
  85. if($d2 != intval($d1)) {
  86. update_contact_birthdays();
  87. proc_run(PRIORITY_LOW,"include/discover_poco.php", "suggestions");
  88. set_config('system','last_expire_day',$d2);
  89. proc_run(PRIORITY_LOW,'include/expire.php');
  90. }
  91. // Clear cache entries
  92. cron_clear_cache($a);
  93. // Repair missing Diaspora values in contacts
  94. cron_repair_diaspora($a);
  95. // Repair entries in the database
  96. cron_repair_database();
  97. // Poll contacts
  98. cron_poll_contacts($argc, $argv);
  99. logger('cron: end');
  100. set_config('system','last_cron', time());
  101. return;
  102. }
  103. /**
  104. * @brief Expire and remove user entries
  105. */
  106. function cron_expire_and_remove_users() {
  107. // expire any expired accounts
  108. q("UPDATE user SET `account_expired` = 1 where `account_expired` = 0
  109. AND `account_expires_on` != '0000-00-00 00:00:00'
  110. AND `account_expires_on` < UTC_TIMESTAMP() ");
  111. // delete user and contact records for recently removed accounts
  112. $r = q("SELECT * FROM `user` WHERE `account_removed` AND `account_expires_on` < UTC_TIMESTAMP() - INTERVAL 3 DAY");
  113. if ($r) {
  114. foreach($r as $user) {
  115. q("DELETE FROM `contact` WHERE `uid` = %d", intval($user['uid']));
  116. q("DELETE FROM `user` WHERE `uid` = %d", intval($user['uid']));
  117. }
  118. }
  119. }
  120. /**
  121. * @brief Poll contacts for unreceived messages
  122. *
  123. * @param Integer $argc Number of command line arguments
  124. * @param Array $argv Array of command line arguments
  125. */
  126. function cron_poll_contacts($argc, $argv) {
  127. $manual_id = 0;
  128. $generation = 0;
  129. $force = false;
  130. $restart = false;
  131. if (($argc > 1) && ($argv[1] == 'force'))
  132. $force = true;
  133. if (($argc > 1) && ($argv[1] == 'restart')) {
  134. $restart = true;
  135. $generation = intval($argv[2]);
  136. if (!$generation)
  137. killme();
  138. }
  139. if (($argc > 1) && intval($argv[1])) {
  140. $manual_id = intval($argv[1]);
  141. $force = true;
  142. }
  143. $interval = intval(get_config('system','poll_interval'));
  144. if (!$interval)
  145. $interval = ((get_config('system','delivery_interval') === false) ? 3 : intval(get_config('system','delivery_interval')));
  146. // If we are using the worker we don't need a delivery interval
  147. if (get_config("system", "worker"))
  148. $interval = false;
  149. $sql_extra = (($manual_id) ? " AND `id` = $manual_id " : "");
  150. reload_plugins();
  151. $d = datetime_convert();
  152. // Only poll from those with suitable relationships,
  153. // and which have a polling address and ignore Diaspora since
  154. // we are unable to match those posts with a Diaspora GUID and prevent duplicates.
  155. $abandon_days = intval(get_config('system','account_abandon_days'));
  156. if($abandon_days < 1)
  157. $abandon_days = 0;
  158. $abandon_sql = (($abandon_days)
  159. ? sprintf(" AND `user`.`login_date` > UTC_TIMESTAMP() - INTERVAL %d DAY ", intval($abandon_days))
  160. : ''
  161. );
  162. $contacts = q("SELECT `contact`.`id` FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
  163. WHERE `rel` IN (%d, %d) AND `poll` != '' AND `network` IN ('%s', '%s', '%s', '%s', '%s', '%s')
  164. $sql_extra
  165. AND NOT `self` AND NOT `contact`.`blocked` AND NOT `contact`.`readonly` AND NOT `contact`.`archive`
  166. AND NOT `user`.`account_expired` AND NOT `user`.`account_removed` $abandon_sql ORDER BY RAND()",
  167. intval(CONTACT_IS_SHARING),
  168. intval(CONTACT_IS_FRIEND),
  169. dbesc(NETWORK_DFRN),
  170. dbesc(NETWORK_ZOT),
  171. dbesc(NETWORK_OSTATUS),
  172. dbesc(NETWORK_FEED),
  173. dbesc(NETWORK_MAIL),
  174. dbesc(NETWORK_MAIL2)
  175. );
  176. if (!count($contacts)) {
  177. return;
  178. }
  179. foreach ($contacts as $c) {
  180. $res = q("SELECT * FROM `contact` WHERE `id` = %d LIMIT 1",
  181. intval($c['id'])
  182. );
  183. if((! $res) || (! count($res)))
  184. continue;
  185. foreach($res as $contact) {
  186. $xml = false;
  187. if($manual_id)
  188. $contact['last-update'] = '0000-00-00 00:00:00';
  189. if(in_array($contact['network'], array(NETWORK_DFRN, NETWORK_ZOT, NETWORK_OSTATUS)))
  190. $contact['priority'] = 2;
  191. if($contact['subhub'] AND in_array($contact['network'], array(NETWORK_DFRN, NETWORK_ZOT, NETWORK_OSTATUS))) {
  192. // We should be getting everything via a hub. But just to be sure, let's check once a day.
  193. // (You can make this more or less frequent if desired by setting 'pushpoll_frequency' appropriately)
  194. // This also lets us update our subscription to the hub, and add or replace hubs in case it
  195. // changed. We will only update hubs once a day, regardless of 'pushpoll_frequency'.
  196. $poll_interval = get_config('system','pushpoll_frequency');
  197. $contact['priority'] = (($poll_interval !== false) ? intval($poll_interval) : 3);
  198. }
  199. if($contact['priority'] AND !$force) {
  200. $update = false;
  201. $t = $contact['last-update'];
  202. /**
  203. * Based on $contact['priority'], should we poll this site now? Or later?
  204. */
  205. switch ($contact['priority']) {
  206. case 5:
  207. if(datetime_convert('UTC','UTC', 'now') > datetime_convert('UTC','UTC', $t . " + 1 month"))
  208. $update = true;
  209. break;
  210. case 4:
  211. if(datetime_convert('UTC','UTC', 'now') > datetime_convert('UTC','UTC', $t . " + 1 week"))
  212. $update = true;
  213. break;
  214. case 3:
  215. if(datetime_convert('UTC','UTC', 'now') > datetime_convert('UTC','UTC', $t . " + 1 day"))
  216. $update = true;
  217. break;
  218. case 2:
  219. if(datetime_convert('UTC','UTC', 'now') > datetime_convert('UTC','UTC', $t . " + 12 hour"))
  220. $update = true;
  221. break;
  222. case 1:
  223. default:
  224. if(datetime_convert('UTC','UTC', 'now') > datetime_convert('UTC','UTC', $t . " + 1 hour"))
  225. $update = true;
  226. break;
  227. }
  228. if (!$update)
  229. continue;
  230. }
  231. logger("Polling ".$contact["network"]." ".$contact["id"]." ".$contact["nick"]." ".$contact["name"]);
  232. proc_run(PRIORITY_MEDIUM,'include/onepoll.php',$contact['id']);
  233. if($interval)
  234. @time_sleep_until(microtime(true) + (float) $interval);
  235. }
  236. }
  237. }
  238. /**
  239. * @brief Clear cache entries
  240. *
  241. * @param App $a
  242. */
  243. function cron_clear_cache(&$a) {
  244. $last = get_config('system','cache_last_cleared');
  245. if($last) {
  246. $next = $last + (3600); // Once per hour
  247. $clear_cache = ($next <= time());
  248. } else
  249. $clear_cache = true;
  250. if (!$clear_cache)
  251. return;
  252. // clear old cache
  253. Cache::clear();
  254. // clear old item cache files
  255. clear_cache();
  256. // clear cache for photos
  257. clear_cache($a->get_basepath(), $a->get_basepath()."/photo");
  258. // clear smarty cache
  259. clear_cache($a->get_basepath()."/view/smarty3/compiled", $a->get_basepath()."/view/smarty3/compiled");
  260. // clear cache for image proxy
  261. if (!get_config("system", "proxy_disabled")) {
  262. clear_cache($a->get_basepath(), $a->get_basepath()."/proxy");
  263. $cachetime = get_config('system','proxy_cache_time');
  264. if (!$cachetime) $cachetime = PROXY_DEFAULT_TIME;
  265. q('DELETE FROM `photo` WHERE `uid` = 0 AND `resource-id` LIKE "pic:%%" AND `created` < NOW() - INTERVAL %d SECOND', $cachetime);
  266. }
  267. // Delete the cached OEmbed entries that are older than one year
  268. q("DELETE FROM `oembed` WHERE `created` < NOW() - INTERVAL 1 YEAR");
  269. // Delete the cached "parse_url" entries that are older than one year
  270. q("DELETE FROM `parsed_url` WHERE `created` < NOW() - INTERVAL 1 YEAR");
  271. // Maximum table size in megabyte
  272. $max_tablesize = intval(get_config('system','optimize_max_tablesize')) * 1000000;
  273. if ($max_tablesize == 0)
  274. $max_tablesize = 100 * 1000000; // Default are 100 MB
  275. if ($max_tablesize > 0) {
  276. // Minimum fragmentation level in percent
  277. $fragmentation_level = intval(get_config('system','optimize_fragmentation')) / 100;
  278. if ($fragmentation_level == 0)
  279. $fragmentation_level = 0.3; // Default value is 30%
  280. // Optimize some tables that need to be optimized
  281. $r = q("SHOW TABLE STATUS");
  282. foreach($r as $table) {
  283. // Don't optimize tables that are too large
  284. if ($table["Data_length"] > $max_tablesize)
  285. continue;
  286. // Don't optimize empty tables
  287. if ($table["Data_length"] == 0)
  288. continue;
  289. // Calculate fragmentation
  290. $fragmentation = $table["Data_free"] / ($table["Data_length"] + $table["Index_length"]);
  291. logger("Table ".$table["Name"]." - Fragmentation level: ".round($fragmentation * 100, 2), LOGGER_DEBUG);
  292. // Don't optimize tables that needn't to be optimized
  293. if ($fragmentation < $fragmentation_level)
  294. continue;
  295. // So optimize it
  296. logger("Optimize Table ".$table["Name"], LOGGER_DEBUG);
  297. q("OPTIMIZE TABLE `%s`", dbesc($table["Name"]));
  298. }
  299. }
  300. set_config('system','cache_last_cleared', time());
  301. }
  302. /**
  303. * @brief Repair missing values in Diaspora contacts
  304. *
  305. * @param App $a
  306. */
  307. function cron_repair_diaspora(&$a) {
  308. $r = q("SELECT `id`, `url` FROM `contact`
  309. WHERE `network` = '%s' AND (`batch` = '' OR `notify` = '' OR `poll` = '' OR pubkey = '')
  310. ORDER BY RAND() LIMIT 50", dbesc(NETWORK_DIASPORA));
  311. if ($r) {
  312. foreach ($r AS $contact) {
  313. if (poco_reachable($contact["url"])) {
  314. $data = probe_url($contact["url"]);
  315. if ($data["network"] == NETWORK_DIASPORA) {
  316. logger("Repair contact ".$contact["id"]." ".$contact["url"], LOGGER_DEBUG);
  317. q("UPDATE `contact` SET `batch` = '%s', `notify` = '%s', `poll` = '%s', pubkey = '%s' WHERE `id` = %d",
  318. dbesc($data["batch"]), dbesc($data["notify"]), dbesc($data["poll"]), dbesc($data["pubkey"]),
  319. intval($contact["id"]));
  320. }
  321. }
  322. }
  323. }
  324. }
  325. /**
  326. * @brief Do some repairs in database entries
  327. *
  328. */
  329. function cron_repair_database() {
  330. // Set the parent if it wasn't set. (Shouldn't happen - but does sometimes)
  331. // This call is very "cheap" so we can do it at any time without a problem
  332. q("UPDATE `item` INNER JOIN `item` AS `parent` ON `parent`.`uri` = `item`.`parent-uri` AND `parent`.`uid` = `item`.`uid` SET `item`.`parent` = `parent`.`id` WHERE `item`.`parent` = 0");
  333. // There was an issue where the nick vanishes from the contact table
  334. q("UPDATE `contact` INNER JOIN `user` ON `contact`.`uid` = `user`.`uid` SET `nick` = `nickname` WHERE `self` AND `nick`=''");
  335. // Update the global contacts for local users
  336. $r = q("SELECT `uid` FROM `user` WHERE `verified` AND NOT `blocked` AND NOT `account_removed` AND NOT `account_expired`");
  337. if ($r)
  338. foreach ($r AS $user)
  339. update_gcontact_for_user($user["uid"]);
  340. /// @todo
  341. /// - remove thread entries without item
  342. /// - remove sign entries without item
  343. /// - remove children when parent got lost
  344. /// - set contact-id in item when not present
  345. }
  346. if (array_search(__file__,get_included_files())===0){
  347. cron_run($_SERVER["argv"],$_SERVER["argc"]);
  348. killme();
  349. }