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.

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