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.
 
 
 
 
 
 

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