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