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