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