]> git.mxchange.org Git - friendica.git/blob - src/Protocol/ActivityPub/Queue.php
Avoid endless loop while deleting
[friendica.git] / src / Protocol / ActivityPub / Queue.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2022, the Friendica project
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\Protocol\ActivityPub;
23
24 use Friendica\Core\Logger;
25 use Friendica\Database\Database;
26 use Friendica\Database\DBA;
27 use Friendica\DI;
28 use Friendica\Util\DateTimeFormat;
29 use Friendica\Util\JsonLD;
30
31 /**
32  * This class handles the processing of incoming posts
33  */
34 class Queue
35 {
36         /**
37          * Add activity to the queue
38          *
39          * @param array $activity
40          * @param string $type
41          * @param integer $uid
42          * @param string $http_signer
43          * @param boolean $push
44          * @return array
45          */
46         public static function add(array $activity, string $type, int $uid, string $http_signer, bool $push, bool $trust_source): array
47         {
48                 $fields = [
49                         'activity-id' => $activity['id'],
50                         'object-id'   => $activity['object_id'],
51                         'type'        => $type,
52                         'object-type' => $activity['object_type'],
53                         'activity'    => json_encode($activity, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT),
54                         'received'    => DateTimeFormat::utcNow(),
55                         'push'        => $push,
56                         'trust'       => $trust_source,
57                 ];
58
59                 if (!empty($activity['reply-to-id'])) {
60                         $fields['in-reply-to-id'] = $activity['reply-to-id'];
61                 }
62
63                 if (!empty($activity['context'])) {
64                         $fields['conversation'] = $activity['context'];
65                 } elseif (!empty($activity['conversation'])) {
66                         $fields['conversation'] = $activity['conversation'];
67                 }
68
69                 if (!empty($activity['object_object_type'])) {
70                         $fields['object-object-type'] = $activity['object_object_type'];
71                 }
72
73                 if (!empty($http_signer)) {
74                         $fields['signer'] = $http_signer;
75                 }
76
77                 DBA::insert('inbox-entry', $fields, Database::INSERT_IGNORE);
78
79                 $queue = DBA::selectFirst('inbox-entry', ['id'], ['activity-id' => $activity['id']]);
80                 if (!empty($queue['id'])) {
81                         $activity['entry-id'] = $queue['id'];
82                         DBA::insert('inbox-entry-receiver', ['queue-id' => $queue['id'], 'uid' => $uid], Database::INSERT_IGNORE);
83                 }
84                 return $activity;
85         }
86
87         /**
88          * Remove activity from the queue
89          *
90          * @param array $activity
91          * @return void
92          */
93         public static function remove(array $activity = [])
94         {
95                 if (empty($activity['entry-id'])) {
96                         return;
97                 }
98                 DBA::delete('inbox-entry', ['id' => $activity['entry-id']]);
99         }
100
101         /**
102          * Delete all entries that depend on the given worker id
103          *
104          * @param integer $wid
105          * @return void
106          */
107         public static function deleteByWorkerId(int $wid)
108         {
109                 $entries = DBA::select('inbox-entry', ['id'], ['wid' => $wid]);
110                 while ($entry = DBA::fetch($entries)) {
111                         self::deleteById($entry['id']);
112                 }
113                 DBA::close($entries);
114         }
115
116         /**
117          * Delete recursively an entry and all their children
118          *
119          * @param integer $id
120          * @return void
121          */
122         public static function deleteById(int $id)
123         {
124                 $entry = DBA::selectFirst('inbox-entry', ['id', 'object-id'], ['id' => $id]);
125                 if (empty($entry)) {
126                         return;
127                 }
128
129                 $children = DBA::select('inbox-entry', ['id'], ['in-reply-to-id' => $entry['object-id']]);
130                 while ($child = DBA::fetch($children)) {
131                         if ($id == $child['id']) {
132                                 continue;
133                         }
134                         self::deleteById($child['id']);
135                 }
136                 DBA::close($children);
137                 DBA::delete('inbox-entry', ['id' => $entry['id']]);
138         }
139
140         /**
141          * Set the worker id for the queue entry
142          *
143          * @param array $activity
144          * @param int   $wid
145          * @return void
146          */
147         public static function setWorkerId(array $activity, int $wid)
148         {
149                 if (empty($activity['entry-id']) || empty($wid)) {
150                         return;
151                 }
152                 DBA::update('inbox-entry', ['wid' => $wid], ['id' => $activity['entry-id']]);
153         }
154
155         /**
156          * Check if there is an assigned worker task
157          *
158          * @param array $activity
159          * @return bool
160          */
161         public static function hasWorker(array $activity = []): bool
162         {
163                 if (empty($activity['worker-id'])) {
164                         return false;
165                 }
166                 return DBA::exists('workerqueue', ['id' => $activity['worker-id'], 'done' => false]);
167         }
168
169         /**
170          * Process the activity with the given id
171          *
172          * @param integer $id
173          *
174          * @return bool
175          */
176         public static function process(int $id): bool
177         {
178                 $entry = DBA::selectFirst('inbox-entry', [], ['id' => $id]);
179                 if (empty($entry)) {
180                         return false;
181                 }
182
183                 Logger::debug('Processing queue entry', ['id' => $entry['id'], 'type' => $entry['type'], 'object-type' => $entry['object-type'], 'uri' => $entry['object-id'], 'in-reply-to' => $entry['in-reply-to-id']]);
184
185                 $activity = json_decode($entry['activity'], true);
186                 $type     = $entry['type'];
187                 $push     = $entry['push'];
188
189                 $activity['entry-id']        = $entry['id'];
190                 $activity['worker-id']       = $entry['wid'];
191                 $activity['recursion-depth'] = 0;
192
193                 $receivers = DBA::select('inbox-entry-receiver', ['uid'], ['queue-id' => $entry['id']]);
194                 while ($receiver = DBA::fetch($receivers)) {
195                         if (!in_array($receiver['uid'], $activity['receiver'])) {
196                                 $activity['receiver'][] = $receiver['uid'];
197                         }
198                 }
199                 DBA::close($receivers);
200
201                 if (!Receiver::routeActivities($activity, $type, $push)) {
202                         self::remove($activity);
203                 }
204
205                 return true;
206         }
207
208         /**
209          * Process all activities
210          *
211          * @return void
212          */
213         public static function processAll()
214         {
215                 $entries = DBA::select('inbox-entry', ['id', 'type', 'object-type', 'object-id', 'in-reply-to-id'], ["`trust` AND `wid` IS NULL"], ['order' => ['id' => true]]);
216                 while ($entry = DBA::fetch($entries)) {
217                         // We don't need to process entries that depend on already existing entries.
218                         if (!empty($entry['in-reply-to-id']) && DBA::exists('inbox-entry', ["`id` != ? AND `object-id` = ?", $entry['id'], $entry['in-reply-to-id']])) {
219                                 continue;
220                         }
221                         Logger::debug('Process leftover entry', $entry);
222                         self::process($entry['id']);
223                 }
224                 DBA::close($entries);
225         }
226
227         /**
228          * Clear old activities
229          *
230          * @return void
231          */
232         public static function clear()
233         {
234                 // We delete all entries that aren't associated with a worker entry after seven days.
235                 // The other entries are deleted when the worker deferred for too long.
236                 DBA::delete('inbox-entry', ["`wid` IS NULL AND `received` < ?", DateTimeFormat::utc('now - 7 days')]);
237
238                 // Optimizing this table only last seconds
239                 if (DI::config()->get('system', 'optimize_tables')) {
240                         Logger::info('Optimize start');
241                         DBA::e("OPTIMIZE TABLE `inbox-entry`");
242                         Logger::info('Optimize end');
243                 }
244         }
245
246         /**
247          * Process all activities that are children of a given post url
248          *
249          * @param string $uri
250          * @return int
251          */
252         public static function processReplyByUri(string $uri): int
253         {
254                 $count = 0;
255                 $entries = DBA::select('inbox-entry', ['id'], ["`in-reply-to-id` = ? AND `object-id` != ?", $uri, $uri]);
256                 while ($entry = DBA::fetch($entries)) {
257                         $count += 1;
258                         self::process($entry['id']);
259                 }
260                 DBA::close($entries);
261                 return $count;
262         }
263
264         /**
265          * Checks if there are children of the given uri
266          *
267          * @param string $uri
268          *
269          * @return bool
270          */
271         public static function hasChildren(string $uri): bool
272         {
273                 return DBA::exists('inbox-entry', ["`in-reply-to-id` = ? AND `object-id` != ?", $uri, $uri]);
274         }
275
276         /**
277          * Prepare the queue entry.
278          * This is a test function that is used solely for development.
279          *
280          * @param integer $id
281          * @return array
282          */
283         public static function reprepareActivityById(int $id): array
284         {
285                 $entry = DBA::selectFirst('inbox-entry', [], ['id' => $id]);
286                 if (empty($entry)) {
287                         return [];
288                 }
289
290                 $receiver = DBA::selectFirst('inbox-entry-receiver', ['uid'], ['queue-id' => $id]);
291                 if (!empty($receiver)) {
292                         $uid = $receiver['uid'];
293                 } else {
294                         $uid = 0;
295                 }
296
297                 $trust_source = $entry['trust'];
298
299                 $data     = json_decode($entry['activity'], true);
300                 $activity = json_decode($data['raw'], true);
301
302                 $ldactivity = JsonLD::compact($activity);
303                 return [
304                         'data'  => Receiver::prepareObjectData($ldactivity, $uid, $entry['push'], $trust_source),
305                         'trust' => $trust_source
306                 ];
307         }
308
309         /**
310          * Set the trust for all untrusted entries.
311          * This is a test function that is used solely for development.
312          *
313          * @return void
314          */
315         public static function reprepareAll()
316         {
317                 $entries = DBA::select('inbox-entry', ['id'], ["NOT `trust` AND `wid` IS NULL"], ['order' => ['id' => true]]);
318                 while ($entry = DBA::fetch($entries)) {
319                         $data = self::reprepareActivityById($entry['id'], false);
320                         if ($data['trust']) {
321                                 DBA::update('inbox-entry', ['trust' => true], ['id' => $entry['id']]);
322                         }
323                 }
324                 DBA::close($entries);
325
326         }
327 }