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