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