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