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