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