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.

443 lines
12 KiB

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