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