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.

282 lines
8.2 KiB

2 years ago
2 years ago
2 years ago
  1. <?php
  2. /**
  3. * @file src/Worker/Cron.php
  4. */
  5. namespace Friendica\Worker;
  6. use Friendica\Core\Addon;
  7. use Friendica\Core\Config;
  8. use Friendica\Core\Hook;
  9. use Friendica\Core\Logger;
  10. use Friendica\Core\Protocol;
  11. use Friendica\Core\Worker;
  12. use Friendica\Database\DBA;
  13. use Friendica\DI;
  14. use Friendica\Model\Contact;
  15. use Friendica\Util\DateTimeFormat;
  16. class Cron
  17. {
  18. public static function execute()
  19. {
  20. $a = DI::app();
  21. $last = Config::get('system', 'last_cron');
  22. $poll_interval = intval(Config::get('system', 'cron_interval'));
  23. if ($last) {
  24. $next = $last + ($poll_interval * 60);
  25. if ($next > time()) {
  26. Logger::log('cron intervall not reached');
  27. return;
  28. }
  29. }
  30. Logger::log('cron: start');
  31. // Fork the cron jobs in separate parts to avoid problems when one of them is crashing
  32. Hook::fork($a->queue['priority'], "cron");
  33. // run the process to update server directories in the background
  34. Worker::add(PRIORITY_LOW, 'UpdateServerDirectories');
  35. // run the process to update locally stored global contacts in the background
  36. Worker::add(PRIORITY_LOW, 'UpdateGContacts');
  37. // Expire and remove user entries
  38. Worker::add(PRIORITY_MEDIUM, "CronJobs", "expire_and_remove_users");
  39. // Call possible post update functions
  40. Worker::add(PRIORITY_LOW, "CronJobs", "post_update");
  41. // Clear cache entries
  42. Worker::add(PRIORITY_LOW, "CronJobs", "clear_cache");
  43. // Repair missing Diaspora values in contacts
  44. Worker::add(PRIORITY_LOW, "CronJobs", "repair_diaspora");
  45. // Repair entries in the database
  46. Worker::add(PRIORITY_LOW, "CronJobs", "repair_database");
  47. // once daily run birthday_updates and then expire in background
  48. $d1 = Config::get('system', 'last_expire_day');
  49. $d2 = intval(DateTimeFormat::utcNow('d'));
  50. // Daily cron calls
  51. if ($d2 != intval($d1)) {
  52. Worker::add(PRIORITY_LOW, "CronJobs", "update_contact_birthdays");
  53. Worker::add(PRIORITY_LOW, "CronJobs", "update_photo_albums");
  54. // update nodeinfo data
  55. Worker::add(PRIORITY_LOW, "CronJobs", "nodeinfo");
  56. Worker::add(PRIORITY_LOW, 'UpdateGServers');
  57. Worker::add(PRIORITY_LOW, 'UpdateSuggestions');
  58. Worker::add(PRIORITY_LOW, 'Expire');
  59. Worker::add(PRIORITY_MEDIUM, 'DBClean');
  60. // check upstream version?
  61. Worker::add(PRIORITY_LOW, 'CheckVersion');
  62. self::checkdeletedContacts();
  63. Config::set('system', 'last_expire_day', $d2);
  64. }
  65. // Hourly cron calls
  66. if (Config::get('system', 'last_cron_hourly', 0) + 3600 < time()) {
  67. // Delete all done workerqueue entries
  68. DBA::delete('workerqueue', ['`done` AND `executed` < UTC_TIMESTAMP() - INTERVAL 1 HOUR']);
  69. // Optimizing this table only last seconds
  70. if (Config::get('system', 'optimize_workerqueue', false)) {
  71. DBA::e("OPTIMIZE TABLE `workerqueue`");
  72. }
  73. Config::set('system', 'last_cron_hourly', time());
  74. }
  75. // Ensure to have a .htaccess file.
  76. // this is a precaution for systems that update automatically
  77. $basepath = $a->getBasePath();
  78. if (!file_exists($basepath . '/.htaccess') && is_writable($basepath)) {
  79. copy($basepath . '/.htaccess-dist', $basepath . '/.htaccess');
  80. }
  81. // Poll contacts
  82. self::pollContacts();
  83. // Update contact information
  84. self::updatePublicContacts();
  85. Logger::log('cron: end');
  86. Config::set('system', 'last_cron', time());
  87. return;
  88. }
  89. /**
  90. * Checks for contacts that are about to be deleted and ensures that they are removed.
  91. * This should be done automatically in the "remove" function. This here is a cleanup job.
  92. */
  93. private static function checkdeletedContacts()
  94. {
  95. $contacts = DBA::select('contact', ['id'], ['deleted' => true]);
  96. while ($contact = DBA::fetch($contacts)) {
  97. Worker::add(PRIORITY_MEDIUM, 'RemoveContact', $contact['id']);
  98. }
  99. DBA::close($contacts);
  100. }
  101. /**
  102. * @brief Update public contacts
  103. * @throws \Friendica\Network\HTTPException\InternalServerErrorException
  104. */
  105. private static function updatePublicContacts() {
  106. $count = 0;
  107. $last_updated = DateTimeFormat::utc('now - 1 week');
  108. $condition = ["`network` IN (?, ?, ?, ?) AND `uid` = ? AND NOT `self` AND `last-update` < ?",
  109. Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS, 0, $last_updated];
  110. $total = DBA::count('contact', $condition);
  111. $oldest_date = '';
  112. $oldest_id = '';
  113. $contacts = DBA::select('contact', ['id', 'last-update'], $condition, ['limit' => 100, 'order' => ['last-update']]);
  114. while ($contact = DBA::fetch($contacts)) {
  115. if (empty($oldest_id)) {
  116. $oldest_id = $contact['id'];
  117. $oldest_date = $contact['last-update'];
  118. }
  119. Worker::add(PRIORITY_LOW, "UpdateContact", $contact['id'], 'force');
  120. ++$count;
  121. }
  122. Logger::info('Initiated update for public contacts', ['interval' => $count, 'total' => $total, 'id' => $oldest_id, 'oldest' => $oldest_date]);
  123. DBA::close($contacts);
  124. }
  125. /**
  126. * @brief Poll contacts for unreceived messages
  127. *
  128. * @throws \Friendica\Network\HTTPException\InternalServerErrorException
  129. */
  130. private static function pollContacts() {
  131. $min_poll_interval = Config::get('system', 'min_poll_interval', 1);
  132. Addon::reload();
  133. $sql = "SELECT `contact`.`id`, `contact`.`nick`, `contact`.`name`, `contact`.`network`, `contact`.`archive`,
  134. `contact`.`last-update`, `contact`.`priority`, `contact`.`rel`, `contact`.`subhub`
  135. FROM `user`
  136. STRAIGHT_JOIN `contact`
  137. ON `contact`.`uid` = `user`.`uid` AND `contact`.`poll` != ''
  138. AND `contact`.`network` IN (?, ?, ?, ?, ?)
  139. AND NOT `contact`.`self` AND NOT `contact`.`blocked`
  140. AND `contact`.`rel` != ?
  141. WHERE NOT `user`.`account_expired` AND NOT `user`.`account_removed`";
  142. $parameters = [Protocol::DFRN, Protocol::ACTIVITYPUB, Protocol::OSTATUS, Protocol::FEED, Protocol::MAIL, Contact::FOLLOWER];
  143. // Only poll from those with suitable relationships,
  144. // and which have a polling address and ignore Diaspora since
  145. // we are unable to match those posts with a Diaspora GUID and prevent duplicates.
  146. $abandon_days = intval(Config::get('system', 'account_abandon_days'));
  147. if ($abandon_days < 1) {
  148. $abandon_days = 0;
  149. }
  150. if (!empty($abandon_days)) {
  151. $sql .= " AND `user`.`login_date` > UTC_TIMESTAMP() - INTERVAL ? DAY";
  152. $parameters[] = $abandon_days;
  153. }
  154. $contacts = DBA::p($sql, $parameters);
  155. if (!DBA::isResult($contacts)) {
  156. return;
  157. }
  158. while ($contact = DBA::fetch($contacts)) {
  159. // Friendica and OStatus are checked once a day
  160. if (in_array($contact['network'], [Protocol::DFRN, Protocol::OSTATUS])) {
  161. $contact['priority'] = 3;
  162. }
  163. // ActivityPub is checked once a week
  164. if ($contact['network'] == Protocol::ACTIVITYPUB) {
  165. $contact['priority'] = 4;
  166. }
  167. // Check archived contacts once a month
  168. if ($contact['archive']) {
  169. $contact['priority'] = 5;
  170. }
  171. if ($contact['priority'] >= 0) {
  172. $update = false;
  173. $t = $contact['last-update'];
  174. /*
  175. * Based on $contact['priority'], should we poll this site now? Or later?
  176. */
  177. switch ($contact['priority']) {
  178. case 5:
  179. if (DateTimeFormat::utcNow() > DateTimeFormat::utc($t . " + 1 month")) {
  180. $update = true;
  181. }
  182. break;
  183. case 4:
  184. if (DateTimeFormat::utcNow() > DateTimeFormat::utc($t . " + 1 week")) {
  185. $update = true;
  186. }
  187. break;
  188. case 3:
  189. if (DateTimeFormat::utcNow() > DateTimeFormat::utc($t . " + 1 day")) {
  190. $update = true;
  191. }
  192. break;
  193. case 2:
  194. if (DateTimeFormat::utcNow() > DateTimeFormat::utc($t . " + 12 hour")) {
  195. $update = true;
  196. }
  197. break;
  198. case 1:
  199. if (DateTimeFormat::utcNow() > DateTimeFormat::utc($t . " + 1 hour")) {
  200. $update = true;
  201. }
  202. break;
  203. case 0:
  204. default:
  205. if (DateTimeFormat::utcNow() > DateTimeFormat::utc($t . " + " . $min_poll_interval . " minute")) {
  206. $update = true;
  207. }
  208. break;
  209. }
  210. if (!$update) {
  211. continue;
  212. }
  213. }
  214. if (($contact['network'] == Protocol::FEED) && ($contact['priority'] <= 3)) {
  215. $priority = PRIORITY_MEDIUM;
  216. } elseif ($contact['archive']) {
  217. $priority = PRIORITY_NEGLIGIBLE;
  218. } else {
  219. $priority = PRIORITY_LOW;
  220. }
  221. Logger::log("Polling " . $contact["network"] . " " . $contact["id"] . " " . $contact['priority'] . " " . $contact["nick"] . " " . $contact["name"]);
  222. Worker::add(['priority' => $priority, 'dont_fork' => true, 'force_priority' => true], 'OnePoll', (int)$contact['id']);
  223. }
  224. DBA::close($contacts);
  225. }
  226. }