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