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.

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