]> git.mxchange.org Git - friendica.git/blob - src/Worker/Cron.php
Merge pull request #9073 from annando/foreign-2
[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                 // Expire and remove user entries
61                 Worker::add(PRIORITY_MEDIUM, 'ExpireAndRemoveUsers');
62
63                 // Call possible post update functions
64                 Worker::add(PRIORITY_LOW, 'PostUpdate');
65
66                 // Repair entries in the database
67                 Worker::add(PRIORITY_LOW, 'RepairDatabase');
68
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'));
72
73                 // Daily cron calls
74                 if ($d2 != intval($d1)) {
75
76                         Worker::add(PRIORITY_LOW, 'UpdateContactBirthdays');
77
78                         Worker::add(PRIORITY_LOW, 'UpdatePhotoAlbums');
79
80                         // update nodeinfo data
81                         Worker::add(PRIORITY_LOW, 'NodeInfo');
82
83                         Worker::add(PRIORITY_LOW, 'UpdateGServers');
84
85                         Worker::add(PRIORITY_LOW, 'Expire');
86
87                         Worker::add(PRIORITY_MEDIUM, 'DBClean');
88
89                         Worker::add(PRIORITY_LOW, 'ExpireConversations');
90
91                         Worker::add(PRIORITY_LOW, 'CleanItemUri');
92
93                         // check upstream version?
94                         Worker::add(PRIORITY_LOW, 'CheckVersion');
95
96                         self::checkdeletedContacts();
97
98                         if (DI::config()->get('system', 'optimize_tables')) {
99                                 self::optimizeTables();
100                         }
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                         // Search for new contacts in the directory
109                         if (DI::config()->get('system', 'synchronize_directory')) {
110                                 Worker::add(PRIORITY_LOW, 'PullDirectory');
111                         }
112
113                         // Delete all done workerqueue entries
114                         DBA::delete('workerqueue', ['`done` AND `executed` < UTC_TIMESTAMP() - INTERVAL 1 HOUR']);
115
116                         // Optimizing this table only last seconds
117                         if (DI::config()->get('system', 'optimize_tables')) {
118                                 // We are acquiring the two locks from the worker to avoid locking problems
119                                 if (DI::lock()->acquire(Worker::LOCK_PROCESS, 10)) {
120                                         if (DI::lock()->acquire(Worker::LOCK_WORKER, 10)) {
121                                                 DBA::e("OPTIMIZE TABLE `workerqueue`");
122                                                 DBA::e("OPTIMIZE TABLE `process`");                     
123                                                 DI::lock()->release(Worker::LOCK_WORKER);
124                                         }
125                                         DI::lock()->release(Worker::LOCK_PROCESS);
126                                 }
127                         }
128
129                         // Clear cache entries
130                         Worker::add(PRIORITY_LOW, 'ClearCache');
131
132                         DI::config()->set('system', 'last_cron_hourly', time());
133                 }
134
135                 // Ensure to have a .htaccess file.
136                 // this is a precaution for systems that update automatically
137                 $basepath = $a->getBasePath();
138                 if (!file_exists($basepath . '/.htaccess') && is_writable($basepath)) {
139                         copy($basepath . '/.htaccess-dist', $basepath . '/.htaccess');
140                 }
141
142                 // Poll contacts
143                 self::pollContacts();
144
145                 // Update contact information
146                 self::updatePublicContacts();
147
148                 Logger::log('cron: end');
149
150                 DI::config()->set('system', 'last_cron', time());
151
152                 return;
153         }
154
155         /**
156          * Optimize tables that are known to grow and shrink all the time
157          *
158          * @return void
159          */
160         private static function optimizeTables()
161         {
162                 Logger::info('Optimize start');
163
164                 DBA::e("OPTIMIZE TABLE `auth_codes`");
165                 DBA::e("OPTIMIZE TABLE `challenge`");
166                 DBA::e("OPTIMIZE TABLE `locks`");
167                 DBA::e("OPTIMIZE TABLE `profile_check`");
168                 DBA::e("OPTIMIZE TABLE `session`");
169                 DBA::e("OPTIMIZE TABLE `tokens`");
170
171                 DI::lock()->release('optimize_tables');
172         }
173
174         /**
175          * Checks for contacts that are about to be deleted and ensures that they are removed.
176          * This should be done automatically in the "remove" function. This here is a cleanup job.
177          */
178         private static function checkdeletedContacts()
179         {
180                 $contacts = DBA::select('contact', ['id'], ['deleted' => true]);
181                 while ($contact = DBA::fetch($contacts)) {
182                         Worker::add(PRIORITY_MEDIUM, 'RemoveContact', $contact['id']);
183                 }
184                 DBA::close($contacts);
185         }
186
187         /**
188          * Update public contacts
189          *
190          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
191          */
192         private static function updatePublicContacts() {
193                 $count = 0;
194                 $last_updated = DateTimeFormat::utc('now - 1 week');
195                 $condition = ["`network` IN (?, ?, ?, ?) AND `uid` = ? AND NOT `self` AND `last-update` < ?",
196                         Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS, 0, $last_updated];
197
198                 $oldest_date = '';
199                 $oldest_id = '';
200                 $contacts = DBA::select('contact', ['id', 'last-update'], $condition, ['limit' => 100, 'order' => ['last-update']]);
201                 while ($contact = DBA::fetch($contacts)) {
202                         if (empty($oldest_id)) {
203                                 $oldest_id = $contact['id'];
204                                 $oldest_date = $contact['last-update'];
205                         }
206                         Worker::add(PRIORITY_LOW, "UpdateContact", $contact['id']);
207                         ++$count;
208                 }
209                 Logger::info('Initiated update for public contacts', ['interval' => $count, 'id' => $oldest_id, 'oldest' => $oldest_date]);
210                 DBA::close($contacts);
211         }
212
213         /**
214          * Poll contacts for unreceived messages
215          *
216          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
217          */
218         private static function pollContacts() {
219                 Addon::reload();
220
221                 $sql = "SELECT `contact`.`id`, `contact`.`nick`, `contact`.`name`, `contact`.`network`, `contact`.`archive`,
222                                         `contact`.`last-update`, `contact`.`priority`, `contact`.`rating`, `contact`.`rel`, `contact`.`subhub`
223                                 FROM `user`
224                                 STRAIGHT_JOIN `contact`
225                                 ON `contact`.`uid` = `user`.`uid` AND `contact`.`poll` != ''
226                                         AND `contact`.`network` IN (?, ?, ?, ?, ?)
227                                         AND NOT `contact`.`self` AND NOT `contact`.`blocked`
228                                         AND `contact`.`rel` != ?
229                                 WHERE NOT `user`.`account_expired` AND NOT `user`.`account_removed`";
230
231                 $parameters = [Protocol::DFRN, Protocol::ACTIVITYPUB, Protocol::OSTATUS, Protocol::FEED, Protocol::MAIL, Contact::FOLLOWER];
232
233                 // Only poll from those with suitable relationships,
234                 // and which have a polling address and ignore Diaspora since
235                 // we are unable to match those posts with a Diaspora GUID and prevent duplicates.
236                 $abandon_days = intval(DI::config()->get('system', 'account_abandon_days'));
237                 if ($abandon_days < 1) {
238                         $abandon_days = 0;
239                 }
240
241                 if (!empty($abandon_days)) {
242                         $sql .= " AND `user`.`login_date` > UTC_TIMESTAMP() - INTERVAL ? DAY";
243                         $parameters[] = $abandon_days;
244                 }
245
246                 $contacts = DBA::p($sql, $parameters);
247
248                 if (!DBA::isResult($contacts)) {
249                         return;
250                 }
251
252                 while ($contact = DBA::fetch($contacts)) {
253                         $ratings = [0, 3, 7, 8, 9, 10];
254                         if (DI::config()->get('system', 'adjust_poll_frequency') && ($contact['network'] == Protocol::FEED)) {
255                                 $rating = $contact['rating'];
256                         } elseif (array_key_exists($contact['priority'], $ratings)) {
257                                 $rating = $ratings[$contact['priority']];
258                         } else {
259                                 $rating = -1;
260                         }
261
262                         // Friendica and OStatus are checked once a day
263                         if (in_array($contact['network'], [Protocol::DFRN, Protocol::OSTATUS])) {
264                                 $rating = 8;
265                         }
266
267                         // ActivityPub is checked once a week
268                         if ($contact['network'] == Protocol::ACTIVITYPUB) {
269                                 $rating = 9;
270                         }
271
272                         // Check archived contacts once a month
273                         if ($contact['archive']) {
274                                 $rating = 10;
275                         }
276
277                         if ($rating < 0) {
278                                 continue;
279                         }
280                         /*
281                          * Based on $contact['priority'], should we poll this site now? Or later?
282                          */
283
284                         $min_poll_interval = DI::config()->get('system', 'min_poll_interval');
285
286                         $poll_intervals = [$min_poll_interval . ' minute', '15 minute', '30 minute',
287                                 '1 hour', '2 hour', '3 hour', '6 hour', '12 hour' ,'1 day', '1 week', '1 month'];
288
289                         $now = DateTimeFormat::utcNow();
290                         $next_update = DateTimeFormat::utc($contact['last-update'] . ' + ' . $poll_intervals[$rating]);
291
292                         if (empty($poll_intervals[$rating]) || ($now < $next_update))  {
293                                 Logger::debug('No update', ['cid' => $contact['id'], 'rating' => $rating, 'next' => $next_update, 'now' => $now]);
294                                 continue;
295                         }
296
297                         if ((($contact['network'] == Protocol::FEED) && ($contact['priority'] <= 3)) || ($contact['network'] == Protocol::MAIL)) {
298                                 $priority = PRIORITY_MEDIUM;
299                         } elseif ($contact['archive']) {
300                                 $priority = PRIORITY_NEGLIGIBLE;
301                         } else {
302                                 $priority = PRIORITY_LOW;
303                         }
304
305                         Logger::log("Polling " . $contact["network"] . " " . $contact["id"] . " " . $contact['priority'] . " " . $contact["nick"] . " " . $contact["name"]);
306
307                         Worker::add(['priority' => $priority, 'dont_fork' => true, 'force_priority' => true], 'OnePoll', (int)$contact['id']);
308                 }
309                 DBA::close($contacts);
310         }
311 }