]> git.mxchange.org Git - friendica.git/blob - src/Model/Item.php
b12eab94835cc30f576f9181ea2966924f6b0b25
[friendica.git] / src / Model / Item.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\Model;
23
24 use Friendica\Content\Text\BBCode;
25 use Friendica\Content\Text\HTML;
26 use Friendica\Core\Hook;
27 use Friendica\Core\Logger;
28 use Friendica\Core\Protocol;
29 use Friendica\Core\Renderer;
30 use Friendica\Core\Session;
31 use Friendica\Core\System;
32 use Friendica\Model\Tag;
33 use Friendica\Core\Worker;
34 use Friendica\Database\DBA;
35 use Friendica\DI;
36 use Friendica\Model\Post;
37 use Friendica\Protocol\Activity;
38 use Friendica\Protocol\ActivityPub;
39 use Friendica\Protocol\Diaspora;
40 use Friendica\Util\DateTimeFormat;
41 use Friendica\Util\Map;
42 use Friendica\Util\Network;
43 use Friendica\Util\Proxy;
44 use Friendica\Util\Strings;
45 use Friendica\Util\Temporal;
46 use Friendica\Worker\Delivery;
47 use GuzzleHttp\Psr7\Uri;
48 use LanguageDetection\Language;
49
50 class Item
51 {
52         // Posting types, inspired by https://www.w3.org/TR/activitystreams-vocabulary/#object-types
53         const PT_ARTICLE = 0;
54         const PT_NOTE = 1;
55         const PT_PAGE = 2;
56         const PT_IMAGE = 16;
57         const PT_AUDIO = 17;
58         const PT_VIDEO = 18;
59         const PT_DOCUMENT = 19;
60         const PT_EVENT = 32;
61         const PT_POLL = 33;
62         const PT_PERSONAL_NOTE = 128;
63
64         // Posting reasons (Why had a post been stored for a user?)
65         const PR_NONE = 0;
66         const PR_TAG = 64;
67         const PR_TO = 65;
68         const PR_CC = 66;
69         const PR_BTO = 67;
70         const PR_BCC = 68;
71         const PR_FOLLOWER = 69;
72         const PR_ANNOUNCEMENT = 70;
73         const PR_COMMENT = 71;
74         const PR_STORED = 72;
75         const PR_GLOBAL = 73;
76         const PR_RELAY = 74;
77         const PR_FETCHED = 75;
78         const PR_COMPLETION = 76;
79         const PR_DIRECT = 77;
80         const PR_ACTIVITY = 78;
81         const PR_DISTRIBUTE = 79;
82         const PR_PUSHED = 80;
83         const PR_LOCAL = 81;
84
85         // system.accept_only_sharer setting values
86         const COMPLETION_NONE    = 1;
87         const COMPLETION_COMMENT = 0;
88         const COMPLETION_LIKE    = 2;
89
90         // Field list that is used to display the items
91         const DISPLAY_FIELDLIST = [
92                 'uid', 'id', 'parent', 'guid', 'network', 'gravity',
93                 'uri-id', 'uri', 'thr-parent-id', 'thr-parent', 'parent-uri-id', 'parent-uri', 'conversation',
94                 'commented', 'created', 'edited', 'received', 'verb', 'object-type', 'postopts', 'plink',
95                 'wall', 'private', 'starred', 'origin', 'parent-origin', 'title', 'body', 'language',
96                 'content-warning', 'location', 'coord', 'app', 'rendered-hash', 'rendered-html', 'object',
97                 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'mention', 'global',
98                 'author-id', 'author-link', 'author-name', 'author-avatar', 'author-network', 'author-updated', 'author-gsid', 'author-addr', 'author-uri-id',
99                 'owner-id', 'owner-link', 'owner-name', 'owner-avatar', 'owner-network', 'owner-contact-type', 'owner-updated',
100                 'causer-id', 'causer-link', 'causer-name', 'causer-avatar', 'causer-contact-type', 'causer-network',
101                 'contact-id', 'contact-uid', 'contact-link', 'contact-name', 'contact-avatar',
102                 'writable', 'self', 'cid', 'alias',
103                 'event-created', 'event-edited', 'event-start', 'event-finish',
104                 'event-summary', 'event-desc', 'event-location', 'event-type',
105                 'event-nofinish', 'event-ignore', 'event-id',
106                 'question-id', 'question-multiple', 'question-voters', 'question-end-time',
107                 'has-categories', 'has-media',
108                 'delivery_queue_count', 'delivery_queue_done', 'delivery_queue_failed'
109         ];
110
111         // Field list that is used to deliver items via the protocols
112         const DELIVER_FIELDLIST = ['uid', 'id', 'parent', 'uri-id', 'uri', 'thr-parent', 'parent-uri', 'guid',
113                         'parent-guid', 'conversation', 'received', 'created', 'edited', 'verb', 'object-type', 'object', 'target',
114                         'private', 'title', 'body', 'raw-body', 'location', 'coord', 'app',
115                         'inform', 'deleted', 'extid', 'post-type', 'post-reason', 'gravity',
116                         'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid',
117                         'author-id', 'author-link', 'author-name', 'author-avatar', 'owner-id', 'owner-link', 'contact-uid',
118                         'signed_text', 'network', 'wall', 'contact-id', 'plink', 'origin',
119                         'thr-parent-id', 'parent-uri-id', 'postopts', 'pubmail',
120                         'event-created', 'event-edited', 'event-start', 'event-finish',
121                         'event-summary', 'event-desc', 'event-location', 'event-type',
122                         'event-nofinish', 'event-ignore', 'event-id'];
123
124         // All fields in the item table
125         const ITEM_FIELDLIST = ['id', 'uid', 'parent', 'uri', 'parent-uri', 'thr-parent',
126                         'guid', 'uri-id', 'parent-uri-id', 'thr-parent-id', 'conversation', 'vid',
127                         'contact-id', 'wall', 'gravity', 'extid', 'psid', 
128                         'created', 'edited', 'commented', 'received', 'changed', 'verb',
129                         'postopts', 'plink', 'resource-id', 'event-id', 'inform',
130                         'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'post-type', 'post-reason',
131                         'private', 'pubmail', 'visible', 'starred',
132                         'unseen', 'deleted', 'origin', 'mention', 'global', 'network',
133                         'title', 'content-warning', 'body', 'location', 'coord', 'app',
134                         'rendered-hash', 'rendered-html', 'object-type', 'object', 'target-type', 'target',
135                         'author-id', 'author-link', 'author-name', 'author-avatar', 'author-network',
136                         'owner-id', 'owner-link', 'owner-name', 'owner-avatar', 'causer-id'];
137
138         // List of all verbs that don't need additional content data.
139         // Never reorder or remove entries from this list. Just add new ones at the end, if needed.
140         const ACTIVITIES = [
141                 Activity::LIKE, Activity::DISLIKE,
142                 Activity::ATTEND, Activity::ATTENDNO, Activity::ATTENDMAYBE,
143                 Activity::FOLLOW,
144                 Activity::ANNOUNCE];
145
146         const PUBLIC = 0;
147         const PRIVATE = 1;
148         const UNLISTED = 2;
149
150         /**
151          * Update existing item entries
152          *
153          * @param array $fields    The fields that are to be changed
154          * @param array $condition The condition for finding the item entries
155          *
156          * In the future we may have to change permissions as well.
157          * Then we had to add the user id as third parameter.
158          *
159          * A return value of "0" doesn't mean an error - but that 0 rows had been changed.
160          *
161          * @return integer|boolean number of affected rows - or "false" if there was an error
162          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
163          */
164         public static function update(array $fields, array $condition)
165         {
166                 if (empty($condition) || empty($fields)) {
167                         return false;
168                 }
169
170                 if (isset($fields['extid'])) {
171                         $fields['external-id'] = ItemURI::getIdByURI($fields['extid']);
172                 }
173
174                 if (!empty($fields['verb'])) {
175                         $fields['vid'] = Verb::getID($fields['verb']);
176                 }
177
178                 if (!empty($fields['edited'])) {
179                         $previous = Post::selectFirst(['edited'], $condition);
180                 }
181
182                 $rows = Post::update($fields, $condition);
183                 if (is_bool($rows)) {
184                         return $rows;
185                 }
186
187                 // We only need to call the line by line update for specific fields
188                 if (empty($fields['body']) && empty($fields['file']) &&
189                         empty($fields['attach']) && empty($fields['edited'])) {
190                         return $rows;
191                 }
192
193                 Logger::info('Updating per single row method', ['fields' => $fields, 'condition' => $condition]);
194
195                 $items = Post::select(['id', 'origin', 'uri-id', 'uid', 'author-network'], $condition);
196
197                 $notify_items = [];
198
199                 while ($item = DBA::fetch($items)) {
200                         if (!empty($fields['body'])) {
201                                 Post\Media::insertFromAttachmentData($item['uri-id'], $fields['body']);
202
203                                 $content_fields = ['raw-body' => trim($fields['raw-body'] ?? $fields['body'])];
204
205                                 // Remove all media attachments from the body and store them in the post-media table
206                                 // @todo On shared postings (Diaspora style and commented reshare) don't fetch content from the shared part
207                                 $content_fields['raw-body'] = Post\Media::insertFromBody($item['uri-id'], $content_fields['raw-body']);
208                                 $content_fields['raw-body'] = self::setHashtags($content_fields['raw-body']);
209
210                                 if ($item['author-network'] != Protocol::DFRN) {
211                                         Post\Media::insertFromRelevantUrl($item['uri-id'], $content_fields['raw-body']);
212                                 }
213
214                                 Post\Content::update($item['uri-id'], $content_fields);
215                         }
216
217                         if (!empty($fields['file'])) {
218                                 Post\Category::storeTextByURIId($item['uri-id'], $item['uid'], $fields['file']);
219                         }
220
221                         if (!empty($fields['attach'])) {
222                                 Post\Media::insertFromAttachment($item['uri-id'], $fields['attach']);
223                         }
224
225                         // We only need to notfiy others when it is an original entry from us.
226                         // Only call the notifier when the item had been edited and records had been changed.
227                         if ($item['origin'] && !empty($fields['edited']) && ($previous['edited'] != $fields['edited'])) {
228                                 $notify_items[] = $item['id'];
229                         }
230                 }
231
232                 DBA::close($items);
233
234                 foreach ($notify_items as $notify_item) {
235                         $post = Post::selectFirst(['uri-id', 'uid'], ['id' => $notify_item]);
236                         Worker::add(PRIORITY_HIGH, 'Notifier', Delivery::POST, (int)$post['uri-id'], (int)$post['uid']);
237                 }
238
239                 return $rows;
240         }
241
242         /**
243          * Delete an item and notify others about it - if it was ours
244          *
245          * @param array   $condition The condition for finding the item entries
246          * @param integer $priority  Priority for the notification
247          * @return void
248          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
249          */
250         public static function markForDeletion(array $condition, int $priority = PRIORITY_HIGH)
251         {
252                 $items = Post::select(['id'], $condition);
253                 while ($item = Post::fetch($items)) {
254                         self::markForDeletionById($item['id'], $priority);
255                 }
256                 DBA::close($items);
257         }
258
259         /**
260          * Delete an item for an user and notify others about it - if it was ours
261          *
262          * @param array   $condition The condition for finding the item entries
263          * @param integer $uid       User who wants to delete this item
264          * @return void
265          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
266          */
267         public static function deleteForUser(array $condition, int $uid)
268         {
269                 if ($uid == 0) {
270                         return;
271                 }
272
273                 $items = Post::select(['id', 'uid', 'uri-id'], $condition);
274                 while ($item = Post::fetch($items)) {
275                         if (in_array($item['uid'], [$uid, 0])) {
276                                 Post\User::update($item['uri-id'], $uid, ['hidden' => true], true);
277                                 Post\ThreadUser::update($item['uri-id'], $uid, ['hidden' => true], true);
278                         }
279
280                         if ($item['uid'] == $uid) {
281                                 self::markForDeletionById($item['id'], PRIORITY_HIGH);
282                         } elseif ($item['uid'] != 0) {
283                                 Logger::notice('Wrong ownership. Not deleting item', ['id' => $item['id']]);
284                         }
285                 }
286                 DBA::close($items);
287         }
288
289         /**
290          * Mark an item for deletion, delete related data and notify others about it - if it was ours
291          *
292          * @param integer $item_id
293          * @param integer $priority Priority for the notification
294          * @return boolean success
295          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
296          */
297         public static function markForDeletionById(int $item_id, int $priority = PRIORITY_HIGH): bool
298         {
299                 Logger::info('Mark item for deletion by id', ['id' => $item_id, 'callstack' => System::callstack()]);
300                 // locate item to be deleted
301                 $fields = ['id', 'uri', 'uri-id', 'uid', 'parent', 'parent-uri-id', 'origin',
302                         'deleted', 'resource-id', 'event-id',
303                         'verb', 'object-type', 'object', 'target', 'contact-id', 'psid', 'gravity'];
304                 $item = Post::selectFirst($fields, ['id' => $item_id]);
305                 if (!DBA::isResult($item)) {
306                         Logger::info('Item not found.', ['id' => $item_id]);
307                         return false;
308                 }
309
310                 if ($item['deleted']) {
311                         Logger::info('Item has already been marked for deletion.', ['id' => $item_id]);
312                         return false;
313                 }
314
315                 $parent = Post::selectFirst(['origin'], ['id' => $item['parent']]);
316                 if (!DBA::isResult($parent)) {
317                         $parent = ['origin' => false];
318                 }
319
320                 // clean up categories and tags so they don't end up as orphans
321                 Post\Category::deleteByURIId($item['uri-id'], $item['uid']);
322
323                 /*
324                  * If item is a link to a photo resource, nuke all the associated photos
325                  * (visitors will not have photo resources)
326                  * This only applies to photos uploaded from the photos page. Photos inserted into a post do not
327                  * generate a resource-id and therefore aren't intimately linked to the item.
328                  */
329                 /// @TODO: this should first check if photo is used elsewhere
330                 if (strlen($item['resource-id'])) {
331                         Photo::delete(['resource-id' => $item['resource-id'], 'uid' => $item['uid']]);
332                 }
333
334                 // If item is a link to an event, delete the event.
335                 if (intval($item['event-id'])) {
336                         Event::delete($item['event-id']);
337                 }
338
339                 // If item has attachments, drop them
340                 $attachments = Post\Media::getByURIId($item['uri-id'], [Post\Media::DOCUMENT]);
341                 foreach($attachments as $attachment) {
342                         if (preg_match('|attach/(\d+)|', $attachment['url'], $matches)) {
343                                 Attach::delete(['id' => $matches[1], 'uid' => $item['uid']]);
344                         }
345                 }
346
347                 // Set the item to "deleted"
348                 $item_fields = ['deleted' => true, 'edited' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow()];
349                 Post::update($item_fields, ['id' => $item['id']]);
350
351                 Post\Category::storeTextByURIId($item['uri-id'], $item['uid'], '');
352
353                 if (!Post::exists(["`uri-id` = ? AND `uid` != 0 AND NOT `deleted`", $item['uri-id']])) {
354                         self::markForDeletion(['uri-id' => $item['uri-id'], 'uid' => 0, 'deleted' => false], $priority);
355                 }
356
357                 Post\DeliveryData::delete($item['uri-id']);
358
359                 // If it's the parent of a comment thread, kill all the kids
360                 if ($item['gravity'] == GRAVITY_PARENT) {
361                         self::markForDeletion(['parent' => $item['parent'], 'deleted' => false], $priority);
362                 }
363
364                 // Is it our comment and/or our thread?
365                 if (($item['origin'] || $parent['origin']) && ($item['uid'] != 0)) {
366                         // When we delete the original post we will delete all existing copies on the server as well
367                         self::markForDeletion(['uri-id' => $item['uri-id'], 'deleted' => false], $priority);
368
369                         // send the notification upstream/downstream
370                         if ($priority) {
371                                 Worker::add(['priority' => $priority, 'dont_fork' => true], 'Notifier', Delivery::DELETION, (int)$item['uri-id'], (int)$item['uid']);
372                         }
373                 } elseif ($item['uid'] != 0) {
374                         Post\User::update($item['uri-id'], $item['uid'], ['hidden' => true]);
375                         Post\ThreadUser::update($item['uri-id'], $item['uid'], ['hidden' => true]);
376                 }
377
378                 Logger::info('Item has been marked for deletion.', ['id' => $item_id]);
379
380                 return true;
381         }
382
383         /**
384          * Get guid from given item record
385          *
386          * @param array $item Item record
387          * @param bool Whether to notify (?)
388          * @return string Guid
389          */
390         public static function guid(array $item, bool $notify): string
391         {
392                 if (!empty($item['guid'])) {
393                         return trim($item['guid']);
394                 }
395
396                 if ($notify) {
397                         // We have to avoid duplicates. So we create the GUID in form of a hash of the plink or uri.
398                         // We add the hash of our own host because our host is the original creator of the post.
399                         $prefix_host = DI::baseUrl()->getHostname();
400                 } else {
401                         $prefix_host = '';
402
403                         // We are only storing the post so we create a GUID from the original hostname.
404                         if (!empty($item['author-link'])) {
405                                 $parsed = parse_url($item['author-link']);
406                                 if (!empty($parsed['host'])) {
407                                         $prefix_host = $parsed['host'];
408                                 }
409                         }
410
411                         if (empty($prefix_host) && !empty($item['plink'])) {
412                                 $parsed = parse_url($item['plink']);
413                                 if (!empty($parsed['host'])) {
414                                         $prefix_host = $parsed['host'];
415                                 }
416                         }
417
418                         if (empty($prefix_host) && !empty($item['uri'])) {
419                                 $parsed = parse_url($item['uri']);
420                                 if (!empty($parsed['host'])) {
421                                         $prefix_host = $parsed['host'];
422                                 }
423                         }
424
425                         // Is it in the format data@host.tld? - Used for mail contacts
426                         if (empty($prefix_host) && !empty($item['author-link']) && strstr($item['author-link'], '@')) {
427                                 $mailparts = explode('@', $item['author-link']);
428                                 $prefix_host = array_pop($mailparts);
429                         }
430                 }
431
432                 if (!empty($item['plink'])) {
433                         $guid = self::guidFromUri($item['plink'], $prefix_host);
434                 } elseif (!empty($item['uri'])) {
435                         $guid = self::guidFromUri($item['uri'], $prefix_host);
436                 } else {
437                         $guid = System::createUUID(hash('crc32', $prefix_host));
438                 }
439
440                 return $guid;
441         }
442
443         /**
444          * Returns contact id from given item record
445          *
446          * @param array $item Item record
447          * @return int Contact id
448          */
449         private static function contactId(array $item): int
450         {
451                 if (!empty($item['contact-id']) && DBA::exists('contact', ['self' => true, 'id' => $item['contact-id']])) {
452                         return $item['contact-id'];
453                 } elseif (($item['gravity'] == GRAVITY_PARENT) && !empty($item['uid']) && !empty($item['contact-id']) && Contact::isSharing($item['contact-id'], $item['uid'])) {
454                         return $item['contact-id'];
455                 } elseif (!empty($item['uid']) && !Contact::isSharing($item['author-id'], $item['uid'])) {
456                         return $item['author-id'];
457                 } elseif (!empty($item['contact-id'])) {
458                         return $item['contact-id'];
459                 } else {
460                         $contact_id = Contact::getIdForURL($item['author-link'], $item['uid']);
461                         if (!empty($contact_id)) {
462                                 return $contact_id;
463                         }
464                 }
465                 return $item['author-id'];
466         }
467
468         /**
469          * Write an item array into a spool file to be inserted later.
470          * This command is called whenever there are issues storing an item.
471          *
472          * @param array $item The item fields that are to be inserted
473          * @throws \Exception
474          */
475         private static function spool(array $item)
476         {
477                 // Now we store the data in the spool directory
478                 // We use "microtime" to keep the arrival order and "mt_rand" to avoid duplicates
479                 $file = 'item-' . round(microtime(true) * 10000) . '-' . mt_rand() . '.msg';
480
481                 $spoolpath = System::getSpoolPath();
482                 if ($spoolpath != '') {
483                         $spool = $spoolpath . '/' . $file;
484
485                         file_put_contents($spool, json_encode($item));
486                         Logger::warning("Item wasn't stored - Item was spooled into file", ['file' => $file]);
487                 }
488         }
489
490         /**
491          * Check if the item array is a duplicate
492          *
493          * @param array $item Item record
494          * @return boolean is it a duplicate?
495          */
496         private static function isDuplicate(array $item): bool
497         {
498                 // Checking if there is already an item with the same guid
499                 $condition = ['guid' => $item['guid'], 'network' => $item['network'], 'uid' => $item['uid']];
500                 if (Post::exists($condition)) {
501                         Logger::notice('Found already existing item', $condition);
502                         return true;
503                 }
504
505                 $condition = ['uri-id' => $item['uri-id'], 'uid' => $item['uid'],
506                         'network' => [$item['network'], Protocol::DFRN]];
507                 if (Post::exists($condition)) {
508                         Logger::notice('duplicated item with the same uri found.', $condition);
509                         return true;
510                 }
511
512                 // On Friendica and Diaspora the GUID is unique
513                 if (in_array($item['network'], [Protocol::DFRN, Protocol::DIASPORA])) {
514                         $condition = ['guid' => $item['guid'], 'uid' => $item['uid']];
515                         if (Post::exists($condition)) {
516                                 Logger::notice('duplicated item with the same guid found.', $condition);
517                                 return true;
518                         }
519                 } elseif ($item['network'] == Protocol::OSTATUS) {
520                         // Check for an existing post with the same content. There seems to be a problem with OStatus.
521                         $condition = ["`body` = ? AND `network` = ? AND `created` = ? AND `contact-id` = ? AND `uid` = ?",
522                                         $item['body'], $item['network'], $item['created'], $item['contact-id'], $item['uid']];
523                         if (Post::exists($condition)) {
524                                 Logger::notice('duplicated item with the same body found.', $item);
525                                 return true;
526                         }
527                 }
528
529                 /*
530                  * Check for already added items.
531                  * There is a timing issue here that sometimes creates double postings.
532                  * An unique index would help - but the limitations of MySQL (maximum size of index values) prevent this.
533                  */
534                 if (($item['uid'] == 0) && Post::exists(['uri-id' => $item['uri-id'], 'uid' => 0])) {
535                         Logger::notice('Global item already stored.', ['uri-id' => $item['uri-id'], 'network' => $item['network']]);
536                         return true;
537                 }
538
539                 return false;
540         }
541
542         /**
543          * Check if the item array is valid
544          *
545          * @param array $item Item record
546          * @return boolean item is valid
547          */
548         public static function isValid(array $item): bool
549         {
550                 // When there is no content then we don't post it
551                 if (($item['body'] . $item['title'] == '') && (empty($item['uri-id']) || !Post\Media::existsByURIId($item['uri-id']))) {
552                         Logger::notice('No body, no title.');
553                         return false;
554                 }
555
556                 if (!empty($item['uid'])) {
557                         $owner = User::getOwnerDataById($item['uid'], false);
558                         if (!$owner) {
559                                 Logger::notice('Missing item user owner data', ['uid' => $item['uid']]);
560                                 return false;
561                         }
562
563                         if ($owner['account_expired'] || $owner['account_removed']) {
564                                 Logger::notice('Item user has been deleted/expired/removed', ['uid' => $item['uid'], 'deleted' => $owner['deleted'], 'account_expired' => $owner['account_expired'], 'account_removed' => $owner['account_removed']]);
565                                 return false;
566                         }
567                 }
568
569                 if (!empty($item['author-id']) && Contact::isBlocked($item['author-id'])) {
570                         Logger::notice('Author is blocked node-wide', ['author-link' => $item['author-link'], 'item-uri' => $item['uri']]);
571                         return false;
572                 }
573
574                 if (!empty($item['author-link']) && Network::isUrlBlocked($item['author-link'])) {
575                         Logger::notice('Author server is blocked', ['author-link' => $item['author-link'], 'item-uri' => $item['uri']]);
576                         return false;
577                 }
578
579                 if (!empty($item['owner-id']) && Contact::isBlocked($item['owner-id'])) {
580                         Logger::notice('Owner is blocked node-wide', ['owner-link' => $item['owner-link'], 'item-uri' => $item['uri']]);
581                         return false;
582                 }
583
584                 if (!empty($item['owner-link']) && Network::isUrlBlocked($item['owner-link'])) {
585                         Logger::notice('Owner server is blocked', ['owner-link' => $item['owner-link'], 'item-uri' => $item['uri']]);
586                         return false;
587                 }
588
589                 if (!empty($item['uid']) && !self::isAllowedByUser($item, $item['uid'])) {
590                         return false;
591                 }
592
593                 if ($item['verb'] == Activity::FOLLOW) {
594                         if (!$item['origin'] && ($item['author-id'] == Contact::getPublicIdByUserId($item['uid']))) {
595                                 // Our own follow request can be relayed to us. We don't store it to avoid notification chaos.
596                                 Logger::info("Follow: Don't store not origin follow request", ['parent-uri' => $item['parent-uri']]);
597                                 return false;
598                         }
599
600                         $condition = ['verb' => Activity::FOLLOW, 'uid' => $item['uid'],
601                                 'parent-uri' => $item['parent-uri'], 'author-id' => $item['author-id']];
602                         if (Post::exists($condition)) {
603                                 // It happens that we receive multiple follow requests by the same author - we only store one.
604                                 Logger::info('Follow: Found existing follow request from author', ['author-id' => $item['author-id'], 'parent-uri' => $item['parent-uri']]);
605                                 return false;
606                         }
607                 }
608
609                 return true;
610         }
611
612         /**
613          * Check if the item array is too old
614          *
615          * @param array $item Item record
616          * @return boolean item is too old
617          */
618         public static function isTooOld(array $item): bool
619         {
620                 // check for create date and expire time
621                 $expire_interval = DI::config()->get('system', 'dbclean-expire-days', 0);
622
623                 $user = DBA::selectFirst('user', ['expire'], ['uid' => $item['uid']]);
624                 if (DBA::isResult($user) && ($user['expire'] > 0) && (($user['expire'] < $expire_interval) || ($expire_interval == 0))) {
625                         $expire_interval = $user['expire'];
626                 }
627
628                 if (($expire_interval > 0) && !empty($item['created'])) {
629                         $expire_date = time() - ($expire_interval * 86400);
630                         $created_date = strtotime($item['created']);
631                         if ($created_date < $expire_date) {
632                                 Logger::notice('Item created before expiration interval.', [
633                                         'created' => date('c', $created_date),
634                                         'expired' => date('c', $expire_date),
635                                         '$item' => $item
636                                 ]);
637                                 return true;
638                         }
639                 }
640
641                 return false;
642         }
643
644         /**
645          * Return the id of the given item array if it has been stored before
646          *
647          * @param array $item Item record
648          * @return integer Item id or zero on error
649          */
650         private static function getDuplicateID(array $item): int
651         {
652                 if (empty($item['network']) || in_array($item['network'], Protocol::FEDERATED)) {
653                         $condition = ['`uri-id` = ? AND `uid` = ? AND `network` IN (?, ?, ?, ?)',
654                                 $item['uri-id'],
655                                 $item['uid'],
656                                 Protocol::ACTIVITYPUB,
657                                 Protocol::DIASPORA,
658                                 Protocol::DFRN,
659                                 Protocol::OSTATUS
660                         ];
661                         $existing = Post::selectFirst(['id', 'network'], $condition);
662                         if (DBA::isResult($existing)) {
663                                 // We only log the entries with a different user id than 0. Otherwise we would have too many false positives
664                                 if ($item['uid'] != 0) {
665                                         Logger::notice('Item already existed for user', [
666                                                 'uri-id' => $item['uri-id'],
667                                                 'uid' => $item['uid'],
668                                                 'network' => $item['network'],
669                                                 'existing_id' => $existing['id'],
670                                                 'existing_network' => $existing['network']
671                                         ]);
672                                 }
673
674                                 return $existing['id'];
675                         }
676                 }
677                 return 0;
678         }
679
680         /**
681          * Fetch top-level parent data for the given item array
682          *
683          * @param array $item
684          * @return array item array with parent data
685          * @throws \Exception
686          */
687         private static function getTopLevelParent(array $item): array
688         {
689                 $fields = ['uid', 'uri', 'parent-uri', 'id', 'deleted',
690                         'uri-id', 'parent-uri-id',
691                         'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid',
692                         'wall', 'private', 'origin', 'author-id'];
693                 $condition = ['uri-id' => [$item['thr-parent-id'], $item['parent-uri-id']], 'uid' => $item['uid']];
694                 $params = ['order' => ['id' => false]];
695                 $parent = Post::selectFirst($fields, $condition, $params);
696
697                 if (!DBA::isResult($parent) && Post::exists(['uri-id' => [$item['thr-parent-id'], $item['parent-uri-id']], 'uid' => 0])) {
698                         $stored = Item::storeForUserByUriId($item['thr-parent-id'], $item['uid'], ['post-reason' => Item::PR_COMPLETION]);
699                         if (!$stored && ($item['thr-parent-id'] != $item['parent-uri-id'])) {
700                                 $stored = Item::storeForUserByUriId($item['parent-uri-id'], $item['uid'], ['post-reason' => Item::PR_COMPLETION]);
701                         }
702                         if ($stored) {
703                                 Logger::info('Stored thread parent item for user', ['uri-id' => $item['thr-parent-id'], 'uid' => $item['uid'], 'stored' => $stored]);
704                                 $parent = Post::selectFirst($fields, $condition, $params);
705                         }
706                 }
707
708                 if (!DBA::isResult($parent)) {
709                         Logger::notice('item parent was not found - ignoring item', ['thr-parent-id' => $item['thr-parent-id'], 'uid' => $item['uid']]);
710                         return [];
711                 }
712
713                 if ($parent['uri-id'] == $parent['parent-uri-id']) {
714                         return $parent;
715                 }
716
717                 $condition = ['uri-id' => $parent['parent-uri-id'],
718                         'parent-uri-id' => $parent['parent-uri-id'],
719                         'uid' => $parent['uid']];
720                 $params = ['order' => ['id' => false]];
721                 $toplevel_parent = Post::selectFirst($fields, $condition, $params);
722
723                 if (!DBA::isResult($toplevel_parent) && $item['origin']) {
724                         $stored = Item::storeForUserByUriId($item['parent-uri-id'], $item['uid'], ['post-reason' => Item::PR_COMPLETION]);
725                         Logger::info('Stored parent item for user', ['uri-id' => $item['parent-uri-id'], 'uid' => $item['uid'], 'stored' => $stored]);
726                         $toplevel_parent = Post::selectFirst($fields, $condition, $params);
727                 }
728
729                 if (!DBA::isResult($toplevel_parent)) {
730                         Logger::notice('item top level parent was not found - ignoring item', ['parent-uri-id' => $parent['parent-uri-id'], 'uid' => $parent['uid']]);
731                         return [];
732                 }
733
734                 return $toplevel_parent;
735         }
736
737         /**
738          * Get the gravity for the given item array
739          *
740          * @param array $item
741          * @return integer gravity
742          */
743         private static function getGravity(array $item): int
744         {
745                 $activity = DI::activity();
746
747                 if (isset($item['gravity'])) {
748                         return intval($item['gravity']);
749                 } elseif ($item['parent-uri-id'] === $item['uri-id']) {
750                         return GRAVITY_PARENT;
751                 } elseif ($activity->match($item['verb'], Activity::POST)) {
752                         return GRAVITY_COMMENT;
753                 } elseif ($activity->match($item['verb'], Activity::FOLLOW)) {
754                         return GRAVITY_ACTIVITY;
755                 } elseif ($activity->match($item['verb'], Activity::ANNOUNCE)) {
756                         return GRAVITY_ACTIVITY;
757                 }
758
759                 Logger::info('Unknown gravity for verb', ['verb' => $item['verb']]);
760                 return GRAVITY_UNKNOWN;   // Should not happen
761         }
762
763         /**
764          * Inserts item record
765          *
766          * @param array $item Item array to be inserted
767          * @param int   $notify Notification (type?)
768          * @param bool  $post_local (???)
769          * @return int Zero means error, otherwise primary key (id) is being returned
770          */
771         public static function insert(array $item, int $notify = 0, bool $post_local = true): int
772         {
773                 $orig_item = $item;
774
775                 $priority = PRIORITY_HIGH;
776
777                 // If it is a posting where users should get notifications, then define it as wall posting
778                 if ($notify) {
779                         $item['wall'] = 1;
780                         $item['origin'] = 1;
781                         $item['network'] = Protocol::DFRN;
782                         $item['protocol'] = Conversation::PARCEL_DIRECT;
783                         $item['direction'] = Conversation::PUSH;
784
785                         if (is_int($notify) && in_array($notify, PRIORITIES)) {
786                                 $priority = $notify;
787                         }
788                 } else {
789                         $item['network'] = trim(($item['network'] ?? '') ?: Protocol::PHANTOM);
790                 }
791
792                 $uid = intval($item['uid']);
793
794                 $item['guid'] = self::guid($item, $notify);
795                 $item['uri'] = substr(trim($item['uri'] ?? '') ?: self::newURI($item['guid']), 0, 255);
796
797                 // Store URI data
798                 $item['uri-id'] = ItemURI::insert(['uri' => $item['uri'], 'guid' => $item['guid']]);
799
800                 // Backward compatibility: parent-uri used to be the direct parent uri.
801                 // If it is provided without a thr-parent, it probably is the old behavior.
802                 if (empty($item['thr-parent']) || empty($item['parent-uri'])) {
803                         $item['thr-parent'] = trim($item['thr-parent'] ?? $item['parent-uri'] ?? $item['uri']);
804                         $item['parent-uri'] = $item['thr-parent'];
805                 }
806
807                 $item['thr-parent-id'] = ItemURI::getIdByURI($item['thr-parent']);
808                 $item['parent-uri-id'] = ItemURI::getIdByURI($item['parent-uri']);
809
810                 // Store conversation data
811                 $source = $item['source'] ?? '';
812                 unset($item['conversation-uri']);
813                 unset($item['conversation-href']);
814                 unset($item['source']);
815
816                 if (in_array($item['network'], Protocol::FEDERATED) && (!isset($item['protocol']) || is_null($item['protocol']))) {
817                         Logger::notice('Blubb', ['guid' => $item['guid'], 'uri-id' => $item['uri-id'], 'uri' => $item['uri'], 'callstack' => System::callstack(20)]);
818                 }
819
820                 /*
821                  * Do we already have this item?
822                  * We have to check several networks since Friendica posts could be repeated
823                  * via OStatus (maybe Diasporsa as well)
824                  */
825                 $duplicate = self::getDuplicateID($item);
826                 if ($duplicate) {
827                         return $duplicate;
828                 }
829
830                 // Additional duplicate checks
831                 /// @todo Check why the first duplication check returns the item number and the second a 0
832                 if (self::isDuplicate($item)) {
833                         return 0;
834                 }
835
836                 if (!isset($item['post-type'])) {
837                         $item['post-type'] = empty($item['title']) ? self::PT_NOTE : self::PT_ARTICLE;
838                 }
839
840                 $item['wall']          = intval($item['wall'] ?? 0);
841                 $item['extid']         = trim($item['extid'] ?? '');
842                 $item['author-name']   = trim($item['author-name'] ?? '');
843                 $item['author-link']   = trim($item['author-link'] ?? '');
844                 $item['author-avatar'] = trim($item['author-avatar'] ?? '');
845                 $item['owner-name']    = trim($item['owner-name'] ?? '');
846                 $item['owner-link']    = trim($item['owner-link'] ?? '');
847                 $item['owner-avatar']  = trim($item['owner-avatar'] ?? '');
848                 $item['received']      = (isset($item['received'])  ? DateTimeFormat::utc($item['received'])  : DateTimeFormat::utcNow());
849                 $item['created']       = (isset($item['created'])   ? DateTimeFormat::utc($item['created'])   : $item['received']);
850                 $item['edited']        = (isset($item['edited'])    ? DateTimeFormat::utc($item['edited'])    : $item['created']);
851                 $item['changed']       = (isset($item['changed'])   ? DateTimeFormat::utc($item['changed'])   : $item['created']);
852                 $item['commented']     = (isset($item['commented']) ? DateTimeFormat::utc($item['commented']) : $item['created']);
853                 $item['title']         = substr(trim($item['title'] ?? ''), 0, 255);
854                 $item['location']      = trim($item['location'] ?? '');
855                 $item['coord']         = trim($item['coord'] ?? '');
856                 $item['visible']       = (isset($item['visible']) ? intval($item['visible']) : 1);
857                 $item['deleted']       = 0;
858                 $item['verb']          = trim($item['verb'] ?? '');
859                 $item['object-type']   = trim($item['object-type'] ?? '');
860                 $item['object']        = trim($item['object'] ?? '');
861                 $item['target-type']   = trim($item['target-type'] ?? '');
862                 $item['target']        = trim($item['target'] ?? '');
863                 $item['plink']         = substr(trim($item['plink'] ?? ''), 0, 255);
864                 $item['allow_cid']     = trim($item['allow_cid'] ?? '');
865                 $item['allow_gid']     = trim($item['allow_gid'] ?? '');
866                 $item['deny_cid']      = trim($item['deny_cid'] ?? '');
867                 $item['deny_gid']      = trim($item['deny_gid'] ?? '');
868                 $item['private']       = intval($item['private'] ?? self::PUBLIC);
869                 $item['body']          = trim($item['body'] ?? '');
870                 $item['raw-body']      = trim($item['raw-body'] ?? $item['body']);
871                 $item['app']           = trim($item['app'] ?? '');
872                 $item['origin']        = intval($item['origin'] ?? 0);
873                 $item['postopts']      = trim($item['postopts'] ?? '');
874                 $item['resource-id']   = trim($item['resource-id'] ?? '');
875                 $item['event-id']      = intval($item['event-id'] ?? 0);
876                 $item['inform']        = trim($item['inform'] ?? '');
877                 $item['file']          = trim($item['file'] ?? '');
878
879                 // Communities aren't working with the Diaspora protoccol
880                 if (($uid != 0) && ($item['network'] == Protocol::DIASPORA)) {
881                         $user = User::getById($uid, ['account-type']);
882                         if ($user['account-type'] == Contact::TYPE_COMMUNITY) {
883                                 Logger::info('Community posts are not supported via Diaspora');
884                                 return 0;
885                         }
886                 }
887
888                 // Items cannot be stored before they happen ...
889                 if ($item['created'] > DateTimeFormat::utcNow()) {
890                         $item['created'] = DateTimeFormat::utcNow();
891                 }
892
893                 // We haven't invented time travel by now.
894                 if ($item['edited'] > DateTimeFormat::utcNow()) {
895                         $item['edited'] = DateTimeFormat::utcNow();
896                 }
897
898                 $item['plink'] = ($item['plink'] ?? '') ?: DI::baseUrl() . '/display/' . urlencode($item['guid']);
899
900                 $item['gravity'] = self::getGravity($item);
901
902                 $item['language'] = self::getLanguage($item);
903
904                 $default = ['url' => $item['author-link'], 'name' => $item['author-name'],
905                         'photo' => $item['author-avatar'], 'network' => $item['network']];
906                 $item['author-id'] = ($item['author-id'] ?? 0) ?: Contact::getIdForURL($item['author-link'], 0, null, $default);
907
908                 $default = ['url' => $item['owner-link'], 'name' => $item['owner-name'],
909                         'photo' => $item['owner-avatar'], 'network' => $item['network']];
910                 $item['owner-id'] = ($item['owner-id'] ?? 0) ?: Contact::getIdForURL($item['owner-link'], 0, null, $default);
911
912                 $actor = ($item['gravity'] == GRAVITY_PARENT) ? $item['owner-id'] : $item['author-id'];
913                 if (!$item['origin'] && ($item['uid'] != 0) && Contact::isSharing($actor, $item['uid'])) {
914                         $item['post-reason'] = self::PR_FOLLOWER;
915                 }
916
917                 if ($item['origin'] && empty($item['post-reason'])) {
918                         $item['post-reason'] = self::PR_LOCAL;
919                 }
920
921                 // Ensure that there is an avatar cache
922                 Contact::checkAvatarCache($item['author-id']);
923                 Contact::checkAvatarCache($item['owner-id']);
924
925                 // The contact-id should be set before "self::insert" was called - but there seems to be issues sometimes
926                 $item['contact-id'] = self::contactId($item);
927
928                 if (!empty($item['direction']) && in_array($item['direction'], [Conversation::PUSH, Conversation::RELAY]) &&
929                         empty($item['origin']) && self::isTooOld($item)) {
930                         Logger::info('Item is too old', ['item' => $item]);
931                         return 0;
932                 }
933
934                 if (!self::isValid($item)) {
935                         return 0;
936                 }
937
938                 if ($item['gravity'] !== GRAVITY_PARENT) {
939                         $toplevel_parent = self::getTopLevelParent($item);
940                         if (empty($toplevel_parent)) {
941                                 return 0;
942                         }
943
944                         // If the thread originated from this node, we check the permission against the thread starter
945                         $condition = ['uri-id' => $toplevel_parent['uri-id'], 'wall' => true];
946                         $localTopLevelParent = Post::selectFirst(['uid'], $condition);
947                         if (!empty($localTopLevelParent['uid']) && !self::isAllowedByUser($item, $localTopLevelParent['uid'])) {
948                                 return 0;
949                         }
950
951                         $parent_id             = $toplevel_parent['id'];
952                         $item['parent-uri']    = $toplevel_parent['uri'];
953                         $item['parent-uri-id'] = $toplevel_parent['uri-id'];
954                         $item['deleted']       = $toplevel_parent['deleted'];
955
956                         // Reshares have to keep their permissions to allow forums to work
957                         if (!$item['origin'] || ($item['verb'] != Activity::ANNOUNCE)) {
958                                 $item['allow_cid']     = $toplevel_parent['allow_cid'];
959                                 $item['allow_gid']     = $toplevel_parent['allow_gid'];
960                                 $item['deny_cid']      = $toplevel_parent['deny_cid'];
961                                 $item['deny_gid']      = $toplevel_parent['deny_gid'];
962                         }
963
964                         $parent_origin         = $toplevel_parent['origin'];
965
966                         // Don't federate received participation messages
967                         if ($item['verb'] != Activity::FOLLOW) {
968                                 $item['wall'] = $toplevel_parent['wall'];
969                         } else {
970                                 $item['wall'] = false;
971                                 // Participations are technical messages, so they are set to "seen" automatically
972                                 $item['unseen'] = false;
973                         }
974
975                         /*
976                          * If the parent is private, force privacy for the entire conversation
977                          * This differs from the above settings as it subtly allows comments from
978                          * email correspondents to be private even if the overall thread is not.
979                          */
980                         if ($toplevel_parent['private']) {
981                                 $item['private'] = $toplevel_parent['private'];
982                         }
983
984                         // If its a post that originated here then tag the thread as "mention"
985                         if ($item['origin'] && $item['uid']) {
986                                 DBA::update('post-thread-user', ['mention' => true], ['uri-id' => $item['parent-uri-id'], 'uid' => $item['uid']]);
987                                 Logger::info('tagged thread as mention', ['parent' => $parent_id, 'parent-uri-id' => $item['parent-uri-id'], 'uid' => $item['uid']]);
988                         }
989
990                         // Update the contact relations
991                         Contact\Relation::store($toplevel_parent['author-id'], $item['author-id'], $item['created']);
992                 } else {
993                         $parent_id = 0;
994                         $parent_origin = $item['origin'];
995
996                         if ($item['wall'] && empty($item['conversation'])) {
997                                 $item['conversation'] = $item['parent-uri'] . '#context';
998                         }
999                 }
1000
1001                 $item['parent-uri-id'] = ItemURI::getIdByURI($item['parent-uri']);
1002                 $item['thr-parent-id'] = ItemURI::getIdByURI($item['thr-parent']);
1003
1004                 if (!empty($item['conversation']) && empty($item['conversation-id'])) {
1005                         $item['conversation-id'] = ItemURI::getIdByURI($item['conversation']);
1006                 }
1007
1008                 // Is this item available in the global items (with uid=0)?
1009                 if ($item['uid'] == 0) {
1010                         $item['global'] = true;
1011
1012                         // Set the global flag on all items if this was a global item entry
1013                         Post::update(['global' => true], ['uri-id' => $item['uri-id']]);
1014                 } else {
1015                         $item['global'] = Post::exists(['uid' => 0, 'uri-id' => $item['uri-id']]);
1016                 }
1017
1018                 // ACL settings
1019                 if (!empty($item['allow_cid'] . $item['allow_gid'] . $item['deny_cid'] . $item['deny_gid'])) {
1020                         $item['private'] = self::PRIVATE;
1021                 }
1022
1023                 if ($notify && $post_local) {
1024                         $item['edit'] = false;
1025                         $item['parent'] = $parent_id;
1026
1027                         // Trigger automatic reactions for addons
1028                         if (!isset($item['api_source'])) {
1029                                 $item['api_source'] = true;
1030                         }
1031
1032                         // We have to tell the hooks who we are - this really should be improved
1033                         if (!local_user()) {
1034                                 $_SESSION['authenticated'] = true;
1035                                 $_SESSION['uid'] = $uid;
1036                                 $dummy_session = true;
1037                         } else {
1038                                 $dummy_session = false;
1039                         }
1040
1041                         Hook::callAll('post_local', $item);
1042
1043                         if ($dummy_session) {
1044                                 unset($_SESSION['authenticated']);
1045                                 unset($_SESSION['uid']);
1046                         }
1047                 } elseif (!$notify) {
1048                         Hook::callAll('post_remote', $item);
1049                 }
1050
1051                 if (!empty($item['cancel'])) {
1052                         Logger::notice('post cancelled by addon.');
1053                         return 0;
1054                 }
1055
1056                 if (empty($item['vid']) && !empty($item['verb'])) {
1057                         $item['vid'] = Verb::getID($item['verb']);
1058                 }
1059
1060                 // Creates or assigns the permission set
1061                 $item['psid'] = DI::permissionSet()->selectOrCreate(
1062                         DI::permissionSetFactory()->createFromString(
1063                                 $item['uid'],
1064                                 $item['allow_cid'],
1065                                 $item['allow_gid'],
1066                                 $item['deny_cid'],
1067                                 $item['deny_gid']
1068                 ))->id;
1069
1070                 if (!empty($item['extid'])) {
1071                         $item['external-id'] = ItemURI::getIdByURI($item['extid']);
1072                 }
1073
1074                 if ($item['verb'] == Activity::ANNOUNCE) {
1075                         self::setOwnerforResharedItem($item);
1076                 }
1077
1078                 if (isset($item['attachments'])) {
1079                         foreach ($item['attachments'] as $attachment) {
1080                                 $attachment['uri-id'] = $item['uri-id'];
1081                                 Post\Media::insert($attachment);
1082                         }
1083                         unset($item['attachments']);
1084                 }
1085
1086                 Post\Media::insertFromAttachmentData($item['uri-id'], $item['body']);
1087
1088                 // Remove all media attachments from the body and store them in the post-media table
1089                 $item['raw-body'] = Post\Media::insertFromBody($item['uri-id'], $item['raw-body']);
1090                 $item['raw-body'] = self::setHashtags($item['raw-body']);
1091
1092                 if (!DBA::exists('contact', ['id' => $item['author-id'], 'network' => Protocol::DFRN])) {
1093                         Post\Media::insertFromRelevantUrl($item['uri-id'], $item['raw-body']);
1094                 }
1095
1096                 // Check for hashtags in the body and repair or add hashtag links
1097                 $item['body'] = self::setHashtags($item['body']);
1098
1099                 if (stristr($item['verb'], Activity::POKE)) {
1100                         $notify_type = Delivery::POKE;
1101                 } else {
1102                         $notify_type = Delivery::POST;
1103                 }
1104
1105                 // Filling item related side tables
1106                 if (!empty($item['attach'])) {
1107                         Post\Media::insertFromAttachment($item['uri-id'], $item['attach']);
1108                 }
1109
1110                 if (empty($item['event-id'])) {
1111                         unset($item['event-id']);
1112
1113                         $ev = Event::fromBBCode($item['body']);
1114                         if ((!empty($ev['desc']) || !empty($ev['summary'])) && !empty($ev['start'])) {
1115                                 Logger::info('Event found.');
1116                                 $ev['cid']       = $item['contact-id'];
1117                                 $ev['uid']       = $item['uid'];
1118                                 $ev['uri']       = $item['uri'];
1119                                 $ev['edited']    = $item['edited'];
1120                                 $ev['private']   = $item['private'];
1121                                 $ev['guid']      = $item['guid'];
1122                                 $ev['plink']     = $item['plink'];
1123                                 $ev['network']   = $item['network'];
1124                                 $ev['protocol']  = $item['protocol'] ?? Conversation::PARCEL_UNKNOWN;
1125                                 $ev['direction'] = $item['direction'] ?? Conversation::UNKNOWN;
1126                                 $ev['source']    = $item['source'] ?? '';
1127
1128                                 $event = DBA::selectFirst('event', ['id'], ['uri' => $item['uri'], 'uid' => $item['uid']]);
1129                                 if (DBA::isResult($event)) {
1130                                         $ev['id'] = $event['id'];
1131                                 }
1132
1133                                 $event_id = Event::store($ev);
1134                                 $item = Event::getItemArrayForImportedId($event_id, $item);
1135
1136                                 Logger::info('Event was stored', ['id' => $event_id]);
1137                         }
1138                 }
1139
1140                 if (empty($item['causer-id'])) {
1141                         unset($item['causer-id']);
1142                 }
1143
1144                 if (in_array($item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN])) {
1145                         $content_warning = BBCode::getAbstract($item['body'], Protocol::ACTIVITYPUB);
1146                         if (!empty($content_warning) && empty($item['content-warning'])) {
1147                                 $item['content-warning'] = BBCode::toPlaintext($content_warning);
1148                         }
1149                 }
1150
1151                 Post::insert($item['uri-id'], $item);
1152
1153                 if ($item['gravity'] == GRAVITY_PARENT) {
1154                         Post\Thread::insert($item['uri-id'], $item);
1155                 }
1156
1157                 if (!in_array($item['verb'], self::ACTIVITIES)) {
1158                         Post\Content::insert($item['uri-id'], $item);
1159                 }
1160
1161                 // Create Diaspora signature
1162                 if ($item['origin'] && empty($item['diaspora_signed_text']) && ($item['gravity'] != GRAVITY_PARENT)) {
1163                         $signed = Diaspora::createCommentSignature($item);
1164                         if (!empty($signed)) {
1165                                 $item['diaspora_signed_text'] = json_encode($signed);
1166                         }
1167                 }
1168
1169                 if (!empty($item['diaspora_signed_text'])) {
1170                         DBA::replace('diaspora-interaction', ['uri-id' => $item['uri-id'], 'interaction' => $item['diaspora_signed_text']]);
1171                 }
1172
1173                 // Attached file links
1174                 if (!empty($item['file'])) {
1175                         Post\Category::storeTextByURIId($item['uri-id'], $item['uid'], $item['file']);
1176                 }
1177
1178                 // Delivery relevant data
1179                 $delivery_data = Post\DeliveryData::extractFields($item);
1180
1181                 if (!empty($item['origin']) || !empty($item['wall']) || !empty($delivery_data['postopts']) || !empty($delivery_data['inform'])) {
1182                         Post\DeliveryData::insert($item['uri-id'], $delivery_data);
1183                 }
1184
1185                 // Store tags from the body if this hadn't been handled previously in the protocol classes
1186                 if (!Tag::existsForPost($item['uri-id'])) {
1187                         Tag::storeFromBody($item['uri-id'], $item['body']);
1188                 }
1189
1190                 $condition = ['uri-id' => $item['uri-id'], 'uid' => $item['uid']];
1191                 if (Post::exists($condition)) {
1192                         Logger::notice('Item is already inserted - aborting', $condition);
1193                         return 0;
1194                 }
1195
1196                 $post_user_id = Post\User::insert($item['uri-id'], $item['uid'], $item);
1197                 if (!$post_user_id) {
1198                         Logger::notice('Post-User is already inserted - aborting', ['uid' => $item['uid'], 'uri-id' => $item['uri-id']]);
1199                         return 0;
1200                 }
1201
1202                 if ($item['gravity'] == GRAVITY_PARENT) {
1203                         $item['post-user-id'] = $post_user_id;
1204                         Post\ThreadUser::insert($item['uri-id'], $item['uid'], $item);
1205                 }
1206
1207                 Logger::notice('created item', ['post-id' => $post_user_id, 'uid' => $item['uid'], 'network' => $item['network'], 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
1208
1209                 $posted_item = Post::selectFirst(self::ITEM_FIELDLIST, ['post-user-id' => $post_user_id]);
1210                 if (!DBA::isResult($posted_item)) {
1211                         // On failure store the data into a spool file so that the "SpoolPost" worker can try again later.
1212                         Logger::warning('Could not store item. it will be spooled', ['id' => $post_user_id]);
1213                         self::spool($orig_item);
1214                         return 0;
1215                 }
1216
1217                 // update the commented timestamp on the parent
1218                 if (DI::config()->get('system', 'like_no_comment')) {
1219                         // Update when it is a comment
1220                         $update_commented = in_array($posted_item['gravity'], [GRAVITY_PARENT, GRAVITY_COMMENT]);
1221                 } else {
1222                         // Update when it isn't a follow or tag verb
1223                         $update_commented = !in_array($posted_item['verb'], [Activity::FOLLOW, Activity::TAG]);
1224                 }
1225
1226                 if ($update_commented) {
1227                         $fields = ['commented' => DateTimeFormat::utcNow(), 'changed' => DateTimeFormat::utcNow()];
1228                 } else {
1229                         $fields = ['changed' => DateTimeFormat::utcNow()];
1230                 }
1231
1232                 Post::update($fields, ['uri-id' => $posted_item['parent-uri-id'], 'uid' => $posted_item['uid']]);
1233
1234                 // In that function we check if this is a forum post. Additionally we delete the item under certain circumstances
1235                 if (self::tagDeliver($posted_item['uid'], $post_user_id)) {
1236                         // Get the user information for the logging
1237                         $user = User::getById($uid);
1238
1239                         Logger::notice('Item had been deleted', ['id' => $post_user_id, 'user' => $uid, 'account-type' => $user['account-type']]);
1240                         return 0;
1241                 }
1242
1243                 if ($notify) {
1244                         if (!\Friendica\Content\Feature::isEnabled($posted_item['uid'], 'explicit_mentions') && ($posted_item['gravity'] == GRAVITY_COMMENT)) {
1245                                 Tag::createImplicitMentions($posted_item['uri-id'], $posted_item['thr-parent-id']);
1246                         }
1247                         Hook::callAll('post_local_end', $posted_item);
1248                 } else {
1249                         Hook::callAll('post_remote_end', $posted_item);
1250                 }
1251
1252                 if ($posted_item['gravity'] === GRAVITY_PARENT) {
1253                         self::addShadow($post_user_id);
1254                 } else {
1255                         self::addShadowPost($post_user_id);
1256                 }
1257
1258                 self::updateContact($posted_item);
1259
1260                 Post\UserNotification::setNotification($posted_item['uri-id'], $posted_item['uid']);
1261
1262                 // Distribute items to users who subscribed to their tags
1263                 self::distributeByTags($posted_item);
1264
1265                 // Automatically reshare the item if the "remote_self" option is selected
1266                 self::autoReshare($posted_item);
1267
1268                 $transmit = $notify || ($posted_item['visible'] && ($parent_origin || $posted_item['origin']));
1269
1270                 if ($transmit) {
1271                         // Don't relay participation messages
1272                         if (($posted_item['verb'] == Activity::FOLLOW) &&
1273                                 (!$posted_item['origin'] || ($posted_item['author-id'] != Contact::getPublicIdByUserId($uid)))) {
1274                                 Logger::info('Participation messages will not be relayed', ['item' => $posted_item['id'], 'uri' => $posted_item['uri'], 'verb' => $posted_item['verb']]);
1275                                 $transmit = false;
1276                         }
1277                 }
1278
1279                 if ($transmit) {
1280                         if (!empty($source)) {
1281                                 Post\Activity::insert($item['uri-id'], $source);
1282                         }
1283                         Worker::add(['priority' => $priority, 'dont_fork' => true], 'Notifier', $notify_type, (int)$posted_item['uri-id'], (int)$posted_item['uid']);
1284                 }
1285
1286                 // Fill the cache with the rendered content.
1287                 if (in_array($posted_item['gravity'], [GRAVITY_PARENT, GRAVITY_COMMENT]) && ($posted_item['uid'] == 0)) {
1288                         self::updateDisplayCache($posted_item['uri-id']);
1289                 }
1290
1291                 if ($posted_item['origin'] && ($posted_item['uid'] != 0) && in_array($posted_item['gravity'], [GRAVITY_PARENT, GRAVITY_COMMENT])) {
1292                         DI::cache()->delete(ActivityPub\Transmitter::CACHEKEY_OUTBOX . $posted_item['uid']);
1293                 }
1294
1295                 return $post_user_id;
1296         }
1297
1298         /**
1299          * Update the display cache
1300          *
1301          * @param integer $uri_id
1302          * @return void
1303          */
1304         public static function updateDisplayCache(int $uri_id)
1305         {
1306                 $item = Post::selectFirst(self::DISPLAY_FIELDLIST, ['uri-id' => $uri_id]);
1307                 self::prepareBody($item, false, false, true);
1308         }
1309
1310         /**
1311          * Change the owner of a parent item if it had been shared by a forum
1312          *
1313          * (public) forum posts in the new format consist of the regular post by the author
1314          * followed by an announce message sent from the forum account.
1315          * Changing the owner helps in grouping forum posts.
1316          *
1317          * @param array $item
1318          * @return void
1319          */
1320         private static function setOwnerforResharedItem(array $item)
1321         {
1322                 $parent = Post::selectFirst(['id', 'causer-id', 'owner-id', 'author-id', 'author-link', 'origin', 'post-reason'],
1323                         ['uri-id' => $item['thr-parent-id'], 'uid' => $item['uid']]);
1324                 if (!DBA::isResult($parent)) {
1325                         Logger::error('Parent not found', ['uri-id' => $item['thr-parent-id'], 'uid' => $item['uid']]);
1326                         return;
1327                 }
1328
1329                 $author = Contact::selectFirst(['url', 'contact-type', 'network'], ['id' => $item['author-id']]);
1330                 if (!DBA::isResult($author)) {
1331                         Logger::error('Author not found', ['id' => $item['author-id']]);
1332                         return;
1333                 }
1334
1335                 $self_contact = Contact::selectFirst(['id'], ['uid' => $item['uid'], 'self' => true]);
1336                 $self = !empty($self_contact) ? $self_contact['id'] : 0;
1337
1338                 $cid = Contact::getIdForURL($author['url'], $item['uid']);
1339                 if (empty($cid) || (!Contact::isSharing($cid, $item['uid']) && ($cid != $self))) {
1340                         Logger::info('The resharer is not a following contact: quit', ['resharer' => $author['url'], 'uid' => $item['uid'], 'cid' => $cid]);
1341                         return;
1342                 }
1343
1344                 if ($author['contact-type'] != Contact::TYPE_COMMUNITY) {
1345                         if ($parent['post-reason'] == self::PR_ANNOUNCEMENT) {
1346                                 Logger::info('The parent is already marked as announced: quit', ['causer' => $parent['causer-id'], 'owner' => $parent['owner-id'], 'author' => $parent['author-id'], 'uid' => $item['uid']]);
1347                                 return;
1348                         }
1349
1350                         if (Contact::isSharing($parent['owner-id'], $item['uid'])) {
1351                                 Logger::info('The resharer is no forum: quit', ['resharer' => $item['author-id'], 'owner' => $parent['owner-id'], 'author' => $parent['author-id'], 'uid' => $item['uid']]);
1352                                 return;
1353                         }
1354                 }
1355
1356                 self::update(['post-reason' => self::PR_ANNOUNCEMENT, 'causer-id' => $item['author-id']], ['id' => $parent['id']]);
1357                 Logger::info('Set announcement post-reason', ['uri-id' => $item['uri-id'], 'thr-parent-id' => $item['thr-parent-id'], 'uid' => $item['uid']]);
1358         }
1359
1360         /**
1361          * Distribute the given item to users who subscribed to their tags
1362          *
1363          * @param array $item     Processed item
1364          */
1365         private static function distributeByTags(array $item)
1366         {
1367                 if (($item['uid'] != 0) || ($item['gravity'] != GRAVITY_PARENT) || !in_array($item['network'], Protocol::FEDERATED)) {
1368                         return;
1369                 }
1370
1371                 $uids = Tag::getUIDListByURIId($item['uri-id']);
1372                 foreach ($uids as $uid) {
1373                         $stored = self::storeForUserByUriId($item['uri-id'], $uid, ['post-reason' => self::PR_TAG]);
1374                         Logger::info('Stored item for users', ['uri-id' => $item['uri-id'], 'uid' => $uid, 'stored' => $stored]);
1375                 }
1376         }
1377
1378         /**
1379          * Distributes public items to the receivers
1380          *
1381          * @param integer $itemid      Item ID that should be added
1382          * @param string  $signed_text Original text (for Diaspora signatures), JSON encoded.
1383          * @throws \Exception
1384          */
1385         public static function distribute(int $itemid, string $signed_text = '')
1386         {
1387                 $condition = ["`id` IN (SELECT `parent` FROM `post-user-view` WHERE `id` = ?)", $itemid];
1388                 $parent = Post::selectFirst(['owner-id'], $condition);
1389                 if (!DBA::isResult($parent)) {
1390                         Logger::warning('Item not found', ['condition' => $condition]);
1391                         return;
1392                 }
1393
1394                 // Only distribute public items from native networks
1395                 $condition = ['id' => $itemid, 'uid' => 0,
1396                         'network' => array_merge(Protocol::FEDERATED ,['']),
1397                         'visible' => true, 'deleted' => false, 'private' => [self::PUBLIC, self::UNLISTED]];
1398                 $item = Post::selectFirst(array_merge(self::ITEM_FIELDLIST, ['protocol']), $condition);
1399                 if (!DBA::isResult($item)) {
1400                         Logger::warning('Item not found', ['condition' => $condition]);
1401                         return;
1402                 }
1403
1404                 $origin = $item['origin'];
1405
1406                 $users = [];
1407
1408                 /// @todo add a field "pcid" in the contact table that referrs to the public contact id.
1409                 $owner = DBA::selectFirst('contact', ['url', 'nurl', 'alias'], ['id' => $parent['owner-id']]);
1410                 if (!DBA::isResult($owner)) {
1411                         return;
1412                 }
1413
1414                 $condition = ['nurl' => $owner['nurl'], 'rel' => [Contact::SHARING, Contact::FRIEND]];
1415                 $contacts = DBA::select('contact', ['uid'], $condition);
1416                 while ($contact = DBA::fetch($contacts)) {
1417                         if ($contact['uid'] == 0) {
1418                                 continue;
1419                         }
1420
1421                         $users[$contact['uid']] = $contact['uid'];
1422                 }
1423                 DBA::close($contacts);
1424
1425                 $condition = ['alias' => $owner['url'], 'rel' => [Contact::SHARING, Contact::FRIEND]];
1426                 $contacts = DBA::select('contact', ['uid'], $condition);
1427                 while ($contact = DBA::fetch($contacts)) {
1428                         if ($contact['uid'] == 0) {
1429                                 continue;
1430                         }
1431
1432                         $users[$contact['uid']] = $contact['uid'];
1433                 }
1434                 DBA::close($contacts);
1435
1436                 if (!empty($owner['alias'])) {
1437                         $condition = ['nurl' => Strings::normaliseLink($owner['alias']), 'rel' => [Contact::SHARING, Contact::FRIEND]];
1438                         $contacts = DBA::select('contact', ['uid'], $condition);
1439                         while ($contact = DBA::fetch($contacts)) {
1440                                 if ($contact['uid'] == 0) {
1441                                         continue;
1442                                 }
1443
1444                                 $users[$contact['uid']] = $contact['uid'];
1445                         }
1446                         DBA::close($contacts);
1447                 }
1448
1449                 $origin_uid = 0;
1450
1451                 if ($item['uri-id'] != $item['parent-uri-id']) {
1452                         $parents = Post::select(['uid', 'origin'], ["`uri-id` = ? AND `uid` != 0", $item['parent-uri-id']]);
1453                         while ($parent = Post::fetch($parents)) {
1454                                 $users[$parent['uid']] = $parent['uid'];
1455                                 if ($parent['origin'] && !$origin) {
1456                                         $origin_uid = $parent['uid'];
1457                                 }
1458                         }
1459                         DBA::close($parents);
1460                 }
1461
1462                 foreach ($users as $uid) {
1463                         if ($origin_uid == $uid) {
1464                                 $item['diaspora_signed_text'] = $signed_text;
1465                         }
1466                         $item['post-reason'] = self::PR_DISTRIBUTE;
1467                         self::storeForUser($item, $uid);
1468                 }
1469         }
1470
1471         /**
1472          * Store a public item defined by their URI-ID for the given users
1473          *
1474          * @param integer $uri_id     URI-ID of the given item
1475          * @param integer $uid        The user that will receive the item entry
1476          * @param array   $fields     Additional fields to be stored
1477          * @param integer $source_uid User id of the source post
1478          * @return integer stored item id
1479          */
1480         public static function storeForUserByUriId(int $uri_id, int $uid, array $fields = [], int $source_uid = 0): int
1481         {
1482                 if ($uid == $source_uid) {
1483                         Logger::warning('target UID must not be be equal to the source UID', ['uri-id' => $uri_id, 'uid' => $uid]);
1484                         return 0;
1485                 }
1486
1487                 $item = Post::selectFirst(array_merge(self::ITEM_FIELDLIST, ['protocol']), ['uri-id' => $uri_id, 'uid' => $source_uid]);
1488                 if (!DBA::isResult($item)) {
1489                         Logger::warning('Item could not be fetched', ['uri-id' => $uri_id, 'uid' => $source_uid]);
1490                         return 0;
1491                 }
1492
1493                 if (($source_uid == 0) && (($item['private'] == self::PRIVATE) || !in_array($item['network'], Protocol::FEDERATED))) {
1494                         Logger::notice('Item is private or not from a federated network. It will not be stored for the user.', ['uri-id' => $uri_id, 'uid' => $uid, 'private' => $item['private'], 'network' => $item['network']]);
1495                         return 0;
1496                 }
1497
1498                 $item['post-reason'] = self::PR_STORED;
1499
1500                 $item = array_merge($item, $fields);
1501
1502                 $is_reshare = ($item['gravity'] == GRAVITY_ACTIVITY) && ($item['verb'] == Activity::ANNOUNCE);
1503
1504                 if ((($item['gravity'] == GRAVITY_PARENT) || $is_reshare) &&
1505                         DI::pConfig()->get($uid, 'system', 'accept_only_sharer') == self::COMPLETION_NONE &&
1506                         !Contact::isSharingByURL($item['author-link'], $uid) &&
1507                         !Contact::isSharingByURL($item['owner-link'], $uid)) {
1508                         Logger::info('Contact is not a follower, thread will not be stored', ['author' => $item['author-link'], 'uid' => $uid]);
1509                         return 0;
1510                 }
1511
1512                 if (($uri_id != $item['thr-parent-id']) && (($item['gravity'] == GRAVITY_COMMENT) || $is_reshare) && !Post::exists(['uri-id' => $item['thr-parent-id'], 'uid' => $uid])) {
1513                         // Fetch the origin user for the post
1514                         $origin_uid = self::GetOriginUidForUriId($item['thr-parent-id'], $uid);
1515                         if (is_null($origin_uid)) {
1516                                 Logger::info('Origin item was not found', ['uid' => $uid, 'uri-id' => $item['thr-parent-id']]);
1517                                 return 0;
1518                         }
1519
1520                         $causer = $item['causer-id'] ?: $item['author-id'];
1521                         $result = self::storeForUserByUriId($item['thr-parent-id'], $uid, ['causer-id' => $causer, 'post-reason' => self::PR_FETCHED], $origin_uid);
1522                         Logger::info('Fetched thread parent', ['uri-id' => $item['thr-parent-id'], 'uid' => $uid, 'causer' => $causer, 'result' => $result]);
1523                 }
1524
1525                 $stored = self::storeForUser($item, $uid);
1526                 Logger::info('Item stored for user', ['uri-id' => $item['uri-id'], 'uid' => $uid, 'source-uid' => $source_uid, 'stored' => $stored]);
1527                 return $stored;
1528         }
1529
1530         /**
1531          * Returns the origin uid of a post if the given user is allowed to see it.
1532          *
1533          * @param int $uriid
1534          * @param int $uid
1535          * @return int
1536          */
1537         private static function GetOriginUidForUriId(int $uriid, int $uid)
1538         {
1539                 if (Post::exists(['uri-id' => $uriid, 'uid' => $uid])) {
1540                         return $uid;
1541                 }
1542
1543                 $post = Post::selectFirst(['uid', 'allow_cid', 'allow_gid', 'deny_cid', 'deny_gid', 'private'], ['uri-id' => $uriid, 'origin' => true]);
1544                 if (!empty($post)) {
1545                         if (in_array($post['private'], [Item::PUBLIC, Item::UNLISTED])) {
1546                                 return $post['uid'];
1547                         }
1548
1549                         $pcid = Contact::getPublicIdByUserId($uid);
1550                         if (empty($pcid)) {
1551                                 return null;
1552                         }
1553
1554                         foreach (Item::enumeratePermissions($post, true) as $receiver) {
1555                                 if ($receiver == $pcid) {
1556                                         return $post['uid'];
1557                                 }
1558                         }
1559
1560                         return null;
1561                 }
1562
1563                 if (Post::exists(['uri-id' => $uriid, 'uid' => 0])) {
1564                         return 0;
1565                 }
1566
1567                 // When the post belongs to a a forum then all forum users are allowed to access it
1568                 foreach (Tag::getByURIId($uriid, [Tag::MENTION, Tag::EXCLUSIVE_MENTION]) as $tag) {
1569                         if (DBA::exists('contact', ['uid' => $uid, 'nurl' => Strings::normaliseLink($tag['url']), 'contact-type' => Contact::TYPE_COMMUNITY])) {
1570                                 $target_uid = User::getIdForURL($tag['url']);
1571                                 if (!empty($target_uid)) {
1572                                         return $target_uid;
1573                                 }
1574                         }
1575                 }
1576
1577                 return null;
1578         }
1579
1580         /**
1581          * Store a public item array for the given users
1582          *
1583          * @param array   $item   The item entry that will be stored
1584          * @param integer $uid    The user that will receive the item entry
1585          * @return integer stored item id
1586          * @throws \Exception
1587          */
1588         private static function storeForUser(array $item, int $uid): int
1589         {
1590                 if (Post::exists(['uri-id' => $item['uri-id'], 'uid' => $uid])) {
1591                         if (!empty($item['event-id'])) {
1592                                 $post = Post::selectFirst(['event-id'], ['uri-id' => $item['uri-id'], 'uid' => $uid]);
1593                                 if (!empty($post['event-id'])) {
1594                                         $event = DBA::selectFirst('event', ['edited', 'start', 'finish', 'summary', 'desc', 'location', 'nofinish', 'adjust'], ['id' => $item['event-id']]);
1595                                         if (!empty($event)) {
1596                                                 // We aren't using "Event::store" here, since we don't want to trigger any further action
1597                                                 $ret = DBA::update('event', $event, ['id' => $post['event-id']]);
1598                                                 Logger::info('Event updated', ['uid' => $uid, 'source-event' => $item['event-id'], 'target-event' => $post['event-id'], 'ret' => $ret]);
1599                                         }
1600                                 }
1601                         }
1602                         Logger::info('Item already exists', ['uri-id' => $item['uri-id'], 'uid' => $uid]);
1603                         return 0;
1604                 }
1605
1606                 // Data from the "post-user" table
1607                 unset($item['id']);
1608                 unset($item['mention']);
1609                 unset($item['starred']);
1610                 unset($item['unseen']);
1611                 unset($item['psid']);
1612                 unset($item['pinned']);
1613                 unset($item['ignored']);
1614                 unset($item['pubmail']);
1615                 unset($item['event-id']);
1616                 unset($item['hidden']);
1617                 unset($item['notification-type']);
1618
1619                 // Data from the "post-delivery-data" table
1620                 unset($item['postopts']);
1621                 unset($item['inform']);
1622
1623                 $item['uid'] = $uid;
1624                 $item['origin'] = 0;
1625                 $item['wall'] = 0;
1626
1627                 if ($item['gravity'] == GRAVITY_PARENT) {
1628                         $contact = Contact::getByURLForUser($item['owner-link'], $uid, false, ['id']);
1629                 } else {
1630                         $contact = Contact::getByURLForUser($item['author-link'], $uid, false, ['id']);
1631                 }
1632
1633                 if (!empty($contact['id'])) {
1634                         $item['contact-id'] = $contact['id'];
1635                 } else {
1636                         // Shouldn't happen at all
1637                         Logger::warning('contact-id could not be fetched', ['uid' => $uid, 'item' => $item]);
1638                         $self = DBA::selectFirst('contact', ['id'], ['self' => true, 'uid' => $uid]);
1639                         if (!DBA::isResult($self)) {
1640                                 // Shouldn't happen even less
1641                                 Logger::warning('self contact could not be fetched', ['uid' => $uid, 'item' => $item]);
1642                                 return 0;
1643                         }
1644                         $item['contact-id'] = $self['id'];
1645                 }
1646
1647                 $notify = false;
1648                 if ($item['gravity'] == GRAVITY_PARENT) {
1649                         $contact = DBA::selectFirst('contact', [], ['id' => $item['contact-id'], 'self' => false]);
1650                         if (DBA::isResult($contact)) {
1651                                 $notify = self::isRemoteSelf($contact, $item);
1652                         }
1653                 }
1654
1655                 $distributed = self::insert($item, $notify);
1656
1657                 if (!$distributed) {
1658                         Logger::info("Distributed item wasn't stored", ['uri-id' => $item['uri-id'], 'user' => $uid]);
1659                 } else {
1660                         Logger::info('Distributed item was stored', ['uri-id' => $item['uri-id'], 'user' => $uid, 'stored' => $distributed]);
1661                 }
1662                 return $distributed;
1663         }
1664
1665         /**
1666          * Add a shadow entry for a given item id that is a thread starter
1667          *
1668          * We store every public item entry additionally with the user id "0".
1669          * This is used for the community page and for the search.
1670          * It is planned that in the future we will store public item entries only once.
1671          *
1672          * @param integer $itemid Item ID that should be added
1673          * @throws \Exception
1674          */
1675         private static function addShadow(int $itemid)
1676         {
1677                 $fields = ['uid', 'private', 'visible', 'deleted', 'network', 'uri-id'];
1678                 $condition = ['id' => $itemid, 'gravity' => GRAVITY_PARENT];
1679                 $item = Post::selectFirst($fields, $condition);
1680
1681                 if (!DBA::isResult($item)) {
1682                         return;
1683                 }
1684
1685                 // is it already a copy?
1686                 if (($itemid == 0) || ($item['uid'] == 0)) {
1687                         return;
1688                 }
1689
1690                 // Is it a visible public post?
1691                 if (!$item["visible"] || $item["deleted"]  || ($item["private"] == self::PRIVATE)) {
1692                         return;
1693                 }
1694
1695                 // is it an entry from a connector? Only add an entry for natively connected networks
1696                 if (!in_array($item["network"], array_merge(Protocol::FEDERATED ,['']))) {
1697                         return;
1698                 }
1699
1700                 if (Post::exists(['uri-id' => $item['uri-id'], 'uid' => 0])) {
1701                         return;
1702                 }
1703
1704                 $item = Post::selectFirst(array_merge(self::ITEM_FIELDLIST, ['protocol']), ['id' => $itemid]);
1705
1706                 if (DBA::isResult($item)) {
1707                         // Preparing public shadow (removing user specific data)
1708                         $item['uid'] = 0;
1709                         unset($item['id']);
1710                         unset($item['parent']);
1711                         unset($item['wall']);
1712                         unset($item['mention']);
1713                         unset($item['origin']);
1714                         unset($item['starred']);
1715                         unset($item['postopts']);
1716                         unset($item['inform']);
1717                         unset($item['post-reason']);
1718                         if ($item['uri-id'] == $item['parent-uri-id']) {
1719                                 $item['contact-id'] = $item['owner-id'];
1720                         } else {
1721                                 $item['contact-id'] = $item['author-id'];
1722                         }
1723
1724                         $public_shadow = self::insert($item);
1725
1726                         Logger::info('Stored public shadow', ['thread' => $itemid, 'id' => $public_shadow]);
1727                 }
1728         }
1729
1730         /**
1731          * Add a shadow entry for a given item id that is a comment
1732          *
1733          * This function does the same like the function above - but for comments
1734          *
1735          * @param integer $itemid Item ID that should be added
1736          * @throws \Exception
1737          */
1738         private static function addShadowPost(int $itemid)
1739         {
1740                 $item = Post::selectFirst(array_merge(self::ITEM_FIELDLIST, ['protocol']), ['id' => $itemid]);
1741                 if (!DBA::isResult($item)) {
1742                         return;
1743                 }
1744
1745                 // Is it a toplevel post?
1746                 if ($item['gravity'] == GRAVITY_PARENT) {
1747                         self::addShadow($itemid);
1748                         return;
1749                 }
1750
1751                 // Is this a shadow entry?
1752                 if ($item['uid'] == 0) {
1753                         return;
1754                 }
1755
1756                 // Is there a shadow parent?
1757                 if (!Post::exists(['uri-id' => $item['parent-uri-id'], 'uid' => 0])) {
1758                         return;
1759                 }
1760
1761                 // Is there already a shadow entry?
1762                 if (Post::exists(['uri-id' => $item['uri-id'], 'uid' => 0])) {
1763                         return;
1764                 }
1765
1766                 // Save "origin" and "parent" state
1767                 $origin = $item['origin'];
1768                 $parent = $item['parent'];
1769
1770                 // Preparing public shadow (removing user specific data)
1771                 $item['uid'] = 0;
1772                 unset($item['id']);
1773                 unset($item['parent']);
1774                 unset($item['wall']);
1775                 unset($item['mention']);
1776                 unset($item['origin']);
1777                 unset($item['starred']);
1778                 unset($item['postopts']);
1779                 unset($item['inform']);
1780                 unset($item['post-reason']);
1781                 $item['contact-id'] = Contact::getIdForURL($item['author-link']);
1782
1783                 $public_shadow = self::insert($item);
1784
1785                 Logger::info('Stored public shadow', ['uri-id' => $item['uri-id'], 'id' => $public_shadow]);
1786
1787                 // If this was a comment to a Diaspora post we don't get our comment back.
1788                 // This means that we have to distribute the comment by ourselves.
1789                 if ($origin && Post::exists(['id' => $parent, 'network' => Protocol::DIASPORA])) {
1790                         self::distribute($public_shadow);
1791                 }
1792         }
1793
1794         /**
1795          * Adds a language specification in a "language" element of given $arr.
1796          * Expects "body" element to exist in $arr.
1797          *
1798          * @param array $item
1799          * @return string detected language
1800          * @throws \Text_LanguageDetect_Exception
1801          */
1802         private static function getLanguage(array $item): string
1803         {
1804                 if (!empty($item['language'])) {
1805                         return $item['language'];
1806                 }
1807
1808                 if (!in_array($item['gravity'], [GRAVITY_PARENT, GRAVITY_COMMENT]) || empty($item['body'])) {
1809                         return '';
1810                 }
1811
1812                 // Convert attachments to links
1813                 $naked_body = BBCode::removeAttachment($item['body']);
1814                 if (empty($naked_body)) {
1815                         return '';
1816                 }
1817
1818                 // Remove links and pictures
1819                 $naked_body = BBCode::removeLinks($naked_body);
1820
1821                 // Convert the title and the body to plain text
1822                 $naked_body = trim($item['title'] . "\n" . BBCode::toPlaintext($naked_body));
1823
1824                 // Remove possibly remaining links
1825                 $naked_body = preg_replace(Strings::autoLinkRegEx(), '', $naked_body);
1826
1827                 if (empty($naked_body)) {
1828                         return '';
1829                 }
1830
1831                 $availableLanguages = DI::l10n()->getAvailableLanguages();
1832                 // See https://github.com/friendica/friendica/issues/10511
1833                 // Persian is manually added to language detection until a persian translation is provided for the interface, at
1834                 // which point it will be automatically available through `getAvailableLanguages()` and this should be removed.
1835                 $availableLanguages['fa'] = 'fa';
1836
1837                 $ld = new Language(array_keys($availableLanguages));
1838                 $languages = $ld->detect($naked_body)->limit(0, 3)->close();
1839                 if (is_array($languages)) {
1840                         return json_encode($languages);
1841                 }
1842
1843                 return '';
1844         }
1845
1846         public static function getLanguageMessage(array $item): string
1847         {
1848                 $iso639 = new \Matriphe\ISO639\ISO639;
1849
1850                 $used_languages = '';
1851                 foreach (json_decode($item['language'], true) as $language => $reliability) {
1852                         $used_languages .= $iso639->languageByCode1($language) . ' (' . $language . "): " . number_format($reliability, 5) . '\n';
1853                 }
1854                 $used_languages = DI::l10n()->t('Detected languages in this post:\n%s', $used_languages);
1855                 return $used_languages;
1856         }
1857
1858         /**
1859          * Creates an unique guid out of a given uri.
1860          * This function is used for messages outside the fediverse (Connector posts, feeds, Mails, ...)
1861          * Posts that are created on this system are using System::createUUID.
1862          * Received ActivityPub posts are using Processor::getGUIDByURL.
1863          *
1864          * @param string      $uri uri of an item entry
1865          * @param string|null $host hostname for the GUID prefix
1866          * @return string Unique guid
1867          */
1868         public static function guidFromUri(string $uri, string $host = null): string
1869         {
1870                 // Our regular guid routine is using this kind of prefix as well
1871                 // We have to avoid that different routines could accidentally create the same value
1872                 $parsed = parse_url($uri);
1873
1874                 // Remove the scheme to make sure that "https" and "http" doesn't make a difference
1875                 unset($parsed['scheme']);
1876
1877                 // Glue it together to be able to make a hash from it
1878                 $host_id = implode('/', $parsed);
1879
1880                 // Use a mixture of several hashes to provide some GUID like experience
1881                 return hash('crc32', $host) . '-'. hash('joaat', $host_id) . '-'. hash('fnv164', $host_id);
1882         }
1883
1884         /**
1885          * generate an unique URI
1886          *
1887          * @param string $guid An existing GUID (Otherwise it will be generated)
1888          *
1889          * @return string
1890          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1891          */
1892         public static function newURI(string $guid = ''): string
1893         {
1894                 if ($guid == '') {
1895                         $guid = System::createUUID();
1896                 }
1897
1898                 return DI::baseUrl()->get() . '/objects/' . $guid;
1899         }
1900
1901         /**
1902          * Set "success_update" and "last-item" to the date of the last time we heard from this contact
1903          *
1904          * This can be used to filter for inactive contacts.
1905          * Only do this for public postings to avoid privacy problems, since poco data is public.
1906          * Don't set this value if it isn't from the owner (could be an author that we don't know)
1907          *
1908          * @param array $arr Contains the just posted item record
1909          * @throws \Exception
1910          */
1911         private static function updateContact(array $arr)
1912         {
1913                 // Unarchive the author
1914                 $contact = DBA::selectFirst('contact', [], ['id' => $arr["author-id"]]);
1915                 if (DBA::isResult($contact)) {
1916                         Contact::unmarkForArchival($contact);
1917                 }
1918
1919                 // Unarchive the contact if it's not our own contact
1920                 $contact = DBA::selectFirst('contact', [], ['id' => $arr["contact-id"], 'self' => false]);
1921                 if (DBA::isResult($contact)) {
1922                         Contact::unmarkForArchival($contact);
1923                 }
1924
1925                 /// @todo On private posts we could obfuscate the date
1926                 $update = ($arr['private'] != self::PRIVATE) || in_array($arr['network'], Protocol::FEDERATED);
1927
1928                 // Is it a forum? Then we don't care about the rules from above
1929                 if (!$update && in_array($arr["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN]) && ($arr["parent-uri-id"] === $arr["uri-id"])) {
1930                         if (DBA::exists('contact', ['id' => $arr['contact-id'], 'forum' => true])) {
1931                                 $update = true;
1932                         }
1933                 }
1934
1935                 if ($update) {
1936                         // The "self" contact id is used (for example in the connectors) when the contact is unknown
1937                         // So we have to ensure to only update the last item when it had been our own post,
1938                         // or it had been done by a "regular" contact.
1939                         if (!empty($arr['wall'])) {
1940                                 $condition = ['id' => $arr['contact-id']];
1941                         } else {
1942                                 $condition = ['id' => $arr['contact-id'], 'self' => false];
1943                         }
1944                         Contact::update(['failed' => false, 'success_update' => $arr['received'], 'last-item' => $arr['received']], $condition);
1945                 }
1946                 // Now do the same for the system wide contacts with uid=0
1947                 if ($arr['private'] != self::PRIVATE) {
1948                         Contact::update(['failed' => false, 'success_update' => $arr['received'], 'last-item' => $arr['received']],
1949                                 ['id' => $arr['owner-id']]);
1950
1951                         if ($arr['owner-id'] != $arr['author-id']) {
1952                                 Contact::update(['failed' => false, 'success_update' => $arr['received'], 'last-item' => $arr['received']],
1953                                         ['id' => $arr['author-id']]);
1954                         }
1955                 }
1956         }
1957
1958         public static function setHashtags(string $body): string
1959         {
1960                 $body = BBCode::performWithEscapedTags($body, ['noparse', 'pre', 'code', 'img'], function ($body) {
1961                         $tags = BBCode::getTags($body);
1962
1963                         // No hashtags?
1964                         if (!count($tags)) {
1965                                 return $body;
1966                         }
1967
1968                         // This sorting is important when there are hashtags that are part of other hashtags
1969                         // Otherwise there could be problems with hashtags like #test and #test2
1970                         // Because of this we are sorting from the longest to the shortest tag.
1971                         usort($tags, function ($a, $b) {
1972                                 return strlen($b) <=> strlen($a);
1973                         });
1974
1975                         $URLSearchString = "^\[\]";
1976
1977                         // All hashtags should point to the home server if "local_tags" is activated
1978                         if (DI::config()->get('system', 'local_tags')) {
1979                                 $body = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
1980                                         "#[url=" . DI::baseUrl() . "/search?tag=$2]$2[/url]", $body);
1981                         }
1982
1983                         // mask hashtags inside of url, bookmarks and attachments to avoid urls in urls
1984                         $body = preg_replace_callback("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
1985                                 function ($match) {
1986                                         return ("[url=" . str_replace("#", "&num;", $match[1]) . "]" . str_replace("#", "&num;", $match[2]) . "[/url]");
1987                                 }, $body);
1988
1989                         $body = preg_replace_callback("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",
1990                                 function ($match) {
1991                                         return ("[bookmark=" . str_replace("#", "&num;", $match[1]) . "]" . str_replace("#", "&num;", $match[2]) . "[/bookmark]");
1992                                 }, $body);
1993
1994                         $body = preg_replace_callback("/\[attachment (.*?)\](.*?)\[\/attachment\]/ism",
1995                                 function ($match) {
1996                                         return ("[attachment " . str_replace("#", "&num;", $match[1]) . "]" . $match[2] . "[/attachment]");
1997                                 }, $body);
1998
1999                         // Repair recursive urls
2000                         $body = preg_replace("/&num;\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2001                                 "&num;$2", $body);
2002
2003                         foreach ($tags as $tag) {
2004                                 if ((strpos($tag, '#') !== 0) || strpos($tag, '[url=') || strlen($tag) < 2 || $tag[1] == '#') {
2005                                         continue;
2006                                 }
2007
2008                                 $basetag = str_replace('_', ' ', substr($tag, 1));
2009                                 $newtag = '#[url=' . DI::baseUrl() . '/search?tag=' . $basetag . ']' . $basetag . '[/url]';
2010
2011                                 $body = str_replace($tag, $newtag, $body);
2012                         }
2013
2014                         // Convert back the masked hashtags
2015                         $body = str_replace("&num;", "#", $body);
2016
2017                         return $body;
2018                 });
2019
2020                 return $body;
2021         }
2022
2023         /**
2024          * look for mention tags and setup a second delivery chain for forum/community posts if appropriate
2025          *
2026          * @param int $uid
2027          * @param int $item_id
2028          * @return boolean true if item was deleted, else false
2029          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2030          * @throws \ImagickException
2031          */
2032         private static function tagDeliver(int $uid, int $item_id): bool
2033         {
2034                 $mention = false;
2035
2036                 $owner = User::getOwnerDataById($uid);
2037                 if (!DBA::isResult($owner)) {
2038                         Logger::warning('User not found, quitting here.', ['uid' => $uid]);
2039                         return false;
2040                 }
2041
2042                 if ($owner['contact-type'] != User::ACCOUNT_TYPE_COMMUNITY) {
2043                         Logger::debug('Owner is no community, quitting here.', ['uid' => $uid, 'id' => $item_id]);
2044                         return false;
2045                 }
2046
2047                 $item = Post::selectFirst(self::ITEM_FIELDLIST, ['id' => $item_id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT], 'origin' => false]);
2048                 if (!DBA::isResult($item)) {
2049                         Logger::debug('Post is an activity or origin or not found at all, quitting here.', ['id' => $item_id]);
2050                         return false;
2051                 }
2052
2053                 if ($item['gravity'] == GRAVITY_PARENT) {
2054                         $tags = Tag::getByURIId($item['uri-id'], [Tag::MENTION, Tag::EXCLUSIVE_MENTION]);
2055                         foreach ($tags as $tag) {
2056                                 if (Strings::compareLink($owner['url'], $tag['url'])) {
2057                                         $mention = true;
2058                                         Logger::info('Mention found in tag.', ['url' => $tag['url'], 'uri' => $item['uri'], 'uid' => $uid, 'id' => $item_id, 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
2059                                 }
2060                         }
2061
2062                         if (!$mention) {
2063                                 Logger::info('Top-level post without mention is deleted.', ['uri' => $item['uri'], $uid, 'id' => $item_id, 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
2064                                 Post\User::delete(['uri-id' => $item['uri-id'], 'uid' => $item['uid']]);
2065                                 return true;
2066                         }
2067
2068                         $arr = ['item' => $item, 'user' => $owner];
2069
2070                         Hook::callAll('tagged', $arr);
2071                 } else {
2072                         $tags = Tag::getByURIId($item['parent-uri-id'], [Tag::MENTION, Tag::EXCLUSIVE_MENTION]);
2073                         foreach ($tags as $tag) {
2074                                 if (Strings::compareLink($owner['url'], $tag['url'])) {
2075                                         $mention = true;
2076                                         Logger::info('Mention found in parent tag.', ['url' => $tag['url'], 'uri' => $item['uri'], 'uid' => $uid, 'id' => $item_id, 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
2077                                 }
2078                         }
2079
2080                         if (!$mention) {
2081                                 Logger::debug('No mentions found in parent, quitting here.', ['id' => $item_id, 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
2082                                 return false;
2083                         }
2084                 }
2085
2086                 Logger::info('Community post will be distributed', ['uri' => $item['uri'], 'uid' => $uid, 'id' => $item_id, 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
2087
2088                 if ($owner['page-flags'] == User::PAGE_FLAGS_PRVGROUP) {
2089                         $allow_cid = '';
2090                         $allow_gid = '<' . Group::FOLLOWERS . '>';
2091                         $deny_cid  = '';
2092                         $deny_gid  = '';
2093                         self::performActivity($item['id'], 'announce', $uid, $allow_cid, $allow_gid, $deny_cid, $deny_gid);
2094                 } else {
2095                         self::performActivity($item['id'], 'announce', $uid);
2096                 }
2097
2098                 Logger::info('Community post had been distributed', ['uri' => $item['uri'], 'uid' => $uid, 'id' => $item_id, 'uri-id' => $item['uri-id'], 'guid' => $item['guid']]);
2099                 return false;
2100         }
2101
2102         /**
2103          * Automatically reshare the item if the "remote_self" option is selected
2104          *
2105          * @param array $item
2106          * @return void
2107          */
2108         private static function autoReshare(array $item)
2109         {
2110                 if ($item['gravity'] != GRAVITY_PARENT) {
2111                         return;
2112                 }
2113
2114                 if (!DBA::exists('contact', ['id' => $item['contact-id'], 'remote_self' => Contact::MIRROR_NATIVE_RESHARE])) {
2115                         return;
2116                 }
2117
2118                 if (!in_array($item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN])) {
2119                         return;
2120                 }
2121
2122                 Logger::info('Automatically reshare item', ['uid' => $item['uid'], 'id' => $item['id'], 'guid' => $item['guid'], 'uri-id' => $item['uri-id']]);
2123
2124                 self::performActivity($item['id'], 'announce', $item['uid']);
2125         }
2126
2127         public static function isRemoteSelf(array $contact, array &$datarray): bool
2128         {
2129                 if (!$contact['remote_self']) {
2130                         return false;
2131                 }
2132
2133                 // Prevent the forwarding of posts that are forwarded
2134                 if (!empty($datarray["extid"]) && ($datarray["extid"] == Protocol::DFRN)) {
2135                         Logger::info('Already forwarded');
2136                         return false;
2137                 }
2138
2139                 // Prevent to forward already forwarded posts
2140                 if ($datarray["app"] == DI::baseUrl()->getHostname()) {
2141                         Logger::info('Already forwarded (second test)');
2142                         return false;
2143                 }
2144
2145                 // Only forward posts
2146                 if ($datarray["verb"] != Activity::POST) {
2147                         Logger::info('No post');
2148                         return false;
2149                 }
2150
2151                 if (($contact['network'] != Protocol::FEED) && ($datarray['private'] == self::PRIVATE)) {
2152                         Logger::info('Not public');
2153                         return false;
2154                 }
2155
2156                 $datarray2 = $datarray;
2157                 Logger::info('remote-self start', ['contact' => $contact['url'], 'remote_self'=> $contact['remote_self'], 'item' => $datarray]);
2158                 if ($contact['remote_self'] == Contact::MIRROR_OWN_POST) {
2159                         $self = DBA::selectFirst('contact', ['id', 'name', 'url', 'thumb'],
2160                                         ['uid' => $contact['uid'], 'self' => true]);
2161                         if (DBA::isResult($self)) {
2162                                 $datarray['contact-id'] = $self["id"];
2163
2164                                 $datarray['owner-name'] = $self["name"];
2165                                 $datarray['owner-link'] = $self["url"];
2166                                 $datarray['owner-avatar'] = $self["thumb"];
2167
2168                                 $datarray['author-name']   = $datarray['owner-name'];
2169                                 $datarray['author-link']   = $datarray['owner-link'];
2170                                 $datarray['author-avatar'] = $datarray['owner-avatar'];
2171
2172                                 unset($datarray['edited']);
2173
2174                                 unset($datarray['network']);
2175                                 unset($datarray['owner-id']);
2176                                 unset($datarray['author-id']);
2177                         }
2178
2179                         if ($contact['network'] != Protocol::FEED) {
2180                                 $old_uri_id = $datarray["uri-id"] ?? 0;
2181                                 $datarray["guid"] = System::createUUID();
2182                                 unset($datarray["plink"]);
2183                                 $datarray["uri"] = self::newURI($datarray["guid"]);
2184                                 $datarray["uri-id"] = ItemURI::getIdByURI($datarray["uri"]);
2185                                 $datarray["extid"] = Protocol::DFRN;
2186                                 $urlpart = parse_url($datarray2['author-link']);
2187                                 $datarray["app"] = $urlpart["host"];
2188                                 if (!empty($old_uri_id)) {
2189                                         Post\Media::copy($old_uri_id, $datarray["uri-id"]);
2190                                 }
2191
2192                                 unset($datarray["parent-uri"]);
2193                                 unset($datarray["thr-parent"]);
2194                         } else {
2195                                 $datarray['private'] = self::PUBLIC;
2196                         }
2197                 }
2198
2199                 if ($contact['network'] != Protocol::FEED) {
2200                         // Store the original post
2201                         $result = self::insert($datarray2);
2202                         Logger::info('remote-self post original item', ['contact' => $contact['url'], 'result'=> $result, 'item' => $datarray2]);
2203                 } else {
2204                         $datarray["app"] = "Feed";
2205                         $result = true;
2206                 }
2207
2208                 return (bool)$result;
2209         }
2210
2211         /**
2212          *
2213          * @param string $s
2214          * @param int    $uid
2215          * @param array  $item
2216          * @param int    $cid
2217          * @return string
2218          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2219          * @throws \ImagickException
2220          */
2221         public static function fixPrivatePhotos(string $s, int $uid, array $item = null, int $cid = 0): string
2222         {
2223                 if (DI::config()->get('system', 'disable_embedded')) {
2224                         return $s;
2225                 }
2226
2227                 Logger::info('check for photos');
2228                 $site = substr(DI::baseUrl(), strpos(DI::baseUrl(), '://'));
2229
2230                 $orig_body = $s;
2231                 $new_body = '';
2232
2233                 $img_start = strpos($orig_body, '[img');
2234                 $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
2235                 $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
2236
2237                 while (($img_st_close !== false) && ($img_len !== false)) {
2238                         $img_st_close++; // make it point to AFTER the closing bracket
2239                         $image = substr($orig_body, $img_start + $img_st_close, $img_len);
2240
2241                         Logger::info('found photo', ['image' => $image]);
2242
2243                         if (stristr($image, $site . '/photo/')) {
2244                                 // Only embed locally hosted photos
2245                                 $replace = false;
2246                                 $i = basename($image);
2247                                 $i = str_replace(['.jpg', '.png', '.gif'], ['', '', ''], $i);
2248                                 $x = strpos($i, '-');
2249
2250                                 if ($x) {
2251                                         $res = substr($i, $x + 1);
2252                                         $i = substr($i, 0, $x);
2253                                         $photo = Photo::getPhotoForUser($uid, $i, $res);
2254                                         if (DBA::isResult($photo)) {
2255                                                 /*
2256                                                  * Check to see if we should replace this photo link with an embedded image
2257                                                  * 1. No need to do so if the photo is public
2258                                                  * 2. If there's a contact-id provided, see if they're in the access list
2259                                                  *    for the photo. If so, embed it.
2260                                                  * 3. Otherwise, if we have an item, see if the item permissions match the photo
2261                                                  *    permissions, regardless of order but first check to see if they're an exact
2262                                                  *    match to save some processing overhead.
2263                                                  */
2264                                                 if (self::hasPermissions($photo)) {
2265                                                         if ($cid) {
2266                                                                 $recips = self::enumeratePermissions($photo);
2267                                                                 if (in_array($cid, $recips)) {
2268                                                                         $replace = true;
2269                                                                 }
2270                                                         } elseif ($item) {
2271                                                                 if (self::samePermissions($uid, $item, $photo)) {
2272                                                                         $replace = true;
2273                                                                 }
2274                                                         }
2275                                                 }
2276                                                 if ($replace) {
2277                                                         $photo_img = Photo::getImageForPhoto($photo);
2278                                                         // If a custom width and height were specified, apply before embedding
2279                                                         if (preg_match("/\[img\=([0-9]*)x([0-9]*)\]/is", substr($orig_body, $img_start, $img_st_close), $match)) {
2280                                                                 Logger::info('scaling photo');
2281
2282                                                                 $width = intval($match[1]);
2283                                                                 $height = intval($match[2]);
2284
2285                                                                 $photo_img->scaleDown(max($width, $height));
2286                                                         }
2287
2288                                                         $data = $photo_img->asString();
2289                                                         $type = $photo_img->getType();
2290
2291                                                         Logger::info('replacing photo');
2292                                                         $image = 'data:' . $type . ';base64,' . base64_encode($data);
2293                                                         Logger::debug('replaced', ['image' => $image]);
2294                                                 }
2295                                         }
2296                                 }
2297                         }
2298
2299                         $new_body = $new_body . substr($orig_body, 0, $img_start + $img_st_close) . $image . '[/img]';
2300                         $orig_body = substr($orig_body, $img_start + $img_st_close + $img_len + strlen('[/img]'));
2301                         if ($orig_body === false) {
2302                                 $orig_body = '';
2303                         }
2304
2305                         $img_start = strpos($orig_body, '[img');
2306                         $img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
2307                         $img_len = ($img_start !== false ? strpos(substr($orig_body, $img_start + $img_st_close + 1), '[/img]') : false);
2308                 }
2309
2310                 $new_body = $new_body . $orig_body;
2311
2312                 return $new_body;
2313         }
2314
2315         private static function hasPermissions(array $obj)
2316         {
2317                 return !empty($obj['allow_cid']) || !empty($obj['allow_gid']) ||
2318                         !empty($obj['deny_cid']) || !empty($obj['deny_gid']);
2319         }
2320
2321         // @TODO $uid is unused parameter
2322         private static function samePermissions($uid, array $obj1, array $obj2): bool
2323         {
2324                 // first part is easy. Check that these are exactly the same.
2325                 if (($obj1['allow_cid'] == $obj2['allow_cid'])
2326                         && ($obj1['allow_gid'] == $obj2['allow_gid'])
2327                         && ($obj1['deny_cid'] == $obj2['deny_cid'])
2328                         && ($obj1['deny_gid'] == $obj2['deny_gid'])) {
2329                         return true;
2330                 }
2331
2332                 // This is harder. Parse all the permissions and compare the resulting set.
2333                 $recipients1 = self::enumeratePermissions($obj1);
2334                 $recipients2 = self::enumeratePermissions($obj2);
2335                 sort($recipients1);
2336                 sort($recipients2);
2337
2338                 /// @TODO Comparison of arrays, maybe use array_diff_assoc() here?
2339                 return ($recipients1 == $recipients2);
2340         }
2341
2342         /**
2343          * Returns an array of contact-ids that are allowed to see this object
2344          *
2345          * @param array $obj        Item array with at least uid, allow_cid, allow_gid, deny_cid and deny_gid
2346          * @param bool  $check_dead Prunes unavailable contacts from the result
2347          * @return array
2348          * @throws \Exception
2349          */
2350         public static function enumeratePermissions(array $obj, bool $check_dead = false): array
2351         {
2352                 $aclFormater = DI::aclFormatter();
2353
2354                 $allow_people = $aclFormater->expand($obj['allow_cid']);
2355                 $allow_groups = Group::expand($obj['uid'], $aclFormater->expand($obj['allow_gid']), $check_dead);
2356                 $deny_people  = $aclFormater->expand($obj['deny_cid']);
2357                 $deny_groups  = Group::expand($obj['uid'], $aclFormater->expand($obj['deny_gid']), $check_dead);
2358                 $recipients   = array_unique(array_merge($allow_people, $allow_groups));
2359                 $deny         = array_unique(array_merge($deny_people, $deny_groups));
2360                 $recipients   = array_diff($recipients, $deny);
2361                 return $recipients;
2362         }
2363
2364         public static function expire(int $uid, int $days, string $network = "", bool $force = false)
2365         {
2366                 if (!$uid || ($days < 1)) {
2367                         return;
2368                 }
2369
2370                 $condition = ["`uid` = ? AND NOT `deleted` AND `gravity` = ?",
2371                         $uid, GRAVITY_PARENT];
2372
2373                 /*
2374                  * $expire_network_only = save your own wall posts
2375                  * and just expire conversations started by others
2376                  */
2377                 $expire_network_only = DI::pConfig()->get($uid, 'expire', 'network_only', false);
2378
2379                 if ($expire_network_only) {
2380                         $condition[0] .= " AND NOT `wall`";
2381                 }
2382
2383                 if ($network != "") {
2384                         $condition[0] .= " AND `network` = ?";
2385                         $condition[] = $network;
2386                 }
2387
2388                 $condition[0] .= " AND `received` < ?";
2389                 $condition[] = DateTimeFormat::utc('now - ' . $days . ' day');
2390
2391                 $items = Post::select(['resource-id', 'starred', 'id', 'post-type', 'uid', 'uri-id'], $condition);
2392
2393                 if (!DBA::isResult($items)) {
2394                         return;
2395                 }
2396
2397                 $expire_items = DI::pConfig()->get($uid, 'expire', 'items', true);
2398
2399                 // Forcing expiring of items - but not notes and marked items
2400                 if ($force) {
2401                         $expire_items = true;
2402                 }
2403
2404                 $expire_notes = DI::pConfig()->get($uid, 'expire', 'notes', true);
2405                 $expire_starred = DI::pConfig()->get($uid, 'expire', 'starred', true);
2406                 $expire_photos = DI::pConfig()->get($uid, 'expire', 'photos', false);
2407
2408                 $expired = 0;
2409
2410                 $priority = DI::config()->get('system', 'expire-notify-priority');
2411
2412                 while ($item = Post::fetch($items)) {
2413                         // don't expire filed items
2414                         if (DBA::exists('post-category', ['uri-id' => $item['uri-id'], 'uid' => $item['uid'], 'type' => Post\Category::FILE])) {
2415                                 continue;
2416                         }
2417
2418                         // Only expire posts, not photos and photo comments
2419
2420                         if (!$expire_photos && !empty($item['resource-id'])) {
2421                                 continue;
2422                         } elseif (!$expire_starred && intval($item['starred'])) {
2423                                 continue;
2424                         } elseif (!$expire_notes && ($item['post-type'] == self::PT_PERSONAL_NOTE)) {
2425                                 continue;
2426                         } elseif (!$expire_items && ($item['post-type'] != self::PT_PERSONAL_NOTE)) {
2427                                 continue;
2428                         }
2429
2430                         self::markForDeletionById($item['id'], $priority);
2431
2432                         ++$expired;
2433                 }
2434                 DBA::close($items);
2435                 Logger::notice('User ' . $uid . ": expired $expired items; expire items: $expire_items, expire notes: $expire_notes, expire starred: $expire_starred, expire photos: $expire_photos");
2436         }
2437
2438         public static function firstPostDate(int $uid, bool $wall = false)
2439         {
2440                 $user = User::getById($uid, ['register_date']);
2441                 if (empty($user)) {
2442                         return false;
2443                 }
2444
2445                 $condition = ["`uid` = ? AND `wall` = ? AND NOT `deleted` AND `visible` AND `received` >= ?",
2446                         $uid, $wall, $user['register_date']];
2447                 $params = ['order' => ['received' => false]];
2448                 $thread = Post::selectFirstThread(['received'], $condition, $params);
2449                 if (DBA::isResult($thread)) {
2450                         $postdate = substr(DateTimeFormat::local($thread['received']), 0, 10);
2451                         return $postdate;
2452                 }
2453                 return false;
2454         }
2455
2456         /**
2457          * add/remove activity to an item
2458          *
2459          * Toggle activities as like,dislike,attend of an item
2460          *
2461          * @param int    $item_id
2462          * @param string $verb
2463          *            Activity verb. One of
2464          *            like, unlike, dislike, undislike, attendyes, unattendyes,
2465          *            attendno, unattendno, attendmaybe, unattendmaybe,
2466          *            announce, unannouce
2467          * @param int    $uid
2468          * @param string $allow_cid
2469          * @param string $allow_gid
2470          * @param string $deny_cid
2471          * @param string $deny_gid
2472          * @return bool
2473          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2474          * @throws \ImagickException
2475          * @hook  'post_local_end'
2476          *            array $arr
2477          *            'post_id' => ID of posted item
2478          */
2479         public static function performActivity(int $item_id, string $verb, int $uid, string $allow_cid = null, string $allow_gid = null, string $deny_cid = null, string $deny_gid = null): bool
2480         {
2481                 if (empty($uid)) {
2482                         return false;
2483                 }
2484
2485                 Logger::notice('Start create activity', ['verb' => $verb, 'item' => $item_id, 'user' => $uid]);
2486
2487                 $item = Post::selectFirst(self::ITEM_FIELDLIST, ['id' => $item_id]);
2488                 if (!DBA::isResult($item)) {
2489                         Logger::notice('like: unknown item', ['id' => $item_id]);
2490                         return false;
2491                 }
2492
2493                 $uri_id = $item['uri-id'];
2494
2495                 if (!in_array($item['uid'], [0, $uid])) {
2496                         return false;
2497                 }
2498
2499                 if (!Post::exists(['uri-id' => $item['parent-uri-id'], 'uid' => $uid])) {
2500                         $stored = self::storeForUserByUriId($item['parent-uri-id'], $uid, ['post-reason' => Item::PR_ACTIVITY]);
2501                         if (($item['parent-uri-id'] == $item['uri-id']) && !empty($stored)) {
2502                                 $item = Post::selectFirst(self::ITEM_FIELDLIST, ['id' => $stored]);
2503                                 if (!DBA::isResult($item)) {
2504                                         Logger::info('Could not fetch just created item - should not happen', ['stored' => $stored, 'uid' => $uid, 'uri-id' => $uri_id]);
2505                                         return false;
2506                                 }
2507                         }
2508                 }
2509
2510                 // Retrieves the local post owner
2511                 $owner = User::getOwnerDataById($uid);
2512                 if (empty($owner)) {
2513                         Logger::info('Empty owner for user', ['uid' => $uid]);
2514                         return false;
2515                 }
2516
2517                 // Retrieve the current logged in user's public contact
2518                 $author_id = Contact::getIdForURL($owner['url']);
2519                 if (empty($author_id)) {
2520                         Logger::info('Empty public contact');
2521                         return false;
2522                 }
2523
2524                 $activity = null;
2525                 switch ($verb) {
2526                         case 'like':
2527                         case 'unlike':
2528                                 $activity = Activity::LIKE;
2529                                 break;
2530                         case 'dislike':
2531                         case 'undislike':
2532                                 $activity = Activity::DISLIKE;
2533                                 break;
2534                         case 'attendyes':
2535                         case 'unattendyes':
2536                                 $activity = Activity::ATTEND;
2537                                 break;
2538                         case 'attendno':
2539                         case 'unattendno':
2540                                 $activity = Activity::ATTENDNO;
2541                                 break;
2542                         case 'attendmaybe':
2543                         case 'unattendmaybe':
2544                                 $activity = Activity::ATTENDMAYBE;
2545                                 break;
2546                         case 'follow':
2547                         case 'unfollow':
2548                                 $activity = Activity::FOLLOW;
2549                                 break;
2550                         case 'announce':
2551                         case 'unannounce':
2552                                 $activity = Activity::ANNOUNCE;
2553                                 break;
2554                         default:
2555                                 Logger::notice('unknown verb', ['verb' => $verb, 'item' => $item_id]);
2556                                 return false;
2557                 }
2558
2559                 $mode = Strings::startsWith($verb, 'un') ? 'delete' : 'create';
2560
2561                 // Enable activity toggling instead of on/off
2562                 $event_verb_flag = $activity === Activity::ATTEND || $activity === Activity::ATTENDNO || $activity === Activity::ATTENDMAYBE;
2563
2564                 // Look for an existing verb row
2565                 // Event participation activities are mutually exclusive, only one of them can exist at all times.
2566                 if ($event_verb_flag) {
2567                         $verbs = [Activity::ATTEND, Activity::ATTENDNO, Activity::ATTENDMAYBE];
2568
2569                         // Translate to the index based activity index
2570                         $vids = [];
2571                         foreach ($verbs as $verb) {
2572                                 $vids[] = Verb::getID($verb);
2573                         }
2574                 } else {
2575                         $vids = Verb::getID($activity);
2576                 }
2577
2578                 $condition = ['vid' => $vids, 'deleted' => false, 'gravity' => GRAVITY_ACTIVITY,
2579                         'author-id' => $author_id, 'uid' => $item['uid'], 'thr-parent-id' => $uri_id];
2580                 $like_item = Post::selectFirst(['id', 'guid', 'verb'], $condition);
2581
2582                 if (DBA::isResult($like_item)) {
2583                         /**
2584                          * Truth table for existing activities
2585                          *
2586                          * |          Inputs            ||      Outputs      |
2587                          * |----------------------------||-------------------|
2588                          * |  Mode  | Event | Same verb || Delete? | Return? |
2589                          * |--------|-------|-----------||---------|---------|
2590                          * | create |  Yes  |    Yes    ||   No    |   Yes   |
2591                          * | create |  Yes  |    No     ||   Yes   |   No    |
2592                          * | create |  No   |    Yes    ||   No    |   Yes   |
2593                          * | create |  No   |    No     ||        N/A†       |
2594                          * | delete |  Yes  |    Yes    ||   Yes   |   N/A‡  |
2595                          * | delete |  Yes  |    No     ||   No    |   N/A‡  |
2596                          * | delete |  No   |    Yes    ||   Yes   |   N/A‡  |
2597                          * | delete |  No   |    No     ||        N/A†       |
2598                          * |--------|-------|-----------||---------|---------|
2599                          * |   A    |   B   |     C     || A xor C | !B or C |
2600                          *
2601                          * â€  Can't happen: It's impossible to find an existing non-event activity without
2602                          *                 the same verb because we are only looking for this single verb.
2603                          *
2604                          * â€¡ The "mode = delete" is returning early whether an existing activity was found or not.
2605                          */
2606                         if ($mode == 'create' xor $like_item['verb'] == $activity) {
2607                                 self::markForDeletionById($like_item['id']);
2608                         }
2609
2610                         if (!$event_verb_flag || $like_item['verb'] == $activity) {
2611                                 return true;
2612                         }
2613                 }
2614
2615                 // No need to go further if we aren't creating anything
2616                 if ($mode == 'delete') {
2617                         return true;
2618                 }
2619
2620                 $objtype = $item['resource-id'] ? Activity\ObjectType::IMAGE : Activity\ObjectType::NOTE;
2621
2622                 $new_item = [
2623                         'guid'          => System::createUUID(),
2624                         'uri'           => self::newURI(),
2625                         'uid'           => $item['uid'],
2626                         'contact-id'    => $owner['id'],
2627                         'wall'          => $item['wall'],
2628                         'origin'        => 1,
2629                         'network'       => Protocol::DFRN,
2630                         'protocol'      => Conversation::PARCEL_DIRECT,
2631                         'direction'     => Conversation::PUSH,
2632                         'gravity'       => GRAVITY_ACTIVITY,
2633                         'parent'        => $item['id'],
2634                         'thr-parent'    => $item['uri'],
2635                         'owner-id'      => $author_id,
2636                         'author-id'     => $author_id,
2637                         'body'          => $activity,
2638                         'verb'          => $activity,
2639                         'object-type'   => $objtype,
2640                         'allow_cid'     => $allow_cid ?? $item['allow_cid'],
2641                         'allow_gid'     => $allow_gid ?? $item['allow_gid'],
2642                         'deny_cid'      => $deny_cid ?? $item['deny_cid'],
2643                         'deny_gid'      => $deny_gid ?? $item['deny_gid'],
2644                         'visible'       => 1,
2645                         'unseen'        => 1,
2646                 ];
2647
2648                 $signed = Diaspora::createLikeSignature($uid, $new_item);
2649                 if (!empty($signed)) {
2650                         $new_item['diaspora_signed_text'] = json_encode($signed);
2651                 }
2652
2653                 $new_item_id = self::insert($new_item);
2654
2655                 // If the parent item isn't visible then set it to visible
2656                 if (!$item['visible']) {
2657                         self::update(['visible' => true], ['id' => $item['id']]);
2658                 }
2659
2660                 $new_item['id'] = $new_item_id;
2661
2662                 Hook::callAll('post_local_end', $new_item);
2663
2664                 return true;
2665         }
2666
2667         /**
2668          * Fetch the SQL condition for the given user id
2669          *
2670          * @param integer $owner_id User ID for which the permissions should be fetched
2671          * @return array condition
2672          */
2673         public static function getPermissionsConditionArrayByUserId(int $owner_id): array
2674         {
2675                 $local_user = local_user();
2676                 $remote_user = Session::getRemoteContactID($owner_id);
2677
2678                 // default permissions - anonymous user
2679                 $condition = ["`private` != ?", self::PRIVATE];
2680
2681                 if ($local_user && ($local_user == $owner_id)) {
2682                         // Profile owner - everything is visible
2683                         $condition = [];
2684                 } elseif ($remote_user) {
2685                          // Authenticated visitor - fetch the matching permissionsets
2686                         $permissionSets = DI::permissionSet()->selectByContactId($remote_user, $owner_id);
2687                         if (!empty($set)) {
2688                                 $condition = ["(`private` != ? OR (`private` = ? AND `wall`
2689                                         AND `psid` IN (" . implode(', ', array_fill(0, count($set), '?')) . ")))",
2690                                         self::PRIVATE, self::PRIVATE];
2691                                 $condition = array_merge($condition, $permissionSets->column('id'));
2692                         }
2693                 }
2694
2695                 return $condition;
2696         }
2697
2698         /**
2699          * Get a permission SQL string for the given user
2700          *
2701          * @param int $owner_id
2702          * @param string $table
2703          * @return string
2704          */
2705         public static function getPermissionsSQLByUserId(int $owner_id, string $table = ''): string
2706         {
2707                 $local_user = local_user();
2708                 $remote_user = Session::getRemoteContactID($owner_id);
2709
2710                 if (!empty($table)) {
2711                         $table = DBA::quoteIdentifier($table) . '.';
2712                 }
2713
2714                 /*
2715                  * Construct permissions
2716                  *
2717                  * default permissions - anonymous user
2718                  */
2719                 $sql = sprintf(" AND " . $table . "`private` != %d", self::PRIVATE);
2720
2721                 // Profile owner - everything is visible
2722                 if ($local_user && ($local_user == $owner_id)) {
2723                         $sql = '';
2724                 } elseif ($remote_user) {
2725                         /*
2726                          * Authenticated visitor. Unless pre-verified,
2727                          * check that the contact belongs to this $owner_id
2728                          * and load the groups the visitor belongs to.
2729                          * If pre-verified, the caller is expected to have already
2730                          * done this and passed the groups into this function.
2731                          */
2732                         $permissionSets = DI::permissionSet()->selectByContactId($remote_user, $owner_id);
2733
2734                         if (!empty($set)) {
2735                                 $sql_set = sprintf(" OR (" . $table . "`private` = %d AND " . $table . "`wall` AND " . $table . "`psid` IN (", self::PRIVATE) . implode(',', $permissionSets->column('id')) . "))";
2736                         } else {
2737                                 $sql_set = '';
2738                         }
2739
2740                         $sql = sprintf(" AND (" . $table . "`private` != %d", self::PRIVATE) . $sql_set . ")";
2741                 }
2742
2743                 return $sql;
2744         }
2745
2746         /**
2747          * get translated item type
2748          *
2749          * @param array                $item
2750          * @param \Friendica\Core\L10n $l10n
2751          * @return string
2752          */
2753         public static function postType(array $item, \Friendica\Core\L10n $l10n): string
2754         {
2755                 if (!empty($item['event-id'])) {
2756                         return $l10n->t('event');
2757                 } elseif (!empty($item['resource-id'])) {
2758                         return $l10n->t('photo');
2759                 } elseif ($item['gravity'] == GRAVITY_ACTIVITY) {
2760                         return $l10n->t('activity');
2761                 } elseif ($item['gravity'] == GRAVITY_COMMENT) {
2762                         return $l10n->t('comment');
2763                 }
2764
2765                 return $l10n->t('post');
2766         }
2767
2768         /**
2769          * Sets the "rendered-html" field of the provided item
2770          *
2771          * Body is preserved to avoid side-effects as we modify it just-in-time for spoilers and private image links
2772          *
2773          * @param array $item
2774          *
2775          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2776          * @todo Remove reference, simply return "rendered-html" and "rendered-hash"
2777          */
2778         private static function putInCache(&$item)
2779         {
2780                 // Save original body to prevent addons to modify it
2781                 $body = $item['body'];
2782
2783                 $rendered_hash = $item['rendered-hash'] ?? '';
2784                 $rendered_html = $item['rendered-html'] ?? '';
2785
2786                 if ($rendered_hash == ''
2787                         || $rendered_html == ''
2788                         || $rendered_hash != hash('md5', BBCode::VERSION . '::' . $body)
2789                         || DI::config()->get('system', 'ignore_cache')
2790                 ) {
2791                         $item['rendered-html'] = BBCode::convertForUriId($item['uri-id'], $item['body']);
2792                         $item['rendered-hash'] = hash('md5', BBCode::VERSION . '::' . $body);
2793
2794                         $hook_data = ['item' => $item, 'rendered-html' => $item['rendered-html'], 'rendered-hash' => $item['rendered-hash']];
2795                         Hook::callAll('put_item_in_cache', $hook_data);
2796                         $item['rendered-html'] = $hook_data['rendered-html'];
2797                         $item['rendered-hash'] = $hook_data['rendered-hash'];
2798                         unset($hook_data);
2799
2800                         // Update if the generated values differ from the existing ones
2801                         if ((($rendered_hash != $item['rendered-hash']) || ($rendered_html != $item['rendered-html'])) && !empty($item['id'])) {
2802                                 self::update(
2803                                         [
2804                                                 'rendered-html' => $item['rendered-html'],
2805                                                 'rendered-hash' => $item['rendered-hash']
2806                                         ],
2807                                         ['id' => $item['id']]
2808                                 );
2809                         }
2810                 }
2811
2812                 $item['body'] = $body;
2813         }
2814
2815         /**
2816          * Given an item array, convert the body element from bbcode to html and add smilie icons.
2817          * If attach is true, also add icons for item attachments.
2818          *
2819          * @param array   $item Record from item table
2820          * @param boolean $attach If true, add icons for item attachments as well
2821          * @param boolean $is_preview Whether this is a preview
2822          * @param boolean $only_cache Whether only cached HTML should be updated
2823          * @return string item body html
2824          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2825          * @throws \ImagickException
2826          * @hook  prepare_body_init item array before any work
2827          * @hook  prepare_body_content_filter ('item'=>item array, 'filter_reasons'=>string array) before first bbcode to html
2828          * @hook  prepare_body ('item'=>item array, 'html'=>body string, 'is_preview'=>boolean, 'filter_reasons'=>string array) after first bbcode to html
2829          * @hook  prepare_body_final ('item'=>item array, 'html'=>body string) after attach icons and blockquote special case handling (spoiler, author)
2830          */
2831         public static function prepareBody(array &$item, bool $attach = false, bool $is_preview = false, bool $only_cache = false): string
2832         {
2833                 $a = DI::app();
2834                 Hook::callAll('prepare_body_init', $item);
2835
2836                 // In order to provide theme developers more possibilities, event items
2837                 // are treated differently.
2838                 if ($item['object-type'] === Activity\ObjectType::EVENT && isset($item['event-id'])) {
2839                         $ev = Event::getItemHTML($item);
2840                         return $ev;
2841                 }
2842
2843                 $tags = Tag::populateFromItem($item);
2844
2845                 $item['tags'] = $tags['tags'];
2846                 $item['hashtags'] = $tags['hashtags'];
2847                 $item['mentions'] = $tags['mentions'];
2848
2849                 $body = $item['body'] ?? '';
2850                 $shared = BBCode::fetchShareAttributes($body);
2851                 if (!empty($shared['guid'])) {
2852                         $shared_item = Post::selectFirst(['uri-id', 'plink', 'has-media'], ['guid' => $shared['guid']]);
2853                         $shared_uri_id = $shared_item['uri-id'] ?? 0;
2854                         $shared_links = [strtolower($shared_item['plink'] ?? '')];
2855                         $shared_attachments = Post\Media::splitAttachments($shared_uri_id, $shared['guid'], [], $shared_item['has-media'] ?? false);
2856                         $shared_links = array_merge($shared_links, array_column($shared_attachments['visual'], 'url'));
2857                         $shared_links = array_merge($shared_links, array_column($shared_attachments['link'], 'url'));
2858                         $shared_links = array_merge($shared_links, array_column($shared_attachments['additional'], 'url'));
2859                         $item['body'] = self::replaceVisualAttachments($shared_attachments, $item['body']);
2860                 } else {
2861                         $shared_uri_id = 0;
2862                         $shared_links = [];
2863                 }
2864
2865                 $attachments = Post\Media::splitAttachments($item['uri-id'], $item['guid'] ?? '', $shared_links, $item['has-media'] ?? false);
2866                 $item['body'] = self::replaceVisualAttachments($attachments, $item['body'] ?? '');
2867
2868                 $item['body'] = preg_replace("/\s*\[attachment .*?\].*?\[\/attachment\]\s*/ism", "\n", $item['body']);
2869                 self::putInCache($item);
2870                 $item['body'] = $body;
2871                 $s = $item["rendered-html"];
2872
2873                 if ($only_cache) {
2874                         return '';
2875                 }
2876
2877                 // Compile eventual content filter reasons
2878                 $filter_reasons = [];
2879                 if (!$is_preview && public_contact() != $item['author-id']) {
2880                         if (!empty($item['content-warning']) && (!local_user() || !DI::pConfig()->get(local_user(), 'system', 'disable_cw', false))) {
2881                                 $filter_reasons[] = DI::l10n()->t('Content warning: %s', $item['content-warning']);
2882                         }
2883
2884                         $item['attachments'] = $attachments;
2885
2886                         $hook_data = [
2887                                 'item' => $item,
2888                                 'filter_reasons' => $filter_reasons
2889                         ];
2890                         Hook::callAll('prepare_body_content_filter', $hook_data);
2891                         $filter_reasons = $hook_data['filter_reasons'];
2892                         unset($hook_data);
2893                 }
2894
2895                 $hook_data = [
2896                         'item' => $item,
2897                         'html' => $s,
2898                         'preview' => $is_preview,
2899                         'filter_reasons' => $filter_reasons
2900                 ];
2901                 Hook::callAll('prepare_body', $hook_data);
2902                 $s = $hook_data['html'];
2903                 unset($hook_data);
2904
2905                 if (!$attach) {
2906                         // Replace the blockquotes with quotes that are used in mails.
2907                         $mailquote = '<blockquote type="cite" class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex;">';
2908                         $s = str_replace(['<blockquote>', '<blockquote class="spoiler">', '<blockquote class="author">'], [$mailquote, $mailquote, $mailquote], $s);
2909                         return $s;
2910                 }
2911
2912                 if (!empty($shared_attachments)) {
2913                         $s = self::addVisualAttachments($shared_attachments, $item, $s, true);
2914                         $s = self::addLinkAttachment($shared_uri_id ?: $item['uri-id'], $shared_attachments, $body, $s, true, []);
2915                         $s = self::addNonVisualAttachments($shared_attachments, $item, $s, true);
2916                         $body = preg_replace("/\s*\[share .*?\].*?\[\/share\]\s*/ism", '', $body);
2917                 }
2918
2919                 $s = self::addVisualAttachments($attachments, $item, $s, false);
2920                 $s = self::addLinkAttachment($item['uri-id'], $attachments, $body, $s, false, $shared_links);
2921                 $s = self::addNonVisualAttachments($attachments, $item, $s, false);
2922                 $s = self::addQuestions($item, $s);
2923
2924                 // Map.
2925                 if (strpos($s, '<div class="map">') !== false && !empty($item['coord'])) {
2926                         $x = Map::byCoordinates(trim($item['coord']));
2927                         if ($x) {
2928                                 $s = preg_replace('/\<div class\=\"map\"\>/', '$0' . $x, $s);
2929                         }
2930                 }
2931
2932                 // Replace friendica image url size with theme preference.
2933                 if (!empty($a->getThemeInfoValue('item_image_size'))) {
2934                         $ps = $a->getThemeInfoValue('item_image_size');
2935                         $s = preg_replace('|(<img[^>]+src="[^"]+/photo/[0-9a-f]+)-[0-9]|', "$1-" . $ps, $s);
2936                 }
2937
2938                 $s = HTML::applyContentFilter($s, $filter_reasons);
2939
2940                 $hook_data = ['item' => $item, 'html' => $s];
2941                 Hook::callAll('prepare_body_final', $hook_data);
2942
2943                 return $hook_data['html'];
2944         }
2945
2946         /**
2947          * Check if the body contains a link
2948          *
2949          * @param string $body
2950          * @param string $url
2951          * @param int    $type
2952          * @return bool
2953          */
2954         public static function containsLink(string $body, string $url, int $type = 0): bool
2955         {
2956                 // Make sure that for example site parameters aren't used when testing if the link is contained in the body
2957                 $urlparts = parse_url($url);
2958                 if (!empty($urlparts)) {
2959                         unset($urlparts['query']);
2960                         unset($urlparts['fragment']);
2961                         $url = (string)Uri::fromParts($urlparts);
2962                 } else {
2963                         return false;
2964                 }
2965
2966                 // Remove media links to only search in embedded content
2967                 // @todo Check images for image link, audio for audio links, ...
2968                 if (in_array($type, [Post\Media::AUDIO, Post\Media::VIDEO, Post\Media::IMAGE])) {
2969                         $body = preg_replace("/\[url=[^\[\]]*\](.*)\[\/url\]/Usi", ' $1 ', $body);
2970                 }
2971
2972                 if (strpos($body, $url)) {
2973                         return true;
2974                 }
2975                 foreach ([0, 1, 2] as $size) {
2976                         if (preg_match('#/photo/.*-' . $size . '\.#ism', $url) &&
2977                                 strpos(preg_replace('#(/photo/.*)-[012]\.#ism', '$1-' . $size . '.', $body), $url)) {
2978                                 return true;
2979                         }
2980                 }
2981                 return false;
2982         }
2983
2984         /**
2985          * Replace visual attachments in the body
2986          *
2987          * @param array $attachments
2988          * @param string $body
2989          * @return string modified body
2990          */
2991         private static function replaceVisualAttachments(array $attachments, string $body): string
2992         {
2993                 DI::profiler()->startRecording('rendering');
2994
2995                 foreach ($attachments['visual'] as $attachment) {
2996                         if (!empty($attachment['preview'])) {
2997                                 $proxy   = Post\Media::getPreviewUrlForId($attachment['id'], Proxy::SIZE_LARGE);
2998                                 $search  = ['[img=' . $attachment['preview'] . ']', ']' . $attachment['preview'] . '[/img]'];
2999                                 $replace = ['[img=' . $proxy . ']', ']' . $proxy . '[/img]'];
3000
3001                                 $body = str_replace($search, $replace, $body);
3002                         } elseif ($attachment['filetype'] == 'image') {
3003                                 $proxy   = Post\Media::getUrlForId($attachment['id']);
3004                                 $search  = ['[img=' . $attachment['url'] . ']', ']' . $attachment['url'] . '[/img]'];
3005                                 $replace = ['[img=' . $proxy . ']', ']' . $proxy . '[/img]'];
3006
3007                                 $body = str_replace($search, $replace, $body);
3008                         }
3009                 }
3010                 DI::profiler()->stopRecording();
3011                 return $body;
3012         }
3013
3014         /**
3015          * Add visual attachments to the content
3016          *
3017          * @param array $attachments
3018          * @param array $item
3019          * @param string $content
3020          * @return string modified content
3021          */
3022         private static function addVisualAttachments(array $attachments, array $item, string $content, bool $shared): string
3023         {
3024                 DI::profiler()->startRecording('rendering');
3025                 $leading = '';
3026                 $trailing = '';
3027
3028                 // @todo In the future we should make a single for the template engine with all media in it. This allows more flexibilty.
3029                 foreach ($attachments['visual'] as $attachment) {
3030                         if (self::containsLink($item['body'], $attachment['preview'] ?? $attachment['url'], $attachment['type'])) {
3031                                 continue;
3032                         }
3033
3034                         if (!empty($attachment['preview'])) {
3035                                 $preview_url = Post\Media::getPreviewUrlForId($attachment['id'], Proxy::SIZE_LARGE);
3036                         } else {
3037                                 $preview_url = '';
3038                         }
3039
3040                         if (($attachment['filetype'] == 'video')) {
3041                                 /// @todo Move the template to /content as well
3042                                 $media = Renderer::replaceMacros(Renderer::getMarkupTemplate('video_top.tpl'), [
3043                                         '$video' => [
3044                                                 'id'      => $attachment['id'],
3045                                                 'src'     => $attachment['url'],
3046                                                 'name'    => $attachment['name'] ?: $attachment['url'],
3047                                                 'preview' => $preview_url,
3048                                                 'mime'    => $attachment['mimetype'],
3049                                         ],
3050                                 ]);
3051                                 if (($item['post-type'] ?? null) == Item::PT_VIDEO) {
3052                                         $leading .= $media;
3053                                 } else {
3054                                         $trailing .= $media;
3055                                 }
3056                         } elseif ($attachment['filetype'] == 'audio') {
3057                                 $media = Renderer::replaceMacros(Renderer::getMarkupTemplate('content/audio.tpl'), [
3058                                         '$audio' => [
3059                                                 'id'     => $attachment['id'],
3060                                                 'src'    => $attachment['url'],
3061                                                 'name'   => $attachment['name'] ?: $attachment['url'],
3062                                                 'mime'   => $attachment['mimetype'],
3063                                         ],
3064                                 ]);
3065                                 if (($item['post-type'] ?? null) == Item::PT_AUDIO) {
3066                                         $leading .= $media;
3067                                 } else {
3068                                         $trailing .= $media;
3069                                 }
3070                         } elseif ($attachment['filetype'] == 'image') {
3071                                 $media = Renderer::replaceMacros(Renderer::getMarkupTemplate('content/image.tpl'), [
3072                                         '$image' => [
3073                                                 'src'        => Post\Media::getUrlForId($attachment['id']),
3074                                                 'preview'    => Post\Media::getPreviewUrlForId($attachment['id'], ($attachment['width'] > $attachment['height']) ? Proxy::SIZE_MEDIUM : Proxy::SIZE_LARGE),
3075                                                 'attachment' => $attachment,
3076                                         ],
3077                                 ]);
3078                                 // On Diaspora posts the attached pictures are leading
3079                                 if ($item['network'] == Protocol::DIASPORA) {
3080                                         $leading .= $media;
3081                                 } else {
3082                                         $trailing .= $media;
3083                                 }
3084                         }
3085                 }
3086
3087                 if ($shared) {
3088                         $content = str_replace(BBCode::TOP_ANCHOR, '<div class="body-attach">' . $leading . '<div class="clear"></div></div>' . BBCode::TOP_ANCHOR, $content);
3089                         $content = str_replace(BBCode::BOTTOM_ANCHOR, '<div class="body-attach">' . $trailing . '<div class="clear"></div></div>' . BBCode::BOTTOM_ANCHOR, $content);
3090                 } else {
3091                         if ($leading != '') {
3092                                 $content = '<div class="body-attach">' . $leading . '<div class="clear"></div></div>' . $content;
3093                         }
3094
3095                         if ($trailing != '') {
3096                                 $content .= '<div class="body-attach">' . $trailing . '<div class="clear"></div></div>';
3097                         }
3098                 }
3099
3100                 DI::profiler()->stopRecording();
3101                 return $content;
3102         }
3103
3104         /**
3105          * Add link attachment to the content
3106          *
3107          * @param array  $attachments
3108          * @param string $body
3109          * @param string $content
3110          * @param bool   $shared
3111          * @param array  $ignore_links A list of URLs to ignore
3112          * @return string modified content
3113          */
3114         private static function addLinkAttachment(int $uriid, array $attachments, string $body, string $content, bool $shared, array $ignore_links): string
3115         {
3116                 DI::profiler()->startRecording('rendering');
3117                 // Don't show a preview when there is a visual attachment (audio or video)
3118                 $types = array_column($attachments['visual'], 'type');
3119                 $preview = !in_array(Post\Media::IMAGE, $types) && !in_array(Post\Media::VIDEO, $types);
3120
3121                 if (!empty($attachments['link'])) {
3122                         foreach ($attachments['link'] as $link) {
3123                                 $found = false;
3124                                 foreach ($ignore_links as $ignore_link) {
3125                                         if (Strings::compareLink($link['url'], $ignore_link)) {
3126                                                 $found = true;
3127                                         }
3128                                 }
3129                                 // @todo Judge between the links to use the one with most information
3130                                 if (!$found && (empty($attachment) || !empty($link['author-name']) ||
3131                                         (empty($attachment['name']) && !empty($link['name'])) ||
3132                                         (empty($attachment['description']) && !empty($link['description'])) ||
3133                                         (empty($attachment['preview']) && !empty($link['preview'])))) {
3134                                         $attachment = $link;
3135                                 }
3136                         }
3137                 }
3138
3139                 if (!empty($attachment)) {
3140                         $data = [
3141                                 'after' => '',
3142                                 'author_name' => $attachment['author-name'] ?? '',
3143                                 'author_url' =>  $attachment['author-url'] ?? '',
3144                                 'description' => $attachment['description'] ?? '',
3145                                 'image' => '',
3146                                 'preview' => '',
3147                                 'provider_name' => $attachment['publisher-name'] ?? '',
3148                                 'provider_url' => $attachment['publisher-url'] ?? '',
3149                                 'text' => '',
3150                                 'title' => $attachment['name'] ?? '',
3151                                 'type' => 'link',
3152                                 'url' => $attachment['url']];
3153
3154                         if ($preview && !empty($attachment['preview'])) {
3155                                 if ($attachment['preview-width'] >= 500) {
3156                                         $data['image'] = Post\Media::getPreviewUrlForId($attachment['id'], Proxy::SIZE_MEDIUM);
3157                                 } else {
3158                                         $data['preview'] = Post\Media::getPreviewUrlForId($attachment['id'], Proxy::SIZE_MEDIUM);
3159                                 }
3160                         }
3161
3162                         if (!empty($data['description']) && !empty($content)) {
3163                                 similar_text($data['description'], $content, $percent);
3164                         } else {
3165                                 $percent = 0;
3166                         }
3167
3168                         if (!empty($data['description']) && (($data['title'] == $data['description']) || ($percent > 95) || (strpos($content, $data['description']) !== false))) {
3169                                 $data['description'] = '';
3170                         }
3171
3172                         if (($data['author_name'] ?? '') == ($data['provider_name'] ?? '')) {
3173                                 $data['author_name'] = '';
3174                         }
3175
3176                         if (($data['author_url'] ?? '') == ($data['provider_url'] ?? '')) {
3177                                 $data['author_url'] = '';
3178                         }
3179                 } elseif (preg_match("/.*(\[attachment.*?\].*?\[\/attachment\]).*/ism", $body, $match)) {
3180                         $data = BBCode::getAttachmentData($match[1]);
3181                 }
3182                 DI::profiler()->stopRecording();
3183
3184                 if (isset($data['url']) && !in_array($data['url'], $ignore_links)) {
3185                         if (!empty($data['description']) || !empty($data['image']) || !empty($data['preview'])) {
3186                                 $parts = parse_url($data['url']);
3187                                 if (!empty($parts['scheme']) && !empty($parts['host'])) {
3188                                         if (empty($data['provider_name'])) {
3189                                                 $data['provider_name'] = $parts['host'];
3190                                         }
3191                                         if (empty($data['provider_url']) || empty(parse_url($data['provider_url'], PHP_URL_SCHEME))) {
3192                                                 $data['provider_url'] = $parts['scheme'] . '://' . $parts['host'];
3193
3194                                                 if (!empty($parts['port'])) {
3195                                                         $data['provider_url'] .= ':' . $parts['port'];
3196                                                 }
3197                                         }
3198                                 }
3199
3200                                 // @todo Use a template
3201                                 $rendered = BBCode::convertAttachment('', BBCode::INTERNAL, false, $data, $uriid);
3202                         } elseif (!self::containsLink($content, $data['url'], Post\Media::HTML)) {
3203                                 $rendered = Renderer::replaceMacros(Renderer::getMarkupTemplate('content/link.tpl'), [
3204                                         '$url'  => $data['url'],
3205                                         '$title' => $data['title'],
3206                                 ]);
3207                         } else {
3208                                 return $content;
3209                         }
3210
3211                         if ($shared) {
3212                                 return str_replace(BBCode::BOTTOM_ANCHOR, BBCode::BOTTOM_ANCHOR . $rendered, $content);
3213                         } else {
3214                                 return $content . $rendered;
3215                         }
3216                 }
3217                 return $content;
3218         }
3219
3220         /**
3221          * Add non visual attachments to the content
3222          *
3223          * @param array $attachments
3224          * @param array $item
3225          * @param string $content
3226          * @return string modified content
3227          */
3228         private static function addNonVisualAttachments(array $attachments, array $item, string $content): string
3229         {
3230                 DI::profiler()->startRecording('rendering');
3231                 $trailing = '';
3232                 foreach ($attachments['additional'] as $attachment) {
3233                         if (strpos($item['body'], $attachment['url'])) {
3234                                 continue;
3235                         }
3236
3237                         $author = ['uid' => 0, 'id' => $item['author-id'],
3238                                 'network' => $item['author-network'], 'url' => $item['author-link']];
3239                         $the_url = Contact::magicLinkByContact($author, $attachment['url']);
3240
3241                         $title = Strings::escapeHtml(trim(($attachment['description'] ?? '') ?: $attachment['url']));
3242
3243                         if (!empty($attachment['size'])) {
3244                                 $title .= ' ' . $attachment['size'] . ' ' . DI::l10n()->t('bytes');
3245                         }
3246
3247                         /// @todo Use a template
3248                         $icon = '<div class="attachtype icon s22 type-' . $attachment['filetype'] . ' subtype-' . $attachment['subtype'] . '"></div>';
3249                         $trailing .= '<a href="' . strip_tags($the_url) . '" title="' . $title . '" class="attachlink" target="_blank" rel="noopener noreferrer" >' . $icon . '</a>';
3250                 }
3251
3252                 if ($trailing != '') {
3253                         $content .= '<div class="body-attach">' . $trailing . '<div class="clear"></div></div>';
3254                 }
3255
3256                 DI::profiler()->stopRecording();
3257                 return $content;
3258         }
3259
3260         private static function addQuestions(array $item, string $content): string
3261         {
3262                 DI::profiler()->startRecording('rendering');
3263                 if (!empty($item['question-id'])) {
3264                         $question = [
3265                                 'id'       => $item['question-id'],
3266                                 'multiple' => $item['question-multiple'],
3267                                 'voters'   => $item['question-voters'],
3268                                 'endtime'  => $item['question-end-time']
3269                         ];
3270
3271                         $options = Post\QuestionOption::getByURIId($item['uri-id']);
3272                         foreach ($options as $key => $option) {
3273                                 $percent = $question['voters'] ? ($option['replies'] / $question['voters'] * 100) : 0;
3274
3275                                 $options[$key]['percent'] = $percent;
3276
3277                                 if ($question['voters'] > 0) {
3278                                         $options[$key]['vote'] = DI::l10n()->t('%s (%d%s, %d votes)', $option['name'], round($percent, 1), '%', $option['replies']);
3279                                 } else {
3280                                         $options[$key]['vote'] = DI::l10n()->t('%s (%d votes)', $option['name'], $option['replies']);
3281                                 }
3282                         }
3283
3284                         if (!empty($question['voters']) && !empty($question['endtime'])) {
3285                                 $summary = DI::l10n()->t('%d voters. Poll end: %s', $question['voters'], Temporal::getRelativeDate($question['endtime']));
3286                         } elseif (!empty($question['voters'])) {
3287                                 $summary = DI::l10n()->t('%d voters.', $question['voters']);
3288                         } elseif (!empty($question['endtime'])) {
3289                                 $summary = DI::l10n()->t('Poll end: %s', Temporal::getRelativeDate($question['endtime']));
3290                         } else {
3291                                 $summary = '';
3292                         }
3293
3294                         $content .= Renderer::replaceMacros(Renderer::getMarkupTemplate('content/question.tpl'), [
3295                                 '$question' => $question,
3296                                 '$options'  => $options,
3297                                 '$summary'  => $summary,
3298                         ]);
3299         }
3300                 DI::profiler()->stopRecording();
3301                 return $content;
3302         }
3303
3304         /**
3305          * get private link for item
3306          *
3307          * @param array $item
3308          * @return boolean|array False if item has not plink, otherwise array('href'=>plink url, 'title'=>translated title)
3309          * @throws \Exception
3310          */
3311         public static function getPlink(array $item)
3312         {
3313                 if (!empty($item['plink']) && Network::isValidHttpUrl($item['plink'])) {
3314                         $plink = $item['plink'];
3315                 } elseif (!empty($item['uri']) && Network::isValidHttpUrl($item['uri']) && !Network::isLocalLink($item['uri'])) {
3316                         $plink = $item['uri'];
3317                 }
3318
3319                 if (local_user()) {
3320                         $ret = [
3321                                 'href' => "display/" . $item['guid'],
3322                                 'orig' => "display/" . $item['guid'],
3323                                 'title' => DI::l10n()->t('View on separate page'),
3324                                 'orig_title' => DI::l10n()->t('View on separate page'),
3325                         ];
3326
3327                         if (!empty($plink) && ($item['private'] == self::PRIVATE)) {
3328                                 $author = ['uid' => 0, 'id' => $item['author-id'],
3329                                         'network' => $item['author-network'], 'url' => $item['author-link']];
3330                                 $plink = Contact::magicLinkByContact($author, $plink);
3331                         }
3332
3333                         if (!empty($plink)) {
3334                                 $ret['href'] = DI::baseUrl()->remove($plink);
3335                                 $ret['title'] = DI::l10n()->t('Link to source');
3336                         }
3337                 } elseif (!empty($plink) && ($item['private'] != self::PRIVATE)) {
3338                         $ret = [
3339                                 'href' => $plink,
3340                                 'orig' => $plink,
3341                                 'title' => DI::l10n()->t('Link to source'),
3342                                 'orig_title' => DI::l10n()->t('Link to source'),
3343                         ];
3344                 } else {
3345                         $ret = [];
3346                 }
3347
3348                 return $ret;
3349         }
3350
3351         /**
3352          * Does the given uri-id belongs to a post that is sent as starting post to a forum?
3353          *
3354          * @param int $uri_id
3355          *
3356          * @return boolean "true" when it is a forum post
3357          */
3358         public static function isForumPost(int $uri_id): bool
3359         {
3360                 foreach (Tag::getByURIId($uri_id, [Tag::EXCLUSIVE_MENTION]) as $tag) {
3361                         if (DBA::exists('contact', ['uid' => 0, 'nurl' => Strings::normaliseLink($tag['url']), 'contact-type' => Contact::TYPE_COMMUNITY])) {
3362                                 return true;
3363                         }
3364                 }
3365                 return false;
3366         }
3367
3368         /**
3369          * Search item id for given URI or plink
3370          *
3371          * @param string $uri
3372          * @param integer $uid
3373          *
3374          * @return integer item id
3375          */
3376         public static function searchByLink(string $uri, int $uid = 0): int
3377         {
3378                 $ssl_uri = str_replace('http://', 'https://', $uri);
3379                 $uris = [$uri, $ssl_uri, Strings::normaliseLink($uri)];
3380
3381                 $item = Post::selectFirst(['id'], ['uri' => $uris, 'uid' => $uid]);
3382                 if (DBA::isResult($item)) {
3383                         return $item['id'];
3384                 }
3385
3386                 $item = Post::selectFirst(['id'], ['plink' => $uris, 'uid' => $uid]);
3387                 if (DBA::isResult($item)) {
3388                         return $item['id'];
3389                 }
3390
3391                 return 0;
3392         }
3393
3394         /**
3395          * Return the URI for a link to the post
3396          *
3397          * @param string $uri URI or link to post
3398          *
3399          * @return string URI
3400          */
3401         public static function getURIByLink(string $uri): string
3402         {
3403                 $ssl_uri = str_replace('http://', 'https://', $uri);
3404                 $uris = [$uri, $ssl_uri, Strings::normaliseLink($uri)];
3405
3406                 $item = Post::selectFirst(['uri'], ['uri' => $uris]);
3407                 if (DBA::isResult($item)) {
3408                         return $item['uri'];
3409                 }
3410
3411                 $item = Post::selectFirst(['uri'], ['plink' => $uris]);
3412                 if (DBA::isResult($item)) {
3413                         return $item['uri'];
3414                 }
3415
3416                 return '';
3417         }
3418
3419         /**
3420          * Fetches item for given URI or plink
3421          *
3422          * @param string $uri
3423          * @param integer $uid
3424          *
3425          * @return integer item id
3426          */
3427         public static function fetchByLink(string $uri, int $uid = 0): int
3428         {
3429                 Logger::info('Trying to fetch link', ['uid' => $uid, 'uri' => $uri]);
3430                 $item_id = self::searchByLink($uri, $uid);
3431                 if (!empty($item_id)) {
3432                         Logger::info('Link found', ['uid' => $uid, 'uri' => $uri, 'id' => $item_id]);
3433                         return $item_id;
3434                 }
3435
3436                 $hookData = [
3437                         'uri'     => $uri,
3438                         'uid'     => $uid,
3439                         'item_id' => null,
3440                 ];
3441
3442                 Hook::callAll('item_by_link', $hookData);
3443
3444                 if (isset($hookData['item_id'])) {
3445                         return is_numeric($hookData['item_id']) ? $hookData['item_id'] : 0;
3446                 }
3447
3448                 $fetched_uri = ActivityPub\Processor::fetchMissingActivity($uri);
3449
3450                 if ($fetched_uri) {
3451                         $item_id = self::searchByLink($fetched_uri, $uid);
3452                 } else {
3453                         $item_id = Diaspora::fetchByURL($uri);
3454                 }
3455
3456                 if (!empty($item_id)) {
3457                         Logger::info('Link fetched', ['uid' => $uid, 'uri' => $uri, 'id' => $item_id]);
3458                         return $item_id;
3459                 }
3460
3461                 Logger::info('Link not found', ['uid' => $uid, 'uri' => $uri]);
3462                 return 0;
3463         }
3464
3465         /**
3466          * Return share data from an item array (if the item is shared item)
3467          * We are providing the complete Item array, because at some time in the future
3468          * we hopefully will define these values not in the body anymore but in some item fields.
3469          * This function is meant to replace all similar functions in the system.
3470          *
3471          * @param array $item
3472          *
3473          * @return array with share information
3474          */
3475         public static function getShareArray(array $item): array
3476         {
3477                 return BBCode::fetchShareAttributes($item['body']);
3478         }
3479
3480         /**
3481          * Fetch item information for shared items from the original items and adds it.
3482          *
3483          * @param array $item
3484          *
3485          * @return array item array with data from the original item
3486          */
3487         public static function addShareDataFromOriginal(array $item): array
3488         {
3489                 $shared = self::getShareArray($item);
3490                 if (empty($shared)) {
3491                         return $item;
3492                 }
3493
3494                 // Real reshares always have got a GUID.
3495                 if (empty($shared['guid'])) {
3496                         return $item;
3497                 }
3498
3499                 $uid = $item['uid'] ?? 0;
3500
3501                 // first try to fetch the item via the GUID. This will work for all reshares that had been created on this system
3502                 $shared_item = Post::selectFirst(['title', 'body'], ['guid' => $shared['guid'], 'uid' => [0, $uid]]);
3503                 if (!DBA::isResult($shared_item)) {
3504                         if (empty($shared['link'])) {
3505                                 return $item;
3506                         }
3507
3508                         // Otherwhise try to find (and possibly fetch) the item via the link. This should work for Diaspora and ActivityPub posts
3509                         $id = self::fetchByLink($shared['link'] ?? '', $uid);
3510                         if (empty($id)) {
3511                                 Logger::info('Original item not found', ['url' => $shared['link'] ?? '', 'callstack' => System::callstack()]);
3512                                 return $item;
3513                         }
3514
3515                         $shared_item = Post::selectFirst(['title', 'body'], ['id' => $id]);
3516                         if (!DBA::isResult($shared_item)) {
3517                                 return $item;
3518                         }
3519                         Logger::info('Got shared data from url', ['url' => $shared['link'], 'callstack' => System::callstack()]);
3520                 } else {
3521                         Logger::info('Got shared data from guid', ['guid' => $shared['guid'], 'callstack' => System::callstack()]);
3522                 }
3523
3524                 if (!empty($shared_item['title'])) {
3525                         $body = '[h3]' . $shared_item['title'] . "[/h3]\n" . $shared_item['body'];
3526                         unset($shared_item['title']);
3527                 } else {
3528                         $body = $shared_item['body'];
3529                 }
3530
3531                 $item['body'] = preg_replace("/\[share ([^\[\]]*)\].*\[\/share\]/ism", '[share $1]' . str_replace('$', '\$', $body) . '[/share]', $item['body']);
3532                 unset($shared_item['body']);
3533
3534                 return array_merge($item, $shared_item);
3535         }
3536
3537         /**
3538          * Check a prospective item array against user-level permissions
3539          *
3540          * @param array $item Expected keys: uri, gravity, and
3541          *                    author-link if is author-id is set,
3542          *                    owner-link if is owner-id is set,
3543          *                    causer-link if is causer-id is set.
3544          * @param int   $user_id Local user ID
3545          * @return bool
3546          * @throws \Exception
3547          */
3548         protected static function isAllowedByUser(array $item, int $user_id): bool
3549         {
3550                 if (!empty($item['author-id']) && Contact\User::isBlocked($item['author-id'], $user_id)) {
3551                         Logger::notice('Author is blocked by user', ['author-link' => $item['author-link'], 'uid' => $user_id, 'item-uri' => $item['uri']]);
3552                         return false;
3553                 }
3554
3555                 if (!empty($item['owner-id']) && Contact\User::isBlocked($item['owner-id'], $user_id)) {
3556                         Logger::notice('Owner is blocked by user', ['owner-link' => $item['owner-link'], 'uid' => $user_id, 'item-uri' => $item['uri']]);
3557                         return false;
3558                 }
3559
3560                 // The causer is set during a thread completion, for example because of a reshare. It countains the responsible actor.
3561                 if (!empty($item['causer-id']) && Contact\User::isBlocked($item['causer-id'], $user_id)) {
3562                         Logger::notice('Causer is blocked by user', ['causer-link' => $item['causer-link'] ?? $item['causer-id'], 'uid' => $user_id, 'item-uri' => $item['uri']]);
3563                         return false;
3564                 }
3565
3566                 if (!empty($item['causer-id']) && ($item['gravity'] === GRAVITY_PARENT) && Contact\User::isIgnored($item['causer-id'], $user_id)) {
3567                         Logger::notice('Causer is ignored by user', ['causer-link' => $item['causer-link'] ?? $item['causer-id'], 'uid' => $user_id, 'item-uri' => $item['uri']]);
3568                         return false;
3569                 }
3570
3571                 return true;
3572         }
3573
3574         /**
3575          * Improve the data in shared posts
3576          *
3577          * @param array $item
3578          * @return string body
3579          */
3580         public static function improveSharedDataInBody(array $item): string
3581         {
3582                 $shared = BBCode::fetchShareAttributes($item['body']);
3583                 if (empty($shared['link'])) {
3584                         return $item['body'];
3585                 }
3586
3587                 $id = self::fetchByLink($shared['link']);
3588                 Logger::info('Fetched shared post', ['uri-id' => $item['uri-id'], 'id' => $id, 'author' => $shared['profile'], 'url' => $shared['link'], 'guid' => $shared['guid'], 'callstack' => System::callstack()]);
3589                 if (!$id) {
3590                         return $item['body'];
3591                 }
3592
3593                 $shared_item = Post::selectFirst(['author-name', 'author-link', 'author-avatar', 'plink', 'created', 'guid', 'title', 'body'], ['id' => $id]);
3594                 if (!DBA::isResult($shared_item)) {
3595                         return $item['body'];
3596                 }
3597
3598                 $shared_content = BBCode::getShareOpeningTag($shared_item['author-name'], $shared_item['author-link'], $shared_item['author-avatar'], $shared_item['plink'], $shared_item['created'], $shared_item['guid']);
3599
3600                 if (!empty($shared_item['title'])) {
3601                         $shared_content .= '[h3]'.$shared_item['title'].'[/h3]'."\n";
3602                 }
3603
3604                 $shared_content .= $shared_item['body'];
3605
3606                 $item['body'] = preg_replace("/\[share.*?\](.*)\[\/share\]/ism", $shared_content . '[/share]', $item['body']);
3607                 Logger::info('New shared data', ['uri-id' => $item['uri-id'], 'id' => $id, 'shared_item' => $shared_item]);
3608                 return $item['body'];
3609         }
3610 }