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