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