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