3 * @copyright Copyright (C) 2020, Friendica
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 namespace Friendica\Worker;
24 use Friendica\Core\Addon;
25 use Friendica\Core\Hook;
26 use Friendica\Core\Logger;
27 use Friendica\Core\Protocol;
28 use Friendica\Core\Worker;
29 use Friendica\Database\DBA;
31 use Friendica\Model\Contact;
32 use Friendica\Util\DateTimeFormat;
36 public static function execute()
40 $last = DI::config()->get('system', 'last_cron');
42 $poll_interval = intval(DI::config()->get('system', 'cron_interval'));
45 $next = $last + ($poll_interval * 60);
47 Logger::log('cron intervall not reached');
52 Logger::log('cron: start');
54 // Fork the cron jobs in separate parts to avoid problems when one of them is crashing
55 Hook::fork($a->queue['priority'], "cron");
57 // run the process to update server directories in the background
58 Worker::add(PRIORITY_LOW, 'UpdateServerDirectories');
60 // Expire and remove user entries
61 Worker::add(PRIORITY_MEDIUM, 'ExpireAndRemoveUsers');
63 // Call possible post update functions
64 Worker::add(PRIORITY_LOW, 'PostUpdate');
66 // Repair entries in the database
67 Worker::add(PRIORITY_LOW, 'RepairDatabase');
69 // once daily run birthday_updates and then expire in background
70 $d1 = DI::config()->get('system', 'last_expire_day');
71 $d2 = intval(DateTimeFormat::utcNow('d'));
74 if ($d2 != intval($d1)) {
76 Worker::add(PRIORITY_LOW, 'UpdateContactBirthdays');
78 Worker::add(PRIORITY_LOW, 'UpdatePhotoAlbums');
80 // update nodeinfo data
81 Worker::add(PRIORITY_LOW, 'NodeInfo');
83 Worker::add(PRIORITY_LOW, 'UpdateGServers');
85 Worker::add(PRIORITY_LOW, 'Expire');
87 Worker::add(PRIORITY_MEDIUM, 'DBClean');
89 // check upstream version?
90 Worker::add(PRIORITY_LOW, 'CheckVersion');
92 self::checkdeletedContacts();
94 if (DI::config()->get('system', 'optimize_tables')) {
95 self::optimizeTables();
98 DI::config()->set('system', 'last_expire_day', $d2);
102 if (DI::config()->get('system', 'last_cron_hourly', 0) + 3600 < time()) {
104 // Search for new contacts in the directory
105 if (DI::config()->get('system', 'synchronize_directory')) {
106 Worker::add(PRIORITY_LOW, 'PullDirectory');
109 // Delete all done workerqueue entries
110 DBA::delete('workerqueue', ['`done` AND `executed` < UTC_TIMESTAMP() - INTERVAL 1 HOUR']);
112 // Optimizing this table only last seconds
113 if (DI::config()->get('system', 'optimize_tables')) {
114 // We are acquiring the two locks from the worker to avoid locking problems
115 if (DI::lock()->acquire(Worker::LOCK_PROCESS, 10)) {
116 if (DI::lock()->acquire(Worker::LOCK_WORKER, 10)) {
117 DBA::e("OPTIMIZE TABLE `workerqueue`");
118 DBA::e("OPTIMIZE TABLE `process`");
119 DI::lock()->release(Worker::LOCK_WORKER);
121 DI::lock()->release(Worker::LOCK_PROCESS);
125 // Clear cache entries
126 Worker::add(PRIORITY_LOW, 'ClearCache');
128 DI::config()->set('system', 'last_cron_hourly', time());
131 // Ensure to have a .htaccess file.
132 // this is a precaution for systems that update automatically
133 $basepath = $a->getBasePath();
134 if (!file_exists($basepath . '/.htaccess') && is_writable($basepath)) {
135 copy($basepath . '/.htaccess-dist', $basepath . '/.htaccess');
139 self::pollContacts();
141 // Update contact information
142 self::updatePublicContacts();
144 Logger::log('cron: end');
146 DI::config()->set('system', 'last_cron', time());
152 * Optimize tables that are known to grow and shrink all the time
156 private static function optimizeTables()
158 Logger::info('Optimize start');
160 DBA::e("OPTIMIZE TABLE `auth_codes`");
161 DBA::e("OPTIMIZE TABLE `challenge`");
162 DBA::e("OPTIMIZE TABLE `locks`");
163 DBA::e("OPTIMIZE TABLE `profile_check`");
164 DBA::e("OPTIMIZE TABLE `session`");
165 DBA::e("OPTIMIZE TABLE `tokens`");
167 DI::lock()->release('optimize_tables');
171 * Checks for contacts that are about to be deleted and ensures that they are removed.
172 * This should be done automatically in the "remove" function. This here is a cleanup job.
174 private static function checkdeletedContacts()
176 $contacts = DBA::select('contact', ['id'], ['deleted' => true]);
177 while ($contact = DBA::fetch($contacts)) {
178 Worker::add(PRIORITY_MEDIUM, 'RemoveContact', $contact['id']);
180 DBA::close($contacts);
184 * Update public contacts
186 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
188 private static function updatePublicContacts() {
190 $last_updated = DateTimeFormat::utc('now - 1 week');
191 $condition = ["`network` IN (?, ?, ?, ?) AND `uid` = ? AND NOT `self` AND `last-update` < ?",
192 Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS, 0, $last_updated];
196 $contacts = DBA::select('contact', ['id', 'last-update'], $condition, ['limit' => 100, 'order' => ['last-update']]);
197 while ($contact = DBA::fetch($contacts)) {
198 if (empty($oldest_id)) {
199 $oldest_id = $contact['id'];
200 $oldest_date = $contact['last-update'];
202 Worker::add(PRIORITY_LOW, "UpdateContact", $contact['id']);
205 Logger::info('Initiated update for public contacts', ['interval' => $count, 'id' => $oldest_id, 'oldest' => $oldest_date]);
206 DBA::close($contacts);
210 * Poll contacts for unreceived messages
212 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
214 private static function pollContacts() {
217 $sql = "SELECT `contact`.`id`, `contact`.`nick`, `contact`.`name`, `contact`.`network`, `contact`.`archive`,
218 `contact`.`last-update`, `contact`.`priority`, `contact`.`rating`, `contact`.`rel`, `contact`.`subhub`
220 STRAIGHT_JOIN `contact`
221 ON `contact`.`uid` = `user`.`uid` AND `contact`.`poll` != ''
222 AND `contact`.`network` IN (?, ?, ?, ?, ?)
223 AND NOT `contact`.`self` AND NOT `contact`.`blocked`
224 AND `contact`.`rel` != ?
225 WHERE NOT `user`.`account_expired` AND NOT `user`.`account_removed`";
227 $parameters = [Protocol::DFRN, Protocol::ACTIVITYPUB, Protocol::OSTATUS, Protocol::FEED, Protocol::MAIL, Contact::FOLLOWER];
229 // Only poll from those with suitable relationships,
230 // and which have a polling address and ignore Diaspora since
231 // we are unable to match those posts with a Diaspora GUID and prevent duplicates.
232 $abandon_days = intval(DI::config()->get('system', 'account_abandon_days'));
233 if ($abandon_days < 1) {
237 if (!empty($abandon_days)) {
238 $sql .= " AND `user`.`login_date` > UTC_TIMESTAMP() - INTERVAL ? DAY";
239 $parameters[] = $abandon_days;
242 $contacts = DBA::p($sql, $parameters);
244 if (!DBA::isResult($contacts)) {
248 while ($contact = DBA::fetch($contacts)) {
249 $ratings = [0, 3, 7, 8, 9, 10];
250 if (DI::config()->get('system', 'adjust_poll_frequency') && ($contact['network'] == Protocol::FEED)) {
251 $rating = $contact['rating'];
252 } elseif (array_key_exists($contact['priority'], $ratings)) {
253 $rating = $ratings[$contact['priority']];
258 // Friendica and OStatus are checked once a day
259 if (in_array($contact['network'], [Protocol::DFRN, Protocol::OSTATUS])) {
263 // ActivityPub is checked once a week
264 if ($contact['network'] == Protocol::ACTIVITYPUB) {
268 // Check archived contacts once a month
269 if ($contact['archive']) {
277 * Based on $contact['priority'], should we poll this site now? Or later?
280 $min_poll_interval = DI::config()->get('system', 'min_poll_interval');
282 $poll_intervals = [$min_poll_interval . ' minute', '15 minute', '30 minute',
283 '1 hour', '2 hour', '3 hour', '6 hour', '12 hour' ,'1 day', '1 week', '1 month'];
285 $now = DateTimeFormat::utcNow();
286 $next_update = DateTimeFormat::utc($contact['last-update'] . ' + ' . $poll_intervals[$rating]);
288 if (empty($poll_intervals[$rating]) || ($now < $next_update)) {
289 Logger::debug('No update', ['cid' => $contact['id'], 'rating' => $rating, 'next' => $next_update, 'now' => $now]);
293 if ((($contact['network'] == Protocol::FEED) && ($contact['priority'] <= 3)) || ($contact['network'] == Protocol::MAIL)) {
294 $priority = PRIORITY_MEDIUM;
295 } elseif ($contact['archive']) {
296 $priority = PRIORITY_NEGLIGIBLE;
298 $priority = PRIORITY_LOW;
301 Logger::log("Polling " . $contact["network"] . " " . $contact["id"] . " " . $contact['priority'] . " " . $contact["nick"] . " " . $contact["name"]);
303 Worker::add(['priority' => $priority, 'dont_fork' => true, 'force_priority' => true], 'OnePoll', (int)$contact['id']);
305 DBA::close($contacts);