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